@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,18 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'fs';
|
|
2
|
-
import { templateSourcePath, writeIfAbsent } from '../../core/templates/template-seed.js';
|
|
3
|
-
import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
|
|
4
|
-
|
|
5
|
-
const FEATURE_PLACEHOLDER = /\{\{FEATURE_NAME\}\}/g;
|
|
6
|
-
|
|
7
|
-
export function planTemplatePath(cwd = process.cwd()) {
|
|
8
|
-
return templateSourcePath('plan', cwd);
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export function renderPlanSkeleton(featureName, cwd = process.cwd()) {
|
|
12
|
-
return readFileSync(planTemplatePath(cwd), 'utf8').replace(FEATURE_PLACEHOLDER, featureName);
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/** @returns {{ path: string, written: boolean }} `written: false` when the file already existed. */
|
|
16
|
-
export function writePlanSkeleton(featureName, cwd = process.cwd()) {
|
|
17
|
-
return writeIfAbsent(getAbsoluteOutputPath(cwd, featureName, 'plan'), renderPlanSkeleton(featureName, cwd));
|
|
18
|
-
}
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
export const MIN_ORPHAN_AGE_MS = 15 * 60 * 1000;
|
|
2
|
-
|
|
3
|
-
const PLAIN_CANDIDATES = new Set(['node', 'dotnet', 'testhost', 'esbuild']);
|
|
4
|
-
const CHROME_NAMES = new Set(['chrome', 'chromium', 'msedge', 'chrome-headless-shell']);
|
|
5
|
-
const BUILD_SERVER_NAMES = new Set(['vbcscompiler', 'msbuild']);
|
|
6
|
-
const BUILD_SERVER_CMD = /vbcscompiler|\/nodemode:\d|msbuild(?:taskhost)?\.dll|razorserver/i;
|
|
7
|
-
const AUTOMATION_CHROME = /--headless|--remote-debugging-pipe|playwright|puppeteer/i;
|
|
8
|
-
const CLAUDE_CLI = /@anthropic-ai[\\/]claude-code/i;
|
|
9
|
-
|
|
10
|
-
export function normalizeCmd(cmd) {
|
|
11
|
-
return String(cmd ?? '').toLowerCase().replace(/\\/g, '/');
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function categorize(proc) {
|
|
15
|
-
const cmd = proc.cmd ?? '';
|
|
16
|
-
if (BUILD_SERVER_NAMES.has(proc.name)) return 'build-server';
|
|
17
|
-
if (proc.name === 'dotnet' && BUILD_SERVER_CMD.test(cmd)) return 'build-server';
|
|
18
|
-
if (CHROME_NAMES.has(proc.name)) {
|
|
19
|
-
return AUTOMATION_CHROME.test(cmd) && !/--type=/.test(cmd) ? 'chrome-headless' : null;
|
|
20
|
-
}
|
|
21
|
-
return PLAIN_CANDIDATES.has(proc.name) ? proc.name : null;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export function isClaudeSession(proc) {
|
|
25
|
-
return proc.name === 'claude' || CLAUDE_CLI.test(proc.cmd ?? '');
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function protectionReason(proc, { mcpTokens, holderPids }) {
|
|
29
|
-
if (holderPids.has(proc.pid)) return 'segura slot do semáforo pesado';
|
|
30
|
-
const cmd = normalizeCmd(proc.cmd);
|
|
31
|
-
if (/graph-refresh\.js/.test(cmd) && /--run\b/.test(cmd)) return 'worker de refresh do grafo';
|
|
32
|
-
const token = mcpTokens.find((t) => cmd.includes(t));
|
|
33
|
-
if (token) return `linha de comando de MCP configurado (${token})`;
|
|
34
|
-
return null;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function classifyProcs(procs, { now = Date.now(), mcpTokens = [], holderPids = [], minAgeMs = MIN_ORPHAN_AGE_MS } = {}) {
|
|
38
|
-
const byPid = new Map(procs.map((p) => [p.pid, p]));
|
|
39
|
-
const tokens = mcpTokens.map((t) => String(t).toLowerCase());
|
|
40
|
-
const holders = new Set(holderPids);
|
|
41
|
-
|
|
42
|
-
const liveParent = (p) => {
|
|
43
|
-
const parent = byPid.get(p.ppid);
|
|
44
|
-
if (!parent) return null;
|
|
45
|
-
if (parent.startedMs !== null && p.startedMs !== null && parent.startedMs > p.startedMs) return null;
|
|
46
|
-
return parent;
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
const rows = [];
|
|
50
|
-
for (const proc of procs) {
|
|
51
|
-
const category = categorize(proc);
|
|
52
|
-
if (!category) continue;
|
|
53
|
-
const orphan = proc.ppid > 4 && liveParent(proc) === null;
|
|
54
|
-
const ageMs = proc.startedMs === null ? null : Math.max(0, now - proc.startedMs);
|
|
55
|
-
const row = {
|
|
56
|
-
pid: proc.pid,
|
|
57
|
-
ppid: proc.ppid,
|
|
58
|
-
name: proc.name,
|
|
59
|
-
category,
|
|
60
|
-
cmd: proc.cmd,
|
|
61
|
-
rssMb: Math.round(proc.rss / (1024 * 1024)),
|
|
62
|
-
startedMs: proc.startedMs,
|
|
63
|
-
ageMs,
|
|
64
|
-
orphan,
|
|
65
|
-
verdict: 'alive-parent',
|
|
66
|
-
reason: null,
|
|
67
|
-
};
|
|
68
|
-
if (orphan) {
|
|
69
|
-
const protectedBy = category === 'build-server' ? null : protectionReason(proc, { mcpTokens: tokens, holderPids: holders });
|
|
70
|
-
if (category === 'build-server') {
|
|
71
|
-
row.verdict = 'build-server';
|
|
72
|
-
row.reason = 'nó de build reutilizável pode servir outra sessão; encerre com `dotnet build-server shutdown` quando ocioso';
|
|
73
|
-
} else if (protectedBy) {
|
|
74
|
-
row.verdict = 'protected';
|
|
75
|
-
row.reason = protectedBy;
|
|
76
|
-
} else if (ageMs === null) {
|
|
77
|
-
row.verdict = 'protected';
|
|
78
|
-
row.reason = 'idade desconhecida';
|
|
79
|
-
} else if (ageMs < minAgeMs) {
|
|
80
|
-
row.verdict = 'protected';
|
|
81
|
-
row.reason = `mais novo que ${Math.round(minAgeMs / 60000)} min`;
|
|
82
|
-
} else {
|
|
83
|
-
row.verdict = 'orphan';
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
rows.push(row);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
const sessions = procs.filter(isClaudeSession).length;
|
|
90
|
-
return { rows, sessions };
|
|
91
|
-
}
|
package/src/lib/procs/list.js
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
import { execFileSync } from 'node:child_process';
|
|
2
|
-
import { readFileSync } from 'node:fs';
|
|
3
|
-
|
|
4
|
-
const PS_PROJECTION = "[pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; name = $_.Name; cmd = $_.CommandLine; rss = [int64]$_.WorkingSetSize; started = if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null } }";
|
|
5
|
-
const PS_PREFIX = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; ';
|
|
6
|
-
|
|
7
|
-
export function defaultProcExec(file, args, { timeout = 30000 } = {}) {
|
|
8
|
-
try {
|
|
9
|
-
const output = execFileSync(file, args, {
|
|
10
|
-
encoding: 'utf8',
|
|
11
|
-
timeout,
|
|
12
|
-
windowsHide: true,
|
|
13
|
-
maxBuffer: 64 * 1024 * 1024,
|
|
14
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
15
|
-
});
|
|
16
|
-
return { code: 0, output };
|
|
17
|
-
} catch (err) {
|
|
18
|
-
return {
|
|
19
|
-
code: err.status ?? 1,
|
|
20
|
-
output: `${err.stdout ?? ''}${err.stderr ?? ''}`,
|
|
21
|
-
missing: err.code === 'ENOENT',
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export function normalizeProcName(name) {
|
|
27
|
-
return String(name ?? '').toLowerCase().replace(/\.exe$/, '');
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function toProc(p) {
|
|
31
|
-
const startedMs = typeof p.startedMs === 'number' ? p.startedMs : p.started ? Date.parse(p.started) : null;
|
|
32
|
-
return {
|
|
33
|
-
pid: Number(p.pid),
|
|
34
|
-
ppid: Number(p.ppid ?? 0),
|
|
35
|
-
name: normalizeProcName(p.name),
|
|
36
|
-
cmd: typeof p.cmd === 'string' && p.cmd.length ? p.cmd : null,
|
|
37
|
-
rss: Number(p.rss ?? 0),
|
|
38
|
-
startedMs: Number.isFinite(startedMs) ? startedMs : null,
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function parseWindowsProcs(text) {
|
|
43
|
-
const trimmed = String(text ?? '').trim();
|
|
44
|
-
if (!trimmed) return [];
|
|
45
|
-
const raw = JSON.parse(trimmed);
|
|
46
|
-
return (Array.isArray(raw) ? raw : [raw]).filter((p) => p && Number.isInteger(p.pid)).map(toProc);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export function parseEtime(etime) {
|
|
50
|
-
const m = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)$/.exec(String(etime).trim());
|
|
51
|
-
if (!m) return null;
|
|
52
|
-
const [, d = 0, h = 0, min, s] = m;
|
|
53
|
-
return ((Number(d) * 24 + Number(h)) * 60 + Number(min)) * 60 + Number(s);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function parsePosixProcs(text, now = Date.now()) {
|
|
57
|
-
const procs = [];
|
|
58
|
-
for (const line of String(text ?? '').split(/\r?\n/)) {
|
|
59
|
-
const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
|
|
60
|
-
if (!m) continue;
|
|
61
|
-
const seconds = parseEtime(m[3]);
|
|
62
|
-
procs.push(toProc({
|
|
63
|
-
pid: Number(m[1]),
|
|
64
|
-
ppid: Number(m[2]),
|
|
65
|
-
name: m[5].split('/').pop(),
|
|
66
|
-
cmd: m[6] || m[5],
|
|
67
|
-
rss: Number(m[4]) * 1024,
|
|
68
|
-
startedMs: seconds === null ? null : now - seconds * 1000,
|
|
69
|
-
}));
|
|
70
|
-
}
|
|
71
|
-
return procs;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function fromFixture(path) {
|
|
75
|
-
const raw = JSON.parse(readFileSync(path, 'utf8').replace(/^/, ''));
|
|
76
|
-
return (Array.isArray(raw) ? raw : []).map(toProc);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function windowsScript(filter) {
|
|
80
|
-
const query = filter ? `Get-CimInstance Win32_Process -Filter "${filter}"` : 'Get-CimInstance Win32_Process';
|
|
81
|
-
return `${PS_PREFIX}${query} | ForEach-Object { ${PS_PROJECTION} } | ConvertTo-Json -Compress`;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const POSIX_COLUMNS = 'pid=,ppid=,etime=,rss=,comm=,args=';
|
|
85
|
-
|
|
86
|
-
function runList({ pid = null, exec, platform, now }) {
|
|
87
|
-
if (platform === 'win32') {
|
|
88
|
-
const filter = pid === null ? '' : `ProcessId=${Number(pid)}`;
|
|
89
|
-
const res = exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', windowsScript(filter)]);
|
|
90
|
-
if (res.code !== 0) return { procs: null, reason: `PowerShell falhou (exit ${res.code})` };
|
|
91
|
-
try {
|
|
92
|
-
return { procs: parseWindowsProcs(res.output), reason: null };
|
|
93
|
-
} catch {
|
|
94
|
-
return { procs: null, reason: 'saída do PowerShell ilegível' };
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
if (platform === 'linux' || platform === 'darwin') {
|
|
98
|
-
const args = pid === null ? ['-eo', POSIX_COLUMNS] : ['-p', String(Number(pid)), '-o', POSIX_COLUMNS];
|
|
99
|
-
const res = exec('ps', args);
|
|
100
|
-
if (res.code !== 0 && pid === null) return { procs: null, reason: `ps falhou (exit ${res.code})` };
|
|
101
|
-
return { procs: parsePosixProcs(res.output, now), reason: null };
|
|
102
|
-
}
|
|
103
|
-
return { procs: null, reason: `plataforma ${platform} sem listador de processos` };
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
export function listProcesses({ exec = defaultProcExec, platform = process.platform, now = Date.now(), env = process.env } = {}) {
|
|
107
|
-
if (env.MORPH_PROCS_FIXTURE) {
|
|
108
|
-
try {
|
|
109
|
-
return { procs: fromFixture(env.MORPH_PROCS_FIXTURE), reason: null };
|
|
110
|
-
} catch {
|
|
111
|
-
return { procs: null, reason: 'MORPH_PROCS_FIXTURE ilegível' };
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
return runList({ exec, platform, now });
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export function readProcess(pid, { exec = defaultProcExec, platform = process.platform, now = Date.now(), env = process.env } = {}) {
|
|
118
|
-
if (env.MORPH_PROCS_FIXTURE) {
|
|
119
|
-
const { procs } = listProcesses({ env });
|
|
120
|
-
return procs?.find((p) => p.pid === pid) ?? null;
|
|
121
|
-
}
|
|
122
|
-
const { procs } = runList({ pid, exec, platform, now });
|
|
123
|
-
return procs?.find((p) => p.pid === pid) ?? null;
|
|
124
|
-
}
|
package/src/lib/procs/prune.js
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { listProcesses, readProcess } from './list.js';
|
|
2
|
-
|
|
3
|
-
export function descendantsOf(pid, procs) {
|
|
4
|
-
const found = [];
|
|
5
|
-
const queue = [pid];
|
|
6
|
-
while (queue.length) {
|
|
7
|
-
const parent = queue.shift();
|
|
8
|
-
for (const child of procs.filter((p) => p.ppid === parent && !found.includes(p.pid))) {
|
|
9
|
-
found.push(child.pid);
|
|
10
|
-
queue.push(child.pid);
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
return found;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function stopTree(pid, { list = listProcesses, kill = (target) => process.kill(target) } = {}) {
|
|
17
|
-
const { procs } = list();
|
|
18
|
-
for (const target of [...descendantsOf(pid, procs ?? []).reverse(), pid]) {
|
|
19
|
-
try {
|
|
20
|
-
kill(target);
|
|
21
|
-
} catch {}
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function pruneOrphans(rows, { read = readProcess, kill = (pid) => process.kill(pid) } = {}) {
|
|
26
|
-
const results = [];
|
|
27
|
-
for (const row of rows) {
|
|
28
|
-
if (row.verdict !== 'orphan') continue;
|
|
29
|
-
const fresh = read(row.pid);
|
|
30
|
-
const base = { pid: row.pid, name: row.name };
|
|
31
|
-
if (!fresh) {
|
|
32
|
-
results.push({ ...base, outcome: 'skipped', reason: 'já encerrado' });
|
|
33
|
-
continue;
|
|
34
|
-
}
|
|
35
|
-
if (fresh.startedMs !== row.startedMs || fresh.cmd !== row.cmd || fresh.name !== row.name) {
|
|
36
|
-
results.push({ ...base, outcome: 'skipped', reason: 'o PID foi reaproveitado por outro processo' });
|
|
37
|
-
continue;
|
|
38
|
-
}
|
|
39
|
-
try {
|
|
40
|
-
kill(row.pid);
|
|
41
|
-
results.push({ ...base, outcome: 'killed' });
|
|
42
|
-
} catch (err) {
|
|
43
|
-
results.push({ ...base, outcome: 'failed', reason: err?.code ?? err?.message ?? 'erro desconhecido' });
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return results;
|
|
47
|
-
}
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { homedir, totalmem } from 'node:os';
|
|
4
|
-
|
|
5
|
-
const GB = 1024 ** 3;
|
|
6
|
-
|
|
7
|
-
export function parseWslConfig(text) {
|
|
8
|
-
const sections = {};
|
|
9
|
-
let current = null;
|
|
10
|
-
for (const raw of String(text).replace(/^/, '').split(/\r?\n/)) {
|
|
11
|
-
const line = raw.trim();
|
|
12
|
-
if (!line || line.startsWith('#') || line.startsWith(';')) continue;
|
|
13
|
-
const header = /^\[([^\]]+)\]$/.exec(line);
|
|
14
|
-
if (header) {
|
|
15
|
-
current = header[1].trim().toLowerCase();
|
|
16
|
-
sections[current] ??= {};
|
|
17
|
-
continue;
|
|
18
|
-
}
|
|
19
|
-
const eq = line.indexOf('=');
|
|
20
|
-
if (eq < 0 || current === null) continue;
|
|
21
|
-
sections[current][line.slice(0, eq).trim().toLowerCase()] = line.slice(eq + 1).trim();
|
|
22
|
-
}
|
|
23
|
-
return sections;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export function suggestedMemoryGb(totalMemBytes) {
|
|
27
|
-
return Math.max(4, Math.floor((totalMemBytes / GB) * 0.4));
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function suggestion({ memory, reclaim, totalMemBytes }) {
|
|
31
|
-
const lines = [];
|
|
32
|
-
if (!memory) lines.push('[wsl2]', `memory=${suggestedMemoryGb(totalMemBytes)}GB`);
|
|
33
|
-
if (!reclaim) lines.push('[experimental]', 'autoMemoryReclaim=gradual');
|
|
34
|
-
return lines.length ? lines.join('\n') : null;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function inspectWslConfig({
|
|
38
|
-
home = homedir(),
|
|
39
|
-
platform = process.platform,
|
|
40
|
-
totalMemBytes = totalmem(),
|
|
41
|
-
exists = existsSync,
|
|
42
|
-
read = (p) => readFileSync(p, 'utf8'),
|
|
43
|
-
} = {}) {
|
|
44
|
-
if (platform !== 'win32') return { status: 'skip', reason: 'WSL só existe no Windows' };
|
|
45
|
-
const path = join(home, '.wslconfig');
|
|
46
|
-
if (!exists(path)) {
|
|
47
|
-
return {
|
|
48
|
-
status: 'missing',
|
|
49
|
-
path,
|
|
50
|
-
memory: null,
|
|
51
|
-
autoMemoryReclaim: null,
|
|
52
|
-
suggestion: suggestion({ memory: null, reclaim: null, totalMemBytes }),
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
let sections;
|
|
56
|
-
try {
|
|
57
|
-
sections = parseWslConfig(read(path));
|
|
58
|
-
} catch {
|
|
59
|
-
return { status: 'skip', reason: `${path} ilegível` };
|
|
60
|
-
}
|
|
61
|
-
const memory = sections.wsl2?.memory ?? null;
|
|
62
|
-
const autoMemoryReclaim = sections.experimental?.automemoryreclaim ?? null;
|
|
63
|
-
return {
|
|
64
|
-
status: 'present',
|
|
65
|
-
path,
|
|
66
|
-
memory,
|
|
67
|
-
autoMemoryReclaim,
|
|
68
|
-
suggestion: suggestion({ memory, reclaim: autoMemoryReclaim, totalMemBytes }),
|
|
69
|
-
};
|
|
70
|
-
}
|
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
// Paths under the system temp dir are never registered: test suites run `init`/`update` there by the
|
|
2
|
-
// hundred, through spawned CLIs that keep the real home. The home is read at call time so isolating it works.
|
|
3
|
-
|
|
4
|
-
import { existsSync, readFileSync, readdirSync } from 'fs';
|
|
5
|
-
import { homedir, tmpdir } from 'os';
|
|
6
|
-
import { join, resolve, basename, dirname } from 'path';
|
|
7
|
-
import { atomicWriteJson } from '../../core/state/state-manager.js';
|
|
8
|
-
import { canonicalPath, isInside } from '../tasks/test-runner.js';
|
|
9
|
-
import { WORKTREE_DIR_NAMES } from '../worktree/dirs.js';
|
|
10
|
-
|
|
11
|
-
export const REGISTRY_VERSION = 1;
|
|
12
|
-
|
|
13
|
-
export function registryPath() {
|
|
14
|
-
return process.env.MORPH_PROJECTS_REGISTRY || join(homedir(), '.morph-spec', 'projects.json');
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/** One spelling per directory: canonical, forward slashes (the registry is read back on any OS). */
|
|
18
|
-
export function projectKey(dir) {
|
|
19
|
-
return canonicalPath(resolve(dir)).replace(/\\/g, '/');
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const sameDir = (a, b) => (process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
23
|
-
|
|
24
|
-
export function isMorphProject(dir) {
|
|
25
|
-
return existsSync(join(dir, '.morph', 'config', 'config.json'));
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** A worktree checkout is part of its repo's project, never a project of its own. */
|
|
29
|
-
function insideWorktreeContainer(dir) {
|
|
30
|
-
if (WORKTREE_DIR_NAMES.includes(basename(dirname(dir)))) return true;
|
|
31
|
-
try {
|
|
32
|
-
return /[\\/]\.git[\\/]worktrees[\\/][^\\/]+\s*$/.test(readFileSync(join(dir, '.git'), 'utf8'));
|
|
33
|
-
} catch {
|
|
34
|
-
return false;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function projectName(dir) {
|
|
39
|
-
try {
|
|
40
|
-
const config = JSON.parse(readFileSync(join(dir, '.morph', 'config', 'config.json'), 'utf8'));
|
|
41
|
-
const name = config?.project?.name;
|
|
42
|
-
// Some configs carry the project path as its name; the folder reads better.
|
|
43
|
-
return typeof name === 'string' && name.trim() && !/[\\/]/.test(name) ? name.trim() : basename(dir);
|
|
44
|
-
} catch {
|
|
45
|
-
return basename(dir);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Folders that were deleted or lost `.morph/` drop out on read. */
|
|
50
|
-
export function readRegistry() {
|
|
51
|
-
let data = null;
|
|
52
|
-
try {
|
|
53
|
-
const path = registryPath();
|
|
54
|
-
if (existsSync(path)) data = JSON.parse(readFileSync(path, 'utf8'));
|
|
55
|
-
} catch {}
|
|
56
|
-
const projects = Array.isArray(data?.projects) ? data.projects : [];
|
|
57
|
-
return {
|
|
58
|
-
version: REGISTRY_VERSION,
|
|
59
|
-
projects: projects.filter((p) => typeof p?.dir === 'string' && isMorphProject(p.dir)),
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function write(projects) {
|
|
64
|
-
atomicWriteJson(registryPath(), { version: REGISTRY_VERSION, projects });
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Idempotent, never throws; `tempRoot` is the test seam for the never-registered folder. */
|
|
68
|
-
export function registerProject(dir, source, { tempRoot = tmpdir() } = {}) {
|
|
69
|
-
try {
|
|
70
|
-
const key = projectKey(dir);
|
|
71
|
-
if (isInside(canonicalPath(key), canonicalPath(tempRoot))) return false;
|
|
72
|
-
if (!isMorphProject(key) || insideWorktreeContainer(key)) return false;
|
|
73
|
-
const now = new Date().toISOString();
|
|
74
|
-
const { projects } = readRegistry();
|
|
75
|
-
const found = projects.find((p) => sameDir(p.dir, key));
|
|
76
|
-
if (found) {
|
|
77
|
-
found.lastSeenAt = now;
|
|
78
|
-
found.name = projectName(key);
|
|
79
|
-
} else {
|
|
80
|
-
projects.push({ dir: key, name: projectName(key), addedAt: now, lastSeenAt: now, source });
|
|
81
|
-
}
|
|
82
|
-
write(projects);
|
|
83
|
-
return true;
|
|
84
|
-
} catch {
|
|
85
|
-
return false;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** Never throws; the project's files are not touched. */
|
|
90
|
-
export function unregisterProject(dir) {
|
|
91
|
-
try {
|
|
92
|
-
const key = projectKey(dir);
|
|
93
|
-
const { projects } = readRegistry();
|
|
94
|
-
const kept = projects.filter((p) => !sameDir(p.dir, key));
|
|
95
|
-
if (kept.length !== projects.length) write(kept);
|
|
96
|
-
return kept.length !== projects.length;
|
|
97
|
-
} catch {
|
|
98
|
-
return false;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/** Unregistered projects one level under each root: deeper would walk node_modules and worktrees. */
|
|
103
|
-
export function discoverProjects(roots) {
|
|
104
|
-
const registered = readRegistry().projects.map((p) => p.dir);
|
|
105
|
-
const out = [];
|
|
106
|
-
const seen = new Set();
|
|
107
|
-
for (const root of roots) {
|
|
108
|
-
let entries = [];
|
|
109
|
-
try { entries = readdirSync(root, { withFileTypes: true }); } catch { continue; }
|
|
110
|
-
for (const e of entries) {
|
|
111
|
-
if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules') continue;
|
|
112
|
-
const dir = join(root, e.name);
|
|
113
|
-
if (!isMorphProject(dir)) continue;
|
|
114
|
-
const key = projectKey(dir);
|
|
115
|
-
if (seen.has(key.toLowerCase()) || registered.some((r) => sameDir(r, key))) continue;
|
|
116
|
-
seen.add(key.toLowerCase());
|
|
117
|
-
out.push({ dir: key, name: projectName(key) });
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
return out.sort((a, b) => a.name.localeCompare(b.name));
|
|
121
|
-
}
|
package/src/lib/recap/piper.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { spawnSync } from 'child_process';
|
|
2
|
-
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
|
|
3
|
-
import { homedir, tmpdir } from 'os';
|
|
4
|
-
import { join } from 'path';
|
|
5
|
-
import { findFirstOnPath } from '../../../framework/hooks/shared/morph-cli.js';
|
|
6
|
-
|
|
7
|
-
export const PIPER_MODEL_DIR = join(homedir(), '.morph-spec', 'piper');
|
|
8
|
-
|
|
9
|
-
/** The piper binary and a voice model, or why narration falls back to the system voice. */
|
|
10
|
-
export function resolvePiper(env = process.env) {
|
|
11
|
-
const bin = findFirstOnPath(process.platform === 'win32' ? ['piper.exe'] : ['piper'], env);
|
|
12
|
-
if (!bin) return { ok: false, reason: 'piper fora do PATH (pip install piper-tts)' };
|
|
13
|
-
const model = env.MORPH_PIPER_MODEL
|
|
14
|
-
|| [join(PIPER_MODEL_DIR, 'pt_BR-faber-medium.onnx')].find((m) => existsSync(m));
|
|
15
|
-
if (!model || !existsSync(model)) {
|
|
16
|
-
return { ok: false, reason: `sem modelo de voz: baixe pt_BR-faber-medium.onnx (+ .onnx.json) para ${PIPER_MODEL_DIR}, ou aponte MORPH_PIPER_MODEL` };
|
|
17
|
-
}
|
|
18
|
-
return { ok: true, bin, model };
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** `{ [sceneId]: dataUri }`, or null when piper fails on any scene: half-narrated is worse than the system voice. */
|
|
22
|
-
export function narrateWithPiper(scenes, piper, { run = spawnSync } = {}) {
|
|
23
|
-
const dir = mkdtempSync(join(tmpdir(), 'morph-recap-'));
|
|
24
|
-
try {
|
|
25
|
-
const audio = {};
|
|
26
|
-
for (const s of scenes) {
|
|
27
|
-
const out = join(dir, `${s.id}.wav`);
|
|
28
|
-
const r = run(piper.bin, ['--model', piper.model, '--output_file', out], { input: s.narration, windowsHide: true, stdio: ['pipe', 'ignore', 'pipe'] });
|
|
29
|
-
if (r.status !== 0 || !existsSync(out)) return null;
|
|
30
|
-
audio[s.id] = `data:audio/wav;base64,${readFileSync(out).toString('base64')}`;
|
|
31
|
-
}
|
|
32
|
-
return audio;
|
|
33
|
-
} finally {
|
|
34
|
-
rmSync(dir, { recursive: true, force: true });
|
|
35
|
-
}
|
|
36
|
-
}
|