@polymorphism-tech/morph-spec 10.12.1 → 11.1.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 +53 -338
- 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 +12 -9
- 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 +32 -87
- 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 +15 -13
- package/framework/rules/resend-standards.md +1 -1
- package/framework/rules/ui-design.md +5 -1
- 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 +13 -342
- 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 +16 -53
- 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 +13 -37
- package/src/utils/atomic-json.js +27 -0
- package/src/utils/file-copier.js +24 -24
- 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,1247 +0,0 @@
|
|
|
1
|
-
import { execFileSync } from 'child_process';
|
|
2
|
-
import { existsSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
|
3
|
-
import { join, resolve } from 'path';
|
|
4
|
-
import {
|
|
5
|
-
findWorktreeForFeature,
|
|
6
|
-
shedRootFeatureScope,
|
|
7
|
-
primaryRootUnexplainedDirt,
|
|
8
|
-
teardownWorktree,
|
|
9
|
-
resolvePrimaryRoot,
|
|
10
|
-
isValidFeatureName,
|
|
11
|
-
buildBranchName,
|
|
12
|
-
branchExists,
|
|
13
|
-
cwdIsInsideWorktree,
|
|
14
|
-
worktreeHeldElsewhere,
|
|
15
|
-
sessionAnchoredInWorktree,
|
|
16
|
-
classifyIgnoredLeftovers,
|
|
17
|
-
} from '../project/worktree.js';
|
|
18
|
-
import { detectDefaultBranch, hasOriginRemote } from '../../lib/git/default-branch.js';
|
|
19
|
-
import { commitsAhead, resolveBaseRef } from '../../lib/git/branch-classifier.js';
|
|
20
|
-
import { resolveGh } from '../../lib/git/gh.js';
|
|
21
|
-
import { releaseClaim } from '../../../framework/hooks/shared/claim-registry.js';
|
|
22
|
-
import { tearDownFeatureStack } from '../../lib/e2e/stack-teardown.js';
|
|
23
|
-
import { findReparsePoints } from '../../../framework/hooks/shared/reparse-scan.js';
|
|
24
|
-
import { runArchive } from './archive.js';
|
|
25
|
-
import { dropLeftoverIgnore, withoutLeftoverIgnore } from '../../../framework/hooks/shared/graph-freshness.js';
|
|
26
|
-
import { newBackupStamp, enforceBackupRetention, inspectFinishBackups } from '../../lib/worktree/finish-backup.js';
|
|
27
|
-
import { isTestArtifact } from '../../lib/worktree/ignored-triage.js';
|
|
28
|
-
import { waitForPrChecks } from '../../lib/ci/pr-checks.js';
|
|
29
|
-
import { atomicWriteJson } from '../../core/state/state-manager.js';
|
|
30
|
-
import { recordGateEvent } from '../../../framework/hooks/shared/gate-event.js';
|
|
31
|
-
import { parsePlan } from '../../lib/plan/plan-parser.js';
|
|
32
|
-
import { reviewReportsFromDir } from '../../lib/review-reports.js';
|
|
33
|
-
import { implementProgressFrom } from '../../../framework/hooks/shared/report-progress.js';
|
|
34
|
-
import {
|
|
35
|
-
CHECK_RESULT_SAY, GATE_NAME, PROOF_SAY, STATUS_SAY, TESTS, WORK_NAME, featureName, featureRef, scenarioLabel,
|
|
36
|
-
} from '../../../framework/hooks/shared/owner-words.js';
|
|
37
|
-
|
|
38
|
-
const PR_TYPE_BY_WORK_TYPE = { feature: 'feat', bug: 'fix', hotfix: 'fix', chore: 'chore' };
|
|
39
|
-
|
|
40
|
-
/** Git's soft limit for a subject line. */
|
|
41
|
-
const PR_TITLE_MAX = 72;
|
|
42
|
-
|
|
43
|
-
// `{type}({slug}): {subject}`, the subject from the plan's `Nome`, then `name` (unless it is the
|
|
44
|
-
// default slug), then `description`, first line only; with none, `{type}: {slug}`.
|
|
45
|
-
export function buildPrTitle(feature, fj, summary = null) {
|
|
46
|
-
const type = PR_TYPE_BY_WORK_TYPE[fj?.workType] || 'chore';
|
|
47
|
-
|
|
48
|
-
const planned = typeof summary?.name === 'string' ? summary.name.trim() : '';
|
|
49
|
-
const named = typeof fj?.name === 'string' ? fj.name.trim() : '';
|
|
50
|
-
// The default `name` IS the slug, which as a subject would only repeat the scope.
|
|
51
|
-
const described = typeof fj?.description === 'string' ? fj.description.trim() : '';
|
|
52
|
-
const raw = (planned || (named && named !== feature ? named : described)).split('\n')[0].trim();
|
|
53
|
-
if (!raw) return `${type}: ${feature}`;
|
|
54
|
-
|
|
55
|
-
const prefix = `${type}(${feature}): `;
|
|
56
|
-
const room = PR_TITLE_MAX - prefix.length;
|
|
57
|
-
// No room left for a subject: drop the scope rather than ship a title that is all prefix.
|
|
58
|
-
if (room < 12) return `${type}: ${raw}`.slice(0, PR_TITLE_MAX);
|
|
59
|
-
return prefix + (raw.length <= room ? raw : `${raw.slice(0, room - 1)}…`);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const ISSUE_URL_RE = /https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/(\d+)/;
|
|
63
|
-
const ISSUE_KEYWORD_RE = /\b(close[sd]?|fix(e[sd])?|resolve[sd]?|refs?)\s+([\w.-]+\/[\w.-]+)?#\d+/i;
|
|
64
|
-
|
|
65
|
-
const ISSUE_KEYWORD_ALL_RE = new RegExp(ISSUE_KEYWORD_RE.source, 'gi');
|
|
66
|
-
|
|
67
|
-
const readText = (path) => { try { return readFileSync(path, 'utf8'); } catch { return null; } };
|
|
68
|
-
const readJsonFile = (path) => { try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; } };
|
|
69
|
-
const flat = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
|
|
70
|
-
|
|
71
|
-
/** What a PR body is built from; every file is optional (a resumed finish reads the pruned archive). */
|
|
72
|
-
export function prSourcesFor(dir) {
|
|
73
|
-
if (!dir) return null;
|
|
74
|
-
const planText = readText(join(dir, '2-plan', 'plan.md'));
|
|
75
|
-
const plan = planText ? parsePlan(planText) : null;
|
|
76
|
-
const checksText = readText(join(dir, '2-plan', 'checks.json'));
|
|
77
|
-
const checksSummary = readJsonFile(join(dir, '2-plan', 'checks.json'))?.summary ?? null;
|
|
78
|
-
const progress = implementProgressFrom(checksText, readText(join(dir, '3-implement', 'report.md')));
|
|
79
|
-
const verifier = existsSync(join(dir, '4-review')) ? reviewReportsFromDir(dir).verifier : null;
|
|
80
|
-
const recap = readJsonFile(join(dir, 'recap.json'));
|
|
81
|
-
const summary = {
|
|
82
|
-
name: plan?.summary?.name ?? checksSummary?.name ?? recap?.summary?.name ?? null,
|
|
83
|
-
today: plan?.summary?.today ?? recap?.summary?.today ?? null,
|
|
84
|
-
after: plan?.summary?.after ?? checksSummary?.after ?? recap?.summary?.after ?? null,
|
|
85
|
-
watch: plan?.summary?.watch ?? recap?.summary?.watch ?? [],
|
|
86
|
-
};
|
|
87
|
-
return { plan, summary, progress, verifierChecks: verifier?.checks ?? null, recap };
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const PROOF_GLYPH = { PROVADO: '✓', FALHA: '✕', 'NÃO PROVADO': '!' };
|
|
91
|
-
|
|
92
|
-
function proofLines(src) {
|
|
93
|
-
const planned = src.plan?.scenarios?.length ? src.plan.scenarios : (src.recap?.scenarios ?? []);
|
|
94
|
-
if (!planned.length) return null;
|
|
95
|
-
const progress = new Map((src.progress?.checks ?? []).map((c) => [c.id, c]));
|
|
96
|
-
const verified = src.verifierChecks
|
|
97
|
-
? new Map(src.verifierChecks.map((c) => [c.id, c]))
|
|
98
|
-
: new Map((src.recap?.scenarios ?? []).filter((c) => c.status).map((c) => [c.id, c]));
|
|
99
|
-
const rows = planned.map((c) => {
|
|
100
|
-
const titled = { ...c, title: c.title ?? progress.get(c.id)?.title ?? null };
|
|
101
|
-
const label = scenarioLabel(titled);
|
|
102
|
-
const how = c.proof ? PROOF_SAY[String(c.proof).toLowerCase()] ?? c.proof : null;
|
|
103
|
-
const v = verified.get(c.id);
|
|
104
|
-
if (v) {
|
|
105
|
-
const said = CHECK_RESULT_SAY[v.status] ?? 'sem resultado da conferência';
|
|
106
|
-
return { ok: v.status === 'PROVADO', line: `- ${PROOF_GLYPH[v.status] ?? '·'} ${label} — ${said} pela revisão independente${how ? `, por ${how}` : ''}.`, id: c.id, evidence: flat(v.evidence) };
|
|
107
|
-
}
|
|
108
|
-
const status = progress.get(c.id)?.status ?? null;
|
|
109
|
-
const said = status ? `${STATUS_SAY[status] ?? status}, sem conferência independente` : 'sem registro de construção';
|
|
110
|
-
return { ok: false, built: status === 'feito', line: `- ${status === 'feito' ? '✓' : '·'} ${label} — ${said}${how ? ` (prova prevista: ${how})` : ''}.`, id: c.id, evidence: flat(progress.get(c.id)?.evidence) };
|
|
111
|
-
});
|
|
112
|
-
const total = rows.length;
|
|
113
|
-
const head = verified.size
|
|
114
|
-
? `${rows.filter((r) => r.ok).length} de ${total} ${total === 1 ? 'cenário conferido' : 'cenários conferidos'} pela revisão independente.`
|
|
115
|
-
: `${rows.filter((r) => r.built).length} de ${total} ${total === 1 ? 'cenário feito' : 'cenários feitos'}; a conferência independente não deixou registro.`;
|
|
116
|
-
return { head, rows };
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// The description's own keyword wins (`Refs #N` keeps the issue open); a bare issue link closes it.
|
|
120
|
-
// Without a plan to read, the body is the description.
|
|
121
|
-
export function prBodyFor(feature, fj, { dir = null, sources = undefined } = {}) {
|
|
122
|
-
const described = typeof fj?.description === 'string' ? fj.description.trim() : '';
|
|
123
|
-
const issue = described.match(ISSUE_URL_RE);
|
|
124
|
-
const keywords = described.match(ISSUE_KEYWORD_ALL_RE) ?? [];
|
|
125
|
-
const closing = keywords.length ? keywords.join('\n') : issue ? `Closes ${issue[1]}#${issue[2]}` : null;
|
|
126
|
-
const src = sources === undefined ? prSourcesFor(dir) : sources;
|
|
127
|
-
const proof = src ? proofLines(src) : null;
|
|
128
|
-
const s = src?.summary ?? {};
|
|
129
|
-
if (!proof && !s.today && !s.after) {
|
|
130
|
-
const body = described || `${feature}: entrega aberta pelo morph-spec.`;
|
|
131
|
-
if (!issue || keywords.length) return body;
|
|
132
|
-
return `${body}\n\nCloses ${issue[1]}#${issue[2]}`;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
const out = ['## O que muda para quem usa', ''];
|
|
136
|
-
if (s.today) out.push(`- Hoje: ${flat(s.today)}`);
|
|
137
|
-
if (s.after) out.push(`- Depois: ${flat(s.after)}`);
|
|
138
|
-
if (!s.today && !s.after) out.push(`- ${featureName(feature, fj, s)}`);
|
|
139
|
-
if (s.watch?.length) out.push('', 'Atenção:', ...s.watch.map((w) => `- ${flat(w)}`));
|
|
140
|
-
|
|
141
|
-
out.push('', '## Prova', '');
|
|
142
|
-
if (proof) out.push(proof.head, '', ...proof.rows.map((r) => r.line));
|
|
143
|
-
else out.push('O plano não lista cenários para conferir.');
|
|
144
|
-
|
|
145
|
-
out.push('', '## Detalhe técnico', '', `- Feature: \`${feature}\``, `- Branch: \`${buildBranchName(feature)}\``);
|
|
146
|
-
if (fj?.workType) out.push(`- Tipo: ${WORK_NAME[fj.workType] ?? fj.workType}`);
|
|
147
|
-
const adrs = src?.plan?.adrs ?? [];
|
|
148
|
-
if (adrs.length) out.push('- Decisões:', ...adrs.map((a) => ` - ${a.id}: ${flat(a.title)}`));
|
|
149
|
-
const evidence = (proof?.rows ?? []).filter((r) => r.evidence);
|
|
150
|
-
if (evidence.length) out.push('- Evidência por cenário:', ...evidence.map((r) => ` - Cenário ${r.id.replace(/^C/i, '')}: ${r.evidence}`));
|
|
151
|
-
if (described) out.push('', '<details><summary>Pedido original</summary>', '', described, '', '</details>');
|
|
152
|
-
if (closing) out.push('', closing);
|
|
153
|
-
return out.join('\n');
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// Regenerated from the tree: on a merge, the default's copy is as good as ours.
|
|
157
|
-
const GENERATED_PATHS = new Set(['.morph/context/README.md']);
|
|
158
|
-
|
|
159
|
-
/** Merges origin/<default> into the feature branch so the PR is never born CONFLICTING. */
|
|
160
|
-
function joinDefault(tree, defaultBranch) {
|
|
161
|
-
const target = `origin/${defaultBranch}`;
|
|
162
|
-
try {
|
|
163
|
-
execFileSync('git', ['fetch', '-q', 'origin', defaultBranch], { cwd: tree, stdio: 'pipe' });
|
|
164
|
-
} catch (err) {
|
|
165
|
-
return { error: 'default-fetch-failed', output: gitErr(err) };
|
|
166
|
-
}
|
|
167
|
-
try {
|
|
168
|
-
execFileSync('git', ['merge-base', '--is-ancestor', target, 'HEAD'], { cwd: tree, stdio: 'pipe' });
|
|
169
|
-
return { merged: false };
|
|
170
|
-
} catch { /* behind the default: merge it */ }
|
|
171
|
-
try {
|
|
172
|
-
execFileSync('git', ['merge', '-q', '--no-edit', target], { cwd: tree, stdio: 'pipe' });
|
|
173
|
-
return { merged: true };
|
|
174
|
-
} catch (err) {
|
|
175
|
-
const conflicts = execFileSync('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: tree, stdio: 'pipe' })
|
|
176
|
-
.toString().split(/\r?\n/).filter(Boolean);
|
|
177
|
-
if (conflicts.length > 0 && conflicts.every((p) => GENERATED_PATHS.has(p))) {
|
|
178
|
-
execFileSync('git', ['checkout', '--theirs', '--', ...conflicts], { cwd: tree, stdio: 'pipe' });
|
|
179
|
-
execFileSync('git', ['add', '--', ...conflicts], { cwd: tree, stdio: 'pipe' });
|
|
180
|
-
execFileSync('git', ['commit', '-q', '--no-edit'], { cwd: tree, stdio: 'pipe' });
|
|
181
|
-
return { merged: true, resolved: conflicts };
|
|
182
|
-
}
|
|
183
|
-
tryGit(['merge', '--abort'], tree);
|
|
184
|
-
return { error: 'default-conflict', conflicts, output: conflicts.length ? undefined : gitErr(err) };
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// A human line, then the command the session runs on its own line.
|
|
189
|
-
const say = (human, session = null) => (session ? `${human}\npara a sessão: ${session}` : human);
|
|
190
|
-
|
|
191
|
-
// `Nome (slug)` from whichever tree holds the feature; the bare slug when nothing names it.
|
|
192
|
-
function labelOf(trees, feature) {
|
|
193
|
-
for (const tree of trees.filter(Boolean)) {
|
|
194
|
-
for (const bucket of ['features', 'archive']) {
|
|
195
|
-
const dir = join(tree, '.morph', bucket, feature);
|
|
196
|
-
if (!existsSync(dir)) continue;
|
|
197
|
-
try {
|
|
198
|
-
return featureRef(feature, readFeatureJson(tree, feature, bucket), prSourcesFor(dir)?.summary);
|
|
199
|
-
} catch {
|
|
200
|
-
return feature;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
return feature;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
const MEMORY_NOTE = 'o fechamento desta feature já está registrado no repositório (commit de archive, `plan.md` com as decisões, índice de ADRs, `git log`) — memória de sessão só para o que NENHUM deles guarda: decisão do usuário, pendência a observar em produção, custo medido.';
|
|
208
|
-
|
|
209
|
-
// Every refusal is fail-CLOSED and happens BEFORE the archive, the first mutation. Resumable: a
|
|
210
|
-
// later run that finds the feature archived on its branch but not integrated picks up there.
|
|
211
|
-
// `--dry-run` diverts to finishPreflight before any exit-1 validation: a preflight explains.
|
|
212
|
-
export async function finishCommand(feature, options = {}) {
|
|
213
|
-
const cwd = options.cwd || process.cwd();
|
|
214
|
-
const root = resolvePrimaryRoot(cwd);
|
|
215
|
-
const rootNorm = resolve(root).replace(/\\/g, '/');
|
|
216
|
-
|
|
217
|
-
// The claim is released on every success through emit (fail-open: a stale claim expires on its
|
|
218
|
-
// TTL). The e2e stack is reclaimed by each path BEFORE its worktree teardown, never here.
|
|
219
|
-
// `resumed` goes on every payload, so a merge of a feature archived by an earlier run is visible.
|
|
220
|
-
let resumed = false;
|
|
221
|
-
|
|
222
|
-
// ONE stamp for every backup this run writes, so they count as a single backup in the retention.
|
|
223
|
-
const backupStamp = newBackupStamp();
|
|
224
|
-
|
|
225
|
-
// Retention runs after this run's own backups exist, and never prunes this run's stamp.
|
|
226
|
-
const emit = (obj) => {
|
|
227
|
-
if (resumed) obj = { ...obj, resumed: true };
|
|
228
|
-
if (obj?.finished === true) {
|
|
229
|
-
// The one path every finished:true takes; the --pr payload is built by hand, outside mergeOutput.
|
|
230
|
-
obj = { ...obj, memoryNote: MEMORY_NOTE };
|
|
231
|
-
try {
|
|
232
|
-
const common = execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: root, stdio: 'pipe' }).toString().trim();
|
|
233
|
-
if (common) releaseClaim(feature, { gitCommonDir: resolve(root, common) });
|
|
234
|
-
} catch { /* fail-open */ }
|
|
235
|
-
const retention = enforceBackupRetention(root, { protectStamps: [backupStamp] });
|
|
236
|
-
if (retention) obj = { ...obj, backupRetention: retention };
|
|
237
|
-
}
|
|
238
|
-
console.log(JSON.stringify(obj));
|
|
239
|
-
};
|
|
240
|
-
|
|
241
|
-
// Anti command-injection: the name flows into every git/gh call below.
|
|
242
|
-
if (!isValidFeatureName(feature)) {
|
|
243
|
-
emit({ finished: false, error: 'invalid-feature-name', feature });
|
|
244
|
-
process.exit(1);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
const wantPr = !!options.pr;
|
|
248
|
-
const wantMerge = !!options.merge;
|
|
249
|
-
if (wantPr === wantMerge) {
|
|
250
|
-
emit({ finished: false, error: 'mode-required', hint: say(`Não sei como entregar ${labelOf([root], feature)}: falta escolher entre abrir um PR ou juntar direto na branch principal. Nada foi mexido.`, `\`morph-spec finish ${feature} --pr\` ou \`morph-spec finish ${feature} --merge\``), feature });
|
|
251
|
-
process.exit(1);
|
|
252
|
-
}
|
|
253
|
-
const mode = wantPr ? 'pr' : 'merge';
|
|
254
|
-
|
|
255
|
-
// `--push` publica a default depois de um merge local, e o `--pr` não faz merge local: recusa
|
|
256
|
-
// AQUI, antes do archive (a primeira mutação), em vez de aceitar em silêncio o que não honra.
|
|
257
|
-
if (wantPr && options.push) {
|
|
258
|
-
emit({
|
|
259
|
-
finished: false,
|
|
260
|
-
error: 'push-with-pr',
|
|
261
|
-
hint: say(
|
|
262
|
-
`Pedido contraditório para ${labelOf([root], feature)}: o PR já publica a branch da entrega, e o envio extra só vale depois de juntar direto na branch principal. Nada foi mexido.`,
|
|
263
|
-
`para abrir o PR, \`morph-spec finish ${feature} --pr\`; para juntar neste computador e publicar a principal, \`morph-spec finish ${feature} --merge --push\``,
|
|
264
|
-
),
|
|
265
|
-
feature,
|
|
266
|
-
});
|
|
267
|
-
process.exit(1);
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
const expectedBranch = buildBranchName(feature);
|
|
271
|
-
|
|
272
|
-
// findWorktreeForFeature also matches the PRIMARY ROOT when the common flow checked the branch
|
|
273
|
-
// out there: a match at the root is the common flow.
|
|
274
|
-
const found = findWorktreeForFeature(feature, root);
|
|
275
|
-
const isWorktreeFlow = !!found && found.path.replace(/\\/g, '/') !== rootNorm;
|
|
276
|
-
const who = () => labelOf([found?.path, root], feature);
|
|
277
|
-
|
|
278
|
-
let worktreePath = null;
|
|
279
|
-
let featureCwd = root; // where the feature's own tree (and its review) lives
|
|
280
|
-
|
|
281
|
-
// Pré-voo AQUI, antes das validações que saem com exit 1: ele existe para rodar antes de o estado
|
|
282
|
-
// estar bom, reporta o que encontrar e sai 0 sem tocar em nada.
|
|
283
|
-
if (options.dryRun) {
|
|
284
|
-
emit(finishPreflight({
|
|
285
|
-
feature,
|
|
286
|
-
root,
|
|
287
|
-
worktreePath: isWorktreeFlow ? found.path : null,
|
|
288
|
-
cwd,
|
|
289
|
-
mode,
|
|
290
|
-
branch: expectedBranch,
|
|
291
|
-
// `options` INTEIRO: `--discard-ignored` inverte a classificação, e um pré-voo sem as flags do
|
|
292
|
-
// comando prevê outro comando.
|
|
293
|
-
options,
|
|
294
|
-
}));
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
if (isWorktreeFlow) {
|
|
299
|
-
if (found.branch !== found.expectedBranch) {
|
|
300
|
-
emit({
|
|
301
|
-
finished: false,
|
|
302
|
-
error: 'worktree-branch-mismatch',
|
|
303
|
-
feature,
|
|
304
|
-
expectedBranch,
|
|
305
|
-
actualBranch: found.branch,
|
|
306
|
-
path: found.path,
|
|
307
|
-
hint: say(`A pasta de trabalho de ${who()} está em outra branch (${found.branch || 'nenhuma'}), não em ${expectedBranch}. Nada foi mexido.`, `volte ${found.path} para ${expectedBranch} e rode o finish de novo`),
|
|
308
|
-
});
|
|
309
|
-
process.exit(1);
|
|
310
|
-
}
|
|
311
|
-
worktreePath = found.path;
|
|
312
|
-
featureCwd = worktreePath;
|
|
313
|
-
|
|
314
|
-
// Windows locks the process cwd, so `git worktree remove` would fail AFTER the archive and the
|
|
315
|
-
// merge, leaving an orphan directory. Refuse here, before the first mutation.
|
|
316
|
-
if (cwdIsInsideWorktree(cwd, worktreePath)) {
|
|
317
|
-
emit({
|
|
318
|
-
finished: false,
|
|
319
|
-
error: 'cwd-inside-worktree',
|
|
320
|
-
feature,
|
|
321
|
-
path: worktreePath,
|
|
322
|
-
root,
|
|
323
|
-
hint: say(`O finish de ${who()} foi chamado de dentro da pasta de trabalho da entrega, que ele precisa apagar no fim. Nada foi mexido.`, `saia do worktree e rode o finish de novo a partir de "${root}"`),
|
|
324
|
-
});
|
|
325
|
-
process.exit(1);
|
|
326
|
-
}
|
|
327
|
-
// The session's own anchor defers the teardown instead; any other holder would orphan the folder.
|
|
328
|
-
if (!options.dryRun && !sessionAnchoredInWorktree(worktreePath) && worktreeHeldElsewhere(worktreePath)) {
|
|
329
|
-
emit({
|
|
330
|
-
finished: false,
|
|
331
|
-
error: 'worktree-in-use',
|
|
332
|
-
feature,
|
|
333
|
-
path: worktreePath,
|
|
334
|
-
root,
|
|
335
|
-
hint: say(`Outro programa está usando a pasta de trabalho de ${who()} (um terminal, o editor ou um servidor de dev). Nada foi mexido.`, `feche o que usa "${worktreePath}" e rode o finish de novo`),
|
|
336
|
-
});
|
|
337
|
-
process.exit(1);
|
|
338
|
-
}
|
|
339
|
-
} else {
|
|
340
|
-
// A feature with no morph/{f} branch predates this flow: route it to archive-without-integrate.
|
|
341
|
-
if (!branchExists(expectedBranch, root)) {
|
|
342
|
-
// No branch AND no folder is not a legacy feature: it is not here at all.
|
|
343
|
-
if (!existsSync(join(root, '.morph', 'features', feature))) {
|
|
344
|
-
emit({ finished: false, error: 'feature-not-found', feature, ...featureElsewhereHint(root, root, feature) });
|
|
345
|
-
process.exit(1);
|
|
346
|
-
}
|
|
347
|
-
emit({
|
|
348
|
-
finished: false,
|
|
349
|
-
error: 'no-feature-branch',
|
|
350
|
-
feature,
|
|
351
|
-
hint: say(`${who()} foi criada antes deste fluxo e não tem branch própria (${expectedBranch}), então não há o que juntar. Nada foi mexido.`, `arquive sem juntar com \`morph-spec archive ${feature}\`, ou continue o trabalho numa branch`),
|
|
352
|
-
});
|
|
353
|
-
process.exit(1);
|
|
354
|
-
}
|
|
355
|
-
const current = currentBranch(root);
|
|
356
|
-
if (current !== expectedBranch) {
|
|
357
|
-
emit({
|
|
358
|
-
finished: false,
|
|
359
|
-
error: 'not-on-feature-branch',
|
|
360
|
-
feature,
|
|
361
|
-
currentBranch: current,
|
|
362
|
-
expectedBranch,
|
|
363
|
-
hint: say(`O repositório está em ${current || 'nenhuma branch'}, não na branch de ${who()}. Nada foi mexido.`, `\`git checkout ${expectedBranch}\` e rode o finish de novo`),
|
|
364
|
-
});
|
|
365
|
-
process.exit(1);
|
|
366
|
-
}
|
|
367
|
-
featureCwd = root;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
// Not in `features/`: gone, archived awaiting integration (resume), or already integrated. Keyed
|
|
371
|
-
// on the DIRECTORY, not the parse: a legacy folder with a broken feature.json is --force's case.
|
|
372
|
-
if (!existsSync(join(featureCwd, '.morph', 'features', feature))) {
|
|
373
|
-
const archivePath = join(featureCwd, '.morph', 'archive', feature);
|
|
374
|
-
if (!existsSync(archivePath)) {
|
|
375
|
-
emit({ finished: false, error: 'feature-not-found', feature, ...featureElsewhereHint(featureCwd, root, feature) });
|
|
376
|
-
process.exit(1);
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
// Every path here already stands on `morph/{f}`, so only the integration is missing. A branch
|
|
380
|
-
// already contained in the default COMPLETED: re-merging it is the hazard this check stops.
|
|
381
|
-
const target = detectDefaultBranch(root);
|
|
382
|
-
if (!target) {
|
|
383
|
-
emit({ finished: false, error: 'no-default-branch', hint: say(`Não achei a branch principal do projeto (origin/HEAD, main ou master). Nada foi mexido.`, 'configure a branch principal do remoto e rode o finish de novo'), feature });
|
|
384
|
-
process.exit(1);
|
|
385
|
-
}
|
|
386
|
-
const merged = branchMergedInto(expectedBranch, target, root);
|
|
387
|
-
if (merged === null) {
|
|
388
|
-
// PROVE-or-DECLINE: refusing is recoverable, a duplicate merge is not.
|
|
389
|
-
emit({
|
|
390
|
-
finished: false,
|
|
391
|
-
error: 'resume-undecidable',
|
|
392
|
-
feature,
|
|
393
|
-
branch: expectedBranch,
|
|
394
|
-
base: target,
|
|
395
|
-
archived: archivePath.replace(/\\/g, '/'),
|
|
396
|
-
hint: say(`${who()} já foi arquivada, mas não consegui saber se a entrega já entrou em ${target}. Parei para não juntar duas vezes.`, `confira se ${expectedBranch} e ${target} existem no git antes de integrar à mão`),
|
|
397
|
-
});
|
|
398
|
-
process.exit(1);
|
|
399
|
-
}
|
|
400
|
-
if (merged) {
|
|
401
|
-
emit({
|
|
402
|
-
finished: false,
|
|
403
|
-
error: 'already-finished',
|
|
404
|
-
feature,
|
|
405
|
-
branch: expectedBranch,
|
|
406
|
-
base: target,
|
|
407
|
-
archived: archivePath.replace(/\\/g, '/'),
|
|
408
|
-
hint: say(`${who()} já foi entregue: está arquivada e já entrou em ${target}. Nada a fazer.`),
|
|
409
|
-
});
|
|
410
|
-
process.exit(1);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// "Already integrated" is per mode: a completed `--pr` leaves its branch unmerged on purpose, so
|
|
414
|
-
// the ancestor test alone would wave a second `gh pr create` through.
|
|
415
|
-
if (mode === 'pr') {
|
|
416
|
-
const openPr = openPrFor(expectedBranch, root);
|
|
417
|
-
if (openPr === null) {
|
|
418
|
-
emit({
|
|
419
|
-
finished: false,
|
|
420
|
-
error: 'resume-undecidable',
|
|
421
|
-
feature,
|
|
422
|
-
branch: expectedBranch,
|
|
423
|
-
archived: archivePath.replace(/\\/g, '/'),
|
|
424
|
-
hint: say(`${who()} já foi arquivada, mas não consegui consultar o GitHub para saber se o PR já existe. Parei para não abrir um PR repetido.`, `\`gh pr list --head ${expectedBranch}\``),
|
|
425
|
-
});
|
|
426
|
-
process.exit(1);
|
|
427
|
-
}
|
|
428
|
-
// A run killed while waiting left the PR open and the proof unread: this run picks the wait up.
|
|
429
|
-
if (openPr && !readFeatureJson(featureCwd, feature, 'archive')?.verification?.pendingPr) {
|
|
430
|
-
emit({
|
|
431
|
-
finished: false,
|
|
432
|
-
error: 'already-finished',
|
|
433
|
-
feature,
|
|
434
|
-
branch: expectedBranch,
|
|
435
|
-
base: target,
|
|
436
|
-
archived: archivePath.replace(/\\/g, '/'),
|
|
437
|
-
...(typeof openPr === 'string' ? { pr: { number: prNumberFromUrl(openPr), url: openPr } } : {}),
|
|
438
|
-
hint: say(`${who()} já está com o PR aberto. Próximo: aprovar e juntar o PR no GitHub.`),
|
|
439
|
-
});
|
|
440
|
-
process.exit(1);
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
resumed = true;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
// Not re-checked on a resume: the archive IS the gate's receipt (runArchive refuses without
|
|
448
|
-
// the review gate), and an archive with no readable feature.json would only fail here wrongly.
|
|
449
|
-
const fj = readFeatureJson(featureCwd, feature, resumed ? 'archive' : 'features');
|
|
450
|
-
const sources = prSourcesFor(join(featureCwd, '.morph', resumed ? 'archive' : 'features', feature));
|
|
451
|
-
if (!resumed && !options.force && !(fj?.approvalGates?.review?.approved === true || fj?.approvals?.review?.approved === true)) {
|
|
452
|
-
emit({ finished: false, error: 'review-not-approved', feature, hint: say(`A ${GATE_NAME.review.toLowerCase()} ainda não aprovou ${who()}. Nada foi mexido.`, `\`morph-spec gate-check ${feature} review\`; o finish só roda depois da aprovação`) });
|
|
453
|
-
process.exit(1);
|
|
454
|
-
}
|
|
455
|
-
const pendingPr = fj?.verification?.pendingPr ?? null;
|
|
456
|
-
if (mode === 'merge' && pendingPr && !options.force) {
|
|
457
|
-
emit({
|
|
458
|
-
finished: false,
|
|
459
|
-
error: 'pr-proof-pending',
|
|
460
|
-
feature,
|
|
461
|
-
hint: say(
|
|
462
|
-
`Parte da prova de ${who()} (os testes de ${pendingPr.covers.join(', ')}) só sai nos testes do PR no GitHub, e juntar direto não abre PR. Nada foi mexido.`,
|
|
463
|
-
`\`morph-spec verify ${feature}\` (sem --ci), \`gate-check ${feature} review\` e o finish de novo`,
|
|
464
|
-
),
|
|
465
|
-
});
|
|
466
|
-
process.exit(1);
|
|
467
|
-
}
|
|
468
|
-
const prTitle = buildPrTitle(feature, fj, sources?.summary);
|
|
469
|
-
const prBody = prBodyFor(feature, fj, { sources });
|
|
470
|
-
|
|
471
|
-
// Clean, so the scoped archive commit contains only the move.
|
|
472
|
-
const cleanCwd = isWorktreeFlow ? worktreePath : root;
|
|
473
|
-
const dirty = gitStatusPorcelain(cleanCwd);
|
|
474
|
-
if (dirty === null) {
|
|
475
|
-
emit({ finished: false, error: 'status-failed', feature });
|
|
476
|
-
process.exit(1);
|
|
477
|
-
}
|
|
478
|
-
const dirtLines = withoutLeftoverIgnore(cleanCwd, dirty.split(/\r?\n/).filter((l) => l.trim()));
|
|
479
|
-
const testArtifacts = untrackedTestArtifacts(dirtLines);
|
|
480
|
-
const commitState = dirtLines.length > testArtifacts.length && onlyFeatureStateDirty(cleanCwd, feature);
|
|
481
|
-
if (dirtLines.length > testArtifacts.length && !commitState) {
|
|
482
|
-
emit({ finished: false, error: isWorktreeFlow ? 'worktree-dirty' : 'working-dir-dirty', hint: say(`Há mudanças de ${who()} ainda não salvas no git. Nada foi mexido.`, 'commite o trabalho na branch e rode o finish de novo'), feature });
|
|
483
|
-
process.exit(1);
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
// Never assume "master".
|
|
487
|
-
const defaultBranch = detectDefaultBranch(root);
|
|
488
|
-
if (!defaultBranch) {
|
|
489
|
-
emit({ finished: false, error: 'no-default-branch', hint: say(`Não achei a branch principal do projeto (origin/HEAD, main ou master). Nada foi mexido.`, 'configure a branch principal do remoto e rode o finish de novo'), feature });
|
|
490
|
-
process.exit(1);
|
|
491
|
-
}
|
|
492
|
-
if (defaultBranch === expectedBranch) {
|
|
493
|
-
emit({ finished: false, error: 'feature-is-default', hint: say(`A branch de ${who()} (${expectedBranch}) é a própria branch principal: não há o que juntar.`), feature });
|
|
494
|
-
process.exit(1);
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
// BEFORE the archive: a dirty root refused after it left a half-finished feature. The own scope
|
|
498
|
-
// is exempt (the shed discards it next), and `--pr` never checks out or merges in the root.
|
|
499
|
-
if (mode === 'merge' && isWorktreeFlow) {
|
|
500
|
-
const rootPre = primaryRootUnexplainedDirt(root, feature, { exemptOwnScope: true });
|
|
501
|
-
if (!rootPre.ok) {
|
|
502
|
-
emit({ finished: false, error: 'primary-root-status-failed', feature });
|
|
503
|
-
process.exit(1);
|
|
504
|
-
}
|
|
505
|
-
if (rootPre.dirt.length) {
|
|
506
|
-
emit({
|
|
507
|
-
finished: false,
|
|
508
|
-
error: 'primary-root-dirty',
|
|
509
|
-
hint: say('A pasta principal do projeto tem mudanças não salvas no git, e é nela que a entrega seria juntada. Nada foi mexido.', 'commite ou faça stash na raiz e rode o finish de novo'),
|
|
510
|
-
feature,
|
|
511
|
-
});
|
|
512
|
-
process.exit(1);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
// BEFORE the archive, so a refused --pr has no side effect.
|
|
517
|
-
if (mode === 'pr') {
|
|
518
|
-
if (!hasOriginRemote(root)) {
|
|
519
|
-
emit({ finished: false, error: 'no-origin-remote', hint: say('O projeto não tem um remoto `origin` no GitHub, então não há onde abrir o PR. Nada foi mexido.', `configure o remoto, ou junte direto com \`morph-spec finish ${feature} --merge\``), feature });
|
|
520
|
-
process.exit(1);
|
|
521
|
-
}
|
|
522
|
-
if (!ghAuthOk()) {
|
|
523
|
-
emit({ finished: false, error: 'gh-unavailable', hint: say('O programa do GitHub (`gh`) não está instalado ou não está logado, então não consigo abrir o PR. Nada foi mexido.', `\`gh auth login\`, ou junte direto com \`morph-spec finish ${feature} --merge\``), feature });
|
|
524
|
-
process.exit(1);
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
// Every refusal is behind us: the leftover of a killed `graph refresh` goes now, never before.
|
|
529
|
-
dropLeftoverIgnore(cleanCwd);
|
|
530
|
-
if (commitState && !commitFeatureState(cleanCwd, feature)) {
|
|
531
|
-
emit({ finished: false, error: 'state-commit-failed', hint: say(`Não consegui salvar no git o estado de ${who()} (falta nome e e-mail no git?). Nada foi entregue.`, `commite .morph/features/${feature} na branch e rode o finish de novo`), feature });
|
|
532
|
-
process.exit(1);
|
|
533
|
-
}
|
|
534
|
-
if (isWorktreeFlow) {
|
|
535
|
-
for (const p of testArtifacts) rmSync(join(cleanCwd, p), { recursive: true, force: true });
|
|
536
|
-
}
|
|
537
|
-
if (mode === 'pr') {
|
|
538
|
-
const joined = joinDefault(cleanCwd, defaultBranch);
|
|
539
|
-
if (joined.error) {
|
|
540
|
-
emit({
|
|
541
|
-
finished: false,
|
|
542
|
-
error: joined.error,
|
|
543
|
-
feature,
|
|
544
|
-
...(joined.conflicts?.length ? { conflicts: joined.conflicts } : {}),
|
|
545
|
-
...(joined.output ? { output: joined.output } : {}),
|
|
546
|
-
hint: joined.error === 'default-conflict'
|
|
547
|
-
? say(`A branch principal mudou nos mesmos arquivos que ${who()} (${joined.conflicts.join(', ') || 'ver output'}). Desfiz a tentativa; nada foi arquivado nem enviado.`, `\`git merge origin/${defaultBranch}\` em ${cleanCwd}, resolva, commite e rode o finish de novo`)
|
|
548
|
-
: say(`Não consegui baixar a branch principal (origin/${defaultBranch}) do GitHub. Nada foi arquivado nem enviado.`, 'confira a rede e o remoto e rode o finish de novo'),
|
|
549
|
-
});
|
|
550
|
-
process.exit(1);
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
const arch = runArchive(feature, { cwd: featureCwd, force: options.force, git: true });
|
|
554
|
-
if (!arch.ok) {
|
|
555
|
-
emit({ finished: false, error: `archive-${arch.error}`, feature, hint: say(`Não consegui arquivar ${who()} (${arch.error}). Nada foi entregue.`, `\`morph-spec archive ${feature}\` mostra o motivo`) });
|
|
556
|
-
process.exit(1);
|
|
557
|
-
}
|
|
558
|
-
// A move that could not be committed (e.g. missing git identity) would leave
|
|
559
|
-
// the tree dirty and break the checkout/merge below — refuse, recoverable.
|
|
560
|
-
if (arch.archived && !arch.committed) {
|
|
561
|
-
emit({ finished: false, error: 'archive-not-committed', hint: say(`Arquivei ${who()}, mas não consegui salvar isso no git (falta nome e e-mail no git?). Nada foi entregue.`, 'configure a identidade do git, commite o archive e rode o finish de novo'), feature });
|
|
562
|
-
process.exit(1);
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
if (mode === 'merge') {
|
|
566
|
-
return integrateMerge({ emit, root, feature, expectedBranch, defaultBranch, isWorktreeFlow, worktreePath, options, arch, backupStamp });
|
|
567
|
-
}
|
|
568
|
-
return integratePr({ emit, root, feature, expectedBranch, defaultBranch, isWorktreeFlow, worktreePath, options, prTitle, prBody, arch, backupStamp, pendingPr, featureTree: cleanCwd });
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
// A junction/symlink in the worktree points at content in the ROOT, and `rm -rf` or
|
|
572
|
-
// `git worktree remove --force` traverse it.
|
|
573
|
-
export const REPARSE_WARNING =
|
|
574
|
-
'estes são junctions/symlinks: apagá-los fora do morph-spec apaga o conteúdo REAL na raiz';
|
|
575
|
-
|
|
576
|
-
// NÃO MUTA NADA: nenhum commit, archive, remoção, `gh` que crie algo nem `git fetch` (efeito de
|
|
577
|
-
// rede). Usa as MESMAS funções do comando real, senão o pré-voo promete o que o comando não
|
|
578
|
-
// cumpre. `cwd` dentro do worktree é AVISO, não recusa. Nunca lança.
|
|
579
|
-
export function finishPreflight({ feature, root, worktreePath, cwd, mode, branch, options = {} }) {
|
|
580
|
-
const warnings = [];
|
|
581
|
-
|
|
582
|
-
const defaultBranch = detectDefaultBranch(root);
|
|
583
|
-
const baseRef = defaultBranch ? resolveBaseRef(defaultBranch, root) : null;
|
|
584
|
-
// `commitsAhead` conta `base..branch`: invertidos, contam o que a default tem e a feature não.
|
|
585
|
-
const commits = baseRef && branchExists(branch, root)
|
|
586
|
-
? commitsAhead(branch, baseRef, root)
|
|
587
|
-
: null;
|
|
588
|
-
|
|
589
|
-
const out = {
|
|
590
|
-
preflight: true,
|
|
591
|
-
finished: false,
|
|
592
|
-
feature,
|
|
593
|
-
mode,
|
|
594
|
-
branch,
|
|
595
|
-
baseAdvanced: { ref: baseRef, commits },
|
|
596
|
-
// `null` é DESCONHECIDO, nunca 0: "não deu para perguntar" e "não andou" são fatos opostos.
|
|
597
|
-
baseAdvancedNote: commits === null
|
|
598
|
-
? (baseRef === null
|
|
599
|
-
? 'sem contraparte remota nem branch default resolvível — a contagem é DESCONHECIDA, não zero'
|
|
600
|
-
: 'não foi possível comparar as refs — a contagem é DESCONHECIDA, não zero')
|
|
601
|
-
: `o dado é do último \`git fetch\`; rode \`git fetch ${PUSH_REMOTE}\` para atualizá-lo (o pré-voo não faz fetch: ele promete não mexer em nada)`,
|
|
602
|
-
warnings,
|
|
603
|
-
wouldDo: mode === 'merge'
|
|
604
|
-
? [
|
|
605
|
-
`arquivar .morph/features/${feature} em .morph/archive/${feature} (commit na branch ${branch})`,
|
|
606
|
-
`fazer merge --no-ff de ${branch} em ${defaultBranch || '<default não resolvida>'} LOCALMENTE (sem push)`,
|
|
607
|
-
...(worktreePath ? [`derrubar o stack e remover o worktree ${worktreePath.replace(/\\/g, '/')}${options.discardIgnored === true ? ' — SEM copiar os gitignored exclusivos para o backup (--discard-ignored)' : ''}`] : []),
|
|
608
|
-
]
|
|
609
|
-
: [
|
|
610
|
-
`arquivar .morph/features/${feature} em .morph/archive/${feature} (commit na branch ${branch})`,
|
|
611
|
-
`publicar ${branch} em ${PUSH_REMOTE} e abrir um PR contra ${defaultBranch || '<default não resolvida>'} (NÃO integra: o merge do PR é que encerra)`,
|
|
612
|
-
...(worktreePath ? [`derrubar o stack e remover o worktree ${worktreePath.replace(/\\/g, '/')}${options.discardIgnored === true ? ' — SEM copiar os gitignored exclusivos para o backup (--discard-ignored)' : ''}`] : []),
|
|
613
|
-
],
|
|
614
|
-
};
|
|
615
|
-
|
|
616
|
-
if (defaultBranch) out.defaultBranch = defaultBranch;
|
|
617
|
-
|
|
618
|
-
try {
|
|
619
|
-
const tree = worktreePath || root;
|
|
620
|
-
const dirt = gitStatusPorcelain(tree);
|
|
621
|
-
const work = dirt === null ? [] : withoutLeftoverIgnore(tree, dirt.split(/\r?\n/).filter((l) => l.trim()));
|
|
622
|
-
if (work.length > untrackedTestArtifacts(work).length && onlyFeatureStateDirty(tree, feature)) {
|
|
623
|
-
out.wouldDo.unshift(`commitar o estado sujo de .morph/features/${feature} (${stateCommitMessage(feature)}) na branch ${branch}`);
|
|
624
|
-
}
|
|
625
|
-
} catch { /* o pré-voo nunca lança */ }
|
|
626
|
-
|
|
627
|
-
// A retenção automática também é mutação do finish real; a contagem é a de AGORA, antes do
|
|
628
|
-
// backup que este finish gravar.
|
|
629
|
-
try {
|
|
630
|
-
const retention = inspectFinishBackups(root);
|
|
631
|
-
if (retention.policy.skipped) {
|
|
632
|
-
out.backupRetention = { skipped: retention.policy.skipped };
|
|
633
|
-
warnings.push(`a retenção dos backups do finish será PULADA: ${retention.policy.skipped}`);
|
|
634
|
-
} else if (retention.outsideRetention || retention.overdueSecrets.length || retention.legacy) {
|
|
635
|
-
out.backupRetention = {
|
|
636
|
-
outsideRetention: retention.outsideRetention,
|
|
637
|
-
overdueSecrets: retention.overdueSecrets.length,
|
|
638
|
-
...(retention.legacy ? { legacyPending: retention.legacy } : {}),
|
|
639
|
-
};
|
|
640
|
-
if (retention.outsideRetention || retention.overdueSecrets.length) {
|
|
641
|
-
out.wouldDo.push(
|
|
642
|
-
`aplicar a retenção de .git/morph-spec/finish-backup: apagar ${retention.outsideRetention} backup(s) fora da política`
|
|
643
|
-
+ ` e ${retention.overdueSecrets.length} arquivo(s) .env* além de ${retention.policy.secretMaxAgeDays} dias`,
|
|
644
|
-
);
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
} catch { /* o pré-voo nunca lança */ }
|
|
648
|
-
|
|
649
|
-
if (worktreePath) {
|
|
650
|
-
out.worktreePath = worktreePath.replace(/\\/g, '/');
|
|
651
|
-
|
|
652
|
-
const inside = cwdIsInsideWorktree(cwd, worktreePath);
|
|
653
|
-
out.cwdInsideWorktree = inside;
|
|
654
|
-
if (!inside && sessionAnchoredInWorktree(worktreePath)) {
|
|
655
|
-
out.teardownDeferred = 'session-anchored';
|
|
656
|
-
warnings.push(
|
|
657
|
-
`a sessão do Claude Code está ancorada em ${out.worktreePath}: o finish vai integrar, mas ADIAR o desmonte `
|
|
658
|
-
+ '(desmontar agora quebraria os hooks desta sessão). Depois, feche a sessão e rode '
|
|
659
|
-
+ `\`morph-spec worktree remove ${feature}\` de uma sessão aberta na raiz`,
|
|
660
|
-
);
|
|
661
|
-
}
|
|
662
|
-
if (inside) {
|
|
663
|
-
warnings.push(
|
|
664
|
-
`você está DENTRO de ${out.worktreePath}: o finish de verdade recusa aqui, antes de qualquer mutação `
|
|
665
|
-
+ `(o Windows tranca o diretório de trabalho do processo e a remoção falharia no meio). `
|
|
666
|
-
+ `Rode o finish a partir de "${root.replace(/\\/g, '/')}"`,
|
|
667
|
-
);
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
// As MESMAS flags do comando real: `--discard-ignored` inverte a classificação, então prever com
|
|
671
|
-
// `options` vazio é prever outro comando.
|
|
672
|
-
const discardIgnored = options.discardIgnored === true;
|
|
673
|
-
const ignored = classifyIgnoredLeftovers(worktreePath, root, { discardIgnored });
|
|
674
|
-
out.discardIgnored = discardIgnored;
|
|
675
|
-
out.ignored = {
|
|
676
|
-
// Copiado para o backup; vazio por construção sob `--discard-ignored`.
|
|
677
|
-
shieldable: ignored.shieldable,
|
|
678
|
-
// Idêntico byte a byte ao da raiz (SHA-256): apagar não perde nada.
|
|
679
|
-
replicable: ignored.replicable,
|
|
680
|
-
// Descartado sem backup.
|
|
681
|
-
discardable: ignored.discarded,
|
|
682
|
-
};
|
|
683
|
-
if (ignored.blocking.length) {
|
|
684
|
-
out.ignored.blocking = ignored.blocking;
|
|
685
|
-
warnings.push('não foi possível enumerar os gitignored do worktree — o finish real vai recusar a remoção');
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
if (discardIgnored) {
|
|
689
|
-
// Sob a flag `shieldable` sai vazia: perguntar à MESMA função sem a flag nomeia o que existe só
|
|
690
|
-
// aqui, sem recriar a regra.
|
|
691
|
-
const semFlag = classifyIgnoredLeftovers(worktreePath, root);
|
|
692
|
-
out.ignored.discardableExclusive = semFlag.shieldable;
|
|
693
|
-
if (semFlag.shieldable.length) {
|
|
694
|
-
warnings.push(
|
|
695
|
-
`--discard-ignored: ${semFlag.shieldable.length} caminho(s) gitignored existem SÓ neste worktree e serão `
|
|
696
|
-
+ `DESTRUÍDOS sem cópia (${semFlag.shieldable.slice(0, 5).join(', ')}). Sem a flag eles iriam para `
|
|
697
|
-
+ '.git/morph-spec/finish-backup e a remoção aconteceria do mesmo jeito.',
|
|
698
|
-
);
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
const scan = findReparsePoints(worktreePath);
|
|
703
|
-
out.reparsePoints = scan.points;
|
|
704
|
-
if (scan.unprovable.length) out.reparseUnprovable = scan.unprovable;
|
|
705
|
-
out.reparseWarning = REPARSE_WARNING;
|
|
706
|
-
if (scan.points.length) {
|
|
707
|
-
warnings.push(
|
|
708
|
-
`${scan.points.length} reparse point(s) no worktree — ${REPARSE_WARNING}. `
|
|
709
|
-
+ 'O `morph-spec worktree remove` derruba os links ANTES de apagar; um `git worktree remove --force` cru, não.',
|
|
710
|
-
);
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
return out;
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
async function integrateMerge({ emit, root, feature, expectedBranch, defaultBranch, isWorktreeFlow, worktreePath, options, arch, backupStamp }) {
|
|
718
|
-
const name = labelOf([worktreePath, root], feature);
|
|
719
|
-
const who = () => name;
|
|
720
|
-
const mergeMsg = `chore(morph): merge ${expectedBranch}`;
|
|
721
|
-
const adrNote = adrIndexNote(arch);
|
|
722
|
-
|
|
723
|
-
if (isWorktreeFlow) {
|
|
724
|
-
// Shed this feature's root-side scaffold, then guard the whole root before the merge commit.
|
|
725
|
-
const { shedBackup } = shedRootFeatureScope(root, feature, { stamp: backupStamp });
|
|
726
|
-
const backupNote = shedBackup ? { shedBackup } : {};
|
|
727
|
-
|
|
728
|
-
// The pre-archive check already refused unrelated dirt, so a refusal here means the shed
|
|
729
|
-
// dirtied the root: a bug signal. Last moment before mutating the default branch.
|
|
730
|
-
const rootClean = primaryRootUnexplainedDirt(root, feature);
|
|
731
|
-
if (!rootClean.ok) {
|
|
732
|
-
emit({ finished: false, error: 'primary-root-status-failed', feature, ...backupNote });
|
|
733
|
-
process.exit(1);
|
|
734
|
-
}
|
|
735
|
-
if (rootClean.dirt.length) {
|
|
736
|
-
emit({ finished: false, error: 'primary-root-dirty', feature, ...backupNote });
|
|
737
|
-
process.exit(1);
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
try {
|
|
741
|
-
execFileSync('git', ['merge', '--no-ff', expectedBranch, '-m', mergeMsg], { cwd: root, stdio: 'pipe' });
|
|
742
|
-
} catch (err) {
|
|
743
|
-
tryGit(['merge', '--abort'], root);
|
|
744
|
-
emit({ finished: false, error: 'merge-conflict', output: gitErr(err), hint: say(`Juntar ${who()} na branch principal deu conflito. Desfiz a tentativa; a entrega continua na branch dela.`, 'resolva o conflito à mão ou rode os finish um de cada vez'), feature, ...backupNote });
|
|
745
|
-
process.exit(1);
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
// Uma medição só para as DUAS saídas deste merge (--keep e normal): é o
|
|
749
|
-
// mesmo merge, então a contagem e a publicação têm de ser as mesmas.
|
|
750
|
-
const publish = publicationState({ root, defaultBranch, push: options.push });
|
|
751
|
-
|
|
752
|
-
if (options.keep) {
|
|
753
|
-
dropFromRootIndex(root, feature);
|
|
754
|
-
emit({
|
|
755
|
-
...mergeOutput({ feature, branch: expectedBranch, defaultBranch, publish, worktreePath, shedBackup, kept: true }),
|
|
756
|
-
...adrNote,
|
|
757
|
-
});
|
|
758
|
-
process.exit(0);
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
// The stack comes down BEFORE the worktree, which holds its compose file, bind mount and ports.
|
|
762
|
-
const e2e = reclaimStack(feature, { root, worktreePath, options });
|
|
763
|
-
// A session ANCHORED in the worktree resolves its hooks through it: tearing it down now would
|
|
764
|
-
// kill every hook of that session, so only the teardown waits.
|
|
765
|
-
const deferred = sessionAnchoredInWorktree(worktreePath);
|
|
766
|
-
const teardown = deferred
|
|
767
|
-
? null
|
|
768
|
-
: await teardownWorktree(worktreePath, { root, feature, branch: expectedBranch, options, deleteBranch: true, stamp: backupStamp });
|
|
769
|
-
dropFromRootIndex(root, feature);
|
|
770
|
-
emit({ ...mergeOutput({ feature, branch: expectedBranch, defaultBranch, publish, worktreePath, teardown, shedBackup, deferred }), ...adrNote, e2e });
|
|
771
|
-
process.exit(0);
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
try {
|
|
775
|
-
execFileSync('git', ['checkout', defaultBranch], { cwd: root, stdio: 'pipe' });
|
|
776
|
-
} catch (err) {
|
|
777
|
-
emit({ finished: false, error: 'checkout-default-failed', output: gitErr(err), hint: say(`Não consegui trocar para a branch principal (${defaultBranch}) para juntar ${who()}. A entrega está arquivada na branch dela.`, `\`git checkout ${defaultBranch}\` mostra o motivo`), feature });
|
|
778
|
-
process.exit(1);
|
|
779
|
-
}
|
|
780
|
-
try {
|
|
781
|
-
execFileSync('git', ['merge', '--no-ff', expectedBranch, '-m', mergeMsg], { cwd: root, stdio: 'pipe' });
|
|
782
|
-
} catch (err) {
|
|
783
|
-
tryGit(['merge', '--abort'], root);
|
|
784
|
-
emit({
|
|
785
|
-
finished: false,
|
|
786
|
-
error: 'merge-conflict',
|
|
787
|
-
output: gitErr(err),
|
|
788
|
-
hint: say(`Juntar ${who()} em ${defaultBranch} deu conflito. Desfiz a tentativa; o trabalho está intacto na branch dela.`, `\`git checkout ${expectedBranch}\` para voltar a ele`),
|
|
789
|
-
feature,
|
|
790
|
-
});
|
|
791
|
-
process.exit(1);
|
|
792
|
-
}
|
|
793
|
-
tryGit(['branch', '-d', expectedBranch], root);
|
|
794
|
-
const publish = publicationState({ root, defaultBranch, push: options.push });
|
|
795
|
-
const e2e = reclaimStack(feature, { root, worktreePath: null, options });
|
|
796
|
-
emit({ ...mergeOutput({ feature, branch: expectedBranch, defaultBranch, publish }), ...adrNote, e2e });
|
|
797
|
-
process.exit(0);
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
// `null` for an unexpected format: better to admit not knowing the number than state a wrong one.
|
|
801
|
-
export function prNumberFromUrl(url) {
|
|
802
|
-
const m = typeof url === 'string' ? url.match(/\/pull\/(\d+)(?:[/?#]|$)/) : null;
|
|
803
|
-
return m ? Number(m[1]) : null;
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
// The checks of the archive commit are the proof: a second push of the same code would pay the CI twice,
|
|
807
|
-
// so a red or unjudged run undoes the archive here and the feature goes back to the session.
|
|
808
|
-
function reopenFeature({ tree, feature, check, ciRun, sha }) {
|
|
809
|
-
const archiveCommit = execFileSync('git', ['log', '-1', '--format=%H', '--fixed-strings', `--grep=chore(morph): archive ${feature}`], { cwd: tree, stdio: 'pipe' }).toString().trim();
|
|
810
|
-
execFileSync('git', ['revert', '--no-edit', archiveCommit], { cwd: tree, stdio: 'pipe' });
|
|
811
|
-
|
|
812
|
-
const path = join(tree, '.morph', 'features', feature, 'feature.json');
|
|
813
|
-
const fj = JSON.parse(readFileSync(path, 'utf8'));
|
|
814
|
-
const now = new Date().toISOString();
|
|
815
|
-
const reason = check.state === 'fail'
|
|
816
|
-
? `Os testes do PR no GitHub falharam (${check.failed.map((c) => c.workflowName).join(', ')}). A entrega voltou para correção.`
|
|
817
|
-
: `Os testes do PR no GitHub não deram resultado (${check.reason}). A entrega voltou para rodar os testes aqui.`;
|
|
818
|
-
fj.approvalGates = { ...fj.approvalGates, review: { approved: false, timestamp: now, approvedBy: null, revokedBy: 'finish', revokedAt: now, reason } };
|
|
819
|
-
if (check.state === 'fail') {
|
|
820
|
-
const { pendingPr: _, ...stamp } = fj.verification;
|
|
821
|
-
fj.verification = { ...stamp, status: 'fail', nodes: { ...stamp.nodes, tests: 'fail' }, sha, ts: now, source: 'pr', ciRun };
|
|
822
|
-
const entry = fj.verifications?.feature;
|
|
823
|
-
if (entry) fj.verifications.feature = { ...entry, status: 'fail', failStreak: (entry.failStreak ?? 0) + 1, updatedAt: now };
|
|
824
|
-
} else {
|
|
825
|
-
delete fj.verification;
|
|
826
|
-
}
|
|
827
|
-
atomicWriteJson(path, fj);
|
|
828
|
-
recordGateEvent(tree, { feature, gate: 'review', step: 'unapprove', approvedBy: null });
|
|
829
|
-
commitFeatureState(tree, feature);
|
|
830
|
-
return reason;
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
// The revert stays local (a push would pay another CI run), so the reopened PR still holds the archive:
|
|
834
|
-
// as a draft it cannot be merged by accident, on a plan without branch protection.
|
|
835
|
-
function setPrDraft(root, prUrl, draft) {
|
|
836
|
-
try {
|
|
837
|
-
const { bin, prefix } = resolveGh();
|
|
838
|
-
execFileSync(bin, [...prefix, 'pr', 'ready', prUrl, ...(draft ? ['--undo'] : [])], { cwd: root, stdio: 'pipe', timeout: 15000 });
|
|
839
|
-
} catch { /* gh refuses a PR already in that state */ }
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
async function integratePr({ emit, root, feature, expectedBranch, defaultBranch, isWorktreeFlow, worktreePath, options, prTitle, prBody, arch, backupStamp, pendingPr, featureTree }) {
|
|
843
|
-
const name = labelOf([featureTree, worktreePath, root], feature);
|
|
844
|
-
const who = () => name;
|
|
845
|
-
try {
|
|
846
|
-
execFileSync('git', ['push', '-u', 'origin', expectedBranch], { cwd: root, stdio: 'pipe' });
|
|
847
|
-
} catch (err) {
|
|
848
|
-
emit({ finished: false, error: 'push-failed', output: gitErr(err), hint: say(`Não consegui enviar ${who()} para o GitHub. O archive está salvo neste computador.`, 'resolva o push e rode o finish de novo'), feature });
|
|
849
|
-
process.exit(1);
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
// A feature reopened by a red PR comes back here with that PR still open.
|
|
853
|
-
const openPr = openPrFor(expectedBranch, root);
|
|
854
|
-
let prUrl = typeof openPr === 'string' ? openPr : null;
|
|
855
|
-
if (prUrl) setPrDraft(root, prUrl, false);
|
|
856
|
-
if (!prUrl) {
|
|
857
|
-
try {
|
|
858
|
-
const { bin, prefix } = resolveGh();
|
|
859
|
-
prUrl = execFileSync(bin, [...prefix, 'pr', 'create', '--base', defaultBranch, '--head', expectedBranch, '--title', prTitle, '--body', prBody], { cwd: root, stdio: 'pipe' }).toString().trim();
|
|
860
|
-
} catch (err) {
|
|
861
|
-
emit({ finished: false, error: 'pr-create-failed', output: gitErr(err), hint: say(`Enviei ${who()} para o GitHub, mas não consegui abrir o PR.`, 'abra o PR à mão com `gh pr create`'), feature, pushed: expectedBranch });
|
|
862
|
-
process.exit(1);
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
let checks = null;
|
|
867
|
-
if (pendingPr) {
|
|
868
|
-
const sha = execFileSync('git', ['rev-parse', expectedBranch], { cwd: root, stdio: 'pipe' }).toString().trim();
|
|
869
|
-
const check = await waitForPrChecks(root, { branch: expectedBranch, sha, workflows: pendingPr.workflows });
|
|
870
|
-
if (check.state === 'fail' || check.state === 'no-verdict') {
|
|
871
|
-
let reason;
|
|
872
|
-
try {
|
|
873
|
-
reason = reopenFeature({ tree: featureTree, feature, check, ciRun: check.failed?.[0]?.detailsUrl ?? prUrl, sha });
|
|
874
|
-
} catch (err) {
|
|
875
|
-
emit({ finished: false, error: 'reopen-failed', output: gitErr(err), hint: say(`Os testes do PR no GitHub não passaram, e não consegui reabrir ${who()}. Não junte ${prUrl}.`, `\`git revert\` do commit de archive em ${featureTree}`), feature });
|
|
876
|
-
process.exit(1);
|
|
877
|
-
}
|
|
878
|
-
const red = check.state === 'fail';
|
|
879
|
-
setPrDraft(root, prUrl, true);
|
|
880
|
-
emit({
|
|
881
|
-
finished: false,
|
|
882
|
-
error: red ? 'pr-checks-fail' : 'pr-checks-no-verdict',
|
|
883
|
-
feature,
|
|
884
|
-
pr: { number: prNumberFromUrl(prUrl), url: prUrl },
|
|
885
|
-
reason,
|
|
886
|
-
...(red ? { failed: check.failed.map((c) => ({ workflow: c.workflowName, url: c.detailsUrl })) } : {}),
|
|
887
|
-
hint: red
|
|
888
|
-
? say(`Os testes do PR no GitHub falharam. Desfiz a entrega de ${who()} e reabri a ${GATE_NAME.review.toLowerCase()}. Próximo: corrigir o que falhou; o mesmo PR será reaproveitado.`, 'corrija (`gh run view <id> --log-failed`), commite e siga review.md §5')
|
|
889
|
-
: say(`Os testes do PR no GitHub não deram resultado. Desfiz a entrega de ${who()} e reabri a ${GATE_NAME.review.toLowerCase()}. Próximo: rodar ${TESTS} aqui; o mesmo PR será reaproveitado.`, `\`morph-spec verify ${feature} --json --detach\` (sem --ci), \`gate-check ${feature} review\`, approve e o finish de novo`),
|
|
890
|
-
});
|
|
891
|
-
process.exit(1);
|
|
892
|
-
}
|
|
893
|
-
checks = check.state === 'pass' ? { status: 'pass' } : { status: 'pending', reason: check.reason };
|
|
894
|
-
}
|
|
895
|
-
|
|
896
|
-
// The worktree flow keeps the branch (the open PR needs it); the common flow stays on morph/{f},
|
|
897
|
-
// since the default has no feature until the PR merges.
|
|
898
|
-
let teardown = null;
|
|
899
|
-
let shedBackup = null;
|
|
900
|
-
// Skipped on --keep, where the worktree and its stack stay alive on purpose.
|
|
901
|
-
const e2e = isWorktreeFlow
|
|
902
|
-
? (options.keep ? null : reclaimStack(feature, { root, worktreePath, options }))
|
|
903
|
-
: reclaimStack(feature, { root, worktreePath: null, options });
|
|
904
|
-
let teardownDeferred = false;
|
|
905
|
-
if (isWorktreeFlow && !options.keep) {
|
|
906
|
-
// Shed BEFORE teardown: otherwise clearRootWorktreeRegistration commits the untracked root
|
|
907
|
-
// scaffold to the default, and the merged PR leaves the feature in both features/ and archive/.
|
|
908
|
-
shedBackup = shedRootFeatureScope(root, feature, { stamp: backupStamp }).shedBackup;
|
|
909
|
-
// Same deferral as --merge (sessionAnchoredInWorktree).
|
|
910
|
-
if (sessionAnchoredInWorktree(worktreePath)) {
|
|
911
|
-
teardownDeferred = true;
|
|
912
|
-
} else {
|
|
913
|
-
teardown = await teardownWorktree(worktreePath, { root, feature, branch: expectedBranch, options, deleteBranch: false, stamp: backupStamp });
|
|
914
|
-
}
|
|
915
|
-
// runArchive dropped the feature only from the WORKTREE index: drop it from the root's too, or
|
|
916
|
-
// `doctor` flags a `stale-index` phantom.
|
|
917
|
-
dropFromRootIndex(root, feature);
|
|
918
|
-
}
|
|
919
|
-
|
|
920
|
-
const prNumber = prNumberFromUrl(prUrl);
|
|
921
|
-
const prLabel = prNumber ? `#${prNumber}` : 'o PR';
|
|
922
|
-
|
|
923
|
-
const out = {
|
|
924
|
-
finished: true,
|
|
925
|
-
// O comando terminou, a INTEGRAÇÃO não: a default só recebe archive/{f} quando o PR mergear.
|
|
926
|
-
integrated: false,
|
|
927
|
-
awaiting: 'merge',
|
|
928
|
-
mode: 'pr',
|
|
929
|
-
feature,
|
|
930
|
-
pushed: expectedBranch,
|
|
931
|
-
base: defaultBranch,
|
|
932
|
-
pr: { number: prNumber, url: prUrl },
|
|
933
|
-
...(checks ? { checks } : {}),
|
|
934
|
-
nextStep: checks?.status === 'pending'
|
|
935
|
-
? say(`PR ${prLabel} aberto para ${who()}. Os testes do PR no GitHub ainda não responderam. Próximo: esperar o resultado antes de juntar.`, `\`gh pr checks ${prNumber ?? expectedBranch}\``)
|
|
936
|
-
: say(`PR ${prLabel} aberto para ${who()}. Próximo: aprovar e juntar o PR no GitHub; a entrega só termina quando ${defaultBranch} receber o PR.`),
|
|
937
|
-
...adrIndexNote(arch),
|
|
938
|
-
...(shedBackup ? { shedBackup } : {}),
|
|
939
|
-
...(e2e ? { e2e } : {}),
|
|
940
|
-
...(teardown
|
|
941
|
-
? { worktreeRemoved: teardown.worktreeRemoved, ...teardownExtras(teardown, worktreePath, expectedBranch, false) }
|
|
942
|
-
: {
|
|
943
|
-
worktreeRemoved: false,
|
|
944
|
-
// Only --keep leaves `teardown` null with a worktree still alive.
|
|
945
|
-
...(isWorktreeFlow && options.keep
|
|
946
|
-
? {
|
|
947
|
-
worktree: { path: worktreePath, branch: expectedBranch },
|
|
948
|
-
hint: say(`A pasta de trabalho ficou guardada em ${worktreePath}, como pedido.`, `\`morph-spec worktree remove ${feature}\` quando não precisar mais dela`),
|
|
949
|
-
}
|
|
950
|
-
: teardownDeferred
|
|
951
|
-
? {
|
|
952
|
-
teardownDeferred: 'session-anchored',
|
|
953
|
-
worktree: { path: worktreePath, branch: expectedBranch },
|
|
954
|
-
hint: deferredTeardownHint(feature, worktreePath),
|
|
955
|
-
}
|
|
956
|
-
: {}),
|
|
957
|
-
}),
|
|
958
|
-
};
|
|
959
|
-
emit(out);
|
|
960
|
-
process.exit(0);
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
function adrIndexNote(arch) {
|
|
964
|
-
return {
|
|
965
|
-
...(arch?.adrIndex ? { adrIndex: arch.adrIndex } : {}),
|
|
966
|
-
...(arch?.revocationProblems?.length ? { revocationProblems: arch.revocationProblems } : {}),
|
|
967
|
-
};
|
|
968
|
-
}
|
|
969
|
-
|
|
970
|
-
// Um nome só, para que o comando que a saída IMPRIME e o push que o `--push` EXECUTA jamais
|
|
971
|
-
// nomeiem remotos diferentes.
|
|
972
|
-
const PUSH_REMOTE = 'origin';
|
|
973
|
-
|
|
974
|
-
// `resolveBaseRef` degrada para a branch LOCAL sem ref remoto: comparada consigo mesma daria um
|
|
975
|
-
// `0` falso, então `ahead` fica `null`. Fail-open: o merge JÁ aconteceu, e um push que falha
|
|
976
|
-
// vira `pushError`, nunca exit 1.
|
|
977
|
-
function publicationState({ root, defaultBranch, push }) {
|
|
978
|
-
const baseRef = resolveBaseRef(defaultBranch, root);
|
|
979
|
-
const tracked = !!baseRef && baseRef !== defaultBranch;
|
|
980
|
-
const ahead = tracked ? commitsAhead(baseRef, defaultBranch, root) : null;
|
|
981
|
-
const state = { remote: PUSH_REMOTE, branch: defaultBranch, ahead, pushed: false };
|
|
982
|
-
|
|
983
|
-
if (!push) return state;
|
|
984
|
-
|
|
985
|
-
if (!hasOriginRemote(root)) {
|
|
986
|
-
return { ...state, pushError: 'no-origin-remote' };
|
|
987
|
-
}
|
|
988
|
-
try {
|
|
989
|
-
execFileSync('git', ['push', PUSH_REMOTE, defaultBranch], { cwd: root, stdio: 'pipe' });
|
|
990
|
-
} catch (err) {
|
|
991
|
-
return { ...state, pushError: gitErr(err) };
|
|
992
|
-
}
|
|
993
|
-
// Re-medir DEPOIS do push: o que ficou para trás é a única prova de que a
|
|
994
|
-
// publicação foi completa, e um `ahead` congelado do antes seria mentira.
|
|
995
|
-
const after = resolveBaseRef(defaultBranch, root);
|
|
996
|
-
const remaining = after && after !== defaultBranch ? commitsAhead(after, defaultBranch, root) : null;
|
|
997
|
-
return { ...state, published: ahead, ahead: remaining, pushed: true };
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
// PRODUTOR ÚNICO: no `--merge` o merge é local e o remoto continua sem a feature; cada saída
|
|
1001
|
-
// que montava o aviso por conta própria podia esquecê-lo.
|
|
1002
|
-
function mergeNextStep(publish) {
|
|
1003
|
-
const { remote, branch, ahead, pushed, published, pushError } = publish;
|
|
1004
|
-
const pushCmd = `\`git push ${remote} ${branch}\``;
|
|
1005
|
-
|
|
1006
|
-
if (pushed) {
|
|
1007
|
-
const n = typeof published === 'number' ? `${published} commit(s)` : 'a entrega';
|
|
1008
|
-
return `Entregue e publicado: ${n} de ${branch} enviado(s) para ${remote}/${branch}.`;
|
|
1009
|
-
}
|
|
1010
|
-
const local = `Entregue em ${branch}, só neste computador.`;
|
|
1011
|
-
if (pushError === 'no-origin-remote') {
|
|
1012
|
-
return `${local} Nada foi publicado: não há remoto \`${remote}\` configurado.`;
|
|
1013
|
-
}
|
|
1014
|
-
if (pushError) {
|
|
1015
|
-
return say(`${local} O envio para o GitHub falhou; nada foi publicado.`, pushCmd);
|
|
1016
|
-
}
|
|
1017
|
-
// Sem contraparte remota não se inventa contagem: fica a frase estática.
|
|
1018
|
-
if (ahead === null) {
|
|
1019
|
-
return say(`${local} Nada foi publicado ainda.`, '`git push`');
|
|
1020
|
-
}
|
|
1021
|
-
return say(`${local} Nada foi publicado: ${branch} tem ${ahead} commit(s) que ${remote}/${branch} ainda não tem.`, `${pushCmd} (ou o finish de novo com --push)`);
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
// CONSTRUTOR ÚNICO das três saídas de sucesso do `--merge`. `teardown === null` cobre o `--keep`
|
|
1025
|
-
// e o fluxo comum.
|
|
1026
|
-
function mergeOutput({ feature, branch, defaultBranch, publish, worktreePath = null, teardown = null, shedBackup = null, kept = false, deferred = false }) {
|
|
1027
|
-
return {
|
|
1028
|
-
finished: true,
|
|
1029
|
-
integrated: true,
|
|
1030
|
-
mode: 'merge',
|
|
1031
|
-
feature,
|
|
1032
|
-
merged: branch,
|
|
1033
|
-
into: defaultBranch,
|
|
1034
|
-
...(kept ? { kept: true } : {}),
|
|
1035
|
-
...(deferred ? { teardownDeferred: 'session-anchored', worktree: { path: worktreePath, branch }, hint: deferredTeardownHint(feature, worktreePath, { deleteBranch: true }) } : {}),
|
|
1036
|
-
worktreeRemoved: teardown ? teardown.worktreeRemoved : false,
|
|
1037
|
-
nextStep: mergeNextStep(publish),
|
|
1038
|
-
publish,
|
|
1039
|
-
...(shedBackup ? { shedBackup } : {}),
|
|
1040
|
-
...(kept
|
|
1041
|
-
? {
|
|
1042
|
-
// The root registration stays VALID (it names a live directory): nothing to clean up.
|
|
1043
|
-
worktree: { path: worktreePath, branch },
|
|
1044
|
-
hint: say(`A pasta de trabalho ficou guardada em ${worktreePath}, como pedido.`, `\`morph-spec worktree remove ${feature}\` quando não precisar mais dela`),
|
|
1045
|
-
}
|
|
1046
|
-
: {}),
|
|
1047
|
-
...(teardown ? teardownExtras(teardown, worktreePath, branch, true) : {}),
|
|
1048
|
-
};
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
// Names the safe command, never `git worktree remove`. `--pr` keeps the branch: the PR needs it.
|
|
1052
|
-
function deferredTeardownHint(feature, worktreePath, { deleteBranch = false } = {}) {
|
|
1053
|
-
return `worktree mantido em ${worktreePath}: a sessão do Claude Code que rodou o finish está ancorada nele, `
|
|
1054
|
-
+ 'e desmontá-lo agora quebraria todos os hooks dela (eles resolvem `.morph/framework` por ele) — '
|
|
1055
|
-
+ `o diretório, aliás, seguiria travado pela sessão. Feche esta sessão e rode \`morph-spec worktree remove ${feature}${deleteBranch ? ' --delete-branch' : ''}\` `
|
|
1056
|
-
+ 'de uma sessão aberta na raiz do repo.';
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
function teardownExtras(teardown, worktreePath, branch, deleteBranch) {
|
|
1060
|
-
const out = {};
|
|
1061
|
-
if (teardown.ignoredBackup) out.worktreeIgnoredBackup = teardown.ignoredBackup;
|
|
1062
|
-
if (teardown.worktreeRemoved && teardown.discarded.length) out.discardedIgnored = teardown.discarded;
|
|
1063
|
-
// After a removal these two lists answer "did I just lose something?".
|
|
1064
|
-
if (teardown.shieldable?.length) out.worktreeIgnoredBackedUp = teardown.shieldable;
|
|
1065
|
-
if (teardown.replicable?.length) out.replicatedInRoot = teardown.replicable;
|
|
1066
|
-
// Proof the primary root's real `.claude/` was unlinked, never followed.
|
|
1067
|
-
if (teardown.unlinked?.length) out.unlinked = teardown.unlinked;
|
|
1068
|
-
if (!teardown.worktreeRemoved) {
|
|
1069
|
-
out.path = worktreePath;
|
|
1070
|
-
out.branch = branch;
|
|
1071
|
-
if (teardown.blockers.length) out.reparsePoints = teardown.blockers;
|
|
1072
|
-
if (teardown.ignoredBlocking.length) out.ignoredFiles = teardown.ignoredBlocking;
|
|
1073
|
-
out.cleanupHint = teardown.declineReason;
|
|
1074
|
-
// REFUSED re-links (the user keeps working here); FAILED leaves the infra down ON PURPOSE so a
|
|
1075
|
-
// retry has nothing to traverse. Say which, or a bare "failed" invites the destructive command.
|
|
1076
|
-
out.relinked = teardown.relinked === true;
|
|
1077
|
-
if (!teardown.refused) {
|
|
1078
|
-
if (teardown.infraLeftUnlinked?.length) out.infraLeftUnlinked = teardown.infraLeftUnlinked;
|
|
1079
|
-
out.relinkHint = `a remoção falhou e as junctions de infra foram deixadas DESMONTADAS de propósito — qualquer nova tentativa é segura. Para voltar a trabalhar no worktree, rode \`morph-spec worktree link --all --target "${worktreePath}"\``;
|
|
1080
|
-
} else {
|
|
1081
|
-
out.relinkHint = teardown.relinked
|
|
1082
|
-
? 'as junctions de infra foram soltas antes da tentativa e RESTAURADAS após a recusa — o worktree segue utilizável'
|
|
1083
|
-
: `as junctions de infra foram soltas antes desta recusa e não puderam ser restauradas — para continuar no worktree, rode \`morph-spec worktree link --all --target "${worktreePath}"\``;
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
return out;
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
function currentBranch(cwd) {
|
|
1090
|
-
try {
|
|
1091
|
-
return execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, stdio: 'pipe' }).toString().trim();
|
|
1092
|
-
} catch {
|
|
1093
|
-
return null;
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
/** Untracked Playwright/test output (`?? test-results/`): never work, so it neither blocks nor survives the teardown. */
|
|
1098
|
-
function untrackedTestArtifacts(lines) {
|
|
1099
|
-
return lines
|
|
1100
|
-
.filter((l) => l.startsWith('?? '))
|
|
1101
|
-
.map((l) => l.slice(3).replace(/^"|"$/g, '').replace(/\/$/, ''))
|
|
1102
|
-
.filter((p) => isTestArtifact(p));
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
|
-
const stateCommitMessage = (feature) => `chore(morph): estado da feature ${feature}`;
|
|
1106
|
-
|
|
1107
|
-
// `--untracked-files=all`: o porcelain padrão colapsa `?? .morph/` e esconderia sujeira fora do escopo.
|
|
1108
|
-
function onlyFeatureStateDirty(cwd, feature) {
|
|
1109
|
-
let out;
|
|
1110
|
-
try {
|
|
1111
|
-
out = execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd, stdio: 'pipe' }).toString();
|
|
1112
|
-
} catch {
|
|
1113
|
-
return false;
|
|
1114
|
-
}
|
|
1115
|
-
const scope = `.morph/features/${feature}/`;
|
|
1116
|
-
const paths = out.split(/\r?\n/).filter((l) => l.trim())
|
|
1117
|
-
.flatMap((l) => l.slice(3).split(' -> '))
|
|
1118
|
-
.map((p) => p.replace(/^"|"$/g, ''));
|
|
1119
|
-
return paths.length > 0 && paths.every((p) => p.startsWith(scope));
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
function commitFeatureState(cwd, feature) {
|
|
1123
|
-
const scope = `.morph/features/${feature}`;
|
|
1124
|
-
try {
|
|
1125
|
-
execFileSync('git', ['add', '-A', '--', scope], { cwd, stdio: 'pipe' });
|
|
1126
|
-
execFileSync('git', ['commit', '-q', '-m', stateCommitMessage(feature), '--', scope], { cwd, stdio: 'pipe' });
|
|
1127
|
-
return true;
|
|
1128
|
-
} catch {
|
|
1129
|
-
return false;
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
function gitStatusPorcelain(cwd) {
|
|
1134
|
-
try {
|
|
1135
|
-
return execFileSync('git', ['status', '--porcelain'], { cwd, stdio: 'pipe' }).toString();
|
|
1136
|
-
} catch {
|
|
1137
|
-
return null;
|
|
1138
|
-
}
|
|
1139
|
-
}
|
|
1140
|
-
|
|
1141
|
-
function ghAuthOk() {
|
|
1142
|
-
const { bin, prefix } = resolveGh();
|
|
1143
|
-
try {
|
|
1144
|
-
execFileSync(bin, [...prefix, 'auth', 'status'], { stdio: 'pipe' });
|
|
1145
|
-
return true;
|
|
1146
|
-
} catch {
|
|
1147
|
-
return false;
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
function tryGit(args, cwd) {
|
|
1152
|
-
try { execFileSync('git', args, { cwd, stdio: 'pipe' }); } catch { /* best-effort */ }
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
function gitErr(err) {
|
|
1156
|
-
return (((err.stdout && err.stdout.toString()) || '') + ((err.stderr && err.stderr.toString()) || '')).slice(0, 2000) || (err.message || '').slice(0, 500);
|
|
1157
|
-
}
|
|
1158
|
-
|
|
1159
|
-
// Where a feature not in `features/` went: ARCHIVED (only the merge is missing) or on its
|
|
1160
|
-
// `morph/{f}` branch. Fail-open: a hint that cannot be computed is absent.
|
|
1161
|
-
function featureElsewhereHint(featureCwd, root, feature) {
|
|
1162
|
-
try {
|
|
1163
|
-
const archived = join(featureCwd, '.morph', 'archive', feature);
|
|
1164
|
-
if (existsSync(archived)) {
|
|
1165
|
-
return {
|
|
1166
|
-
archived: archived.replace(/\\/g, '/'),
|
|
1167
|
-
hint: say(`${feature} já foi arquivada por um finish anterior; o que faltou foi juntar a entrega.`, 'confira se o merge ou o PR já aconteceu antes de refazer à mão'),
|
|
1168
|
-
};
|
|
1169
|
-
}
|
|
1170
|
-
} catch { /* fail-open */ }
|
|
1171
|
-
|
|
1172
|
-
try {
|
|
1173
|
-
const branch = `morph/${feature}`;
|
|
1174
|
-
const listed = execFileSync('git', ['branch', '--list', branch], { cwd: root, stdio: 'pipe' }).toString().trim();
|
|
1175
|
-
if (listed) {
|
|
1176
|
-
return {
|
|
1177
|
-
onBranch: branch,
|
|
1178
|
-
hint: say(`${feature} não está nesta pasta, mas a branch dela (${branch}) existe.`, `rode o finish de lá (\`git checkout ${branch}\`) ou da pasta de trabalho da feature`),
|
|
1179
|
-
};
|
|
1180
|
-
}
|
|
1181
|
-
} catch { /* fail-open — sem git, sem hint */ }
|
|
1182
|
-
|
|
1183
|
-
return { hint: say(`Não achei a feature ${feature} nesta pasta.`, 'confira o nome com `morph-spec list --all`') };
|
|
1184
|
-
}
|
|
1185
|
-
|
|
1186
|
-
function readFeatureJson(cwd, feature, bucket = 'features') {
|
|
1187
|
-
try {
|
|
1188
|
-
return JSON.parse(readFileSync(join(cwd, '.morph', bucket, feature, 'feature.json'), 'utf8'));
|
|
1189
|
-
} catch {
|
|
1190
|
-
return null;
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
/**
|
|
1195
|
-
* Three-valued ON PURPOSE: `merge-base --is-ancestor` exit 1 is "not merged", 128 is "a ref does
|
|
1196
|
-
* not resolve". `null` when the comparison could not be made.
|
|
1197
|
-
*/
|
|
1198
|
-
export function branchMergedInto(branch, target, cwd) {
|
|
1199
|
-
try {
|
|
1200
|
-
execFileSync('git', ['merge-base', '--is-ancestor', branch, target], { cwd, stdio: 'pipe' });
|
|
1201
|
-
return true;
|
|
1202
|
-
} catch (err) {
|
|
1203
|
-
return err?.status === 1 ? false : null;
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
// Three-valued: an unanswerable query (no `gh`, auth or network) is not evidence of "no PR".
|
|
1208
|
-
// Returns the PR url, `true` (open, url unknown), `false` (none) or `null`.
|
|
1209
|
-
function openPrFor(branch, cwd) {
|
|
1210
|
-
const { bin, prefix } = resolveGh();
|
|
1211
|
-
try {
|
|
1212
|
-
const out = execFileSync(bin, [...prefix, 'pr', 'list', '--head', branch, '--state', 'open', '--json', 'url'], { cwd, stdio: 'pipe' })
|
|
1213
|
-
.toString()
|
|
1214
|
-
.trim();
|
|
1215
|
-
const arr = JSON.parse(out || '[]');
|
|
1216
|
-
if (!Array.isArray(arr) || !arr.length) return false;
|
|
1217
|
-
return typeof arr[0]?.url === 'string' ? arr[0].url : true;
|
|
1218
|
-
} catch {
|
|
1219
|
-
return null;
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
|
|
1223
|
-
// Never throws: a stack that refuses to come down must not fail a finish that already merged.
|
|
1224
|
-
function reclaimStack(feature, { root, worktreePath, options }) {
|
|
1225
|
-
try {
|
|
1226
|
-
return tearDownFeatureStack(feature, {
|
|
1227
|
-
root, worktreePath, volumes: !options.keepVolumes, images: 'local', _exec: options._exec,
|
|
1228
|
-
});
|
|
1229
|
-
} catch {
|
|
1230
|
-
return { attempted: false, cwd: worktreePath || root, status: 'fail', stampDeleted: false };
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
|
-
// Never via saveState, which would re-materialize the feature folder.
|
|
1235
|
-
function dropFromRootIndex(root, feature) {
|
|
1236
|
-
const rootPath = join(root, '.morph', 'state.json');
|
|
1237
|
-
if (!existsSync(rootPath)) return;
|
|
1238
|
-
try {
|
|
1239
|
-
const idx = JSON.parse(readFileSync(rootPath, 'utf8'));
|
|
1240
|
-
if (idx.features && idx.features[feature]) {
|
|
1241
|
-
delete idx.features[feature];
|
|
1242
|
-
idx.metadata = idx.metadata || {};
|
|
1243
|
-
idx.metadata.totalFeatures = Object.keys(idx.features).length;
|
|
1244
|
-
writeFileSync(rootPath, JSON.stringify(idx, null, 2), 'utf8');
|
|
1245
|
-
}
|
|
1246
|
-
} catch { /* index is derivable — non-fatal */ }
|
|
1247
|
-
}
|