@polymorphism-tech/morph-spec 10.12.1 → 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 +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 +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,440 +0,0 @@
|
|
|
1
|
-
// Host processes that the e2e stack runs next to compose (api, portal), one PID file per project.
|
|
2
|
-
// Nothing here imports e2e-check.js: it imports this module, and the timing constants mirror its own.
|
|
3
|
-
|
|
4
|
-
import { execFileSync, spawn, spawnSync } from 'child_process';
|
|
5
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs';
|
|
6
|
-
import { join, resolve } from 'path';
|
|
7
|
-
|
|
8
|
-
import { tokenize } from './command-tokens.js';
|
|
9
|
-
import { pidAlive } from './process-alive.js';
|
|
10
|
-
|
|
11
|
-
export const DEFAULT_HOST_TIMEOUT = 180_000;
|
|
12
|
-
|
|
13
|
-
const HEALTH_POLL_MS = 2_000;
|
|
14
|
-
|
|
15
|
-
const OUTPUT_TAIL_LINES = 20;
|
|
16
|
-
|
|
17
|
-
const NO_HEALTH_GRACE_MS = 2_000;
|
|
18
|
-
|
|
19
|
-
const KILL_WAIT_MS = 5_000;
|
|
20
|
-
|
|
21
|
-
const VAR_RE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
22
|
-
|
|
23
|
-
export function hostStatePath(gitCommonDir, projectName) {
|
|
24
|
-
return join(gitCommonDir, 'morph-spec', `e2e-host-${projectName}.json`);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function hostLogPath(gitCommonDir, projectName, name) {
|
|
28
|
-
return join(gitCommonDir, 'morph-spec', `e2e-host-${projectName}-${name}.log`);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** Process creation time as the OS reports it, or null when the PID is gone. */
|
|
32
|
-
export function readProcessCreatedAt(pid, platform = process.platform) {
|
|
33
|
-
try {
|
|
34
|
-
const out = platform === 'win32'
|
|
35
|
-
? execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command',
|
|
36
|
-
`(Get-Process -Id ${Number(pid)}).StartTime.ToFileTimeUtc()`],
|
|
37
|
-
{ encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })
|
|
38
|
-
: execFileSync('ps', ['-o', 'lstart=', '-p', String(Number(pid))],
|
|
39
|
-
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
40
|
-
return out.trim() || null;
|
|
41
|
-
} catch {
|
|
42
|
-
return null;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** Resolves `${VAR}` in `env` and `health`: stack env first, then `process.env`. */
|
|
47
|
-
export function interpolateEnv(service, stackEnv = {}) {
|
|
48
|
-
const missing = new Set();
|
|
49
|
-
const sub = (text) => String(text).replace(VAR_RE, (_, name) => {
|
|
50
|
-
const value = stackEnv?.[name] ?? process.env[name];
|
|
51
|
-
if (value === undefined || value === null || value === '') {
|
|
52
|
-
missing.add(name);
|
|
53
|
-
return '';
|
|
54
|
-
}
|
|
55
|
-
return String(value);
|
|
56
|
-
});
|
|
57
|
-
const env = {};
|
|
58
|
-
for (const [key, value] of Object.entries(service.env ?? {})) env[key] = sub(value);
|
|
59
|
-
const health = service.health ? sub(service.health) : null;
|
|
60
|
-
return { env, health, missing: [...missing] };
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
const SERVICE_KEYS = new Set(['name', 'cwd', 'build', 'start', 'env', 'health', 'timeoutMs']);
|
|
64
|
-
|
|
65
|
-
function validateServices(services) {
|
|
66
|
-
if (!Array.isArray(services)) return 'e2e.hostServices must be an array';
|
|
67
|
-
const seen = new Set();
|
|
68
|
-
for (const [i, svc] of services.entries()) {
|
|
69
|
-
const label = typeof svc?.name === 'string' && svc.name ? `"${svc.name}"` : `#${i}`;
|
|
70
|
-
if (!svc || typeof svc !== 'object' || Array.isArray(svc)) return `e2e.hostServices[${i}] must be an object`;
|
|
71
|
-
if (typeof svc.name !== 'string' || !/^[A-Za-z0-9._-]+$/.test(svc.name)) {
|
|
72
|
-
return `e2e.hostServices[${i}].name must be a non-empty string of [A-Za-z0-9._-]`;
|
|
73
|
-
}
|
|
74
|
-
if (seen.has(svc.name)) return `e2e.hostServices has two services named "${svc.name}"`;
|
|
75
|
-
seen.add(svc.name);
|
|
76
|
-
const unknown = Object.keys(svc).find((key) => !SERVICE_KEYS.has(key));
|
|
77
|
-
if (unknown) return `hostService ${label}: unknown field "${unknown}"`;
|
|
78
|
-
if (typeof svc.start !== 'string' || !svc.start.trim()) return `hostService ${label}: "start" must be a non-empty string`;
|
|
79
|
-
for (const field of ['cwd', 'build', 'health']) {
|
|
80
|
-
if (svc[field] !== undefined && typeof svc[field] !== 'string') return `hostService ${label}: "${field}" must be a string`;
|
|
81
|
-
}
|
|
82
|
-
if (svc.env !== undefined) {
|
|
83
|
-
if (!svc.env || typeof svc.env !== 'object' || Array.isArray(svc.env)) return `hostService ${label}: "env" must be an object`;
|
|
84
|
-
for (const [key, value] of Object.entries(svc.env)) {
|
|
85
|
-
if (typeof value !== 'string' && typeof value !== 'number') {
|
|
86
|
-
return `hostService ${label}: env.${key} must be a string or number`;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
if (svc.timeoutMs !== undefined && !(Number.isFinite(svc.timeoutMs) && svc.timeoutMs > 0)) {
|
|
91
|
-
return `hostService ${label}: "timeoutMs" must be a positive number`;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return null;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function readState(gitCommonDir, projectName) {
|
|
98
|
-
try {
|
|
99
|
-
const parsed = JSON.parse(readFileSync(hostStatePath(gitCommonDir, projectName), 'utf8').replace(/^/, ''));
|
|
100
|
-
return Array.isArray(parsed?.services) ? parsed.services : null;
|
|
101
|
-
} catch {
|
|
102
|
-
return null;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function writeState(gitCommonDir, projectName, records) {
|
|
107
|
-
const target = hostStatePath(gitCommonDir, projectName);
|
|
108
|
-
if (records.length === 0) {
|
|
109
|
-
try { unlinkSync(target); } catch { /* already gone */ }
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
mkdirSync(join(gitCommonDir, 'morph-spec'), { recursive: true });
|
|
113
|
-
const tmp = `${target}.tmp.${process.pid}`;
|
|
114
|
-
writeFileSync(tmp, `${JSON.stringify({ version: 1, project: projectName, services: records }, null, 2)}\n`, 'utf8');
|
|
115
|
-
renameSync(tmp, target);
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function sleep(ms) {
|
|
119
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const PROBE_SCRIPT =
|
|
123
|
-
'fetch(process.argv[1],{signal:AbortSignal.timeout(Number(process.argv[2]))})' +
|
|
124
|
-
'.then(r=>process.exit(r.status<500?0:1),()=>process.exit(1))';
|
|
125
|
-
|
|
126
|
-
function probeHealth(url, timeoutMs = 1_500) {
|
|
127
|
-
const r = spawnSync(process.execPath, ['-e', PROBE_SCRIPT, url, String(timeoutMs)], {
|
|
128
|
-
timeout: timeoutMs + 1_000,
|
|
129
|
-
windowsHide: true,
|
|
130
|
-
stdio: 'ignore',
|
|
131
|
-
});
|
|
132
|
-
return r.status === 0;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// Only the recorded identity may be killed: a recycled PID belongs to someone else.
|
|
136
|
-
function killRecord(record, readCreatedAt) {
|
|
137
|
-
if (!processRunning(record.pid)) {
|
|
138
|
-
return { killed: false, warning: `hostService "${record.name}": PID ${record.pid} was no longer running; record dropped` };
|
|
139
|
-
}
|
|
140
|
-
const current = readCreatedAt(record.pid);
|
|
141
|
-
if (!record.createdAt || current !== record.createdAt) {
|
|
142
|
-
return {
|
|
143
|
-
killed: false,
|
|
144
|
-
warning: `hostService "${record.name}": PID ${record.pid} is alive but its creation time differs ` +
|
|
145
|
-
`from the recorded one (recycled PID); not killed, record dropped`,
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
if (process.platform === 'win32') killWindowsTree(record.pid);
|
|
149
|
-
else killPosixGroup(record.pid);
|
|
150
|
-
return { killed: true };
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function waitUntil(predicate) {
|
|
154
|
-
const deadline = Date.now() + KILL_WAIT_MS;
|
|
155
|
-
while (!predicate() && Date.now() < deadline) sleep(100);
|
|
156
|
-
return predicate();
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// The process that spawned the shell blocks in a sync loop and never reaps it: a zombie is not alive.
|
|
160
|
-
export function processRunning(pid) {
|
|
161
|
-
if (!pidAlive(pid)) return false;
|
|
162
|
-
if (process.platform === 'win32') return true;
|
|
163
|
-
const r = spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8' });
|
|
164
|
-
if (r.error) return true;
|
|
165
|
-
// ps exits non-zero when the process vanished between pidAlive and here.
|
|
166
|
-
const stat = String(r.stdout).trim();
|
|
167
|
-
return stat !== '' && !stat.startsWith('Z');
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
function groupAlive(pgid) {
|
|
171
|
-
const r = spawnSync('ps', ['-A', '-o', 'pgid=,stat='], { encoding: 'utf8' });
|
|
172
|
-
if (r.status !== 0) {
|
|
173
|
-
try {
|
|
174
|
-
process.kill(-pgid, 0);
|
|
175
|
-
return true;
|
|
176
|
-
} catch (err) {
|
|
177
|
-
return err?.code === 'EPERM';
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
return String(r.stdout).split('\n').some((line) => {
|
|
181
|
-
const [group, stat = ''] = line.trim().split(/\s+/);
|
|
182
|
-
return Number(group) === pgid && !stat.startsWith('Z');
|
|
183
|
-
});
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// The port belongs to the grandchild, not the shell: wait on the whole group.
|
|
187
|
-
function killPosixGroup(pgid) {
|
|
188
|
-
try { process.kill(-pgid, 'SIGTERM'); } catch { /* group already gone */ }
|
|
189
|
-
if (!waitUntil(() => !groupAlive(pgid))) {
|
|
190
|
-
try { process.kill(-pgid, 'SIGKILL'); } catch { /* group already gone */ }
|
|
191
|
-
waitUntil(() => !groupAlive(pgid));
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
const WIN_SNAPSHOT =
|
|
196
|
-
'Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ p = $_.ProcessId; pp = $_.ParentProcessId; ' +
|
|
197
|
-
't = if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { 0 } } } | ConvertTo-Json -Compress';
|
|
198
|
-
|
|
199
|
-
function windowsSnapshot() {
|
|
200
|
-
try {
|
|
201
|
-
const out = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', WIN_SNAPSHOT],
|
|
202
|
-
{ encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 16 * 1024 * 1024 });
|
|
203
|
-
const parsed = JSON.parse(out.trim() || '[]');
|
|
204
|
-
return Array.isArray(parsed) ? parsed : [parsed];
|
|
205
|
-
} catch {
|
|
206
|
-
return [];
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// Windows keeps a dead parent's PID in ParentProcessId, so a child only counts when born after its parent.
|
|
211
|
-
function windowsDescendants(rows, roots) {
|
|
212
|
-
const byPid = new Map(rows.map((r) => [r.p, r]));
|
|
213
|
-
const found = [];
|
|
214
|
-
const queue = [...roots];
|
|
215
|
-
while (queue.length > 0) {
|
|
216
|
-
const parent = byPid.get(queue.shift());
|
|
217
|
-
if (!parent) continue;
|
|
218
|
-
for (const row of rows) {
|
|
219
|
-
if (row.pp === parent.p && row.p !== parent.p && row.t >= parent.t && !found.includes(row.p) && !roots.includes(row.p)) {
|
|
220
|
-
found.push(row.p);
|
|
221
|
-
queue.push(row.p);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
return found;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// Every PID goes through process.kill: killing via a console tool is banned in hooks (doctor-procs canary).
|
|
229
|
-
// The rescan catches a child spawned between the snapshot and its parent's death.
|
|
230
|
-
function killWindowsTree(rootPid) {
|
|
231
|
-
const first = windowsSnapshot();
|
|
232
|
-
const killed = [rootPid, ...windowsDescendants(first, [rootPid])];
|
|
233
|
-
for (const pid of killed) {
|
|
234
|
-
try { process.kill(pid); } catch { /* already gone */ }
|
|
235
|
-
}
|
|
236
|
-
const killedRows = first.filter((r) => killed.includes(r.p));
|
|
237
|
-
const rescan = windowsSnapshot().filter((r) => !killed.includes(r.p));
|
|
238
|
-
const stragglers = windowsDescendants([...killedRows, ...rescan], killed);
|
|
239
|
-
for (const pid of stragglers) {
|
|
240
|
-
try { process.kill(pid); } catch { /* already gone */ }
|
|
241
|
-
}
|
|
242
|
-
waitUntil(() => [...killed, ...stragglers].every((pid) => !pidAlive(pid)));
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
function tailLines(text, n = OUTPUT_TAIL_LINES) {
|
|
246
|
-
return String(text || '').trimEnd().split(/\r?\n/).slice(-n).join('\n');
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
function readLogTail(path) {
|
|
250
|
-
try { return tailLines(readFileSync(path, 'utf8')); } catch { return ''; }
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/** @returns {{ killed: string[], skipped: string[], warnings: string[] }} */
|
|
254
|
-
export function stopHostServices(gitCommonDir, projectName, { readCreatedAt = readProcessCreatedAt } = {}) {
|
|
255
|
-
const result = { killed: [], skipped: [], warnings: [] };
|
|
256
|
-
if (!gitCommonDir) return result;
|
|
257
|
-
const records = readState(gitCommonDir, projectName);
|
|
258
|
-
if (!records) return result;
|
|
259
|
-
for (const record of records) {
|
|
260
|
-
const outcome = killRecord(record, readCreatedAt);
|
|
261
|
-
if (outcome.killed) result.killed.push(record.name);
|
|
262
|
-
else {
|
|
263
|
-
result.skipped.push(record.name);
|
|
264
|
-
result.warnings.push(outcome.warning);
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
writeState(gitCommonDir, projectName, []);
|
|
268
|
-
return result;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/** Liveness by PID only: the creation-time read is too slow for a poll. */
|
|
272
|
-
export function hostServicesStatus(gitCommonDir, projectName) {
|
|
273
|
-
const records = readState(gitCommonDir, projectName) ?? [];
|
|
274
|
-
return records.map((r) => {
|
|
275
|
-
const alive = pidAlive(r.pid);
|
|
276
|
-
return { name: r.name, pid: r.pid, alive, health: r.health ? alive && probeHealth(r.health) : null };
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// A detached cmd.exe has no console, so the console apps it starts get a fresh one and drop the
|
|
281
|
-
// log handles; a detached node holding the shell keeps them inherited down the tree.
|
|
282
|
-
const WIN_LAUNCHER =
|
|
283
|
-
"const c=require('child_process').spawn(process.argv[1],{shell:true,stdio:'inherit',windowsHide:true});" +
|
|
284
|
-
'c.on(\'exit\',(k)=>process.exit(k??1))';
|
|
285
|
-
|
|
286
|
-
function launch(svc, ctx, deadline, exec) {
|
|
287
|
-
const fail = (reason, output = '') => ({ ok: false, reason: `hostService "${svc.name}": ${reason}`, output });
|
|
288
|
-
const remaining = () => deadline - Date.now();
|
|
289
|
-
|
|
290
|
-
if (svc.build && !ctx.skipBuild) {
|
|
291
|
-
const [file, ...args] = tokenize(svc.build);
|
|
292
|
-
const built = exec(file, args, { cwd: svc.dir, env: svc.childEnv, timeout: remaining() });
|
|
293
|
-
// A build killed at its timeout comes back as a plain non-zero exit: the deadline decides first.
|
|
294
|
-
if (remaining() <= 0) return fail(`timed out after ${svc.timeoutMs} ms during build`, tailLines(built.output));
|
|
295
|
-
if (built.code !== 0) return fail(`build failed (${svc.build}, exit ${built.code})`, tailLines(built.output));
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
const log = hostLogPath(ctx.gitCommonDir, ctx.projectName, svc.name);
|
|
299
|
-
mkdirSync(join(ctx.gitCommonDir, 'morph-spec'), { recursive: true });
|
|
300
|
-
const fd = openSync(log, 'w');
|
|
301
|
-
let child;
|
|
302
|
-
try {
|
|
303
|
-
// The CLI ends with process.exit: the child must own its group and hold none of our pipes.
|
|
304
|
-
const win = process.platform === 'win32';
|
|
305
|
-
child = spawn(win ? process.execPath : svc.start, win ? ['-e', WIN_LAUNCHER, svc.start] : [], {
|
|
306
|
-
cwd: svc.dir,
|
|
307
|
-
env: { ...process.env, ...svc.childEnv },
|
|
308
|
-
shell: !win,
|
|
309
|
-
detached: true,
|
|
310
|
-
windowsHide: true,
|
|
311
|
-
stdio: ['ignore', fd, fd],
|
|
312
|
-
});
|
|
313
|
-
child.on('error', () => {});
|
|
314
|
-
child.unref();
|
|
315
|
-
} finally {
|
|
316
|
-
closeSync(fd);
|
|
317
|
-
}
|
|
318
|
-
if (!child?.pid) return fail(`could not start (${svc.start})`, readLogTail(log));
|
|
319
|
-
|
|
320
|
-
const record = {
|
|
321
|
-
name: svc.name,
|
|
322
|
-
pid: child.pid,
|
|
323
|
-
createdAt: ctx.readCreatedAt(child.pid),
|
|
324
|
-
stamp: ctx.stamp ?? null,
|
|
325
|
-
log,
|
|
326
|
-
health: svc.health,
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
if (!svc.health) {
|
|
330
|
-
sleep(Math.min(NO_HEALTH_GRACE_MS, Math.max(remaining(), 0)));
|
|
331
|
-
if (!processRunning(child.pid)) return { ...fail('exited right after start', readLogTail(log)), record };
|
|
332
|
-
return { ok: true, record };
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
while (true) {
|
|
336
|
-
if (probeHealth(svc.health)) return { ok: true, record };
|
|
337
|
-
if (!processRunning(child.pid)) return { ...fail('exited before its health check went green', readLogTail(log)), record };
|
|
338
|
-
if (remaining() <= 0) {
|
|
339
|
-
return { ...fail(`health ${svc.health} not green within ${svc.timeoutMs} ms`, readLogTail(log)), record };
|
|
340
|
-
}
|
|
341
|
-
sleep(Math.min(HEALTH_POLL_MS, remaining()));
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
function isReusable(record, svc, ctx) {
|
|
346
|
-
if (!record || !processRunning(record.pid)) return false;
|
|
347
|
-
if (ctx.readCreatedAt(record.pid) !== record.createdAt) return false;
|
|
348
|
-
return svc.health ? probeHealth(svc.health) : true;
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
/** @returns {{ status: 'pass'|'fail'|'skip', reused: boolean, services: object[], warnings: string[], reason?: string, output?: string }} */
|
|
352
|
-
export function startHostServices(cwd, options = {}, exec) {
|
|
353
|
-
const {
|
|
354
|
-
services,
|
|
355
|
-
env: stackEnv = {},
|
|
356
|
-
gitCommonDir,
|
|
357
|
-
projectName,
|
|
358
|
-
stamp = null,
|
|
359
|
-
forceFresh = false,
|
|
360
|
-
restart = false,
|
|
361
|
-
readCreatedAt = readProcessCreatedAt,
|
|
362
|
-
} = options;
|
|
363
|
-
|
|
364
|
-
if (services === undefined || (Array.isArray(services) && services.length === 0)) {
|
|
365
|
-
return { status: 'skip', reused: false, services: [], warnings: [], reason: 'no e2e.hostServices configured' };
|
|
366
|
-
}
|
|
367
|
-
const invalid = validateServices(services);
|
|
368
|
-
if (invalid) return { status: 'fail', reused: false, services: [], warnings: [], reason: invalid };
|
|
369
|
-
|
|
370
|
-
const resolved = [];
|
|
371
|
-
for (const svc of services) {
|
|
372
|
-
const { env, health, missing } = interpolateEnv(svc, stackEnv);
|
|
373
|
-
if (missing.length > 0) {
|
|
374
|
-
return {
|
|
375
|
-
status: 'fail',
|
|
376
|
-
reused: false,
|
|
377
|
-
services: [],
|
|
378
|
-
warnings: [],
|
|
379
|
-
reason: `hostService "${svc.name}": no value for ${missing.map((v) => `\${${v}}`).join(', ')} ` +
|
|
380
|
-
'(looked in the e2e stack env and the process env)',
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
const dir = resolve(cwd, svc.cwd ?? '.');
|
|
384
|
-
if (!existsSync(dir)) {
|
|
385
|
-
return { status: 'fail', reused: false, services: [], warnings: [], reason: `hostService "${svc.name}": cwd ${dir} does not exist` };
|
|
386
|
-
}
|
|
387
|
-
resolved.push({
|
|
388
|
-
name: svc.name,
|
|
389
|
-
dir,
|
|
390
|
-
build: svc.build,
|
|
391
|
-
start: svc.start,
|
|
392
|
-
health,
|
|
393
|
-
timeoutMs: svc.timeoutMs ?? DEFAULT_HOST_TIMEOUT,
|
|
394
|
-
childEnv: { ...stackEnv, ...env },
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
const previous = readState(gitCommonDir, projectName) ?? [];
|
|
399
|
-
// A restart relaunches the binaries already built: they keep the stamp of the build they came from.
|
|
400
|
-
const ctx = restart
|
|
401
|
-
? { gitCommonDir, projectName, stamp: previous[0]?.stamp ?? stamp, readCreatedAt, skipBuild: true }
|
|
402
|
-
: { gitCommonDir, projectName, stamp, readCreatedAt };
|
|
403
|
-
const sameSet = previous.length === resolved.length && resolved.every((s) => previous.some((r) => r.name === s.name));
|
|
404
|
-
const divergent = forceFresh || restart || !sameSet || previous.some((r) => r.stamp !== stamp);
|
|
405
|
-
const warnings = divergent && previous.length > 0
|
|
406
|
-
? stopHostServices(gitCommonDir, projectName, { readCreatedAt }).warnings
|
|
407
|
-
: [];
|
|
408
|
-
const prior = divergent ? [] : previous;
|
|
409
|
-
|
|
410
|
-
const records = [];
|
|
411
|
-
const startedNow = [];
|
|
412
|
-
const out = [];
|
|
413
|
-
for (const [i, svc] of resolved.entries()) {
|
|
414
|
-
const old = prior.find((r) => r.name === svc.name);
|
|
415
|
-
if (isReusable(old, svc, ctx)) {
|
|
416
|
-
records.push(old);
|
|
417
|
-
out.push({ name: svc.name, pid: old.pid, reused: true, log: old.log });
|
|
418
|
-
continue;
|
|
419
|
-
}
|
|
420
|
-
if (old) {
|
|
421
|
-
const killed = killRecord(old, readCreatedAt);
|
|
422
|
-
if (killed.warning) warnings.push(killed.warning);
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
const result = launch(svc, ctx, Date.now() + svc.timeoutMs, exec);
|
|
426
|
-
if (!result.ok) {
|
|
427
|
-
for (const r of [...startedNow, result.record].filter(Boolean)) killRecord(r, readCreatedAt);
|
|
428
|
-
const unreached = resolved.slice(i + 1).map((s) => prior.find((r) => r.name === s.name)).filter(Boolean);
|
|
429
|
-
const kept = [...records.filter((r) => !startedNow.includes(r)), ...unreached];
|
|
430
|
-
writeState(gitCommonDir, projectName, kept);
|
|
431
|
-
return { status: 'fail', reused: false, services: out, warnings, reason: result.reason, output: result.output };
|
|
432
|
-
}
|
|
433
|
-
records.push(result.record);
|
|
434
|
-
startedNow.push(result.record);
|
|
435
|
-
writeState(gitCommonDir, projectName, records);
|
|
436
|
-
out.push({ name: svc.name, pid: result.record.pid, reused: false, log: result.record.log });
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
return { status: 'pass', reused: startedNow.length === 0, services: out, warnings };
|
|
440
|
-
}
|
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
// The single rule of "what the session does next". `decideNext` is pure: collectors feed facts.
|
|
2
|
-
// Hooks and the CLI share it so the SessionStart pre-fetch and `morph-spec next` never disagree.
|
|
3
|
-
|
|
4
|
-
import { existsSync, readFileSync } from 'fs';
|
|
5
|
-
import { join } from 'path';
|
|
6
|
-
import { derivePhaseForFeature } from './state-reader.js';
|
|
7
|
-
import { implementProgress } from './report-progress.js';
|
|
8
|
-
import { gateQuestion, retrato, scenarioLabel, TESTS } from './owner-words.js';
|
|
9
|
-
|
|
10
|
-
export const FIX_ATTEMPTS = 3;
|
|
11
|
-
|
|
12
|
-
const step = (action, command, reason, say, extra = {}) => ({ action, command, reason, say, ...extra });
|
|
13
|
-
|
|
14
|
-
function firstAndMore(checks) {
|
|
15
|
-
const [first, ...rest] = checks;
|
|
16
|
-
return rest.length ? `${scenarioLabel(first)} e mais ${rest.length}` : scenarioLabel(first);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
const HOW = {
|
|
20
|
-
plan: (f) => [
|
|
21
|
-
`Rode \`/morph-plan ${f}\`: escreva 2-plan/plan.md e rode \`morph-spec plan-check ${f}\` até zero erro.`,
|
|
22
|
-
],
|
|
23
|
-
gate: (f, q) => [
|
|
24
|
-
`Rode \`morph-spec gate-check ${f} plan\`; se pausar, AskUserQuestion "${q('plan')}".`,
|
|
25
|
-
],
|
|
26
|
-
design: (f, q) => [
|
|
27
|
-
`Rode \`/morph-uiux ${f}\` (opções em 1-design/opcoes/, protótipo e prints); depois \`morph-spec gate-check ${f} uiux\`.`,
|
|
28
|
-
`Se pausar, AskUserQuestion "${q('uiux')}".`,
|
|
29
|
-
],
|
|
30
|
-
implement: (f) => [
|
|
31
|
-
'Implemente os Cn pendentes em sequência; ao fechar cada um, marque `feito` + evidência (teste ou arquivo:linha) '
|
|
32
|
-
+ `em 3-implement/report.md e commite \`wip(${f}): Cn …\`.`,
|
|
33
|
-
],
|
|
34
|
-
decide: () => [
|
|
35
|
-
'Leia a pergunta do Cn bloqueado em 3-implement/report.md ## Notas; decida pelo plano/ADR ou faça AskUserQuestion com ela. Se o `Resultado buscado` ficou falso, o plano não decide: pergunte.',
|
|
36
|
-
'Registre a resposta em ## Notas, volte o Cn para `pendente` e siga implementando; resposta que muda escopo vai por `unapprove`.',
|
|
37
|
-
],
|
|
38
|
-
verify: (f) => [
|
|
39
|
-
`\`morph-spec verify ${f} --affected --json --detach\`, em run_in_background: só os testes que o diff alcança; repetir o comando retoma a rodada.`,
|
|
40
|
-
],
|
|
41
|
-
fix: (f) => [
|
|
42
|
-
`Leia o \`feedback\` do último verify de ${f}, corrija a causa e rode o comando acima de novo, com \`--json\`.`,
|
|
43
|
-
],
|
|
44
|
-
escalate: () => [
|
|
45
|
-
'AskUserQuestion com o texto do reason (aceitar/continuar/parar) e siga a resposta; não rode outro verify antes dela.',
|
|
46
|
-
],
|
|
47
|
-
review: () => [
|
|
48
|
-
'Siga .claude/skills/morph-apply/references/review.md.',
|
|
49
|
-
],
|
|
50
|
-
finish: (f) => [
|
|
51
|
-
`\`morph-spec context refresh\`, commit, e \`morph-spec finish ${f} --pr\` (\`--merge\` com \`finish.mode: "merge"\` no config), sem perguntar.`,
|
|
52
|
-
],
|
|
53
|
-
status: (f) => [
|
|
54
|
-
`Rode \`morph-spec status ${f}\` e confira a fase em .morph/features/${f}/feature.json.`,
|
|
55
|
-
],
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* @param {{ feature: string, phase: string, progress: object|null, gates: object,
|
|
60
|
-
* verification: { status?: string }|null, verificationStale?: boolean, failStreak?: number }} s
|
|
61
|
-
* `verificationStale` undefined = unknown (the hook has no git): read as fresh.
|
|
62
|
-
*/
|
|
63
|
-
export function decideNext(s) {
|
|
64
|
-
const n = decide(s);
|
|
65
|
-
const q = (gate) => gateQuestion(gate, s.feature, s.featureJson, s.progress?.summary);
|
|
66
|
-
const how = (HOW[n.action] ?? HOW.status)(s.feature, q);
|
|
67
|
-
const hotfix = s.workType === 'hotfix' && n.command.startsWith('/morph-hotfix');
|
|
68
|
-
return { ...n, how: hotfix ? ['Fluxo de hotfix: siga .claude/skills/morph-apply/references/hotfix.md.', ...how] : how };
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function decide(s) {
|
|
72
|
-
const f = s.feature;
|
|
73
|
-
const approved = (g) => s.gates?.[g]?.approved === true;
|
|
74
|
-
const skill = (name) => (s.workType === 'hotfix' ? `/morph-hotfix ${f}` : `/${name} ${f}`);
|
|
75
|
-
|
|
76
|
-
switch (s.phase) {
|
|
77
|
-
case 'plan':
|
|
78
|
-
return s.progress
|
|
79
|
-
? step('gate', `morph-spec gate-check ${f} plan`, 'plano extraído: o gate do plano decide a pausa',
|
|
80
|
-
'a sessão confere o plano e, se houver risco, pede a sua aprovação.')
|
|
81
|
-
: step('plan', `/morph-plan ${f}`, 'sem checks.json: escreva o plan.md e rode plan-check até zero erro', 'a sessão escreve o plano.');
|
|
82
|
-
|
|
83
|
-
case 'uiux':
|
|
84
|
-
return step('design', `morph-spec gate-check ${f} uiux`, 'complete 1-design/ (morph-uiux) e passe o gate de uiux',
|
|
85
|
-
'a sessão desenha as telas para você aprovar.');
|
|
86
|
-
|
|
87
|
-
case 'implement': {
|
|
88
|
-
const p = s.progress;
|
|
89
|
-
if (!p) return step('plan', skill('morph-plan'), 'sem checks.json: plan.md curto e plan-check até zero erro', 'a sessão escreve o plano.');
|
|
90
|
-
const blocked = p.checks.filter((c) => c.status === 'bloqueado');
|
|
91
|
-
if (blocked.length) {
|
|
92
|
-
return step('decide', 'AskUserQuestion (decisão do cenário)',
|
|
93
|
-
'Cn bloqueado no report.md: decida pelo plano/ADR ou pergunte, e siga implementando',
|
|
94
|
-
`decidir o ${firstAndMore(blocked)}, que está travado.`, { checks: blocked.map((c) => c.id) });
|
|
95
|
-
}
|
|
96
|
-
const pending = p.checks.filter((c) => c.status === 'pendente');
|
|
97
|
-
if (pending.length) {
|
|
98
|
-
return step('implement', skill('morph-apply'), 'implemente nesta sessão e marque cada Cn feito no report.md',
|
|
99
|
-
`a sessão constrói o ${firstAndMore(pending)}.`, { checks: pending.map((c) => c.id) });
|
|
100
|
-
}
|
|
101
|
-
const fullFresh = s.verification?.status && s.verificationStale !== true;
|
|
102
|
-
const affectedFresh = s.affected?.status && s.affectedStale !== true;
|
|
103
|
-
const v = fullFresh ? s.verification : affectedFresh ? s.affected : null;
|
|
104
|
-
if (!v) {
|
|
105
|
-
const ran = s.verification?.status || s.affected?.status;
|
|
106
|
-
return step('verify', `morph-spec verify ${f} --affected`, ran ? 'a árvore andou desde o último verify' : 'todo Cn feito, sem verify',
|
|
107
|
-
`rodar ${TESTS}.`);
|
|
108
|
-
}
|
|
109
|
-
if (v.status === 'fail') {
|
|
110
|
-
const streak = (fullFresh ? s.failStreak : s.affected.failStreak) ?? 0;
|
|
111
|
-
if (streak > 0 && streak % FIX_ATTEMPTS === 0) {
|
|
112
|
-
return step('escalate', 'AskUserQuestion (aceitar/continuar/parar)',
|
|
113
|
-
`${streak} verifies vermelhos seguidos, nunca uma tentativa a mais por conta própria. `
|
|
114
|
-
+ `aceitar → ${skill('morph-review')} (o verify vermelho pausa o gate: o humano assina lá); `
|
|
115
|
-
+ 'continuar → corrija e rode o verify de novo; parar → encerre aqui. Segue `escalate` até a árvore andar',
|
|
116
|
-
'esperar a sua decisão sobre os testes automáticos.',
|
|
117
|
-
{ ask: `${TESTS} falharam ${streak} vezes seguidas. Você decide: aceitar assim, tentar de novo ou parar.` });
|
|
118
|
-
}
|
|
119
|
-
return step('fix', `morph-spec verify ${f}${fullFresh ? '' : ' --affected'}`,
|
|
120
|
-
`corrija pelo feedback do verify e rode de novo (${FIX_ATTEMPTS - (streak % FIX_ATTEMPTS)} tentativa(s) antes de perguntar)`,
|
|
121
|
-
`a sessão corrige o que ${TESTS} apontaram (${FIX_ATTEMPTS - (streak % FIX_ATTEMPTS)} tentativa(s) antes de perguntar a você).`);
|
|
122
|
-
}
|
|
123
|
-
return step('review', skill('morph-review'), 'verify verde: Gate 3', 'a revisão independente roda sozinha.');
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
case 'review':
|
|
127
|
-
return approved('review')
|
|
128
|
-
? step('finish', `morph-spec finish ${f} --pr|--merge`, 'Gate 3 aprovado: arquiva e integra num passo', 'a sessão abre o PR e entrega.')
|
|
129
|
-
: step('review', skill('morph-review'), 'relatórios do Gate 3 e gate-check review', 'a revisão independente roda sozinha.');
|
|
130
|
-
|
|
131
|
-
default:
|
|
132
|
-
return step('status', `morph-spec status ${f}`, `fase desconhecida: ${s.phase ?? '—'}`, 'conferir o estado da feature.');
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
export const SESSION_MARK = 'para a sessão:';
|
|
137
|
-
|
|
138
|
-
export function sessionLine(n) {
|
|
139
|
-
const ids = n.checks?.length ? ` [${n.checks.join(', ')}]` : '';
|
|
140
|
-
return `${SESSION_MARK} ${n.action}${ids} → ${n.command} — ${n.reason}`;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// Owner line first; the second line is the exact instruction the session runs.
|
|
144
|
-
export function formatNext(n) {
|
|
145
|
-
return `Próximo: ${n.say}\n ${sessionLine(n)}`;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export function retratoOf(signals, next) {
|
|
149
|
-
return retrato({
|
|
150
|
-
slug: signals.feature, feature: signals.featureJson, progress: signals.progress,
|
|
151
|
-
phase: signals.phase, next, hasDesign: signals.hasDesign,
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** Facts readable from `hooks/shared`; the CLI adds `verificationStale` (git) on top. Null without feature.json. */
|
|
156
|
-
export function collectNextSignals(featureName, cwd) {
|
|
157
|
-
const featureDir = join(cwd, '.morph', 'features', featureName);
|
|
158
|
-
let feature;
|
|
159
|
-
try {
|
|
160
|
-
const path = join(featureDir, 'feature.json');
|
|
161
|
-
if (!existsSync(path)) return null;
|
|
162
|
-
feature = JSON.parse(readFileSync(path, 'utf8').replace(/^/, ''));
|
|
163
|
-
} catch {
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
let phase = 'plan';
|
|
167
|
-
try { phase = derivePhaseForFeature(featureName, cwd) || 'plan'; } catch {}
|
|
168
|
-
return {
|
|
169
|
-
feature: featureName,
|
|
170
|
-
workType: feature.workType ?? 'feature',
|
|
171
|
-
featureJson: feature,
|
|
172
|
-
worktreePath: feature.worktree?.path ?? null,
|
|
173
|
-
phase,
|
|
174
|
-
progress: implementProgress(featureDir),
|
|
175
|
-
hasDesign: existsSync(join(featureDir, '1-design')),
|
|
176
|
-
gates: feature.approvals || feature.approvalGates || {},
|
|
177
|
-
verification: feature.verification ?? null,
|
|
178
|
-
failStreak: feature.verifications?.feature?.failStreak ?? 0,
|
|
179
|
-
affected: feature.verifications?.affected ?? null,
|
|
180
|
-
};
|
|
181
|
-
}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
// Catches a secret written next to its name or in a known token shape; a bare
|
|
2
|
-
// value is invisible to any pattern, which is why tool OUTPUT is never
|
|
3
|
-
// persisted at all instead of being redacted.
|
|
4
|
-
|
|
5
|
-
export const REDACTED = '[REDACTED]';
|
|
6
|
-
|
|
7
|
-
const SECRET_KEY =
|
|
8
|
-
'[A-Za-z0-9_.-]*(?:secret|token|passw(?:or)?d|pwd|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|sharedaccesskey|credentials?|auth[_-]?key)[A-Za-z0-9_.-]*';
|
|
9
|
-
|
|
10
|
-
const VALUE = `("[^"]*"|'[^']*'|[^\\s'",;&|}]+)`;
|
|
11
|
-
|
|
12
|
-
const RULES = [
|
|
13
|
-
// A port (`host:8080/…`) is not a password; a password may contain `/`.
|
|
14
|
-
[/\b([a-z][a-z0-9+.-]*:\/\/[^\s:@/?#]+:)(?!\d+(?:[/?#\s]|$))[^\s@]+@/gi, `$1${REDACTED}@`],
|
|
15
|
-
[/\b(authorization\s*[:=]\s*)(?:(bearer|basic|token|digest)\s+)?[^\s'",;]+/gi,
|
|
16
|
-
(_, head, scheme) => `${head}${scheme ? `${scheme} ` : ''}${REDACTED}`],
|
|
17
|
-
// A token carries a digit; "Bearer authentication" is prose.
|
|
18
|
-
[/\b(bearer\s+)(?=[A-Za-z0-9._~+/=-]*\d)[A-Za-z0-9._~+/=-]{8,}/gi, `$1${REDACTED}`],
|
|
19
|
-
// `-u 1000:1000` is a uid:gid, not credentials.
|
|
20
|
-
[/(\s-u\s+|--user[=\s]+)(['"]?)(?!\d+:\d+\b)[^\s:'"]+:[^\s'"]+\2/g, `$1${REDACTED}`],
|
|
21
|
-
[new RegExp(`(["']?)(${SECRET_KEY})\\1(\\s*[:=]\\s*)${VALUE}`, 'gi'),
|
|
22
|
-
(_, quote, key, sep) => `${quote}${key}${quote}${sep}${REDACTED}`],
|
|
23
|
-
[new RegExp(`\\b([A-Z][A-Z0-9_]*_(?:KEY|PASS|PAT|SIG))(\\s*=\\s*)${VALUE}`, 'g'), `$1$2${REDACTED}`],
|
|
24
|
-
[new RegExp(`(--(?:password|passwd|pass|token|secret|api-?key|access-key|auth-token)(?:\\s+|=))${VALUE}`, 'gi'),
|
|
25
|
-
`$1${REDACTED}`],
|
|
26
|
-
[new RegExp(`(\\buser-secrets\\s+set\\s+(?:"[^"]*"|'[^']*'|\\S+)\\s+)${VALUE}`, 'gi'), `$1${REDACTED}`],
|
|
27
|
-
[/([?&](?:sig|access_token|token|api[_-]?key|key|password|secret|code)=)[^&\s'"#]+/gi, `$1${REDACTED}`],
|
|
28
|
-
[/\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})\b/g, REDACTED],
|
|
29
|
-
[/\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}/g, REDACTED],
|
|
30
|
-
[/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g, REDACTED],
|
|
31
|
-
[/\bnpm_[A-Za-z0-9]{36}\b/g, REDACTED],
|
|
32
|
-
[/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, REDACTED],
|
|
33
|
-
[/\bAKIA[0-9A-Z]{16}\b/g, REDACTED],
|
|
34
|
-
[/\bAIza[0-9A-Za-z_-]{35}\b/g, REDACTED],
|
|
35
|
-
[/\beyJ[A-Za-z0-9_-]{5,}\.eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]+/g, REDACTED],
|
|
36
|
-
];
|
|
37
|
-
|
|
38
|
-
/** Non-strings pass through unchanged. */
|
|
39
|
-
export function redactSecrets(text) {
|
|
40
|
-
if (typeof text !== 'string' || text === '') return text;
|
|
41
|
-
let out = text;
|
|
42
|
-
for (const [pattern, replacement] of RULES) out = out.replace(pattern, replacement);
|
|
43
|
-
return out;
|
|
44
|
-
}
|