@aibyzero/cm-workflow 0.10.5
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/.codex-plugin/plugin.json +30 -0
- package/AGENTS.md +74 -0
- package/CONTRIBUTING.md +62 -0
- package/LICENSE +21 -0
- package/README.md +263 -0
- package/SECURITY.md +49 -0
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/VERSION +1 -0
- package/agents/cm-backend-agent.md +34 -0
- package/agents/cm-contract-agent.md +34 -0
- package/agents/cm-database-agent.md +34 -0
- package/agents/cm-frontend-agent.md +33 -0
- package/agents/cm-miniprogram-agent.md +33 -0
- package/agents/cm-ui-agent.md +34 -0
- package/assets/docs/command-picker-mobile.svg +56 -0
- package/assets/docs/command-picker.svg +56 -0
- package/assets/docs/user-guide-hero-mobile.svg +35 -0
- package/assets/docs/user-guide-hero.svg +36 -0
- package/assets/readme/delivery-flow.svg +86 -0
- package/assets/readme/hero.svg +77 -0
- package/assets/readme/recovery-record.svg +73 -0
- package/assets/readme/test-evidence.svg +64 -0
- package/compat/claude-commands/cm-ai.md +3 -0
- package/compat/claude-commands/cm-check.md +3 -0
- package/compat/claude-commands/cm-fix.md +3 -0
- package/compat/claude-commands/cm-idea.md +3 -0
- package/compat/claude-commands/cm-init.md +3 -0
- package/compat/claude-commands/cm-prd.md +3 -0
- package/compat/claude-commands/cm-refactor.md +3 -0
- package/compat/claude-commands/cm-test.md +3 -0
- package/docs/architecture.md +155 -0
- package/docs/fixes/.reviews/fix-cancel-throw-T-FIX-cancel-throw-a1-handoff.json +57 -0
- package/docs/fixes/.reviews/fix-cancel-throw-T-FIX-cancel-throw-a2-handoff.json +58 -0
- package/docs/fixes/.reviews/fix-cancel-throw-T-FIX-cancel-throw-r1.md +121 -0
- package/docs/fixes/.reviews/fix-cancel-throw-v2-T-FIX-cancel-throw-v2-a1-handoff.json +56 -0
- package/docs/fixes/.reviews/fix-cancel-throw-v2-T-FIX-cancel-throw-v2-r1.md +100 -0
- package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-a1-handoff.json +61 -0
- package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-a2-handoff.json +63 -0
- package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-r1.md +58 -0
- package/docs/fixes/.reviews/fix-cm-js-n1n2-admission-successor-T-FIX-cm-js-n1n2-admission-successor-r2.md +55 -0
- package/docs/fixes/.reviews/fix-f01-dual-failure-terminal-T-FIX-f01-dual-failure-terminal-a1-handoff.json +65 -0
- package/docs/fixes/.reviews/fix-f01-dual-failure-terminal-T-FIX-f01-dual-failure-terminal-r1.md +88 -0
- package/docs/fixes/.reviews/fix-manifest-runtime-checkbox-drift-r1.md +33 -0
- package/docs/fixes/.reviews/fix-manifest-runtime-checkbox-drift-r2.md +31 -0
- package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-a1-handoff.json +56 -0
- package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-a2-handoff.json +85 -0
- package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-r1.md +53 -0
- package/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-r2.md +80 -0
- package/docs/fixes/.reviews/fix-review-evidence-scope-honesty-T-FIX-review-evidence-scope-honesty-a1-handoff.json +35 -0
- package/docs/fixes/.reviews/fix-review-evidence-scope-honesty-T-FIX-review-evidence-scope-honesty-r1.md +33 -0
- package/docs/fixes/.reviews/fix-windows-cp1252-log-output-r1.md +30 -0
- package/docs/fixes/.reviews/fix-windows-cp1252-log-output-r2.md +16 -0
- package/docs/fixes/.reviews/openai-compatible-depth-fixture-T-FIX-openai-compatible-depth-fixture-a1-handoff.json +40 -0
- package/docs/fixes/.reviews/openai-compatible-depth-fixture-T-FIX-openai-compatible-depth-fixture-r1.md +30 -0
- package/docs/fixes/20260729-windows-cp1252-log-output.md +65 -0
- package/docs/fixes/20260804-manifest-runtime-checkbox-drift.md +67 -0
- package/docs/fixes/20260806-model-call-boundary-identity.md +80 -0
- package/docs/fixes/20260807-prelanding-integrity.md +58 -0
- package/docs/fixes/20260826-openai-compatible-depth-fixture.md +39 -0
- package/docs/fixes/20260903-cm-js-n1n2-admission-r1.md +64 -0
- package/docs/fixes/20260903-cm-js-n1n2-admission-successor.md +83 -0
- package/docs/fixes/20260903-s4c1b-v3-cancel-throw.md +89 -0
- package/docs/fixes/20260904-f01-codex-dual-failure-terminal.md +89 -0
- package/docs/fixes/20260907-wip-triage-log.md +44 -0
- package/docs/installation.md +202 -0
- package/docs/js-workflow-control.md +1010 -0
- package/docs/sample-prd/prd-funding-rate-alert.md +42 -0
- package/docs/sample-specs/docs//351/234/200/346/261/202/347/244/272/344/276/213.md +24 -0
- package/docs/user-guide.md +526 -0
- package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/README.md +19 -0
- package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.excalidraw +3650 -0
- package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.mp4 +0 -0
- package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.png +0 -0
- package/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.spec.json +223 -0
- package/install-codex.sh +184 -0
- package/install.ps1 +206 -0
- package/install.sh +244 -0
- package/package.json +58 -0
- package/runtime/external-expert.md +302 -0
- package/runtime/js/cm-ai/accepted-fix.mjs +28 -0
- package/runtime/js/cm-ai/claude-developer-adapter.mjs +6 -0
- package/runtime/js/cm-ai/claude-review-adapter.mjs +16 -0
- package/runtime/js/cm-ai/claude-review-stream.mjs +53 -0
- package/runtime/js/cm-ai/claude-tool-preview.mjs +107 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +353 -0
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +217 -0
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +538 -0
- package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +119 -0
- package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +172 -0
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +320 -0
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +107 -0
- package/runtime/js/cm-ai/code-projects.mjs +85 -0
- package/runtime/js/cm-ai/codex-config.mjs +48 -0
- package/runtime/js/cm-ai/codex-developer-adapter.mjs +5 -0
- package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +6 -0
- package/runtime/js/cm-ai/codex-developer-output.schema.json +37 -0
- package/runtime/js/cm-ai/codex-review-adapter.mjs +73 -0
- package/runtime/js/cm-ai/contracts.mjs +156 -0
- package/runtime/js/cm-ai/developer-adapter.mjs +93 -0
- package/runtime/js/cm-ai/durable-runner-state.mjs +504 -0
- package/runtime/js/cm-ai/effect-contract.mjs +102 -0
- package/runtime/js/cm-ai/execution-platform.mjs +7 -0
- package/runtime/js/cm-ai/execution-store.mjs +211 -0
- package/runtime/js/cm-ai/fix-code-association.mjs +40 -0
- package/runtime/js/cm-ai/gate-bridge.mjs +25 -0
- package/runtime/js/cm-ai/host-bootstrap.mjs +170 -0
- package/runtime/js/cm-ai/host-check.mjs +89 -0
- package/runtime/js/cm-ai/host-conversation-execution.mjs +125 -0
- package/runtime/js/cm-ai/host-documentation.mjs +40 -0
- package/runtime/js/cm-ai/host-handoff.mjs +71 -0
- package/runtime/js/cm-ai/host-project-execution.mjs +58 -0
- package/runtime/js/cm-ai/host-qa-executor.mjs +238 -0
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +131 -0
- package/runtime/js/cm-ai/host-qa-fix.mjs +30 -0
- package/runtime/js/cm-ai/host-qa-policy.mjs +70 -0
- package/runtime/js/cm-ai/host-review-authority.mjs +36 -0
- package/runtime/js/cm-ai/host-review-file.mjs +56 -0
- package/runtime/js/cm-ai/host-role-routing.mjs +41 -0
- package/runtime/js/cm-ai/host-session.mjs +96 -0
- package/runtime/js/cm-ai/host-tool-bridge.mjs +53 -0
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +45 -0
- package/runtime/js/cm-ai/host.mjs +20 -0
- package/runtime/js/cm-ai/index.mjs +7 -0
- package/runtime/js/cm-ai/provider-review-observation.mjs +86 -0
- package/runtime/js/cm-ai/qa-fix-definition.mjs +21 -0
- package/runtime/js/cm-ai/review-evidence-file.mjs +38 -0
- package/runtime/js/cm-ai/review-package.mjs +426 -0
- package/runtime/js/cm-ai/review-result.schema.json +40 -0
- package/runtime/js/cm-ai/review-runner.mjs +35 -0
- package/runtime/js/cm-ai/task-commit-codec.mjs +54 -0
- package/runtime/js/cm-ai/task-commit.mjs +201 -0
- package/runtime/js/cm-ai/task-owner.mjs +97 -0
- package/runtime/js/cm-ai/task-runner.mjs +766 -0
- package/runtime/js/cm-ai/tool-preview.mjs +205 -0
- package/runtime/js/cm-ai/worker-claude.mjs +104 -0
- package/runtime/js/cm-ai/worker-codex-developer.mjs +124 -0
- package/runtime/js/cm-ai/worker-codex.mjs +143 -0
- package/runtime/js/cm-check/host.mjs +101 -0
- package/runtime/js/cm-fix/baseline.mjs +70 -0
- package/runtime/js/cm-fix/cause-evidence.mjs +24 -0
- package/runtime/js/cm-fix/cause-invocation.mjs +40 -0
- package/runtime/js/cm-fix/cause-package.mjs +68 -0
- package/runtime/js/cm-fix/dossier.mjs +140 -0
- package/runtime/js/cm-fix/execution.mjs +1549 -0
- package/runtime/js/cm-fix/final-review-evidence.mjs +20 -0
- package/runtime/js/cm-fix/final-review.mjs +156 -0
- package/runtime/js/cm-fix/finish.mjs +124 -0
- package/runtime/js/cm-fix/handoff.mjs +64 -0
- package/runtime/js/cm-fix/host-review.mjs +38 -0
- package/runtime/js/cm-fix/host.mjs +96 -0
- package/runtime/js/cm-fix/investigation.mjs +25 -0
- package/runtime/js/cm-fix/layout.mjs +17 -0
- package/runtime/js/cm-fix/learning-writeback.mjs +86 -0
- package/runtime/js/cm-fix/learning.mjs +31 -0
- package/runtime/js/cm-fix/metrics.mjs +75 -0
- package/runtime/js/cm-fix/progress.mjs +64 -0
- package/runtime/js/cm-fix/protected-edits.mjs +95 -0
- package/runtime/js/cm-fix/qa-source.mjs +58 -0
- package/runtime/js/cm-fix/red-test.mjs +92 -0
- package/runtime/js/cm-fix/regression-evidence.mjs +64 -0
- package/runtime/js/cm-fix/regression.mjs +41 -0
- package/runtime/js/cm-fix/repair.mjs +95 -0
- package/runtime/js/cm-fix/reproduce.mjs +54 -0
- package/runtime/js/cm-fix/retrospective.mjs +41 -0
- package/runtime/js/cm-fix/review-baseline.mjs +47 -0
- package/runtime/js/cm-fix/start.mjs +49 -0
- package/runtime/js/cm-fix/test-author.mjs +63 -0
- package/runtime/js/cm-fix/visual.mjs +72 -0
- package/runtime/js/cm-fix/walkthrough.mjs +126 -0
- package/runtime/js/cm-idea/session.mjs +79 -0
- package/runtime/js/cm-init/draft-generation.mjs +66 -0
- package/runtime/js/cm-init/draft-inspection.mjs +70 -0
- package/runtime/js/cm-init/project-analysis.mjs +60 -0
- package/runtime/js/cm-init/project-scan.mjs +55 -0
- package/runtime/js/cm-init/review-evidence.mjs +80 -0
- package/runtime/js/cm-prd/accepted-design.mjs +46 -0
- package/runtime/js/cm-prd/analysis.mjs +260 -0
- package/runtime/js/cm-prd/change.mjs +268 -0
- package/runtime/js/cm-prd/correction-check.mjs +49 -0
- package/runtime/js/cm-prd/design-risk.mjs +30 -0
- package/runtime/js/cm-prd/disposition-plan.mjs +33 -0
- package/runtime/js/cm-prd/draft-save.mjs +122 -0
- package/runtime/js/cm-prd/draft.mjs +70 -0
- package/runtime/js/cm-prd/materials.mjs +48 -0
- package/runtime/js/cm-prd/review-correction.mjs +158 -0
- package/runtime/js/cm-prd/review-disposition.mjs +96 -0
- package/runtime/js/cm-prd/review-findings.mjs +36 -0
- package/runtime/js/cm-prd/review-host.mjs +48 -0
- package/runtime/js/cm-prd/review-preparation.mjs +49 -0
- package/runtime/js/cm-prd/review-publication.mjs +56 -0
- package/runtime/js/cm-prd/self-check.mjs +75 -0
- package/runtime/js/cm-prd/session.mjs +74 -0
- package/runtime/js/cm-prd/summary.mjs +133 -0
- package/runtime/js/cm-refactor/host.mjs +2 -0
- package/runtime/js/cm-refactor/records.mjs +86 -0
- package/runtime/js/cm-refactor/workflow.mjs +478 -0
- package/runtime/js/cm-test/declared-command.mjs +32 -0
- package/runtime/js/cm-test/host.mjs +319 -0
- package/runtime/js/cm-test/logic-results.mjs +39 -0
- package/runtime/js/cm-test/recovery.mjs +58 -0
- package/runtime/js/cm-test/session.mjs +56 -0
- package/runtime/js/cm-test/source-snapshot.mjs +136 -0
- package/runtime/logging.md +207 -0
- package/runtime/model-efficiency.md +201 -0
- package/runtime/orchestration.md +113 -0
- package/runtime/project-context.md +43 -0
- package/runtime/project-learning.md +49 -0
- package/runtime/review.md +140 -0
- package/runtime/steelman-review.md +111 -0
- package/runtime/task-gates.md +283 -0
- package/runtime/task-handoff.schema.json +103 -0
- package/runtime/test-contract.md +212 -0
- package/runtime/workflow-config.md +118 -0
- package/runtime/workflow-routing.md +82 -0
- package/scripts/cm-ai-admission.mjs +50 -0
- package/scripts/cm-ai-admission.test.mjs +38 -0
- package/scripts/cm-ai-batch-host.mjs +77 -0
- package/scripts/cm-ai-batch-host.test.mjs +155 -0
- package/scripts/cm-ai-batch-run.mjs +136 -0
- package/scripts/cm-ai-batch-run.test.mjs +128 -0
- package/scripts/cm-ai-bootstrap.test.mjs +228 -0
- package/scripts/cm-ai-fix-integration.test.mjs +233 -0
- package/scripts/cm-ai-host.mjs +175 -0
- package/scripts/cm-ai-host.test.mjs +368 -0
- package/scripts/cm-ai-multi-root.test.mjs +289 -0
- package/scripts/cm-ai-nested-execution.test.mjs +313 -0
- package/scripts/cm-ai-run.mjs +293 -0
- package/scripts/cm-ai-run.test.mjs +336 -0
- package/scripts/cm-check-entry.mjs +120 -0
- package/scripts/cm-check-host.mjs +29 -0
- package/scripts/cm-check-host.test.mjs +71 -0
- package/scripts/cm-check-runtime.ps1 +69 -0
- package/scripts/cm-check-runtime.sh +910 -0
- package/scripts/cm-claude-probe.test.mjs +54 -0
- package/scripts/cm-claude-review-stream.test.mjs +45 -0
- package/scripts/cm-claude-worker.test.mjs +92 -0
- package/scripts/cm-codex-developer-adapter.test.mjs +85 -0
- package/scripts/cm-codex-developer-worker.test.mjs +128 -0
- package/scripts/cm-codex-review-progress.test.mjs +96 -0
- package/scripts/cm-execution-platform.test.mjs +47 -0
- package/scripts/cm-fix-cause-invocation.test.mjs +72 -0
- package/scripts/cm-fix-cause-package.test.mjs +68 -0
- package/scripts/cm-fix-code-association.test.mjs +55 -0
- package/scripts/cm-fix-entry.mjs +132 -0
- package/scripts/cm-fix-execution.test.mjs +63 -0
- package/scripts/cm-fix-final-review.test.mjs +124 -0
- package/scripts/cm-fix-host-review-assembly.test.mjs +34 -0
- package/scripts/cm-fix-host-review.test.mjs +261 -0
- package/scripts/cm-fix-host-sequence.test.mjs +26 -0
- package/scripts/cm-fix-host.mjs +89 -0
- package/scripts/cm-fix-host.test.mjs +105 -0
- package/scripts/cm-fix-learning-writeback.test.mjs +73 -0
- package/scripts/cm-fix-learning.test.mjs +66 -0
- package/scripts/cm-fix-metrics.test.mjs +58 -0
- package/scripts/cm-fix-no-existing-tests.test.mjs +92 -0
- package/scripts/cm-fix-observation-dossier.test.mjs +452 -0
- package/scripts/cm-fix-progress.test.mjs +45 -0
- package/scripts/cm-fix-protected-edits.test.mjs +54 -0
- package/scripts/cm-fix-qa-source.test.mjs +206 -0
- package/scripts/cm-fix-red-owner.test.mjs +143 -0
- package/scripts/cm-fix-red-test.test.mjs +38 -0
- package/scripts/cm-fix-regression.test.mjs +57 -0
- package/scripts/cm-fix-repair-owner.test.mjs +370 -0
- package/scripts/cm-fix-repair.test.mjs +68 -0
- package/scripts/cm-fix-reproduce.test.mjs +31 -0
- package/scripts/cm-fix-retrospective.test.mjs +46 -0
- package/scripts/cm-fix-review-baseline.test.mjs +54 -0
- package/scripts/cm-fix-review-recovery.test.mjs +197 -0
- package/scripts/cm-fix-test-author.test.mjs +105 -0
- package/scripts/cm-fix-visual-bare.test.mjs +171 -0
- package/scripts/cm-fix-walkthrough.test.mjs +45 -0
- package/scripts/cm-host-check.test.mjs +113 -0
- package/scripts/cm-host-documentation.test.mjs +45 -0
- package/scripts/cm-host-handoff.test.mjs +58 -0
- package/scripts/cm-host-qa-executor.test.mjs +156 -0
- package/scripts/cm-host-qa-policy.test.mjs +59 -0
- package/scripts/cm-host-review-authority.test.mjs +60 -0
- package/scripts/cm-host-role-routing.test.mjs +33 -0
- package/scripts/cm-idea-entry.mjs +104 -0
- package/scripts/cm-idea-host.mjs +144 -0
- package/scripts/cm-idea-host.test.mjs +75 -0
- package/scripts/cm-idea-recovery.test.mjs +90 -0
- package/scripts/cm-init-analysis-host.test.mjs +50 -0
- package/scripts/cm-init-draft-generation.test.mjs +52 -0
- package/scripts/cm-init-draft-inspection.test.mjs +41 -0
- package/scripts/cm-init-entry.mjs +170 -0
- package/scripts/cm-init-host.mjs +284 -0
- package/scripts/cm-init-host.test.mjs +231 -0
- package/scripts/cm-init-project-analysis.test.mjs +47 -0
- package/scripts/cm-init-project-scan.test.mjs +41 -0
- package/scripts/cm-init-revision-host.test.mjs +61 -0
- package/scripts/cm-init-session.test.mjs +122 -0
- package/scripts/cm-log-event.mjs +538 -0
- package/scripts/cm-log-event.py +133 -0
- package/scripts/cm-log-event.test.mjs +70 -0
- package/scripts/cm-openai-compatible-call.py +661 -0
- package/scripts/cm-prd-analysis.test.mjs +67 -0
- package/scripts/cm-prd-completion.test.mjs +190 -0
- package/scripts/cm-prd-design-phase.test.mjs +296 -0
- package/scripts/cm-prd-draft-save.test.mjs +63 -0
- package/scripts/cm-prd-draft.test.mjs +39 -0
- package/scripts/cm-prd-entry.mjs +245 -0
- package/scripts/cm-prd-host.mjs +273 -0
- package/scripts/cm-prd-host.test.mjs +169 -0
- package/scripts/cm-prd-materials.test.mjs +41 -0
- package/scripts/cm-prd-review-claim.test.mjs +42 -0
- package/scripts/cm-prd-review-disposition.test.mjs +196 -0
- package/scripts/cm-prd-review-gate.mjs +194 -0
- package/scripts/cm-prd-review-gate.py +26 -0
- package/scripts/cm-prd-review-host.test.mjs +30 -0
- package/scripts/cm-prd-review-preparation.test.mjs +69 -0
- package/scripts/cm-prd-review-publication.test.mjs +95 -0
- package/scripts/cm-prd-revision.test.mjs +32 -0
- package/scripts/cm-prd-self-check.test.mjs +23 -0
- package/scripts/cm-prd-sources.test.mjs +76 -0
- package/scripts/cm-prd-timing.py +272 -0
- package/scripts/cm-refactor-entry.mjs +145 -0
- package/scripts/cm-refactor-host.mjs +26 -0
- package/scripts/cm-refactor-host.test.mjs +201 -0
- package/scripts/cm-review-dependency-snapshot.test.mjs +67 -0
- package/scripts/cm-review-inventory.test.mjs +109 -0
- package/scripts/cm-spec-manifest.mjs +104 -0
- package/scripts/cm-spec-manifest.py +26 -0
- package/scripts/cm-task-gate.mjs +879 -0
- package/scripts/cm-task-gate.py +312 -0
- package/scripts/cm-task-gate.test.mjs +202 -0
- package/scripts/cm-test-declared-command.test.mjs +18 -0
- package/scripts/cm-test-entry.mjs +231 -0
- package/scripts/cm-test-host.mjs +40 -0
- package/scripts/cm-test-host.test.mjs +169 -0
- package/scripts/cm-test-logic-results.test.mjs +26 -0
- package/scripts/cm-test-session.test.mjs +138 -0
- package/scripts/cm-usage-report.py +516 -0
- package/scripts/cm-workflow-config.mjs +463 -0
- package/scripts/cm-workflow-config.test.mjs +181 -0
- package/scripts/cm-workflow.mjs +36 -0
- package/scripts/cm-workflow.test.mjs +51 -0
- package/scripts/cm_workflow_config.py +52 -0
- package/scripts/fixtures/claude-review-process.mjs +35 -0
- package/scripts/fixtures/codex-review-process.mjs +22 -0
- package/scripts/fixtures/prd-review-gate-python-oracle.py +320 -0
- package/scripts/fixtures/spec-manifest-python-oracle.py +172 -0
- package/scripts/scan-public-safety.py +117 -0
- package/scripts/test-cm-log-event.py +1213 -0
- package/scripts/test-cm-openai-compatible-call.py +1185 -0
- package/scripts/test-cm-prd-review-gate.py +272 -0
- package/scripts/test-cm-prd-timing.py +168 -0
- package/scripts/test-cm-usage-report.py +584 -0
- package/scripts/test-npm-install.py +171 -0
- package/scripts/test-scan-public-safety.py +76 -0
- package/scripts/test-shell-compat.sh +365 -0
- package/scripts/test-spec-manifest.py +263 -0
- package/scripts/test-task-gate.py +46 -0
- package/scripts/test-workflow-config.py +30 -0
- package/scripts/validate-public-repo.py +245 -0
- package/scripts/validate-test-cases.mjs +71 -0
- package/scripts/validate-test-cases.py +27 -0
- package/scripts/validate-test-cases.test.mjs +36 -0
- package/skills/cm-ai/SKILL.md +137 -0
- package/skills/cm-ai/references/N1-init.md +108 -0
- package/skills/cm-ai/references/N2-enter-feature.md +38 -0
- package/skills/cm-ai/references/N3-execute-task.md +123 -0
- package/skills/cm-ai/references/N4-review.md +103 -0
- package/skills/cm-ai/references/N5-mark-done.md +117 -0
- package/skills/cm-ai/references/N6-qa-eval.md +102 -0
- package/skills/cm-ai/references/N7-context.md +23 -0
- package/skills/cm-ai/references/N8-finish.md +103 -0
- package/skills/cm-ai/references/js-host.md +126 -0
- package/skills/cm-backend-engineer/SKILL.md +100 -0
- package/skills/cm-check/SKILL.md +52 -0
- package/skills/cm-check/references/js-host.md +44 -0
- package/skills/cm-contract-engineer/SKILL.md +136 -0
- package/skills/cm-database-engineer/SKILL.md +89 -0
- package/skills/cm-devops-engineer/SKILL.md +137 -0
- package/skills/cm-doc-syncer/SKILL.md +150 -0
- package/skills/cm-finance-expert/SKILL.md +85 -0
- package/skills/cm-fix/SKILL.md +199 -0
- package/skills/cm-fix/references/cross-boundary-debugging.md +44 -0
- package/skills/cm-fix/references/js-host.md +135 -0
- package/skills/cm-frontend-engineer/SKILL.md +127 -0
- package/skills/cm-idea/SKILL.md +55 -0
- package/skills/cm-idea/references/domains/trading.md +97 -0
- package/skills/cm-idea/references/example-prd.md +92 -0
- package/skills/cm-idea/references/idea-to-prd.md +282 -0
- package/skills/cm-idea/references/js-host.md +63 -0
- package/skills/cm-init/SKILL.md +191 -0
- package/skills/cm-init/references/js-host.md +123 -0
- package/skills/cm-miniprogram-engineer/SKILL.md +141 -0
- package/skills/cm-miniprogram-engineer/references/platform-readiness.md +58 -0
- package/skills/cm-miniprogram-engineer/references/release-checklist.md +59 -0
- package/skills/cm-prd/SKILL.md +548 -0
- package/skills/cm-prd/references/brownfield.md +13 -0
- package/skills/cm-prd/references/change-mode.md +145 -0
- package/skills/cm-prd/references/context-scope.md +62 -0
- package/skills/cm-prd/references/greenfield.md +80 -0
- package/skills/cm-prd/references/js-change-recovery.md +57 -0
- package/skills/cm-prd/references/js-host.md +98 -0
- package/skills/cm-prd/references/phase-timing.md +68 -0
- package/skills/cm-prd/references/spec-self-check.md +22 -0
- package/skills/cm-product-manager/SKILL.md +83 -0
- package/skills/cm-qa-engineer/SKILL.md +142 -0
- package/skills/cm-refactor/SKILL.md +236 -0
- package/skills/cm-refactor/references/js-batch.md +75 -0
- package/skills/cm-refactor/references/js-host.md +78 -0
- package/skills/cm-test/SKILL.md +288 -0
- package/skills/cm-test/references/js-host.md +118 -0
- package/skills/cm-ui-engineer/SKILL.md +105 -0
- package/skills/codebase-context/SKILL.md +489 -0
- package/skills/darwin-skill/NOTICE.md +26 -0
- package/skills/darwin-skill/README.md +272 -0
- package/skills/darwin-skill/SKILL.md +492 -0
- package/skills/darwin-skill/references/runtime-neutrality.md +68 -0
- package/skills/darwin-skill/references/skilllens-evidence.md +142 -0
- package/skills/darwin-skill/scripts/screenshot.mjs +71 -0
- package/skills/darwin-skill/templates/result-card-dark.html +698 -0
- package/skills/darwin-skill/templates/result-card-white.html +444 -0
- package/skills/darwin-skill/templates/result-card.html +616 -0
- package/skills/external-expert/SKILL.md +250 -0
- package/templates/arch-reference.md +68 -0
- package/templates/auto-update/cm-announce.sh +19 -0
- package/templates/auto-update/cm-update.sh +274 -0
- package/templates/cm-workflow.yml +52 -0
- package/templates/dashboard/dashboard.html +153 -0
- package/templates/dashboard/serve.sh +10 -0
- package/templates/hooks/pre-commit-cm-task-check +67 -0
- package/templates/pixel/cm-pixel.html +388 -0
- package/templates/pixel/cm-pixel.sh +212 -0
- package/templates/pixel/dev/README.md +20 -0
- package/templates/pixel/dev/atlas-preview.png +0 -0
- package/templates/pixel/dev/build.py +55 -0
- package/templates/pixel/dev/sheets/roguelikeChar_transparent.png +0 -0
- package/templates/pixel/dev/sheets/roguelikeCity_tilemap.png +0 -0
- package/templates/pixel/dev/sheets/roguelikeIndoor_transparent.png +0 -0
- package/templates/pixel/dev/template.html +388 -0
- package/templates/pixel/serve.sh +12 -0
- package/templates/refactor/cm-refactor-denies.json +14 -0
- package/templates/rules/backend-api.md +36 -0
- package/templates/rules/coding-style.md +44 -0
- package/templates/rules/database.md +27 -0
- package/templates/rules/finance.md +32 -0
- package/templates/rules/frontend.md +32 -0
- package/templates/rules/git-workflow.md +25 -0
- package/templates/rules/miniprogram.md +31 -0
- package/templates/rules/security.md +31 -0
- package/templates/rules/smart-contract.md +28 -0
- package/templates/rules/testing.md +36 -0
- package/templates/statusline/cm-statusline.sh +73 -0
- package/templates/ui-lens/cm-ui-lens-extract.mjs +55 -0
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
// Fixed cm-refactor flow; the host proposes text, the owner applies and judges it.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {randomUUID} from 'node:crypto';
|
|
5
|
+
import {spawnSync} from 'node:child_process';
|
|
6
|
+
import {inspectCmRefactorAdmission} from '../../../scripts/cm-refactor-entry.mjs';
|
|
7
|
+
import {loadConfig,resolveRole} from '../../../scripts/cm-workflow-config.mjs';
|
|
8
|
+
import {checkN4,checkN5,implementationSha256,validateReview} from '../../../scripts/cm-task-gate.mjs';
|
|
9
|
+
import {createHostCheck} from '../cm-ai/host-check.mjs';
|
|
10
|
+
import {writeImmutableWorkflowFile} from '../cm-ai/review-evidence-file.mjs';
|
|
11
|
+
import {mergeLessons} from '../cm-ai/cm-ai-learning-writer.mjs';
|
|
12
|
+
import {readLearningRetrospectiveContent} from '../cm-ai/cm-ai-context-refresh.mjs';
|
|
13
|
+
import {need,shape,json,digest} from '../cm-ai/effect-contract.mjs';
|
|
14
|
+
import {inside,canonicalFuture,snapshotSource} from '../cm-test/source-snapshot.mjs';
|
|
15
|
+
import {openRefactorRecords,readText,replaceText,sha} from './records.mjs';
|
|
16
|
+
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
17
|
+
const markdown=value=>'```json\n'+JSON.stringify(value,null,2)+'\n```\n';
|
|
18
|
+
const relative=name=>typeof name==='string'&&!path.isAbsolute(name)&&!name.includes('\\')
|
|
19
|
+
&&name.split('/').every(part=>part&&part!=='.'&&part!=='..');
|
|
20
|
+
const protectedName=name=>/(^|\/)(AGENTS\.md|CLAUDE\.md|\.env(?:\..*)?|\.claude|\.codex|\.git|.*\.(pem|key|p12))(\/|$)/i.test(name);
|
|
21
|
+
function orderedUnits(units,scope,assembly){
|
|
22
|
+
need(Array.isArray(units)&&units.length>0,'refactor_units_invalid');const seen=new Set(),done=new Set(),result=[];
|
|
23
|
+
for(const unit of units){shape(unit,['id','files','dependsOn']);need(/^[a-z][a-z0-9-]*$/.test(unit.id)&&!seen.has(unit.id)
|
|
24
|
+
&&Array.isArray(unit.files)&&unit.files.length>0&&Array.isArray(unit.dependsOn),'refactor_units_invalid');seen.add(unit.id);}
|
|
25
|
+
const files=units.flatMap(unit=>unit.files);
|
|
26
|
+
need(new Set(files).size===files.length&&digest([...files,...assembly].sort())===digest([...scope].sort()),'refactor_units_coverage');
|
|
27
|
+
while(result.length<units.length){const next=units.find(unit=>!done.has(unit.id)&&unit.dependsOn.every(id=>done.has(id)));
|
|
28
|
+
need(next,'refactor_dependency_cycle');result.push(next);done.add(next.id);}
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
export function createCmRefactorHost(raw,{call}){
|
|
32
|
+
const config=json(raw,256*1024),optional=['batch','testSetup','writebackPaths'];
|
|
33
|
+
shape(config,['skillDir','project','specs','runtime','target','slug','scope','crossModule','baselineCommands','judgeCommand','mutations','logHome',...optional.filter(key=>Object.hasOwn(config,key))]);
|
|
34
|
+
need(nonempty(config.target)&&/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(config.slug),'refactor_target_invalid');
|
|
35
|
+
const admission=inspectCmRefactorAdmission({skillDir:config.skillDir,project:config.project,
|
|
36
|
+
...(config.specs?{specs:config.specs}:{}),intent:'structure-only',targetPresent:true});
|
|
37
|
+
const {project,specs,workflowRoot}=admission;
|
|
38
|
+
need(['codex','claude'].includes(config.runtime)&&typeof call==='function','refactor_runtime_invalid');
|
|
39
|
+
need(Array.isArray(config.scope)&&config.scope.length>0&&new Set(config.scope).size===config.scope.length
|
|
40
|
+
&&typeof config.crossModule==='boolean','refactor_scope_invalid');
|
|
41
|
+
const archiveRoot=specs?path.join(specs,'refactors'):path.join(project,'docs','refactors'),directory=path.join(archiveRoot,config.slug);
|
|
42
|
+
const reviews=specs?path.join(specs,'.reviews'):path.join(archiveRoot,'.reviews');
|
|
43
|
+
for(const target of [archiveRoot,reviews,config.logHome])need(path.isAbsolute(target)&&canonicalFuture(target)===target,'refactor_archive_invalid');
|
|
44
|
+
need(!inside(project,config.logHome)&&(!specs||!inside(specs,config.logHome)),'refactor_log_home_invalid');
|
|
45
|
+
const setup=config.testSetup??{paths:[]},writebacks=config.writebackPaths??[],batch=config.batch??{assemblyFiles:[],cheapCommands:[],maxPasses:6};
|
|
46
|
+
need(Array.isArray(setup.paths)&&Array.isArray(writebacks)&&Array.isArray(batch.assemblyFiles)&&Array.isArray(batch.cheapCommands)
|
|
47
|
+
&&Number.isInteger(batch.maxPasses)&&batch.maxPasses>=3&&batch.maxPasses<=9,'refactor_options_invalid');
|
|
48
|
+
need(Array.isArray(config.baselineCommands)&&config.baselineCommands.length>0&&Array.isArray(config.judgeCommand)
|
|
49
|
+
&&Array.isArray(config.mutations)&&config.mutations.length>=2,'refactor_judge_setup_required');
|
|
50
|
+
for(const name of [...config.scope,...setup.paths])need(relative(name)&&!protectedName(name)
|
|
51
|
+
&&!inside(archiveRoot,path.join(project,name))&&(!specs||!inside(specs,path.join(project,name))),'refactor_protected_scope');
|
|
52
|
+
for(const name of writebacks)need(relative(name)&&(name==='AGENTS.md'||name==='CLAUDE.md'||name==='README.md'
|
|
53
|
+
||/^\.claude\/rules\/[a-zA-Z0-9._-]+\.md$/.test(name)),'refactor_writeback_scope');
|
|
54
|
+
need(new Set([...config.scope,...setup.paths,...writebacks]).size===config.scope.length+setup.paths.length+writebacks.length,'refactor_scope_overlap');
|
|
55
|
+
const records=openRefactorRecords(directory),routes={};
|
|
56
|
+
for(const role of ['coder','tester','reviewer'])routes[role]=resolveRole(loadConfig({projectRoot:project}),role,config.runtime);
|
|
57
|
+
let controller=new AbortController(),active=false,view=records.progress??{stage:records.context?'interrupted':'ready',reason:null};
|
|
58
|
+
let context=records.context,files={},reports=view.reports??[],judgeBefore=null,analysis=null,proposal=null,rulebook=null,reviewResult=null;
|
|
59
|
+
let attempt=1,commandCount=0,hostCalls=0,humanCalls=0,interceptions=0,initialPlan=null;
|
|
60
|
+
const feature=`refactor-${config.slug}`,task=`T-REFACTOR-${config.slug}`;
|
|
61
|
+
const absolute=name=>path.join(project,name);
|
|
62
|
+
const managedNames=[...config.scope,...setup.paths,...writebacks];
|
|
63
|
+
const lessons=specs?path.join(specs,'LESSONS.md'):path.join(archiveRoot,'LESSONS.md');
|
|
64
|
+
const unknown=()=>[...records.effects.values()].some(entry=>['host','command'].includes(entry.kind)&&!Object.hasOwn(entry,'result'));
|
|
65
|
+
const ignored=target=>inside(archiveRoot,target)||inside(reviews,target)||(specs&&['运行日志.jsonl','.cm-run.json','.cm-run.lock','.cm-status.json']
|
|
66
|
+
.some(name=>target===path.join(specs,name)));
|
|
67
|
+
function guard(){
|
|
68
|
+
need(context&&digest(config)===context.configDigest,'refactor_config_changed');
|
|
69
|
+
for(const target of [archiveRoot,reviews])need(canonicalFuture(target)===target,'refactor_archive_changed');
|
|
70
|
+
const expected=new Map(Object.entries(context.original).map(([name,content])=>[absolute(name),{content,mode:context.modes[name]}]));
|
|
71
|
+
expected.set(lessons,{content:context.lessons,mode:context.lessonsMode});
|
|
72
|
+
if(specs)expected.set(path.join(specs,'METRICS.md'),{content:context.metrics,mode:context.metricsMode});
|
|
73
|
+
for(const entry of records.effects.values())if(entry.kind==='write'){
|
|
74
|
+
const {target,before,after,mode}=entry.input,current=readText(target);
|
|
75
|
+
// An interrupted atomic replacement has only two legitimate values.
|
|
76
|
+
if(!Object.hasOwn(entry,'result'))need(current===before||current===after,'refactor_write_conflict');
|
|
77
|
+
expected.set(target,{content:Object.hasOwn(entry,'result')?after:current,mode});
|
|
78
|
+
}
|
|
79
|
+
for(const entry of records.effects.values())if(entry.kind==='publish'){
|
|
80
|
+
const current=readText(entry.input.target);need(current===null||current===entry.input.content,'refactor_evidence_changed');
|
|
81
|
+
}
|
|
82
|
+
for(const [target,{content,mode}] of expected){need(readText(target)===content,'refactor_source_changed');
|
|
83
|
+
if(content!==null)need((fs.statSync(target).mode&0o777)===mode,'refactor_source_changed');}
|
|
84
|
+
const now=snapshotSource(project,archiveRoot);
|
|
85
|
+
need(now.gitState?.head===context.baseline.gitState?.head,'refactor_git_changed');
|
|
86
|
+
for(const name of new Set([...Object.keys(context.baseline.files),...Object.keys(now.files)])){
|
|
87
|
+
const target=absolute(name);if(expected.has(target)||ignored(target))continue;
|
|
88
|
+
need(digest(context.baseline.files[name]??null)===digest(now.files[name]??null),'refactor_out_of_scope_change');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function status(){return json({...view,runId:context?.runId??null,attempt:active?attempt:view.attempt??attempt,scope:config.scope,reports,
|
|
92
|
+
commandCount:active?commandCount:view.commandCount??0,hostCalls:active?hostCalls:view.hostCalls??0,
|
|
93
|
+
baselineCount:config.baselineCommands.length,differentialCount:judgeBefore?.cases.length??view.differentialCount??0,completionAuthorized:false},1024*1024);}
|
|
94
|
+
function projectStatus(){if(specs){const target=path.join(specs,'.cm-status.json');replaceText(target,readText(target),JSON.stringify({node:'REFACTOR',feature,task,
|
|
95
|
+
detail:`Refactor ${config.slug}: ${view.stage}`,state:view.stage==='done'?'run_done':view.stage,at:new Date().toTimeString().slice(0,8)})+'\n',0o600);}}
|
|
96
|
+
function progress(stage,reason=null){view={stage,reason,attempt,reports:[...reports],commandCount,hostCalls,differentialCount:judgeBefore?.cases.length??0};records.progressWrite(view);projectStatus();}
|
|
97
|
+
const identity=()=>({repositoryId:'cm-refactor',runId:context.runId,taskId:task,attempt});
|
|
98
|
+
async function event(key,event,phase,data={}){
|
|
99
|
+
return records.effect(`log/${key}`,'log',{event,phase,data},()=>{
|
|
100
|
+
const args=[path.join(workflowRoot,'scripts/cm-log-event.py'),'--workflow','cm-refactor','--event',event,'--runtime',config.runtime,
|
|
101
|
+
'--project-root',project,'--run-id',context.runId,'--detail',`Refactor ${config.slug}: ${key}`,
|
|
102
|
+
'--data-json',JSON.stringify({node:'REFACTOR',feature,task,...data})];
|
|
103
|
+
if(specs)args.push('--specs-dir',specs);if(phase)args.push('--phase',phase);
|
|
104
|
+
const out=spawnSync('python3',args,{env:{...process.env,CM_WORKFLOW_LOG_HOME:config.logHome},timeout:10000,maxBuffer:1024*1024});
|
|
105
|
+
need(!out.error&&out.status===0,'refactor_log_failed');return JSON.parse(out.stdout.toString());
|
|
106
|
+
},(_entry,perform)=>perform()); // Original writer deduplicates the exact deterministic event identity.
|
|
107
|
+
}
|
|
108
|
+
async function recover(entry,perform){
|
|
109
|
+
guard();const response=json(await call('refactor_recover',{kind:entry.kind,input:entry.input,
|
|
110
|
+
instructions:'Trusted host reconciliation only. Inspect original invocation/process receipt. Return {decision:completed,result,evidence} only for the actual recorded outcome, or {decision:not_started,evidence} with proof no dispatch/execution occurred. Unknown => {decision:unknown,evidence}. Never infer from time or repeat an unknown review/command. No new execution.'},controller.signal),4*1024*1024);
|
|
111
|
+
need(nonempty(response.evidence),'refactor_unknown_effect');
|
|
112
|
+
if(response.decision==='not_started')return perform();
|
|
113
|
+
need(response.decision==='completed','refactor_unknown_effect');
|
|
114
|
+
if(entry.kind==='command'){
|
|
115
|
+
need(response.cleanupConfirmed===true,'refactor_cleanup_unconfirmed');
|
|
116
|
+
const key=[...records.effects.entries()].find(([,value])=>value===entry)[0].slice('command/'.length);
|
|
117
|
+
await event(`${key}-release`,'resource','released',{resource_id:`cmd-${sha(key).slice(0,24)}`,resource_kind:'refactor_judge'});
|
|
118
|
+
}
|
|
119
|
+
return response.result;
|
|
120
|
+
}
|
|
121
|
+
async function invoke(key,kind,payload){
|
|
122
|
+
const input={kind,payload};hostCalls++;
|
|
123
|
+
return records.effect(`host/${key}`,'host',input,async()=>{
|
|
124
|
+
guard();need(!controller.signal.aborted,'cancelled');const at=Date.now();
|
|
125
|
+
const result=json(await call(kind,payload,controller.signal),1024*1024);
|
|
126
|
+
guard();need(!controller.signal.aborted,'cancelled');return {value:result,durationMs:Date.now()-at};
|
|
127
|
+
},recover).then(result=>result.value);
|
|
128
|
+
}
|
|
129
|
+
async function confirm(key,gate,payload){
|
|
130
|
+
humanCalls++;await event(`${key}-pause`,'pause',gate);progress(`awaiting_${gate}`);
|
|
131
|
+
const response=await invoke(key,'refactor_confirm',{gate,...payload,
|
|
132
|
+
instructions:'Show the current user the exact scope/evidence and obtain their explicit decision; {decision:approved|rejected}. Do not assume consent or execute tools.'});
|
|
133
|
+
shape(response,['decision']);need(['approved','rejected'].includes(response.decision),'refactor_decision_invalid');
|
|
134
|
+
await event(`${key}-resume`,'resume',gate,{decision:response.decision});return response.decision==='approved';
|
|
135
|
+
}
|
|
136
|
+
async function write(key,target,before,after,mode=0o644){
|
|
137
|
+
// Cached steps reconstruct virtual text, while guard checks the latest durable disk version.
|
|
138
|
+
if(!records.effects.has(`write/${key}`))guard();
|
|
139
|
+
await records.write(`write/${key}`,target,before,after,mode);
|
|
140
|
+
if(inside(project,target))files[path.relative(project,target)]=after;
|
|
141
|
+
}
|
|
142
|
+
async function publish(key,target,value){
|
|
143
|
+
const content=typeof value==='string'?value:JSON.stringify(value,null,2)+'\n';
|
|
144
|
+
const perform=()=>{
|
|
145
|
+
need(canonicalFuture(path.dirname(target))===path.dirname(target),'refactor_archive_changed');fs.mkdirSync(path.dirname(target),{recursive:true,mode:0o700});
|
|
146
|
+
return writeImmutableWorkflowFile({reviewsDir:path.dirname(target),name:path.basename(target),bytes:Buffer.from(content)});
|
|
147
|
+
};
|
|
148
|
+
await records.effect(`publish/${key}`,'publish',{target,content},perform,perform);
|
|
149
|
+
if(readText(target)===null)perform();else need(readText(target)===content,'refactor_evidence_changed');
|
|
150
|
+
if(!reports.includes(target))reports.push(target);return target;
|
|
151
|
+
}
|
|
152
|
+
async function command(key,argv){
|
|
153
|
+
commandCount++;return records.effect(`command/${key}`,'command',{argv},async()=>{
|
|
154
|
+
guard();need(!controller.signal.aborted,'cancelled');const resource={resource_id:`cmd-${sha(key).slice(0,24)}`,resource_kind:'refactor_judge'};
|
|
155
|
+
await event(`${key}-acquire`,'resource','acquired',{...resource,cleanup_required:true});let stdout='',stderr='';
|
|
156
|
+
const check=createHostCheck({cwd:project,commands:[{id:'judge',command:argv}],onOutput:({stream,chunk})=>{
|
|
157
|
+
if(stream==='stdout')stdout+=chunk.toString();else stderr+=chunk.toString();need(Buffer.byteLength(stdout+stderr)<=256*1024,'refactor_output_limit');}});
|
|
158
|
+
const [observed]=await check({identity:identity()},{signal:controller.signal});
|
|
159
|
+
const clean=observed.evidence!=='host check: cleanup_failed';await event(`${key}-release`,'resource',clean?'released':'cleanup_failed',resource);
|
|
160
|
+
guard();need(clean,'refactor_cleanup_failed');return {observed,stdout,stderr};
|
|
161
|
+
},recover);
|
|
162
|
+
}
|
|
163
|
+
async function judge(key){
|
|
164
|
+
const out=await command(key,config.judgeCommand);need(out.observed.outcome==='passed','refactor_judge_failed');
|
|
165
|
+
const value=json(JSON.parse(out.stdout),256*1024);shape(value,['cases']);
|
|
166
|
+
need(Array.isArray(value.cases)&&value.cases.length>0,'refactor_judge_invalid');const seen=new Set();
|
|
167
|
+
for(const item of value.cases){shape(item,['id','input','output']);need(nonempty(item.id)&&!seen.has(item.id),'refactor_judge_invalid');seen.add(item.id);}return value;
|
|
168
|
+
}
|
|
169
|
+
async function baseline(key){for(const item of config.baselineCommands){const out=await command(`${key}/${item.id}`,item.command);
|
|
170
|
+
need(out.observed.outcome==='passed','refactor_baseline_failed');}}
|
|
171
|
+
async function equivalents(key){await baseline(`${key}/baseline`);const after=await judge(`${key}/differential`);
|
|
172
|
+
await publish(`${key}-diff`,path.join(directory,`${key.replaceAll('/','-')}-diff.md`),markdown({before:judgeBefore,after}));
|
|
173
|
+
need(digest(after)===digest(judgeBefore),'refactor_behavior_changed');return after;}
|
|
174
|
+
const source=names=>names.map(name=>({path:name,content:files[name]??null,beforeDigest:digest(files[name]??null)}));
|
|
175
|
+
async function apply(key,items,allowed,{annotation=false}={}){
|
|
176
|
+
need(Array.isArray(items)&&new Set(items.map(item=>item.path)).size===items.length,'refactor_proposal_invalid');
|
|
177
|
+
for(const item of items){shape(item,['path','beforeDigest','content']);need(allowed.includes(item.path)
|
|
178
|
+
&&item.beforeDigest===digest(files[item.path]??null)&&(item.content===null||typeof item.content==='string'),'refactor_proposal_scope');
|
|
179
|
+
if(annotation&&item.content!==null){const match=/\/\/ REFACTOR STATUS: confidence=(high|medium|low) todos=(\d+)/.exec(item.content);
|
|
180
|
+
need(match&&Number(match[2])===(item.content.match(/TODO\(refactor\)/g)??[]).length,'refactor_status_tail_invalid');}}
|
|
181
|
+
for(const item of items)await write(`${key}/${item.path}`,absolute(item.path),files[item.path]??null,item.content,context.modes[item.path]??0o644);
|
|
182
|
+
}
|
|
183
|
+
async function restore(key,before){for(const [name,value] of Object.entries(before))if(!name.startsWith('__')&&files[name]!==value)
|
|
184
|
+
await write(`${key}/${name}`,absolute(name),files[name],value,context.modes[name]??0o644);}
|
|
185
|
+
async function prepareJudges(){
|
|
186
|
+
if(setup.paths.some(name=>files[name]===null)){
|
|
187
|
+
const result=await invoke('judge-prepare','refactor_prepare_tests',{target:config.target,files:source(config.scope),assets:source(setup.paths),
|
|
188
|
+
baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,route:routes.tester,
|
|
189
|
+
instructions:'Return {files:[{path,beforeDigest,content}]} only for declared test assets. Lock current behavior including bugs and boundary cases; preserve original environment resolution. No direct writes or commands, no new dependencies.'});
|
|
190
|
+
await apply('judge-prepare',result.files,setup.paths);
|
|
191
|
+
}
|
|
192
|
+
for(let revision=1;revision<=3;revision++){
|
|
193
|
+
const key=`judge-${revision}`;let failure=null;const mutations=[];
|
|
194
|
+
try{
|
|
195
|
+
await baseline(`${key}/baseline`);judgeBefore=await judge(`${key}/original`);
|
|
196
|
+
for(let n=0;n<config.mutations.length;n++){
|
|
197
|
+
const mutation=config.mutations[n];shape(mutation,['path','find','replace']);
|
|
198
|
+
need(config.scope.includes(mutation.path)&&nonempty(mutation.find)&&typeof mutation.replace==='string'
|
|
199
|
+
&&mutation.find!==mutation.replace,'refactor_mutation_invalid');
|
|
200
|
+
const old=files[mutation.path];need(typeof old==='string'&&old.split(mutation.find).length===2,'refactor_mutation_not_unique');
|
|
201
|
+
await write(`${key}-mutant-${n}`,absolute(mutation.path),old,old.replace(mutation.find,mutation.replace),context.modes[mutation.path]);
|
|
202
|
+
let observed;try{observed=await judge(`${key}/mutant-${n}`);}finally{
|
|
203
|
+
await write(`${key}-restore-${n}`,absolute(mutation.path),files[mutation.path],old,context.modes[mutation.path]);}
|
|
204
|
+
const inputs=value=>value.cases.map(({id,input})=>({id,input}));
|
|
205
|
+
const detected=digest(inputs(observed))===digest(inputs(judgeBefore))&&digest(observed)!==digest(judgeBefore);
|
|
206
|
+
mutations.push({mutation,detected,observed});need(detected,'refactor_judge_missed_mutation');
|
|
207
|
+
}
|
|
208
|
+
}catch(error){if(unknown())throw error;failure=error.code??error.message;}
|
|
209
|
+
await publish(key,path.join(directory,`${key}-report.md`),markdown({judgeBefore,mutations,failure}));
|
|
210
|
+
if(!failure)return;
|
|
211
|
+
need(!controller.signal.aborted,'cancelled');need(setup.paths.length&&revision<3,failure);
|
|
212
|
+
const result=await invoke(`${key}-repair`,'refactor_prepare_tests',{failure,mutations,files:source(config.scope),assets:source(setup.paths),
|
|
213
|
+
baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,route:routes.tester,
|
|
214
|
+
instructions:'Diagnose judge first; correct only declared test harness, never production behavior or configured mutations. Return {files:[{path,beforeDigest,content}]}. No commands or direct writes.'});
|
|
215
|
+
await apply(`${key}-repair`,result.files,setup.paths);await event(`${key}-repair`,'decision','judge_repair',{reason:failure});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async function defineRules(key,previous=null,findings=null){
|
|
219
|
+
const plan=await invoke(key,'refactor_batch',{action:'plan',target:config.target,project,
|
|
220
|
+
files:source(config.scope).map(({path,content,beforeDigest})=>({path,exists:content!==null,beforeDigest})),assemblyFiles:batch.assemblyFiles,
|
|
221
|
+
previous,findings,route:routes.coder,instructions:'Return {rulebook,units:[{id,files,dependsOn}],sample:[file],perFileEstimate,reason}. Resolve naming/shape/prohibitions/escape hatch. File AND module dependencies must be acyclic; encode both into unit dependsOn. Cover scope exactly including declared assembly exclusions. sample chooses hardest files: <10 files ceil(20%), >=10 choose 2-3. perFileEstimate is estimated tokens per file, not observed usage. No writes.'});
|
|
222
|
+
need(nonempty(plan.rulebook)&&nonempty(plan.reason)&&Number.isFinite(plan.perFileEstimate)&&plan.perFileEstimate>0,'refactor_rulebook_invalid');
|
|
223
|
+
const units=orderedUnits(plan.units,config.scope,batch.assemblyFiles);
|
|
224
|
+
const count=config.scope.length<10?Math.max(1,Math.ceil(config.scope.length*.2)):2;
|
|
225
|
+
need(Array.isArray(plan.sample)&&new Set(plan.sample).size===plan.sample.length&&plan.sample.length>=count&&plan.sample.length<=Math.max(count,3)
|
|
226
|
+
&&plan.sample.every(name=>config.scope.includes(name)&&files[name]!==null),'refactor_sample_invalid');
|
|
227
|
+
return {...plan,units};
|
|
228
|
+
}
|
|
229
|
+
async function batchFlow(prefix,findings){
|
|
230
|
+
const denies=JSON.parse(readText(path.join(workflowRoot,'templates/refactor/cm-refactor-denies.json')));
|
|
231
|
+
let plan=prefix==='a1'?{...initialPlan}:await defineRules(`${prefix}/plan`,rulebook,findings),revision=1;
|
|
232
|
+
const trial={};
|
|
233
|
+
for(const variant of ['guided','blind'])trial[variant]=await invoke(`${prefix}/bakeoff-${variant}`,'refactor_batch',{
|
|
234
|
+
action:'bakeoff',variant,files:source(plan.sample),target:config.target,...(variant==='guided'?{rulebook:plan.rulebook}:{}),
|
|
235
|
+
denies,route:routes.coder,instructions:'Use a fresh isolated text-only author context for this variant, no other variant history. Return {files:[{path,beforeDigest,content}],channelId}. No tools/writes/git/heavy tests. Blind variant receives no rulebook or rulebook history.'});
|
|
236
|
+
need(nonempty(trial.guided.channelId)&&nonempty(trial.blind.channelId)&&trial.guided.channelId!==trial.blind.channelId,'refactor_bakeoff_not_independent');
|
|
237
|
+
const adjudication=await invoke(`${prefix}/bakeoff-judge`,'refactor_batch',{action:'adjudicate',files:source(plan.sample),rulebook:plan.rulebook,trial,
|
|
238
|
+
instructions:'Use third fresh context, no authorship. Return {channelId,rulebook,decisions:[{path,verdict,reason}]}; classify every differing file as rule_correct/rule_missing/rule_wrong. No writes.'});
|
|
239
|
+
need(nonempty(adjudication.channelId)&&![trial.guided.channelId,trial.blind.channelId].includes(adjudication.channelId)
|
|
240
|
+
&&nonempty(adjudication.rulebook)&&Array.isArray(adjudication.decisions),'refactor_bakeoff_invalid');
|
|
241
|
+
for(const name of plan.sample){const a=trial.guided.files.find(item=>item.path===name),b=trial.blind.files.find(item=>item.path===name);
|
|
242
|
+
need(a&&b,'refactor_bakeoff_coverage');if(digest(a.content)!==digest(b.content))need(adjudication.decisions.some(row=>row.path===name
|
|
243
|
+
&&['rule_correct','rule_missing','rule_wrong'].includes(row.verdict)&&nonempty(row.reason)),'refactor_bakeoff_coverage');}
|
|
244
|
+
plan.rulebook=adjudication.rulebook;
|
|
245
|
+
await publish(`${prefix}-bakeoff`,path.join(directory,`${prefix}-bakeoff.md`),markdown({trial,adjudication}));
|
|
246
|
+
// Pilot uses the same generation/cheap checks/assembly/equivalence pipeline; discard its products.
|
|
247
|
+
let pilotPassed=false;
|
|
248
|
+
for(let cycle=1;cycle<=3;cycle++){
|
|
249
|
+
const pilotBefore={...files},trialResult=await runBatch(`${prefix}/pilot-${cycle}`,plan.sample,plan.rulebook,revision,[],true);
|
|
250
|
+
await restore(`${prefix}/pilot-discard-${cycle}`,pilotBefore);files.__needs=pilotBefore.__needs??[];
|
|
251
|
+
if(trialResult.passed){pilotPassed=true;break;}
|
|
252
|
+
if(cycle<3){const revised=await defineRules(`${prefix}/pilot-revise-${cycle}`,plan.rulebook,trialResult);
|
|
253
|
+
need(digest(revised.units)===digest(plan.units),'refactor_revision_scope_changed');plan.rulebook=revised.rulebook;}
|
|
254
|
+
}
|
|
255
|
+
need(pilotPassed,'refactor_pilot_failed');
|
|
256
|
+
if(!await confirm(`${prefix}/rulebook`,'rulebook',{rulebook:plan.rulebook,units:plan.units,trial:adjudication,
|
|
257
|
+
budget:{files:config.scope.length,perFileEstimate:plan.perFileEstimate,total:config.scope.length*plan.perFileEstimate}}))return false;
|
|
258
|
+
let history=[{revision,reason:plan.reason,approvedBy:'current-user',rulebook:plan.rulebook}];
|
|
259
|
+
async function saveRules(){rulebook=plan.rulebook;const content='# RULEBOOK\n\n'+rulebook+'\n\n## 修订史\n\n'+markdown(history);
|
|
260
|
+
history.at(-1).rendered=content;
|
|
261
|
+
await write(`${prefix}-rules-${revision}`,path.join(directory,'RULEBOOK.md'),readVirtualRulebook,content,0o600);readVirtualRulebook=content;}
|
|
262
|
+
let readVirtualRulebook=prefix==='a1'?null:files.__rulebook??null;await saveRules();
|
|
263
|
+
for(let index=0;index<plan.units.length;index++){
|
|
264
|
+
const unit=plan.units[index],errors=Object.create(null);let passed=false;
|
|
265
|
+
for(let cycle=1;cycle<=batch.maxPasses;cycle++){
|
|
266
|
+
const key=`${prefix}/batch-${index+1}-${cycle}`,before={...files};
|
|
267
|
+
await event(`${key}-start`,'task_start',null,{batch:index+1,total:plan.units.length,cycle});
|
|
268
|
+
const result=await runBatch(key,unit.files,rulebook,revision,[],false);
|
|
269
|
+
if(result.passed){passed=true;await event(`${key}-done`,'task_done',null,{batch:index+1,total:plan.units.length,differential_groups:judgeBefore.cases.length});break;}
|
|
270
|
+
await restore(`${key}-rollback`,before);await publish(`${key}-rollback`,path.join(directory,`${key.replaceAll('/','-')}-rollback.md`),markdown({unit,cycle,failure:result.failure,baselineHead:context.baseline.gitState?.head??null}));
|
|
271
|
+
await event(`${key}-rollback`,'error','rollback',{batch:index+1,cycle,reason:result.failure});
|
|
272
|
+
const diagnosed=await invoke(`${key}-diagnose`,'refactor_batch',{action:'diagnose',failure:result.failure,output:result.output,rulebook,
|
|
273
|
+
instructions:'Return {errorClass,reason}; identify root error category, not individual filename/line; judge-wide anomalies must be treated as judge faults first. No writes.'});
|
|
274
|
+
need(nonempty(diagnosed.errorClass)&&nonempty(diagnosed.reason),'refactor_diagnosis_invalid');
|
|
275
|
+
errors[diagnosed.errorClass]=(errors[diagnosed.errorClass]??0)+1;
|
|
276
|
+
if(errors[diagnosed.errorClass]===3){
|
|
277
|
+
const revised=await defineRules(`${key}-revise`,rulebook,{...diagnosed,failure:result.failure});
|
|
278
|
+
need(digest(revised.units)===digest(plan.units),'refactor_revision_scope_changed');
|
|
279
|
+
if(!await confirm(`${key}-rulebook`,'rulebook_revision',{previous:rulebook,next:revised.rulebook,reason:diagnosed.reason}))return false;
|
|
280
|
+
plan.rulebook=revised.rulebook;revision++;history.push({revision,reason:diagnosed.reason,approvedBy:'current-user',rulebook:plan.rulebook});await saveRules();
|
|
281
|
+
await event(`${key}-rules`,'decision','rule_revision',{revision,reason:diagnosed.reason});
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
need(passed,'refactor_batch_retry_exhausted');
|
|
285
|
+
}
|
|
286
|
+
files.__rulebook=readVirtualRulebook;return true;
|
|
287
|
+
}
|
|
288
|
+
async function runBatch(key,names,rules,revision,needs=[],pilot=false){
|
|
289
|
+
const before={...files},rows=[];let output=null;
|
|
290
|
+
try{
|
|
291
|
+
for(const name of names){
|
|
292
|
+
const result=await invoke(`${key}/unit-${name}`,'refactor_batch',{action:'generate',files:source([name]),rulebook:rules,rulebookRevision:revision,
|
|
293
|
+
assemblyFiles:batch.assemblyFiles,route:routes.coder,
|
|
294
|
+
denies:JSON.parse(readText(path.join(workflowRoot,'templates/refactor/cm-refactor-denies.json'))),
|
|
295
|
+
instructions:'Text-only worker; no commands/writes/git/tests. Return {files:[{path,beforeDigest,content}],needs:[{id,path,instruction}],summary}. Only assigned file; deletion content=null. Non-deleted output includes // REFACTOR STATUS: confidence=high|medium|low todos=N in language-appropriate comment. Report every assembly/registration/doc need, do not implement it.'});
|
|
296
|
+
need(Array.isArray(result.needs)&&nonempty(result.summary),'refactor_unit_invalid');
|
|
297
|
+
for(const item of result.needs)need(nonempty(item.id)&&[...batch.assemblyFiles,...writebacks.filter(n=>['README.md','CLAUDE.md'].includes(n))].includes(item.path)
|
|
298
|
+
&&nonempty(item.instruction),'refactor_assembly_scope');
|
|
299
|
+
needs.push(...result.needs);await apply(`${key}/unit-${name}`,result.files,[name],{annotation:true});
|
|
300
|
+
const content=files[name],match=content===null?null:/confidence=(high|medium|low) todos=(\d+)/.exec(content);
|
|
301
|
+
const host=records.effects.get(`host/${key}/unit-${name}`)?.result;
|
|
302
|
+
rows.push({file:name,agent:'current-host-isolated-author',model:routes.coder.model??null,rulebook_rev:revision,
|
|
303
|
+
diff_pass:false,todos:match?Number(match[2]):0,confidence:match?.[1]??'deleted',duration:host?.durationMs??null,phase:pilot?'pilot':'production',batch:key});
|
|
304
|
+
for(const check of batch.cheapCommands){if(files[name]===null)continue;
|
|
305
|
+
output=await command(`${key}/${name}/${check.id}`,check.command.map(arg=>arg.replaceAll('{file}',name)));need(output.observed.outcome==='passed','refactor_cheap_check_failed');}
|
|
306
|
+
}
|
|
307
|
+
const assemblyNeeds=needs.filter(item=>batch.assemblyFiles.includes(item.path));
|
|
308
|
+
if(assemblyNeeds.length){
|
|
309
|
+
const result=await invoke(`${key}/assembly`,'refactor_batch',{action:'assemble',needs:assemblyNeeds,files:source(batch.assemblyFiles),rulebook:rules,
|
|
310
|
+
instructions:'Main host assembly, NOT delegated worker. Consume every need including loading/registration/build manifests. Return {files:[{path,beforeDigest,content}],resolved:[id]}; no direct writes/commands.'});
|
|
311
|
+
need(Array.isArray(result.resolved)&&assemblyNeeds.every(item=>result.resolved.includes(item.id)),'refactor_assembly_incomplete');
|
|
312
|
+
await apply(`${key}/assembly`,result.files,batch.assemblyFiles);
|
|
313
|
+
}
|
|
314
|
+
await equivalents(key);rows.forEach(row=>{row.diff_pass=true;});
|
|
315
|
+
await publish(`${key}-units`,path.join(directory,`${key.replaceAll('/','-')}-units.md`),markdown({rows,needs,pilot}));
|
|
316
|
+
const logTarget=path.join(directory,'batch-log.jsonl'),old=files.__batchLog??null;
|
|
317
|
+
const next=(old??'')+rows.map(row=>JSON.stringify(row)).join('\n')+'\n';await write(`${key}-batch-log`,logTarget,old,next,0o600);files.__batchLog=next;
|
|
318
|
+
files.__needs=[...(files.__needs??[]),...needs.filter(item=>!batch.assemblyFiles.includes(item.path))];
|
|
319
|
+
return {passed:true};
|
|
320
|
+
}catch(error){
|
|
321
|
+
if(unknown()||controller.signal.aborted||['refactor_unknown_effect','refactor_source_changed','refactor_out_of_scope_change','refactor_write_conflict'].includes(error.code))throw error;
|
|
322
|
+
await restore(`${key}/failed-restore`,Object.fromEntries(Object.entries(before).filter(([name])=>!name.startsWith('__'))));
|
|
323
|
+
const failure=error.code??error.message;await publish(`${key}-failure`,path.join(directory,`${key.replaceAll('/','-')}-failure.md`),markdown({failure,output,rows,pilot}));
|
|
324
|
+
return {passed:false,failure,output};
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async function writeback(prefix){
|
|
328
|
+
let result;
|
|
329
|
+
if(context.batch||writebacks.length||analysis.claimedMemos.length)result=await invoke(`${prefix}/retrospective`,'refactor_retrospective',{
|
|
330
|
+
analysis,proposal,rulebook,needs:files.__needs??[],files:source(writebacks),lessons:context.lessons,route:routes.coder,
|
|
331
|
+
docSyncerSkill:path.join(workflowRoot,'skills/cm-doc-syncer/SKILL.md'),
|
|
332
|
+
instructions:'Main host retrospective; read the supplied doc-syncer Skill for structure synchronization. Return {learningApplication,learning:{status,candidates,reason},conventions:[{path,text,evidence}],documentation:[{path,beforeDigest,content}],resolved:[needId],unfixedDefects:[],metricAfter}. Only evidence-backed max3 Learning candidates; no_new_lesson is valid. Preserve all instructions; conventions append only, not permissions. Every README/CLAUDE structure need must be resolved. No direct writes, no bug fixes.'});
|
|
333
|
+
else result={learningApplication:proposal.learningApplication,learning:typeof proposal.learningRetrospective==='string'
|
|
334
|
+
?{status:proposal.learningRetrospective,candidates:[],reason:null}:proposal.learningRetrospective,
|
|
335
|
+
conventions:proposal.conventions,documentation:[],resolved:[],unfixedDefects:proposal.unfixedDefects,metricAfter:proposal.metricAfter};
|
|
336
|
+
need(nonempty(result.learningApplication)&&Array.isArray(result.conventions)&&Array.isArray(result.documentation)
|
|
337
|
+
&&Array.isArray(result.resolved)&&Array.isArray(result.unfixedDefects)&&Number.isFinite(result.metricAfter),'refactor_retrospective_invalid');
|
|
338
|
+
const learning=readLearningRetrospectiveContent(result.learning);need(learning.status!=='writeback_pending','refactor_learning_writeback_required');
|
|
339
|
+
if(learning.status==='lesson_candidate'){
|
|
340
|
+
need(writebacks.includes('AGENTS.md'),'refactor_learning_permission_required');
|
|
341
|
+
const old=files['AGENTS.md']??null,next=mergeLessons(old??'',{...learning,identity:identity(),feature});
|
|
342
|
+
await write(`${prefix}-learning`,absolute('AGENTS.md'),old,next,context.modes['AGENTS.md']??0o644);
|
|
343
|
+
}
|
|
344
|
+
let lessonText=files.__lessons??context.lessons;
|
|
345
|
+
for(let n=0;n<result.conventions.length;n++){
|
|
346
|
+
const item=result.conventions[n];need(nonempty(item.text)&&Array.isArray(item.evidence)&&item.evidence.length>0,'refactor_convention_invalid');
|
|
347
|
+
const marker=`<!-- cm-refactor-convention:${digest(item)} -->`;
|
|
348
|
+
if(fs.existsSync(path.join(project,'.claude','rules'))){need(writebacks.includes(item.path)&&/^\.claude\/rules\/.+\.md$/.test(item.path),'refactor_convention_permission_required');
|
|
349
|
+
const old=files[item.path]??null,next=(old??'').includes(marker)?old:(old??'')+'\n'+item.text+'\n'+marker+'\n';
|
|
350
|
+
await write(`${prefix}-convention-${n}`,absolute(item.path),old,next,context.modes[item.path]??0o644);
|
|
351
|
+
}else if(!(lessonText??'').includes(marker))lessonText=(lessonText??'')+`\n[仅记忆] ${item.text}\n证据:${item.evidence.join('、')}。请在 cm-init 后迁入项目规则。\n${marker}\n`;
|
|
352
|
+
}
|
|
353
|
+
for(const memo of analysis.claimedMemos){need(nonempty(memo)&&!memo.includes('\n')&&(context.lessons??'').split(/\r?\n/).includes(memo),'refactor_memo_invalid');
|
|
354
|
+
const next=`${memo} [已认领] 档案:${dossierPath()}`;
|
|
355
|
+
if(!(lessonText??'').includes(next)){need(lessonText.split(memo).length===2,'refactor_memo_conflict');lessonText=lessonText.replace(memo,next);}}
|
|
356
|
+
if(lessonText!==files.__lessons){await write(`${prefix}-lessons`,lessons,files.__lessons??context.lessons,lessonText,context.lessonsMode);files.__lessons=lessonText;}
|
|
357
|
+
need(result.documentation.every(item=>['README.md','CLAUDE.md'].includes(item.path)&&writebacks.includes(item.path)),'refactor_documentation_scope');
|
|
358
|
+
need((files.__needs??[]).every(item=>result.resolved.includes(item.id)),'refactor_documentation_incomplete');
|
|
359
|
+
await apply(`${prefix}-documentation`,result.documentation,writebacks);
|
|
360
|
+
return {...result,learning};
|
|
361
|
+
}
|
|
362
|
+
const dossierPath=()=>context.batch?path.join(directory,'dossier.md'):path.join(archiveRoot,`${context.startedAt.slice(0,10).replaceAll('-','')}-${config.slug}.md`);
|
|
363
|
+
async function flow(){
|
|
364
|
+
files={...context.original};reports=[];commandCount=0;hostCalls=0;humanCalls=0;interceptions=0;rulebook=null;reviewResult=null;proposal=null;judgeBefore=null;attempt=1;
|
|
365
|
+
await event('start','run_start',null);await event('g0','node_enter',null);
|
|
366
|
+
for(const [role,route] of Object.entries(routes))await event(`route-${role}`,'decision','route',{role,adapter:route.adapter,requested_model:route.model,source:route.source,route_state:route.route_state});
|
|
367
|
+
analysis=await invoke('analysis','refactor_analyze',{target:config.target,project,scope:config.scope,
|
|
368
|
+
files:source(config.scope).map(({path,content,beforeDigest})=>({path,exists:content!==null,beforeDigest})),route:routes.coder,
|
|
369
|
+
learningPath:absolute('AGENTS.md'),lessonsPath:lessons,instructions:'Read applicable root/nested instructions, callers and related pending structural memos. Return {decision:proceed|no_refactor,metric:{name,before,unit},impact:[],claimedMemos:[exact source lines],reason}. Quantify real benefit. Behavior changes must not proceed. No writes/commands.'});
|
|
370
|
+
need(['proceed','no_refactor'].includes(analysis.decision)&&nonempty(analysis.reason)&&Array.isArray(analysis.claimedMemos)
|
|
371
|
+
&&Number.isFinite(analysis.metric?.before),'refactor_analysis_invalid');
|
|
372
|
+
if(analysis.decision==='no_refactor'){await event('not-needed','run_done',null,{result:'not_needed'});progress('not_needed');return false;}
|
|
373
|
+
if(context.batch)initialPlan=await defineRules('initial-plan');
|
|
374
|
+
if(!await confirm('g0','g0',{analysis,scope:config.scope,track:context.batch?'batch':'light',testPaths:setup.paths,writebackPaths:writebacks,
|
|
375
|
+
budget:initialPlan?{files:config.scope.length,perFileEstimate:initialPlan.perFileEstimate,total:config.scope.length*initialPlan.perFileEstimate}:null,
|
|
376
|
+
baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,mutations:config.mutations,
|
|
377
|
+
warning:'Source additions/deletions and declared project-only rules/tests writeback are included. No provider/install/Git authorization.'})){
|
|
378
|
+
await event('rejected','run_done',null,{result:'rejected'});progress('rejected');return false;}
|
|
379
|
+
await event('judge','node_enter',null);await prepareJudges();
|
|
380
|
+
for(attempt=1;attempt<=2;attempt++){
|
|
381
|
+
const prefix=`a${attempt}`;await event(`${prefix}-execute`,'node_enter',null);progress('implementing');
|
|
382
|
+
if(!context.batch)await event(`${prefix}-task`,'task_start',null,{attempt});
|
|
383
|
+
if(context.batch){if(!await batchFlow(prefix,reviewResult)){progress('rulebook_rejected');return false;}}
|
|
384
|
+
else{
|
|
385
|
+
proposal=await invoke(`${prefix}/apply`,'refactor_apply',{target:config.target,analysis,attempt,files:source(config.scope),findings:reviewResult,route:routes.coder,
|
|
386
|
+
instructions:'Propose structure-only replacements, no file writes/commands/bug fixes. Return {files:[{path,beforeDigest,content}],summary,metricAfter,unfixedDefects:[],conventions:[],learningApplication,learningRetrospective}. New lessons must be reported, not hidden.'});
|
|
387
|
+
need(proposal.files.every(item=>item.content!==null),'refactor_deletion_requires_batch');await apply(`${prefix}/apply`,proposal.files,config.scope);
|
|
388
|
+
try{await equivalents(prefix);}catch(error){if(!unknown())await restore(`${prefix}/rollback`,Object.fromEntries(config.scope.map(name=>[name,context.original[name]])));throw error;}
|
|
389
|
+
}
|
|
390
|
+
const retrospective=await writeback(prefix);
|
|
391
|
+
const changed=managedNames.filter(name=>(files[name]??null)!==context.original[name]);
|
|
392
|
+
need(changed.length>0,'refactor_no_change');
|
|
393
|
+
const payload={schema_version:1,task_id:task,attempt,status:'ready_for_review',changed_files:changed,
|
|
394
|
+
implementation_sha256:await records.effect(`${prefix}-implementation`,'hash',{changed},()=>implementationSha256(project,changed)),
|
|
395
|
+
verification:[{command:'baseline + differential + judge self-validation',status:'passed',evidence:`${config.baselineCommands.length} baseline commands; ${judgeBefore.cases.length} groups equal; ${config.mutations.length} mutations detected`}],
|
|
396
|
+
evidence:[`learning: applied ${retrospective.learningApplication}`,`learning: retrospective ${changed.includes('AGENTS.md')?'written AGENTS.md':'no_new_lesson'}`,
|
|
397
|
+
...reports,`LESSONS reviewed SHA: ${sha(files.__lessons??context.lessons??'')}`],blockers:[],scope_deviation:[]};
|
|
398
|
+
const handoff=await publish(`${prefix}-handoff`,path.join(reviews,`${feature}-${task}-${prefix}-handoff.json`),payload);
|
|
399
|
+
const options={handoff,reviewsDir:reviews,feature,task,projectRoot:project,requireLearning:true};
|
|
400
|
+
// Cached reviewed attempts use their exact archived snapshot; current N5 is rechecked before finish.
|
|
401
|
+
await records.effect(`${prefix}-n4`,'gate',{handoff},()=>{guard();return checkN4(options);});
|
|
402
|
+
await event(`${prefix}-review-start`,'review','start',{attempt});
|
|
403
|
+
const reviewed=await invoke(`${prefix}/review`,'refactor_review',{handoff,handoffSha256:sha(JSON.stringify(payload,null,2)+'\n'),attempt,feature,task,
|
|
404
|
+
files:changed.map(name=>({path:name,before:context.original[name],after:files[name]})),analysis,retrospective,rulebook,judgeBefore,reports,
|
|
405
|
+
lessons:{path:lessons,before:context.lessons,after:files.__lessons??context.lessons},project,baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,
|
|
406
|
+
preTaskDirty:context.baseline.gitState,route:routes.reviewer,
|
|
407
|
+
instructions:'Fresh independent reviewer per runtime/review.md, no author history. Review ALL diff including tests/Learning/rules/docs/LESSONS and judge coverage. Return {markdown} with original N4 header binding exact handoff SHA, attempt=round, scope, findings. No writes or unapproved provider. Missing channel is blocked, never invent approval.'});
|
|
408
|
+
const review=await publish(`${prefix}-review`,path.join(reviews,`${feature}-${task}-r${attempt}.md`),reviewed.markdown);
|
|
409
|
+
reviewResult=validateReview(review,{task,attempt,handoff,changedFiles:changed});interceptions+=Number(reviewResult.blocking_findings);
|
|
410
|
+
await event(`${prefix}-review-complete`,'review','complete',{attempt,verdict:reviewResult.verdict,blocking_findings:Number(reviewResult.blocking_findings)});
|
|
411
|
+
if(reviewResult.verdict==='changes_requested'&&attempt===1){reviewResult={...reviewResult,markdown:reviewed.markdown};continue;}
|
|
412
|
+
guard();checkN5(options);proposal={...retrospective,changed,options};progress('awaiting_finish');return true;
|
|
413
|
+
}
|
|
414
|
+
need(false,'refactor_review_exhausted');
|
|
415
|
+
}
|
|
416
|
+
async function finish(){
|
|
417
|
+
const previous=[...records.effects.entries()].filter(([key])=>/^host\/finish-\d+$/.test(key));
|
|
418
|
+
const pending=previous.find(([,entry])=>!Object.hasOwn(entry,'result'));
|
|
419
|
+
const approved=previous.find(([,entry])=>entry.result?.value?.decision==='approved');
|
|
420
|
+
const selected=pending??approved,key=selected?selected[0].slice(5):`finish-${previous.length+1}`;
|
|
421
|
+
const presented=selected?selected[1].input.payload:{analysis,metricAfter:proposal.metricAfter,reports,baselineCount:config.baselineCommands.length,
|
|
422
|
+
budget:{estimatedTokens:initialPlan?config.scope.length*initialPlan.perFileEstimate:null,observedTokens:null,
|
|
423
|
+
hostDurationMs:[...records.effects.values()].filter(entry=>entry.kind==='host').reduce((sum,entry)=>sum+(entry.result?.durationMs??0),0)},
|
|
424
|
+
differentialCount:judgeBefore.cases.length,hostCalls,commandCount,unfixedDefects:proposal.unfixedDefects};
|
|
425
|
+
if(!await confirm(key,'finish',presented)){progress('awaiting_finish');return;}
|
|
426
|
+
need(!unknown(),'refactor_unknown_effect');guard();checkN5(proposal.options);
|
|
427
|
+
const calls=[...records.effects.values()].filter(entry=>entry.kind==='host'&&Object.hasOwn(entry,'result'));
|
|
428
|
+
const usage={agentCalls:calls.filter(entry=>entry.input.kind!=='refactor_confirm').length,
|
|
429
|
+
hostDurationMs:calls.reduce((sum,entry)=>sum+(entry.result.durationMs??0),0),
|
|
430
|
+
estimatedTokens:initialPlan?config.scope.length*initialPlan.perFileEstimate:null,observedTokens:null};
|
|
431
|
+
await publish('dossier',dossierPath(),'# Refactor dossier\n\n'+markdown({analysis,metricAfter:proposal.metricAfter,changed:proposal.changed,reports,
|
|
432
|
+
delivery:'diff',hostCalls,commandCount,baselineCount:config.baselineCommands.length,differentialCount:judgeBefore.cases.length,
|
|
433
|
+
learning:proposal.learning,unfixedDefects:proposal.unfixedDefects,deviations:[],usage}));
|
|
434
|
+
if(specs){const header='| 任务 | Feature | 开始 | 结束 | 审查轮次 | 独立审查拦截 | QA | 人工介入(次:原因) |',old=context.metrics;
|
|
435
|
+
need(!old||old.split(/\r?\n/).includes(header),'refactor_metrics_format');
|
|
436
|
+
const at=await records.effect('finish-time','clock',{},()=>new Date().toISOString());
|
|
437
|
+
const line=`| ${task} | refactor | ${context.startedAt} | ${at} | ${attempt} | ${interceptions} | 等价通过 | ${calls.filter(entry=>entry.input.kind==='refactor_confirm').length}:人门; delivery-diff; agents=${usage.agentCalls}; host_ms=${usage.hostDurationMs}; estimate_tokens=${usage.estimatedTokens??'unavailable'}; actual_tokens=unavailable; commands=${commandCount} |\n`;
|
|
438
|
+
await write('metrics',path.join(specs,'METRICS.md'),old,(old??`${header}\n| --- | --- | --- | --- | --- | --- | --- | --- |\n`)+(old&&!old.endsWith('\n')?'\n':'')+line,context.metricsMode);}
|
|
439
|
+
guard();checkN5(proposal.options);await event('task-finish','task_done',null,{attempt});
|
|
440
|
+
await event('run-finish','run_done',null,{result:'done',baseline_count:config.baselineCommands.length,differential_count:judgeBefore.cases.length});progress('done');
|
|
441
|
+
}
|
|
442
|
+
return Object.freeze({async handle(request){
|
|
443
|
+
need(request&&typeof request.operation==='string','invalid_request');
|
|
444
|
+
if(request.operation==='status'){
|
|
445
|
+
if(context)try{guard();}catch(error){return {...status(),stage:'correction_required',reason:error.code??error.message,historicalStage:view.stage};}return status();}
|
|
446
|
+
if(request.operation==='cancel'){controller.abort();return {...status(),stage:'cancelled'};}
|
|
447
|
+
need(!active,'refactor_busy');active=true;controller=new AbortController();
|
|
448
|
+
try{
|
|
449
|
+
need(['start','resume','finish'].includes(request.operation),'invalid_request');records.acquire();
|
|
450
|
+
if(!context){
|
|
451
|
+
need(request.operation==='start','refactor_not_started');
|
|
452
|
+
need(fs.readdirSync(directory).every(name=>name==='.writer.json'),'refactor_legacy_recovery_required');
|
|
453
|
+
need(!fs.existsSync(path.join(reviews,`${feature}-${task}-a1-handoff.json`)),'refactor_legacy_recovery_required');
|
|
454
|
+
const original=Object.fromEntries(managedNames.map(name=>[name,readText(absolute(name))]));
|
|
455
|
+
const batchTrack=Boolean(config.batch)||config.scope.length>3||config.crossModule||config.scope.some(name=>original[name]===null);
|
|
456
|
+
const baselineSnapshot=snapshotSource(project,archiveRoot);need(!batchTrack||baselineSnapshot.gitState,'refactor_batch_requires_git');
|
|
457
|
+
context={configDigest:digest(config),runId:`refactor-${randomUUID()}`,startedAt:new Date().toISOString(),original,
|
|
458
|
+
modes:Object.fromEntries(managedNames.map(name=>[name,original[name]===null?0o644:fs.statSync(absolute(name)).mode&0o777])),
|
|
459
|
+
baseline:baselineSnapshot,batch:batchTrack,lessons:readText(lessons),lessonsMode:fs.existsSync(lessons)?fs.statSync(lessons).mode&0o777:0o644,
|
|
460
|
+
metrics:specs?readText(path.join(specs,'METRICS.md')):null,metricsMode:specs&&fs.existsSync(path.join(specs,'METRICS.md'))?fs.statSync(path.join(specs,'METRICS.md')).mode&0o777:0o600};records.initialize(context);
|
|
461
|
+
}else{guard();if(view.stage==='done')return status();need(request.operation!=='start','refactor_resume_required');}
|
|
462
|
+
if(await flow()){
|
|
463
|
+
if(request.operation==='resume'){
|
|
464
|
+
const rounds=[...records.effects.keys()].map(key=>/^command\/resume-check\/(\d+)\//.exec(key)).filter(Boolean).map(match=>Number(match[1]));
|
|
465
|
+
const last=Math.max(0,...rounds),complete=records.effects.get(`resume-check-${last}-complete`);
|
|
466
|
+
const n=last===0?1:Object.hasOwn(complete??{},'result')?last+1:last;
|
|
467
|
+
await equivalents(`resume-check/${n}`);guard();checkN5(proposal.options);
|
|
468
|
+
await records.effect(`resume-check-${n}-complete`,'checkpoint',{round:n},()=>({completed:true}),()=>({completed:true}));
|
|
469
|
+
}
|
|
470
|
+
if(request.operation==='finish')await finish();
|
|
471
|
+
}
|
|
472
|
+
projectStatus();
|
|
473
|
+
return status();
|
|
474
|
+
}catch(error){view={...view,stage:controller.signal.aborted?'cancelled':'blocked',reason:error.code??error.message};
|
|
475
|
+
try{records.progressWrite(view);projectStatus();}catch{}return status();
|
|
476
|
+
}finally{records.release();active=false;}
|
|
477
|
+
}});
|
|
478
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Resolve declarations, never rewrite argv or run an implicit install/fallback.
|
|
2
|
+
import {need} from '../cm-ai/effect-contract.mjs';
|
|
3
|
+
import {checkSourceEvidence} from './source-snapshot.mjs';
|
|
4
|
+
|
|
5
|
+
export function inspectDeclaredTestCommand(item,sources){
|
|
6
|
+
checkSourceEvidence([{evidence:[item.declaration]}],sources);
|
|
7
|
+
need(Array.isArray(item.command)&&item.command.length>0
|
|
8
|
+
&&item.command.every(arg=>typeof arg==='string'&&arg.length>0&&!arg.includes('\0')),'cm_test_commands_invalid');
|
|
9
|
+
const source=sources.find(file=>file.path===item.declaration.path);
|
|
10
|
+
if(source.path!=='package.json'){
|
|
11
|
+
need(source.content.split('\n')[item.declaration.line-1].includes(item.command.join(' ')),
|
|
12
|
+
'cm_test_command_not_declared');
|
|
13
|
+
return {kind:'literal'};
|
|
14
|
+
}
|
|
15
|
+
const [manager,verb,name,...rest]=item.command;
|
|
16
|
+
need(['npm','pnpm','yarn','bun'].includes(manager),'cm_test_command_not_declared');
|
|
17
|
+
// Only script execution forms, never exec/dlx/install, workspace selection,
|
|
18
|
+
// cwd overrides, or flags that turn a missing script into success.
|
|
19
|
+
// `bun test` is a built-in runner, not the package script named "test".
|
|
20
|
+
const implicit=manager!=='bun'&&verb==='test'&&item.command.length===2;
|
|
21
|
+
need(implicit||(verb==='run'&&typeof name==='string'&&/^[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(name)
|
|
22
|
+
&&(rest.length===0||(rest[0]==='--'&&rest.length>1))),'cm_test_command_not_declared');
|
|
23
|
+
const script=implicit?'test':name;
|
|
24
|
+
let manifest;try{manifest=JSON.parse(source.content);}catch{need(false,'cm_test_package_invalid');}
|
|
25
|
+
need(manifest&&typeof manifest==='object'&&!Array.isArray(manifest)&&manifest.scripts
|
|
26
|
+
&&Object.hasOwn(manifest.scripts,script)&&typeof manifest.scripts[script]==='string'
|
|
27
|
+
&&manifest.scripts[script].trim(),'cm_test_command_not_declared');
|
|
28
|
+
// Lifecycle scripts are part of the declared execution, not invisible extras.
|
|
29
|
+
const lifecycle=Object.fromEntries([`pre${script}`,script,`post${script}`]
|
|
30
|
+
.filter(key=>Object.hasOwn(manifest.scripts,key)).map(key=>[key,manifest.scripts[key]]));
|
|
31
|
+
return {kind:'package-script',manager,script,lifecycle,packageDigest:source.sha256};
|
|
32
|
+
}
|