@apralabs/apra-fleet 0.4.0 → 0.4.2
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/README.md +159 -13
- package/dist/agents/backlog-groomer.md +31 -19
- package/dist/agents/ci-watcher.md +16 -1
- package/dist/agents/deployer.md +37 -47
- package/dist/agents/doer.md +147 -114
- package/dist/agents/harvester.md +41 -34
- package/dist/agents/integ-test-runner.md +98 -114
- package/dist/agents/kb-reconciler.md +205 -0
- package/dist/agents/plan-reviewer.md +45 -44
- package/dist/agents/planner.md +121 -50
- package/dist/agents/regression-test-runner.md +84 -81
- package/dist/agents/reviewer.md +118 -44
- package/dist/agents/schemas/doer-output.json +63 -3
- package/dist/agents/schemas/harvester-output.json +59 -2
- package/dist/agents/schemas/integ-test-runner-output.json +3 -3
- package/dist/agents/schemas/kb-reconciler-output.json +87 -0
- package/dist/agents/schemas/planner-output.json +65 -0
- package/dist/agents/schemas/regression-test-runner-output.json +4 -17
- package/dist/agents/schemas/reviewer-output.json +105 -8
- package/dist/cli/auth.d.ts.map +1 -1
- package/dist/cli/auth.js +1 -2
- package/dist/cli/auth.js.map +1 -1
- package/dist/cli/config.d.ts +3 -3
- package/dist/cli/config.d.ts.map +1 -1
- package/dist/cli/config.js +4 -13
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/install.d.ts +1 -0
- package/dist/cli/install.d.ts.map +1 -1
- package/dist/cli/install.js +141 -44
- package/dist/cli/install.js.map +1 -1
- package/dist/cli/join.js +1 -1
- package/dist/cli/join.js.map +1 -1
- package/dist/cli/kb-commit.d.ts +12 -0
- package/dist/cli/kb-commit.d.ts.map +1 -0
- package/dist/cli/kb-commit.js +53 -0
- package/dist/cli/kb-commit.js.map +1 -0
- package/dist/cli/kb-directives.d.ts +17 -0
- package/dist/cli/kb-directives.d.ts.map +1 -0
- package/dist/cli/kb-directives.js +146 -0
- package/dist/cli/kb-directives.js.map +1 -0
- package/dist/cli/kb-import.d.ts +13 -0
- package/dist/cli/kb-import.d.ts.map +1 -0
- package/dist/cli/kb-import.js +56 -0
- package/dist/cli/kb-import.js.map +1 -0
- package/dist/cli/register-member.js +1 -1
- package/dist/cli/start.d.ts.map +1 -1
- package/dist/cli/start.js +7 -0
- package/dist/cli/start.js.map +1 -1
- package/dist/cli/uninstall.d.ts.map +1 -1
- package/dist/cli/uninstall.js +16 -3
- package/dist/cli/uninstall.js.map +1 -1
- package/dist/cli/watch.d.ts +76 -4
- package/dist/cli/watch.d.ts.map +1 -1
- package/dist/cli/watch.js +150 -17
- package/dist/cli/watch.js.map +1 -1
- package/dist/commands/kb-server.d.ts +8 -0
- package/dist/commands/kb-server.d.ts.map +1 -0
- package/dist/commands/kb-server.js +221 -0
- package/dist/commands/kb-server.js.map +1 -0
- package/dist/index.js +77 -2
- package/dist/index.js.map +1 -1
- package/dist/os/git-bash-candidates.d.ts +35 -0
- package/dist/os/git-bash-candidates.d.ts.map +1 -0
- package/dist/os/git-bash-candidates.js +46 -0
- package/dist/os/git-bash-candidates.js.map +1 -0
- package/dist/os/index.d.ts +13 -4
- package/dist/os/index.d.ts.map +1 -1
- package/dist/os/index.js +17 -2
- package/dist/os/index.js.map +1 -1
- package/dist/os/linux.d.ts +1 -0
- package/dist/os/linux.d.ts.map +1 -1
- package/dist/os/linux.js +19 -2
- package/dist/os/linux.js.map +1 -1
- package/dist/os/os-commands.d.ts +12 -0
- package/dist/os/os-commands.d.ts.map +1 -1
- package/dist/os/os-commands.js.map +1 -1
- package/dist/os/windows-gitbash.d.ts +93 -0
- package/dist/os/windows-gitbash.d.ts.map +1 -0
- package/dist/os/windows-gitbash.js +244 -0
- package/dist/os/windows-gitbash.js.map +1 -0
- package/dist/os/windows.d.ts +35 -0
- package/dist/os/windows.d.ts.map +1 -1
- package/dist/os/windows.js +93 -35
- package/dist/os/windows.js.map +1 -1
- package/dist/providers/agy.d.ts +15 -3
- package/dist/providers/agy.d.ts.map +1 -1
- package/dist/providers/agy.js +145 -11
- package/dist/providers/agy.js.map +1 -1
- package/dist/providers/claude.d.ts +14 -3
- package/dist/providers/claude.d.ts.map +1 -1
- package/dist/providers/claude.js +69 -22
- package/dist/providers/claude.js.map +1 -1
- package/dist/providers/codex.d.ts +14 -3
- package/dist/providers/codex.d.ts.map +1 -1
- package/dist/providers/codex.js +34 -8
- package/dist/providers/codex.js.map +1 -1
- package/dist/providers/copilot.d.ts +14 -3
- package/dist/providers/copilot.d.ts.map +1 -1
- package/dist/providers/copilot.js +33 -8
- package/dist/providers/copilot.js.map +1 -1
- package/dist/providers/email/headers.d.ts +15 -0
- package/dist/providers/email/headers.d.ts.map +1 -0
- package/dist/providers/email/headers.js +42 -0
- package/dist/providers/email/headers.js.map +1 -0
- package/dist/providers/email/index.d.ts +18 -0
- package/dist/providers/email/index.d.ts.map +1 -0
- package/dist/providers/email/index.js +60 -0
- package/dist/providers/email/index.js.map +1 -0
- package/dist/providers/email/provider.d.ts +49 -0
- package/dist/providers/email/provider.d.ts.map +1 -0
- package/dist/providers/email/provider.js +2 -0
- package/dist/providers/email/provider.js.map +1 -0
- package/dist/providers/email/sendgrid.d.ts +12 -0
- package/dist/providers/email/sendgrid.d.ts.map +1 -0
- package/dist/providers/email/sendgrid.js +67 -0
- package/dist/providers/email/sendgrid.js.map +1 -0
- package/dist/providers/email/smtp.d.ts +65 -0
- package/dist/providers/email/smtp.d.ts.map +1 -0
- package/dist/providers/email/smtp.js +373 -0
- package/dist/providers/email/smtp.js.map +1 -0
- package/dist/providers/index.d.ts +0 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +0 -3
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/none.d.ts +14 -3
- package/dist/providers/none.d.ts.map +1 -1
- package/dist/providers/none.js +26 -2
- package/dist/providers/none.js.map +1 -1
- package/dist/providers/opencode.d.ts +14 -3
- package/dist/providers/opencode.d.ts.map +1 -1
- package/dist/providers/opencode.js +60 -6
- package/dist/providers/opencode.js.map +1 -1
- package/dist/providers/provider.d.ts +91 -5
- package/dist/providers/provider.d.ts.map +1 -1
- package/dist/providers/provider.js +45 -1
- package/dist/providers/provider.js.map +1 -1
- package/dist/services/agent-provisioner.d.ts.map +1 -1
- package/dist/services/agent-provisioner.js +5 -8
- package/dist/services/agent-provisioner.js.map +1 -1
- package/dist/services/cloud/activity.js +2 -2
- package/dist/services/cloud/activity.js.map +1 -1
- package/dist/services/cloud/lifecycle.d.ts.map +1 -1
- package/dist/services/cloud/lifecycle.js +3 -0
- package/dist/services/cloud/lifecycle.js.map +1 -1
- package/dist/services/cloud/task-wrapper.d.ts +18 -0
- package/dist/services/cloud/task-wrapper.d.ts.map +1 -1
- package/dist/services/cloud/task-wrapper.js +157 -0
- package/dist/services/cloud/task-wrapper.js.map +1 -1
- package/dist/services/context-admission.d.ts.map +1 -1
- package/dist/services/context-admission.js +9 -7
- package/dist/services/context-admission.js.map +1 -1
- package/dist/services/credential-cleanup.d.ts.map +1 -1
- package/dist/services/credential-cleanup.js +22 -3
- package/dist/services/credential-cleanup.js.map +1 -1
- package/dist/services/github-app.d.ts.map +1 -1
- package/dist/services/github-app.js +11 -2
- package/dist/services/github-app.js.map +1 -1
- package/dist/services/knowledge/audn.d.ts +37 -0
- package/dist/services/knowledge/audn.d.ts.map +1 -0
- package/dist/services/knowledge/audn.js +219 -0
- package/dist/services/knowledge/audn.js.map +1 -0
- package/dist/services/knowledge/file-hash.d.ts +11 -0
- package/dist/services/knowledge/file-hash.d.ts.map +1 -0
- package/dist/services/knowledge/file-hash.js +123 -0
- package/dist/services/knowledge/file-hash.js.map +1 -0
- package/dist/services/knowledge/http-provider.d.ts +46 -0
- package/dist/services/knowledge/http-provider.d.ts.map +1 -0
- package/dist/services/knowledge/http-provider.js +254 -0
- package/dist/services/knowledge/http-provider.js.map +1 -0
- package/dist/services/knowledge/kb-providers.d.ts +15 -0
- package/dist/services/knowledge/kb-providers.d.ts.map +1 -0
- package/dist/services/knowledge/kb-providers.js +92 -0
- package/dist/services/knowledge/kb-providers.js.map +1 -0
- package/dist/services/knowledge/kb-scope-input.d.ts +5 -0
- package/dist/services/knowledge/kb-scope-input.d.ts.map +1 -0
- package/dist/services/knowledge/kb-scope-input.js +11 -0
- package/dist/services/knowledge/kb-scope-input.js.map +1 -0
- package/dist/services/knowledge/kb-service.d.ts +3 -0
- package/dist/services/knowledge/kb-service.d.ts.map +1 -0
- package/dist/services/knowledge/kb-service.js +2 -0
- package/dist/services/knowledge/kb-service.js.map +1 -0
- package/dist/services/knowledge/path-validation.d.ts +2 -0
- package/dist/services/knowledge/path-validation.d.ts.map +1 -0
- package/dist/services/knowledge/path-validation.js +13 -0
- package/dist/services/knowledge/path-validation.js.map +1 -0
- package/dist/services/knowledge/pre-init.d.ts +14 -0
- package/dist/services/knowledge/pre-init.d.ts.map +1 -0
- package/dist/services/knowledge/pre-init.js +147 -0
- package/dist/services/knowledge/pre-init.js.map +1 -0
- package/dist/services/knowledge/project-slug.d.ts +2 -0
- package/dist/services/knowledge/project-slug.d.ts.map +1 -0
- package/dist/services/knowledge/project-slug.js +49 -0
- package/dist/services/knowledge/project-slug.js.map +1 -0
- package/dist/services/knowledge/sqlite-provider.d.ts +147 -0
- package/dist/services/knowledge/sqlite-provider.d.ts.map +1 -0
- package/dist/services/knowledge/sqlite-provider.js +1646 -0
- package/dist/services/knowledge/sqlite-provider.js.map +1 -0
- package/dist/services/knowledge/types.d.ts +163 -0
- package/dist/services/knowledge/types.d.ts.map +1 -0
- package/dist/services/knowledge/types.js +9 -0
- package/dist/services/knowledge/types.js.map +1 -0
- package/dist/services/member-home.d.ts +89 -0
- package/dist/services/member-home.d.ts.map +1 -0
- package/dist/services/member-home.js +259 -0
- package/dist/services/member-home.js.map +1 -0
- package/dist/services/member-remote-url.d.ts +34 -0
- package/dist/services/member-remote-url.d.ts.map +1 -0
- package/dist/services/member-remote-url.js +39 -0
- package/dist/services/member-remote-url.js.map +1 -0
- package/dist/services/model-pricing.d.ts.map +1 -1
- package/dist/services/model-pricing.js +0 -5
- package/dist/services/model-pricing.js.map +1 -1
- package/dist/services/orphan-recovery.d.ts +9 -3
- package/dist/services/orphan-recovery.d.ts.map +1 -1
- package/dist/services/orphan-recovery.js +22 -8
- package/dist/services/orphan-recovery.js.map +1 -1
- package/dist/services/preflight-check.d.ts +56 -0
- package/dist/services/preflight-check.d.ts.map +1 -0
- package/dist/services/preflight-check.js +277 -0
- package/dist/services/preflight-check.js.map +1 -0
- package/dist/services/shell-probe.d.ts +131 -0
- package/dist/services/shell-probe.d.ts.map +1 -0
- package/dist/services/shell-probe.js +210 -0
- package/dist/services/shell-probe.js.map +1 -0
- package/dist/services/singleton.d.ts +2 -0
- package/dist/services/singleton.d.ts.map +1 -1
- package/dist/services/singleton.js +1 -1
- package/dist/services/singleton.js.map +1 -1
- package/dist/services/ssh.js +2 -2
- package/dist/services/ssh.js.map +1 -1
- package/dist/services/stall/find-log-file.d.ts.map +1 -1
- package/dist/services/stall/find-log-file.js +22 -16
- package/dist/services/stall/find-log-file.js.map +1 -1
- package/dist/services/stall/log-path-resolver.d.ts +11 -8
- package/dist/services/stall/log-path-resolver.d.ts.map +1 -1
- package/dist/services/stall/log-path-resolver.js +17 -40
- package/dist/services/stall/log-path-resolver.js.map +1 -1
- package/dist/services/stall/read-log-tail.d.ts.map +1 -1
- package/dist/services/stall/read-log-tail.js +6 -5
- package/dist/services/stall/read-log-tail.js.map +1 -1
- package/dist/services/stall/stall-detector.d.ts +32 -0
- package/dist/services/stall/stall-detector.d.ts.map +1 -1
- package/dist/services/stall/stall-detector.js +149 -6
- package/dist/services/stall/stall-detector.js.map +1 -1
- package/dist/services/stall/stall-poller.d.ts +34 -0
- package/dist/services/stall/stall-poller.d.ts.map +1 -1
- package/dist/services/stall/stall-poller.js +160 -35
- package/dist/services/stall/stall-poller.js.map +1 -1
- package/dist/services/strategy.d.ts +9 -0
- package/dist/services/strategy.d.ts.map +1 -1
- package/dist/services/strategy.js +41 -7
- package/dist/services/strategy.js.map +1 -1
- package/dist/services/tool-registry.d.ts.map +1 -1
- package/dist/services/tool-registry.js +87 -1
- package/dist/services/tool-registry.js.map +1 -1
- package/dist/services/user-config.js +1 -1
- package/dist/services/user-config.js.map +1 -1
- package/dist/services/vcs/azure-devops.d.ts +1 -1
- package/dist/services/vcs/azure-devops.d.ts.map +1 -1
- package/dist/services/vcs/azure-devops.js +105 -10
- package/dist/services/vcs/azure-devops.js.map +1 -1
- package/dist/services/vcs/bitbucket.d.ts.map +1 -1
- package/dist/services/vcs/bitbucket.js +16 -0
- package/dist/services/vcs/bitbucket.js.map +1 -1
- package/dist/services/vcs/github.d.ts.map +1 -1
- package/dist/services/vcs/github.js +56 -1
- package/dist/services/vcs/github.js.map +1 -1
- package/dist/services/vcs/types.d.ts +123 -2
- package/dist/services/vcs/types.d.ts.map +1 -1
- package/dist/services/version-check.d.ts +22 -0
- package/dist/services/version-check.d.ts.map +1 -0
- package/dist/services/version-check.js +103 -0
- package/dist/services/version-check.js.map +1 -0
- package/dist/skills/fleet-sprint-cli/SKILL.md +15 -3
- package/dist/skills/pm/SKILL.md +0 -1
- package/dist/skills/pm/beads.md +6 -0
- package/dist/skills/pm/cost.md +0 -1
- package/dist/skills/pm/fleet-addendum.md +6 -1
- package/dist/skills/pm/index.md +56 -0
- package/dist/skills/pm/kb-reconcile.md +132 -0
- package/dist/skills/pm/kb-review.md +109 -0
- package/dist/tools/check-status.d.ts +47 -0
- package/dist/tools/check-status.d.ts.map +1 -1
- package/dist/tools/check-status.js +245 -3
- package/dist/tools/check-status.js.map +1 -1
- package/dist/tools/child-id-allocator.d.ts +2 -2
- package/dist/tools/cloud-control.js +2 -2
- package/dist/tools/cloud-control.js.map +1 -1
- package/dist/tools/code-intelligence-codebase-memory.d.ts +11 -0
- package/dist/tools/code-intelligence-codebase-memory.d.ts.map +1 -0
- package/dist/tools/code-intelligence-codebase-memory.js +270 -0
- package/dist/tools/code-intelligence-codebase-memory.js.map +1 -0
- package/dist/tools/code-intelligence-freshness.d.ts +2 -0
- package/dist/tools/code-intelligence-freshness.d.ts.map +1 -0
- package/dist/tools/code-intelligence-freshness.js +26 -0
- package/dist/tools/code-intelligence-freshness.js.map +1 -0
- package/dist/tools/code-intelligence-gitnexus.d.ts +14 -0
- package/dist/tools/code-intelligence-gitnexus.d.ts.map +1 -0
- package/dist/tools/code-intelligence-gitnexus.js +475 -0
- package/dist/tools/code-intelligence-gitnexus.js.map +1 -0
- package/dist/tools/code-intelligence-kb-enrich.d.ts +2 -0
- package/dist/tools/code-intelligence-kb-enrich.d.ts.map +1 -0
- package/dist/tools/code-intelligence-kb-enrich.js +65 -0
- package/dist/tools/code-intelligence-kb-enrich.js.map +1 -0
- package/dist/tools/code-intelligence-reindex.d.ts +7 -0
- package/dist/tools/code-intelligence-reindex.d.ts.map +1 -0
- package/dist/tools/code-intelligence-reindex.js +106 -0
- package/dist/tools/code-intelligence-reindex.js.map +1 -0
- package/dist/tools/code-intelligence-telemetry.d.ts +5 -0
- package/dist/tools/code-intelligence-telemetry.d.ts.map +1 -0
- package/dist/tools/code-intelligence-telemetry.js +52 -0
- package/dist/tools/code-intelligence-telemetry.js.map +1 -0
- package/dist/tools/code-intelligence-tests.d.ts +2 -0
- package/dist/tools/code-intelligence-tests.d.ts.map +1 -0
- package/dist/tools/code-intelligence-tests.js +24 -0
- package/dist/tools/code-intelligence-tests.js.map +1 -0
- package/dist/tools/code-intelligence.d.ts +114 -0
- package/dist/tools/code-intelligence.d.ts.map +1 -0
- package/dist/tools/code-intelligence.js +124 -0
- package/dist/tools/code-intelligence.js.map +1 -0
- package/dist/tools/compose-permissions.d.ts +26 -0
- package/dist/tools/compose-permissions.d.ts.map +1 -1
- package/dist/tools/compose-permissions.js +257 -33
- package/dist/tools/compose-permissions.js.map +1 -1
- package/dist/tools/execute-command.d.ts +2 -0
- package/dist/tools/execute-command.d.ts.map +1 -1
- package/dist/tools/execute-command.js +114 -28
- package/dist/tools/execute-command.js.map +1 -1
- package/dist/tools/execute-prompt.d.ts +13 -1
- package/dist/tools/execute-prompt.d.ts.map +1 -1
- package/dist/tools/execute-prompt.js +310 -61
- package/dist/tools/execute-prompt.js.map +1 -1
- package/dist/tools/kb-capture.d.ts +53 -0
- package/dist/tools/kb-capture.d.ts.map +1 -0
- package/dist/tools/kb-capture.js +130 -0
- package/dist/tools/kb-capture.js.map +1 -0
- package/dist/tools/kb-context.d.ts +17 -0
- package/dist/tools/kb-context.d.ts.map +1 -0
- package/dist/tools/kb-context.js +29 -0
- package/dist/tools/kb-context.js.map +1 -0
- package/dist/tools/kb-export.d.ts +19 -0
- package/dist/tools/kb-export.d.ts.map +1 -0
- package/dist/tools/kb-export.js +344 -0
- package/dist/tools/kb-export.js.map +1 -0
- package/dist/tools/kb-feedback.d.ts +23 -0
- package/dist/tools/kb-feedback.d.ts.map +1 -0
- package/dist/tools/kb-feedback.js +43 -0
- package/dist/tools/kb-feedback.js.map +1 -0
- package/dist/tools/kb-freshness-sweep.d.ts +14 -0
- package/dist/tools/kb-freshness-sweep.d.ts.map +1 -0
- package/dist/tools/kb-freshness-sweep.js +29 -0
- package/dist/tools/kb-freshness-sweep.js.map +1 -0
- package/dist/tools/kb-harvest.d.ts +20 -0
- package/dist/tools/kb-harvest.d.ts.map +1 -0
- package/dist/tools/kb-harvest.js +143 -0
- package/dist/tools/kb-harvest.js.map +1 -0
- package/dist/tools/kb-import.d.ts +44 -0
- package/dist/tools/kb-import.d.ts.map +1 -0
- package/dist/tools/kb-import.js +239 -0
- package/dist/tools/kb-import.js.map +1 -0
- package/dist/tools/kb-invalidate.d.ts +19 -0
- package/dist/tools/kb-invalidate.d.ts.map +1 -0
- package/dist/tools/kb-invalidate.js +34 -0
- package/dist/tools/kb-invalidate.js.map +1 -0
- package/dist/tools/kb-list.d.ts +32 -0
- package/dist/tools/kb-list.d.ts.map +1 -0
- package/dist/tools/kb-list.js +43 -0
- package/dist/tools/kb-list.js.map +1 -0
- package/dist/tools/kb-promote.d.ts +20 -0
- package/dist/tools/kb-promote.d.ts.map +1 -0
- package/dist/tools/kb-promote.js +20 -0
- package/dist/tools/kb-promote.js.map +1 -0
- package/dist/tools/kb-query.d.ts +35 -0
- package/dist/tools/kb-query.d.ts.map +1 -0
- package/dist/tools/kb-query.js +111 -0
- package/dist/tools/kb-query.js.map +1 -0
- package/dist/tools/kb-reconcile-prefilter.d.ts +14 -0
- package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -0
- package/dist/tools/kb-reconcile-prefilter.js +26 -0
- package/dist/tools/kb-reconcile-prefilter.js.map +1 -0
- package/dist/tools/kb-resolve-contradiction.d.ts +23 -0
- package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -0
- package/dist/tools/kb-resolve-contradiction.js +37 -0
- package/dist/tools/kb-resolve-contradiction.js.map +1 -0
- package/dist/tools/kb-session-prime.d.ts +26 -0
- package/dist/tools/kb-session-prime.d.ts.map +1 -0
- package/dist/tools/kb-session-prime.js +392 -0
- package/dist/tools/kb-session-prime.js.map +1 -0
- package/dist/tools/kb-setup.d.ts +20 -0
- package/dist/tools/kb-setup.d.ts.map +1 -0
- package/dist/tools/kb-setup.js +49 -0
- package/dist/tools/kb-setup.js.map +1 -0
- package/dist/tools/kb-stats.d.ts +20 -0
- package/dist/tools/kb-stats.d.ts.map +1 -0
- package/dist/tools/kb-stats.js +115 -0
- package/dist/tools/kb-stats.js.map +1 -0
- package/dist/tools/list-members.d.ts.map +1 -1
- package/dist/tools/list-members.js +6 -2
- package/dist/tools/list-members.js.map +1 -1
- package/dist/tools/member-detail.d.ts.map +1 -1
- package/dist/tools/member-detail.js +13 -3
- package/dist/tools/member-detail.js.map +1 -1
- package/dist/tools/member-reservation.d.ts.map +1 -1
- package/dist/tools/member-reservation.js +13 -1
- package/dist/tools/member-reservation.js.map +1 -1
- package/dist/tools/monitor-task.d.ts.map +1 -1
- package/dist/tools/monitor-task.js +38 -5
- package/dist/tools/monitor-task.js.map +1 -1
- package/dist/tools/provision-auth.d.ts.map +1 -1
- package/dist/tools/provision-auth.js +15 -8
- package/dist/tools/provision-auth.js.map +1 -1
- package/dist/tools/provision-vcs-auth.d.ts +5 -2
- package/dist/tools/provision-vcs-auth.d.ts.map +1 -1
- package/dist/tools/provision-vcs-auth.js +58 -52
- package/dist/tools/provision-vcs-auth.js.map +1 -1
- package/dist/tools/register-member.d.ts +21 -12
- package/dist/tools/register-member.d.ts.map +1 -1
- package/dist/tools/register-member.js +70 -3
- package/dist/tools/register-member.js.map +1 -1
- package/dist/tools/remove-member.d.ts.map +1 -1
- package/dist/tools/remove-member.js +19 -5
- package/dist/tools/remove-member.js.map +1 -1
- package/dist/tools/report-status.d.ts.map +1 -1
- package/dist/tools/report-status.js +2 -1
- package/dist/tools/report-status.js.map +1 -1
- package/dist/tools/revoke-vcs-auth.js +2 -2
- package/dist/tools/revoke-vcs-auth.js.map +1 -1
- package/dist/tools/send-email.d.ts +69 -0
- package/dist/tools/send-email.d.ts.map +1 -0
- package/dist/tools/send-email.js +177 -0
- package/dist/tools/send-email.js.map +1 -0
- package/dist/tools/setup-ssh-key.d.ts.map +1 -1
- package/dist/tools/setup-ssh-key.js +4 -1
- package/dist/tools/setup-ssh-key.js.map +1 -1
- package/dist/tools/stop-prompt.js +2 -2
- package/dist/tools/stop-prompt.js.map +1 -1
- package/dist/tools/update-agent-cli.js +2 -2
- package/dist/tools/update-agent-cli.js.map +1 -1
- package/dist/tools/update-member.d.ts +21 -12
- package/dist/tools/update-member.d.ts.map +1 -1
- package/dist/tools/update-member.js +43 -2
- package/dist/tools/update-member.js.map +1 -1
- package/dist/types.d.ts +12 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/agent-helpers.d.ts +36 -0
- package/dist/utils/agent-helpers.d.ts.map +1 -1
- package/dist/utils/agent-helpers.js +39 -1
- package/dist/utils/agent-helpers.js.map +1 -1
- package/dist/utils/platform.d.ts +7 -0
- package/dist/utils/platform.d.ts.map +1 -1
- package/dist/utils/platform.js +11 -1
- package/dist/utils/platform.js.map +1 -1
- package/dist/utils/prompt-errors.js +1 -1
- package/dist/utils/prompt-errors.js.map +1 -1
- package/dist/utils/session-caller.d.ts +28 -0
- package/dist/utils/session-caller.d.ts.map +1 -0
- package/dist/utils/session-caller.js +24 -0
- package/dist/utils/session-caller.js.map +1 -0
- package/dist/utils/work-folder-validation.d.ts +39 -0
- package/dist/utils/work-folder-validation.d.ts.map +1 -0
- package/dist/utils/work-folder-validation.js +60 -0
- package/dist/utils/work-folder-validation.js.map +1 -0
- package/dist/utils/workspace-trust.d.ts.map +1 -1
- package/dist/utils/workspace-trust.js +5 -1
- package/dist/utils/workspace-trust.js.map +1 -1
- package/dist/workflows/auto-sprint.js +550 -23
- package/package.json +7 -4
- package/packages/apra-fleet-client/src/client/api.mjs +210 -7
- package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +31 -19
- package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +16 -1
- package/packages/apra-fleet-se/apra-pm/agents/deployer.md +37 -47
- package/packages/apra-fleet-se/apra-pm/agents/doer.md +147 -114
- package/packages/apra-fleet-se/apra-pm/agents/harvester.md +41 -34
- package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +98 -114
- package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +205 -0
- package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +45 -44
- package/packages/apra-fleet-se/apra-pm/agents/planner.md +121 -50
- package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +84 -81
- package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +118 -44
- package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +63 -3
- package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-output.json +59 -2
- package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +3 -3
- package/packages/apra-fleet-se/apra-pm/agents/schemas/kb-reconciler-output.json +87 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +65 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +4 -17
- package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +105 -8
- package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +0 -1
- package/packages/apra-fleet-se/apra-pm/skills/pm/beads.md +6 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +0 -1
- package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +6 -1
- package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +56 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +132 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +109 -0
- package/packages/apra-fleet-se/bin/cli.mjs +139 -3
- package/packages/apra-fleet-se/bin/serve.mjs +49 -2
- package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +182 -38
- package/packages/apra-fleet-se/fleet-sprint/docs/README.md +23 -8
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-manual-recovery-verified.md +258 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +1487 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +908 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/shared-orchestrator-reservation-design.md +399 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/stabilization-log.md +14 -4
- package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +1148 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +229 -112
- package/packages/apra-fleet-se/fleet-sprint/errors.mjs +91 -6
- package/packages/apra-fleet-se/fleet-sprint/runner.js +2469 -238
- package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +134 -0
- package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +154 -0
- package/packages/apra-fleet-se/fleet-sprint/se-windows-gitbash.mjs +97 -0
- package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +143 -0
- package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +15 -3
- package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +350 -0
- package/packages/apra-fleet-se/fleet-sprint/sprint-progress.mjs +101 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +51 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +657 -12
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/dolt.mjs +33 -4
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +60 -30
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +205 -2
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +164 -0
- package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +141 -26
- package/packages/apra-fleet-se/package.json +1 -0
- package/packages/apra-fleet-workflow/src/viewer/index.mjs +294 -14
- package/packages/apra-fleet-workflow/src/viewer/run-title.mjs +60 -0
- package/packages/apra-fleet-workflow/src/workflow/index.mjs +443 -35
- package/skills/fleet/SKILL.md +20 -9
- package/skills/fleet/auth-azdevops.md +44 -5
- package/skills/fleet/auth-bitbucket.md +3 -3
- package/skills/fleet/auth-github.md +2 -2
- package/skills/fleet/beads-conflict-resolution.md +141 -0
- package/skills/fleet/beads.md +16 -12
- package/skills/fleet/knowledge-agent.md +66 -0
- package/skills/fleet/onboarding.md +4 -4
- package/skills/fleet/permissions.md +32 -8
- package/skills/fleet/profiles/base-dev.json +10 -1
- package/skills/fleet/profiles/base-reviewer.json +8 -1
- package/skills/fleet/profiles/tag-kb-reconciler.json +20 -0
- package/skills/fleet/skill-matrix.md +1 -1
- package/skills/fleet/troubleshooting.md +2 -1
- package/version.json +1 -1
- package/dist/providers/gemini.d.ts +0 -42
- package/dist/providers/gemini.d.ts.map +0 -1
- package/dist/providers/gemini.js +0 -202
- package/dist/providers/gemini.js.map +0 -1
- package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +0 -151
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-tier2-runbook.md +0 -127
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-path-b.mjs +0 -339
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-tier2.mjs +0 -360
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery.mjs +0 -363
|
@@ -4,8 +4,9 @@ import { AgentOutputError, AgentDispatchError, FleetTransportError, CommandError
|
|
|
4
4
|
import {
|
|
5
5
|
ROLES, normalizeRole, planReviewerVerdict, doerReport, reviewerVerdict, streakAssignment,
|
|
6
6
|
deployerReport, integReport, regressionReport, finalVerdict, harvesterReport, wrapUntrustedBlock,
|
|
7
|
+
validateCredentialStoreName,
|
|
7
8
|
} from './contracts.mjs';
|
|
8
|
-
import { SprintPlanRejectedError, StalledSprintError, ReviewerContractViolationError, GitDivergedError, GitSyncError, DoltDivergedError, DoltSyncError, PostDispatchSyncError, PlanReviewDispatchFailedError, isNonRetryableDispatchError, isAuthDispatchError, isInfraDispatchFailure, isPostDispatchSyncFailure } from './errors.mjs';
|
|
9
|
+
import { SprintPlanRejectedError, StalledSprintError, ReviewerContractViolationError, GitDivergedError, GitSyncError, DoltDivergedError, DoltSyncError, PostDispatchSyncError, PlanReviewDispatchFailedError, MemberReservationResumeError, isNonRetryableDispatchError, isAuthDispatchError, isInfraDispatchFailure, isPostDispatchSyncFailure } from './errors.mjs';
|
|
9
10
|
// The ONLY dolt command surface in fleet-sprint (apra-fleet-417.2.1). Every
|
|
10
11
|
// runner.js call site uses the purpose-based entry points on DoltSync
|
|
11
12
|
// (apra-fleet-417.2.2); the named primitives are imported here only to be
|
|
@@ -24,13 +25,16 @@ const POST_DISPATCH_SYNC_RETRY_DELAYS_MS = [0, 5000, 15000];
|
|
|
24
25
|
const mockInstantRetryBackoff = () => process.env.APRA_FLEET_MOCK_INSTANT_RETRY_BACKOFF === '1';
|
|
25
26
|
import { ApraFleet } from '@apralabs/apra-fleet-client';
|
|
26
27
|
import { parseUnmergedPaths, detectAndAbortRebaseConflict, dispatchConflictResolutionAgent } from './conflict-ladder.mjs';
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
|
|
28
|
+
// The deterministic dolt conflict settlement callback (docs/dolt-sync-
|
|
29
|
+
// redesign.md). It REPLACES the retired Path A -> Path B -> Tier 2 ladder at
|
|
30
|
+
// BOTH divergence terminals: the post-dispatch D-push bracket
|
|
31
|
+
// (syncMemberAfterOrdered) and the pre-dispatch D-pull / readiness gate, so a
|
|
32
|
+
// wedged beads clone self-heals instead of surfacing BEADS_SYNC_CONFLICT or
|
|
33
|
+
// hard-aborting the run at its readiness gate.
|
|
34
|
+
import { buildSettleCallback } from './dolt-settle.mjs';
|
|
32
35
|
import { acquireSprintLock } from './sprint-lock.mjs';
|
|
33
|
-
import { buildCreatePrCommand, resolveProvider, capabilities as vcsCapabilities, classifyFailure, toGitVerdict } from './vcs-module.mjs';
|
|
36
|
+
import { buildCreatePrCommand, resolveProvider, capabilities as vcsCapabilities, classifyFailure, toGitVerdict, parseProviderRepoRef, getVcsProvider } from './vcs-module.mjs';
|
|
37
|
+
import { getSeCommands } from './se-os-commands.mjs';
|
|
34
38
|
|
|
35
39
|
// Re-exported so importers of parseUnmergedPaths from runner.js keep working;
|
|
36
40
|
// conflict-ladder.mjs is the single source of truth for its implementation.
|
|
@@ -320,6 +324,13 @@ const KNOWN_ARG_KEYS = new Set([
|
|
|
320
324
|
// and per-bead work-claiming. All three are no-ops without it -- a lone
|
|
321
325
|
// sprint has no sibling to coordinate with.
|
|
322
326
|
'serviceUrl',
|
|
327
|
+
// apra-fleet-5co8.37: this launch's incarnation-unique run identity -- the
|
|
328
|
+
// SAME string the supervisor's reservation ledger keys this sprint by
|
|
329
|
+
// (bin/cli.mjs forwards the supervisor's --run-id, falling back to the
|
|
330
|
+
// branch name for a direct/standalone launch, which is also what cli.mjs
|
|
331
|
+
// reserves members under). Threaded to the deployer so its active-sprints
|
|
332
|
+
// gate can tell this sprint's OWN reservation from a foreign one.
|
|
333
|
+
'run_id',
|
|
323
334
|
// The assignee identity this sprint claims beads as and filters ready work
|
|
324
335
|
// by (`bd update --claim` / `bd ready --assignee`). Nothing sets this
|
|
325
336
|
// today; the claiming layer stays dormant and bead selection uses the
|
|
@@ -353,6 +364,11 @@ const KNOWN_ARG_KEYS = new Set([
|
|
|
353
364
|
// `import()`, never across a subprocess boundary). Absent for direct
|
|
354
365
|
// runSprintCycle()/main() test calls, where the guard is a no-op.
|
|
355
366
|
'callTool',
|
|
367
|
+
// Per-sprint override for the Azure DevOps PAT secret name. When provided, this
|
|
368
|
+
// credential store entry name is used instead of the documented default
|
|
369
|
+
// (azdevops_pat). No CLI flag sets this today; only test/programmatic callers
|
|
370
|
+
// pass it.
|
|
371
|
+
'azdevops_pat_secret_name',
|
|
356
372
|
]);
|
|
357
373
|
|
|
358
374
|
/**
|
|
@@ -908,7 +924,7 @@ export async function syncMemberBefore(member, opts = {}) {
|
|
|
908
924
|
export async function syncMemberAfter(member, opts = {}) {
|
|
909
925
|
const {
|
|
910
926
|
command, pushCode = true, log = () => {}, maxTransientRetries = 1, remote = 'origin', branch,
|
|
911
|
-
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider,
|
|
927
|
+
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider, setUpstream = false,
|
|
912
928
|
} = opts;
|
|
913
929
|
if (typeof command !== 'function') {
|
|
914
930
|
throw new Error("syncMemberAfter requires an injected command() in opts");
|
|
@@ -919,7 +935,15 @@ export async function syncMemberAfter(member, opts = {}) {
|
|
|
919
935
|
}
|
|
920
936
|
const provider = await resolveGitProviderForClassification(resolveMemberProvider, member, log);
|
|
921
937
|
|
|
922
|
-
|
|
938
|
+
// apra-fleet: `setUpstream` (opt-in, default false -- every existing
|
|
939
|
+
// caller's command text is byte-for-byte unchanged) is for Publish PR's
|
|
940
|
+
// push specifically: it needs `-u` to set the tracking branch on a brand
|
|
941
|
+
// new sprint branch's first push, AND that distinct spelling is what lets
|
|
942
|
+
// mock-sprint-publish-push-failure.test.mjs's `gitGhFailurePattern` (and
|
|
943
|
+
// any real-world log grep) target Publish's push in isolation from every
|
|
944
|
+
// OTHER per-dispatch G-push in the same sprint, which all share the plain
|
|
945
|
+
// `git push <remote> <branch>` spelling below.
|
|
946
|
+
const pushCmd = branch ? `git push${setUpstream ? ' -u' : ''} ${remote} ${branch}` : 'git push';
|
|
923
947
|
|
|
924
948
|
let push = await runGitStep({
|
|
925
949
|
command, member, cmd: pushCmd,
|
|
@@ -1088,6 +1112,7 @@ export {
|
|
|
1088
1112
|
* remote?: string, agent?: Function, resolveConflictModel?: string,
|
|
1089
1113
|
* onAuthFailure?: Function,
|
|
1090
1114
|
* resolveMemberProvider?: (member: string) => Promise<string|undefined>,
|
|
1115
|
+
* args?: { callTool?: Function },
|
|
1091
1116
|
* }} opts
|
|
1092
1117
|
* @returns {Promise<{ ok: true, member: string, gPush: object, dPush: object }>}
|
|
1093
1118
|
*/
|
|
@@ -1095,7 +1120,7 @@ export async function syncMemberAfterOrdered(member, opts = {}) {
|
|
|
1095
1120
|
const {
|
|
1096
1121
|
command, pushCode = true, pushBeads = true, log = () => {},
|
|
1097
1122
|
mutex, sprintId, branch, maxTransientRetries = 1, remote = 'origin',
|
|
1098
|
-
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider,
|
|
1123
|
+
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider, args,
|
|
1099
1124
|
} = opts;
|
|
1100
1125
|
|
|
1101
1126
|
let gPush;
|
|
@@ -1114,33 +1139,27 @@ export async function syncMemberAfterOrdered(member, opts = {}) {
|
|
|
1114
1139
|
// ordering above exists to prevent, and would erase the
|
|
1115
1140
|
// BEADS_SYNC_CONFLICT terminal reason the dashboard reports.
|
|
1116
1141
|
//
|
|
1117
|
-
//
|
|
1118
|
-
//
|
|
1119
|
-
//
|
|
1120
|
-
//
|
|
1121
|
-
//
|
|
1122
|
-
//
|
|
1123
|
-
// (
|
|
1124
|
-
//
|
|
1142
|
+
// Before that fatal divergence surfaces, run the deterministic settle
|
|
1143
|
+
// (settleDoltConflicts, dolt-settle.mjs). It is TOTAL over row-level
|
|
1144
|
+
// conflicts -- no gates, no allowlist, no LLM escalation -- and a resolved
|
|
1145
|
+
// settle is a VERIFIED recovery, because settle republishes (bd dolt pull
|
|
1146
|
+
// + push) and checks the push actually landed before returning. The streak
|
|
1147
|
+
// only fails (DoltDivergedError -> BEADS_SYNC_CONFLICT) when settle itself
|
|
1148
|
+
// hits an operational failure (no usable dolt binary, the ephemeral server
|
|
1149
|
+
// would not start, a SQL statement errored).
|
|
1125
1150
|
//
|
|
1126
|
-
//
|
|
1127
|
-
//
|
|
1128
|
-
//
|
|
1129
|
-
//
|
|
1130
|
-
//
|
|
1131
|
-
//
|
|
1132
|
-
//
|
|
1133
|
-
//
|
|
1134
|
-
//
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
// own doc comment (dolt-recovery-tier2.mjs) for the general hazard this
|
|
1139
|
-
// guards against, and DoltSync.repair() for an explicit, operator-driven
|
|
1140
|
-
// entry point where a real pendingMutation and member-scoped
|
|
1141
|
-
// readConfig/removePath/listLocalState CAN be supplied deliberately.
|
|
1142
|
-
const recover = buildDoltRecoveryLadder(member, { command, agent, log, model: resolveConflictModel, enablePathB: false });
|
|
1143
|
-
const dPush = await DoltSync.syncAfter(member, { command, pushBeads, log, mutex, sprintId, onAuthFailure, fatal: true, recover });
|
|
1151
|
+
// Notably, the data-loss hazard that forced the old ladder's Path B to be
|
|
1152
|
+
// disabled at THIS call site does not exist for settle: it never discards
|
|
1153
|
+
// and re-bootstraps a clone, so an arbitrary multi-command dispatch's bead
|
|
1154
|
+
// mutations cannot be silently thrown away here. There is no pendingMutation
|
|
1155
|
+
// to capture and replay because nothing is ever dropped.
|
|
1156
|
+
// Thread this member's REGISTERED shell into dolt-settle the same way
|
|
1157
|
+
// the pre-dispatch bracket does (apra-fleet-7dir.16/.24), guarded on
|
|
1158
|
+
// `args.callTool` so a caller with no MCP client (mock-sprint scenarios)
|
|
1159
|
+
// keeps the pre-shell-aware default.
|
|
1160
|
+
const shell = await resolveSettleShell({ args, member, log });
|
|
1161
|
+
const settle = buildSettleCallback(member, { command, log, shell });
|
|
1162
|
+
const dPush = await DoltSync.syncAfter(member, { command, pushBeads, log, mutex, sprintId, onAuthFailure, fatal: true, settle });
|
|
1144
1163
|
return { ok: true, member, gPush, dPush };
|
|
1145
1164
|
}
|
|
1146
1165
|
|
|
@@ -1213,6 +1232,22 @@ export function createHttpDoltPushMutexClient(opts = {}) {
|
|
|
1213
1232
|
return false;
|
|
1214
1233
|
}
|
|
1215
1234
|
},
|
|
1235
|
+
// Lease renewal (docs/dolt-sync-redesign.md Part 3.4): doltPushAfter()
|
|
1236
|
+
// renews on an interval while it holds the mutex, so a legitimately
|
|
1237
|
+
// long hold (push + reconcile + settle) is never force-evicted by the
|
|
1238
|
+
// supervisor's 60s lease expiry while this sprint is still pushing.
|
|
1239
|
+
async renew(token) {
|
|
1240
|
+
if (token == null) return false;
|
|
1241
|
+
const id = boundSprintId;
|
|
1242
|
+
if (!id) throw new Error('[dolt-mutex] renew requires a bound sprintId');
|
|
1243
|
+
try {
|
|
1244
|
+
const payload = await postJson(routeFor(id, 'renew'), { token });
|
|
1245
|
+
return Boolean(payload.renewed);
|
|
1246
|
+
} catch (err) {
|
|
1247
|
+
log(`[dolt-mutex] renew failed (non-fatal; the lease may expire): ${err.message}`);
|
|
1248
|
+
return false;
|
|
1249
|
+
}
|
|
1250
|
+
},
|
|
1216
1251
|
};
|
|
1217
1252
|
}
|
|
1218
1253
|
|
|
@@ -1382,6 +1417,18 @@ export function createMcpDoltPushMutexClient(opts = {}) {
|
|
|
1382
1417
|
return false;
|
|
1383
1418
|
}
|
|
1384
1419
|
},
|
|
1420
|
+
// Same lease-renewal contract as the HTTP client above (design doc
|
|
1421
|
+
// Part 3.4); the fleet tool exposes action 'renew'.
|
|
1422
|
+
async renew(token) {
|
|
1423
|
+
if (token == null) return false;
|
|
1424
|
+
try {
|
|
1425
|
+
const payload = await call({ action: 'renew', token });
|
|
1426
|
+
return Boolean(payload.renewed);
|
|
1427
|
+
} catch (err) {
|
|
1428
|
+
log(`[dolt-mutex/mcp] renew failed (non-fatal; the lease may expire): ${err.message}`);
|
|
1429
|
+
return false;
|
|
1430
|
+
}
|
|
1431
|
+
},
|
|
1385
1432
|
};
|
|
1386
1433
|
}
|
|
1387
1434
|
|
|
@@ -1467,6 +1514,554 @@ export function createMcpChildIdAllocatorClient(opts = {}) {
|
|
|
1467
1514
|
* @param {{ callTool: (name: string, args: object) => Promise<any>, members?: string[], sprintId?: string, log?: Function }} opts
|
|
1468
1515
|
* @returns {{ reserveAll: () => Promise<void>, releaseAll: () => Promise<void> }}
|
|
1469
1516
|
*/
|
|
1517
|
+
/**
|
|
1518
|
+
* apra-fleet-e28 / KB trust pipeline Phase 2: KB priming for the fleet-sprint
|
|
1519
|
+
* engine, which had none -- it lived only in the Claude workflow copy.
|
|
1520
|
+
*
|
|
1521
|
+
* `callTool` is injected exactly like `createMemberReservationClient`'s, so this
|
|
1522
|
+
* stays transport-agnostic and unit-testable without a live fleet server.
|
|
1523
|
+
*
|
|
1524
|
+
* WHY PER MEMBER, NOT PER SPRINT: this engine has no repo path of its own. It
|
|
1525
|
+
* coordinates members by name and branch; the repo lives on each member's side,
|
|
1526
|
+
* possibly on a different host at a different path. `kb_session_prime` selects
|
|
1527
|
+
* WHICH project KB is read from its `repo_path`, and omitting that argument
|
|
1528
|
+
* falls back to the fleet server's own cwd -- collapsing every member's
|
|
1529
|
+
* knowledge into whichever repo the server happens to sit in, which is exactly
|
|
1530
|
+
* the apra-fleet-tm7 / apra-fleet-3zl repo-blindness defect. So the work folder
|
|
1531
|
+
* is resolved per member via `member_detail` (which reports it as `folder`) and
|
|
1532
|
+
* each member is primed against its own repo.
|
|
1533
|
+
*
|
|
1534
|
+
* Best-effort throughout, matching the reservation client's precedent: a member
|
|
1535
|
+
* whose folder cannot be resolved, or whose prime call fails, is logged and
|
|
1536
|
+
* skipped. A sprint must not fail because the KB is cold -- priming is an
|
|
1537
|
+
* optimisation, and every role contract's Step 0 already degrades gracefully
|
|
1538
|
+
* when the KB tools are unavailable.
|
|
1539
|
+
*
|
|
1540
|
+
* @param {{ callTool?: (name: string, args: object) => Promise<any>, members?: string[], log?: Function }} opts
|
|
1541
|
+
* @returns {{ primeAll: () => Promise<{primed: number, skipped: number}> }}
|
|
1542
|
+
*/
|
|
1543
|
+
/**
|
|
1544
|
+
* Cap on primed entries carried into a dispatch prompt. kb_session_prime can
|
|
1545
|
+
* return up to ~28 (10 direct FTS hits + 3 global + 5 graph-neighbour + 5
|
|
1546
|
+
* project-bible + 5 global-bible); a dispatch prompt is not a place to spend
|
|
1547
|
+
* that much budget on context the role may not need, and the entries are
|
|
1548
|
+
* already returned in relevance order.
|
|
1549
|
+
*/
|
|
1550
|
+
export const KB_MAX_KNOWLEDGE_ENTRIES = 12;
|
|
1551
|
+
|
|
1552
|
+
/**
|
|
1553
|
+
* The URL-based KB scope selector, spread into a kb_* call's arguments.
|
|
1554
|
+
*
|
|
1555
|
+
* repo_path alone is only sufficient for a LOCAL member: resolveProjectSlug
|
|
1556
|
+
* (src/services/knowledge/project-slug.ts) runs git in that directory to derive
|
|
1557
|
+
* the project slug. A remote member's work folder is a path on another host, so
|
|
1558
|
+
* both git probes fail and the slug degrades to 'default' -- collapsing every
|
|
1559
|
+
* remote member's knowledge into one shared KB. repo_remote_url selects the DB
|
|
1560
|
+
* directly (apra-fleet-b4g.1) and is what makes a sprint's kb_* calls land in
|
|
1561
|
+
* the member's own project KB.
|
|
1562
|
+
*
|
|
1563
|
+
* Absent when no URL is known: an omitted scope is the honest pre-existing
|
|
1564
|
+
* degradation, while a fabricated one routes writes into a slug that does not
|
|
1565
|
+
* match the repo's real local-clone slug. The engine never derives a URL -- it
|
|
1566
|
+
* forwards only what member_detail reports (knownRepoRemoteUrl's rule).
|
|
1567
|
+
*/
|
|
1568
|
+
function kbScope(remoteUrl) {
|
|
1569
|
+
return (typeof remoteUrl === 'string' && remoteUrl.length > 0) ? { repo_remote_url: remoteUrl } : {};
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
export function createKbPrimingClient(opts = {}) {
|
|
1573
|
+
const { callTool, members = [], log = () => {} } = opts;
|
|
1574
|
+
const active = typeof callTool === 'function' && members.length > 0;
|
|
1575
|
+
|
|
1576
|
+
function parseResult(result) {
|
|
1577
|
+
if (result && typeof result === 'string') { try { return JSON.parse(result); } catch { return null; } }
|
|
1578
|
+
if (result && Array.isArray(result.content) && result.content[0] && typeof result.content[0].text === 'string') {
|
|
1579
|
+
try { return JSON.parse(result.content[0].text); } catch { return null; }
|
|
1580
|
+
}
|
|
1581
|
+
return (result && typeof result === 'object') ? result : null;
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
async function scopeFor(member) {
|
|
1585
|
+
// apra-fleet-n78: format:'json' is REQUIRED. member_detail defaults to
|
|
1586
|
+
// 'compact', whose renderer emits no folder at all -- `folder` is set only
|
|
1587
|
+
// on the json path (src/tools/member-detail.ts). Omitting it made this
|
|
1588
|
+
// return null for every member, so the KB was never primed for anyone.
|
|
1589
|
+
const detail = parseResult(await callTool('member_detail', { member_name: member, format: 'json' }));
|
|
1590
|
+
// member_detail reports the work folder as `folder` and the repo origin
|
|
1591
|
+
// URL as `repo_remote_url` (src/tools/member-detail.ts). The URL is
|
|
1592
|
+
// reported only when the member's registration record proves it, so an
|
|
1593
|
+
// absent one is normal and must stay absent rather than be derived here.
|
|
1594
|
+
const folder = detail && (detail.folder || (detail.member && detail.member.folder));
|
|
1595
|
+
const url = detail && (detail.repo_remote_url || (detail.member && detail.member.repo_remote_url));
|
|
1596
|
+
return {
|
|
1597
|
+
folder: (typeof folder === 'string' && folder.length > 0) ? folder : null,
|
|
1598
|
+
remoteUrl: (typeof url === 'string' && url.length > 0) ? url : null,
|
|
1599
|
+
};
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
// member -> work folder, populated by primeAll(). createKbWorkClient reads
|
|
1603
|
+
// it so a capture lands in the repo the member actually worked in, rather
|
|
1604
|
+
// than being resolved against the fleet server's cwd.
|
|
1605
|
+
const folders = new Map();
|
|
1606
|
+
|
|
1607
|
+
// member -> the repo origin URL member_detail reported for it, when it
|
|
1608
|
+
// reported one. This is what scopes a REMOTE member's kb_* calls to its own
|
|
1609
|
+
// project KB instead of the shared 'default' one (see kbScope).
|
|
1610
|
+
const remoteUrls = new Map();
|
|
1611
|
+
|
|
1612
|
+
// work folder -> that folder's origin URL, or CONFLICTING_URL when two
|
|
1613
|
+
// members claim the same path string for DIFFERENT repos. The work client
|
|
1614
|
+
// resolves its scope through this map rather than taking the URL as an
|
|
1615
|
+
// extra argument at each of its nine call sites: threading the repo path is
|
|
1616
|
+
// then the same act as threading the scope, so a site cannot forget one
|
|
1617
|
+
// while remembering the other.
|
|
1618
|
+
const urlByFolder = new Map();
|
|
1619
|
+
const CONFLICTING_URL = Symbol('conflicting-remote-url');
|
|
1620
|
+
|
|
1621
|
+
// member -> the entries kb_session_prime returned for that member.
|
|
1622
|
+
//
|
|
1623
|
+
// KB audit 2026-08-11: primeAll() used to `await callTool(...)` and throw
|
|
1624
|
+
// the result away, on the assumption that priming "warms" something the
|
|
1625
|
+
// role's own Step 0 would later read. It does not: prime is a pure read,
|
|
1626
|
+
// and the role CANNOT repeat it -- a member-dispatched subagent has the
|
|
1627
|
+
// fleet MCP server disabled (src/providers/claude.ts
|
|
1628
|
+
// composePermissionConfig), so every contract's Step 0 kb_session_prime is
|
|
1629
|
+
// unreachable there. Nothing consumed the knowledge and nothing could, which
|
|
1630
|
+
// is why six sprints retrieved zero entries. Retaining the result is what
|
|
1631
|
+
// lets kbKnowledgeBlock() hand it to the role in its dispatch prompt --
|
|
1632
|
+
// the same shape of fix that made kb_promotions reachable.
|
|
1633
|
+
const knowledge = new Map();
|
|
1634
|
+
|
|
1635
|
+
return {
|
|
1636
|
+
folderOf(member) {
|
|
1637
|
+
return folders.get(member) || null;
|
|
1638
|
+
},
|
|
1639
|
+
remoteUrlOf(member) {
|
|
1640
|
+
return remoteUrls.get(member) || null;
|
|
1641
|
+
},
|
|
1642
|
+
/**
|
|
1643
|
+
* The URL scoping kb_* calls made against `repoPath`, or null.
|
|
1644
|
+
*
|
|
1645
|
+
* Null for an unknown path, for a local member (no URL was reported),
|
|
1646
|
+
* and for a path two members claim with different URLs. Members on
|
|
1647
|
+
* different hosts can share a work-folder path string while being
|
|
1648
|
+
* clones of different repos; picking either URL there would route one
|
|
1649
|
+
* member's captures into the other's KB, which is strictly worse than
|
|
1650
|
+
* the 'default' degradation this scoping exists to remove. Refusing
|
|
1651
|
+
* leaves that case exactly as it was before.
|
|
1652
|
+
*/
|
|
1653
|
+
remoteUrlForPath(repoPath) {
|
|
1654
|
+
if (typeof repoPath !== 'string' || repoPath.length === 0) return null;
|
|
1655
|
+
const url = urlByFolder.get(repoPath);
|
|
1656
|
+
return (typeof url === 'string') ? url : null;
|
|
1657
|
+
},
|
|
1658
|
+
knowledgeOf(member) {
|
|
1659
|
+
return knowledge.get(member) || [];
|
|
1660
|
+
},
|
|
1661
|
+
async primeAll() {
|
|
1662
|
+
if (!active) return { primed: 0, skipped: members.length };
|
|
1663
|
+
let primed = 0;
|
|
1664
|
+
let skipped = 0;
|
|
1665
|
+
for (const member of members) {
|
|
1666
|
+
try {
|
|
1667
|
+
const { folder: repoPath, remoteUrl } = await scopeFor(member);
|
|
1668
|
+
if (repoPath) folders.set(member, repoPath);
|
|
1669
|
+
if (remoteUrl) remoteUrls.set(member, remoteUrl);
|
|
1670
|
+
if (repoPath && remoteUrl) {
|
|
1671
|
+
const known = urlByFolder.get(repoPath);
|
|
1672
|
+
if (known !== undefined && known !== remoteUrl) {
|
|
1673
|
+
urlByFolder.set(repoPath, CONFLICTING_URL);
|
|
1674
|
+
log(`[kb-prime] work folder ${repoPath} is claimed by two different repos -- KB calls for it stay unscoped`);
|
|
1675
|
+
} else {
|
|
1676
|
+
urlByFolder.set(repoPath, remoteUrl);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
if (!repoPath) {
|
|
1680
|
+
// No folder means no repo to scope the KB to. Priming without
|
|
1681
|
+
// one would read the fleet server's own KB, so skip instead.
|
|
1682
|
+
log(`[kb-prime] no work folder for member '${member}' -- skipping (KB stays cold)`);
|
|
1683
|
+
skipped++;
|
|
1684
|
+
continue;
|
|
1685
|
+
}
|
|
1686
|
+
// Land the committed bible in the WARM KB before priming.
|
|
1687
|
+
//
|
|
1688
|
+
// Without this the bible is reachable only through
|
|
1689
|
+
// kb_session_prime's cold-seed, which reads it as a FILE
|
|
1690
|
+
// and caps at 5 entries -- apra-fleet's own bible holds 17,
|
|
1691
|
+
// so a sprint could see at most 5 arbitrary ones and FTS
|
|
1692
|
+
// could rank none of them, because they were never rows.
|
|
1693
|
+
// Importing first is what gives the per-dispatch kb_query
|
|
1694
|
+
// (see relevantKnowledge) anything to match against.
|
|
1695
|
+
// Idempotent by id, and best-effort: a repo with no bible,
|
|
1696
|
+
// or an import that rejects every entry, must not stop the
|
|
1697
|
+
// prime it was meant to feed.
|
|
1698
|
+
//
|
|
1699
|
+
// skip_sweep IS LOAD-BEARING (audit 2026-08-12, caught by a
|
|
1700
|
+
// live sprint). kb_import's post-import freshnessSweep
|
|
1701
|
+
// re-judges the ENTIRE KB against this member's worktree. At
|
|
1702
|
+
// sprint start that staled 16 of 17 CONFIRMED entries purely
|
|
1703
|
+
// because the repo had moved on since capture, and the
|
|
1704
|
+
// damage cascaded: retrieval fell to one matchable entry,
|
|
1705
|
+
// kb_export attempted a 17 -> 9 bible truncation, and
|
|
1706
|
+
// kb_list (stale=0) returned an EMPTY promotion candidate
|
|
1707
|
+
// list -- reinstating apra-fleet-0ef, "kb_promote can never
|
|
1708
|
+
// fire". This import exists to WARM the KB, never to audit
|
|
1709
|
+
// it; prime()'s own bounded checkFreshness still guards each
|
|
1710
|
+
// entry it actually returns.
|
|
1711
|
+
try {
|
|
1712
|
+
const imported = parseResult(await callTool('kb_import', { repo_path: repoPath, ...kbScope(remoteUrl), skip_sweep: true }));
|
|
1713
|
+
if (imported && typeof imported.imported === 'number' && imported.imported > 0) {
|
|
1714
|
+
log(`[kb-prime] imported ${imported.imported} bible entr(ies) into the warm KB for ${repoPath}`);
|
|
1715
|
+
}
|
|
1716
|
+
} catch (err) {
|
|
1717
|
+
log(`[kb-prime] kb_import skipped for ${repoPath} (non-fatal): ${err.message}`);
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
const primeResult = parseResult(await callTool('kb_session_prime', { repo_path: repoPath, ...kbScope(remoteUrl) }));
|
|
1721
|
+
const entries = (primeResult && Array.isArray(primeResult.top_entries))
|
|
1722
|
+
? primeResult.top_entries.filter((e) => e && typeof e.id === 'string')
|
|
1723
|
+
: [];
|
|
1724
|
+
if (entries.length > 0) knowledge.set(member, entries.slice(0, KB_MAX_KNOWLEDGE_ENTRIES));
|
|
1725
|
+
primed++;
|
|
1726
|
+
} catch (err) {
|
|
1727
|
+
log(`[kb-prime] failed for member '${member}' (non-fatal): ${err.message}`);
|
|
1728
|
+
skipped++;
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
if (primed > 0) log(`[kb-prime] primed ${primed} member repo(s)`);
|
|
1732
|
+
return { primed, skipped };
|
|
1733
|
+
},
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
/**
|
|
1738
|
+
* KB trust pipeline Phase 2, execution half for this engine.
|
|
1739
|
+
*
|
|
1740
|
+
* The role output schemas are SHARED with apra-pm (contracts.mjs loads them from
|
|
1741
|
+
* apra-pm/agents/schemas), so every role dispatched here is now asked for
|
|
1742
|
+
* kb_captures, and the reviewer for kb_promotions. Without a consumer those
|
|
1743
|
+
* fields would be silently dropped -- the knowledge would be gathered and
|
|
1744
|
+
* thrown away. This is that consumer.
|
|
1745
|
+
*
|
|
1746
|
+
* Unlike apra-pm's auto-sprint.js -- a Claude Workflow script with no tool
|
|
1747
|
+
* access, which must hand its vetted payload to an executor subagent -- this
|
|
1748
|
+
* engine runs in-process with an injected callTool, so it makes the kb_capture
|
|
1749
|
+
* and kb_promote calls DIRECTLY. Judgment still belongs to the role; execution
|
|
1750
|
+
* belongs here.
|
|
1751
|
+
*
|
|
1752
|
+
* Validation mirrors lib/vet-kb-work.mjs in apra-pm and the provider invariants
|
|
1753
|
+
* it reflects: a capture must cite at least one source file (SqliteProvider
|
|
1754
|
+
* rejects an entry the freshness sweep can never stale), a promotion needs a
|
|
1755
|
+
* recorded evidence string, and kb_promotions is refused from any role other
|
|
1756
|
+
* than reviewer -- widening capture to four roles must not widen promotion.
|
|
1757
|
+
*
|
|
1758
|
+
* @param {{ callTool?: (name: string, args: object) => Promise<any>, log?: Function }} opts
|
|
1759
|
+
* @returns {{ apply: (role: string, repoPath: string, result: any) => Promise<{captured: number, promoted: number, refused: number}> }}
|
|
1760
|
+
*/
|
|
1761
|
+
export const KB_PROMOTER_ROLES = Object.freeze(new Set([ROLE_REVIEWER]));
|
|
1762
|
+
export const KB_MIN_PROMOTE_REASON = 20;
|
|
1763
|
+
export const KB_CAPTURE_TYPES = Object.freeze(['knowledge', 'learning', 'runbook']);
|
|
1764
|
+
|
|
1765
|
+
/**
|
|
1766
|
+
* True when an MCP tool result represents a tool-level failure. The MCP client
|
|
1767
|
+
* resolves such results instead of throwing (apra-fleet-23c), so callers that
|
|
1768
|
+
* only catch exceptions silently treat failures as successes.
|
|
1769
|
+
*/
|
|
1770
|
+
function isToolError(res) {
|
|
1771
|
+
return !!(res && typeof res === 'object' && res.isError === true);
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/** Best-effort human-readable text out of an MCP error result, for logging. */
|
|
1775
|
+
function toolErrorText(res) {
|
|
1776
|
+
const first = res && Array.isArray(res.content) ? res.content[0] : null;
|
|
1777
|
+
return (first && typeof first.text === 'string' && first.text) || 'no error text returned';
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
export function vetKbWork(role, result) {
|
|
1781
|
+
const captures = [];
|
|
1782
|
+
const promotions = [];
|
|
1783
|
+
const refused = [];
|
|
1784
|
+
|
|
1785
|
+
const rawCaptures = (result && Array.isArray(result.kb_captures)) ? result.kb_captures : [];
|
|
1786
|
+
for (const c of rawCaptures) {
|
|
1787
|
+
if (!c || typeof c.title !== 'string' || typeof c.summary !== 'string') {
|
|
1788
|
+
refused.push(`${role}: capture missing title/summary`);
|
|
1789
|
+
continue;
|
|
1790
|
+
}
|
|
1791
|
+
if (!Array.isArray(c.source_files) || c.source_files.length === 0) {
|
|
1792
|
+
refused.push(`${role}: capture "${c.title}" cites no source files`);
|
|
1793
|
+
continue;
|
|
1794
|
+
}
|
|
1795
|
+
if (!KB_CAPTURE_TYPES.includes(c.type)) {
|
|
1796
|
+
refused.push(`${role}: capture "${c.title}" has unsupported type ${String(c.type)}`);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
// apra-fleet-23c: kbCaptureSchema requires content (z.string().min(1)).
|
|
1800
|
+
// Omitting it here meant every kb_capture the engine sent failed zod
|
|
1801
|
+
// validation at the MCP boundary and persisted nothing.
|
|
1802
|
+
if (typeof c.content !== 'string' || c.content.trim().length === 0) {
|
|
1803
|
+
refused.push(`${role}: capture "${c.title}" has no content`);
|
|
1804
|
+
continue;
|
|
1805
|
+
}
|
|
1806
|
+
captures.push({
|
|
1807
|
+
type: c.type,
|
|
1808
|
+
title: c.title,
|
|
1809
|
+
summary: c.summary,
|
|
1810
|
+
content: c.content,
|
|
1811
|
+
source_files: c.source_files,
|
|
1812
|
+
symbols: Array.isArray(c.symbols) ? c.symbols : [],
|
|
1813
|
+
});
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
const rawPromotions = (result && Array.isArray(result.kb_promotions)) ? result.kb_promotions : [];
|
|
1817
|
+
if (rawPromotions.length > 0 && !KB_PROMOTER_ROLES.has(role)) {
|
|
1818
|
+
refused.push(`${role}: kb_promotions refused -- promotion is reviewer-only`);
|
|
1819
|
+
} else {
|
|
1820
|
+
for (const p of rawPromotions) {
|
|
1821
|
+
if (!p || typeof p.id !== 'string' || p.id.length === 0) {
|
|
1822
|
+
refused.push(`${role}: promotion missing id`);
|
|
1823
|
+
continue;
|
|
1824
|
+
}
|
|
1825
|
+
if (typeof p.reason !== 'string' || p.reason.trim().length < KB_MIN_PROMOTE_REASON) {
|
|
1826
|
+
refused.push(`${role}: promotion ${p.id} has no recorded evidence`);
|
|
1827
|
+
continue;
|
|
1828
|
+
}
|
|
1829
|
+
promotions.push({ id: p.id, reason: p.reason.trim() });
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
return { captures, promotions, refused };
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
/** Max promotion candidates offered to one reviewer, so the prompt stays bounded. */
|
|
1837
|
+
export const KB_MAX_PROMOTION_CANDIDATES = 40;
|
|
1838
|
+
|
|
1839
|
+
export function createKbWorkClient(opts = {}) {
|
|
1840
|
+
const { callTool, log = () => {}, remoteUrlFor } = opts;
|
|
1841
|
+
const active = typeof callTool === 'function';
|
|
1842
|
+
|
|
1843
|
+
/**
|
|
1844
|
+
* The URL-based KB scope for a repo path, resolved through the injected
|
|
1845
|
+
* lookup (createKbPrimingClient's remoteUrlForPath). Deliberately NOT an
|
|
1846
|
+
* extra parameter on the methods below: they are called from nine places
|
|
1847
|
+
* across runSprintCycle/finalReview/harvest, and an omitted argument is
|
|
1848
|
+
* indistinguishable from "no URL known" -- it would silently reinstate the
|
|
1849
|
+
* repo-blindness this exists to fix. With no lookup injected (every
|
|
1850
|
+
* construction site predating this, and direct unit calls) the scope is
|
|
1851
|
+
* absent and behaviour is exactly as before.
|
|
1852
|
+
*/
|
|
1853
|
+
function scopeOf(repoPath) {
|
|
1854
|
+
return kbScope(typeof remoteUrlFor === 'function' ? remoteUrlFor(repoPath) : null);
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
/** Best-effort JSON out of an MCP result (string, content-block, or plain object). */
|
|
1858
|
+
function parseResult(result) {
|
|
1859
|
+
if (typeof result === 'string') { try { return JSON.parse(result); } catch { return null; } }
|
|
1860
|
+
if (result && Array.isArray(result.content) && result.content[0] && typeof result.content[0].text === 'string') {
|
|
1861
|
+
try { return JSON.parse(result.content[0].text); } catch { return null; }
|
|
1862
|
+
}
|
|
1863
|
+
return (result && typeof result === 'object') ? result : null;
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
return {
|
|
1867
|
+
/**
|
|
1868
|
+
* apra-fleet-0ef: the INFERRED entries this reviewer may promote.
|
|
1869
|
+
*
|
|
1870
|
+
* The engine's contract is "judgment belongs to the role, execution
|
|
1871
|
+
* belongs here" -- the reviewer returns `kb_promotions:[{id, reason}]`
|
|
1872
|
+
* and `apply()` calls kb_promote. But an entry id exists only inside
|
|
1873
|
+
* the KB, and the reviewer subagent has no apra-fleet MCP tools to
|
|
1874
|
+
* look one up, so it could never name an id: `kb_promotions` was
|
|
1875
|
+
* structurally always empty and nothing was ever promoted. (kb_captures
|
|
1876
|
+
* worked only because a capture needs no pre-existing id.) This is the
|
|
1877
|
+
* missing input: the engine reads the candidates and hands them to the
|
|
1878
|
+
* reviewer in its prompt.
|
|
1879
|
+
*
|
|
1880
|
+
* Best-effort by design -- a cold or unreachable KB must degrade to
|
|
1881
|
+
* "nothing to promote", never fail the review dispatch.
|
|
1882
|
+
*/
|
|
1883
|
+
async promotionCandidates(repoPath) {
|
|
1884
|
+
// Without a repo path kb_list would resolve against the fleet
|
|
1885
|
+
// server's cwd and offer entries from an unrelated project's KB
|
|
1886
|
+
// (the apra-fleet-tm7 repo-blindness class). Refuse rather than guess.
|
|
1887
|
+
if (!active || !repoPath) return [];
|
|
1888
|
+
try {
|
|
1889
|
+
const parsed = parseResult(await callTool('kb_list', {
|
|
1890
|
+
repo_path: repoPath,
|
|
1891
|
+
...scopeOf(repoPath),
|
|
1892
|
+
confidence: 'INFERRED',
|
|
1893
|
+
limit: KB_MAX_PROMOTION_CANDIDATES,
|
|
1894
|
+
}));
|
|
1895
|
+
const results = parsed && Array.isArray(parsed.results) ? parsed.results : [];
|
|
1896
|
+
return results
|
|
1897
|
+
// promote() refuses type='user-directive' outright (activation
|
|
1898
|
+
// is human-terminal, CLI-only), so offering one as a candidate
|
|
1899
|
+
// can only produce a guaranteed refusal.
|
|
1900
|
+
.filter((e) => e && typeof e.id === 'string' && e.type !== 'user-directive')
|
|
1901
|
+
.slice(0, KB_MAX_PROMOTION_CANDIDATES);
|
|
1902
|
+
} catch (err) {
|
|
1903
|
+
log(`[kb-work] could not list promotion candidates for ${repoPath} (non-fatal): ${err.message}`);
|
|
1904
|
+
return [];
|
|
1905
|
+
}
|
|
1906
|
+
},
|
|
1907
|
+
/**
|
|
1908
|
+
* KB audit follow-up: the per-dispatch, relevance-ranked read.
|
|
1909
|
+
*
|
|
1910
|
+
* primeAll() runs ONCE per member at sprint start with no hints, so
|
|
1911
|
+
* every role received the same handful of entries no matter what it was
|
|
1912
|
+
* about to work on -- and kb_query went unused by this engine entirely.
|
|
1913
|
+
* This asks the KB what it knows about THIS dispatch, using the terms
|
|
1914
|
+
* the engine already holds (bead ids and their titles).
|
|
1915
|
+
*
|
|
1916
|
+
* `expand_related` is what finally reads the KB's own graph. The KB has
|
|
1917
|
+
* been writing `refines` and `contradiction_of` edges since AUDN
|
|
1918
|
+
* shipped and traversing none of them: 554 edges, 0 reads. A role about
|
|
1919
|
+
* to act on an entry is precisely who needs to know that entry has a
|
|
1920
|
+
* newer framing or a standing dispute -- especially since confidence
|
|
1921
|
+
* tier does NOT track correctness across a contradiction chain (the
|
|
1922
|
+
* warehouse chain-A shape, where the incorrect entry outranks both of
|
|
1923
|
+
* its corrections).
|
|
1924
|
+
*
|
|
1925
|
+
* Best-effort, like every other KB read here: no repo path, no terms, a
|
|
1926
|
+
* cold KB or an unreachable one all degrade to "no knowledge", never to
|
|
1927
|
+
* a failed dispatch.
|
|
1928
|
+
*/
|
|
1929
|
+
async relevantKnowledge(repoPath, terms) {
|
|
1930
|
+
if (!active || !repoPath || !Array.isArray(terms) || terms.length === 0) return [];
|
|
1931
|
+
const query = terms.filter((t) => typeof t === 'string' && t.trim()).join(' ');
|
|
1932
|
+
if (!query) return [];
|
|
1933
|
+
try {
|
|
1934
|
+
const parsed = parseResult(await callTool('kb_query', {
|
|
1935
|
+
repo_path: repoPath,
|
|
1936
|
+
...scopeOf(repoPath),
|
|
1937
|
+
query,
|
|
1938
|
+
limit: KB_MAX_KNOWLEDGE_ENTRIES,
|
|
1939
|
+
expand_related: true,
|
|
1940
|
+
}));
|
|
1941
|
+
if (!parsed) return [];
|
|
1942
|
+
const hits = Array.isArray(parsed.l1_results) ? parsed.l1_results : [];
|
|
1943
|
+
const related = Array.isArray(parsed.related_claims) ? parsed.related_claims : [];
|
|
1944
|
+
const seen = new Set();
|
|
1945
|
+
const out = [];
|
|
1946
|
+
for (const e of hits) {
|
|
1947
|
+
if (!e || typeof e.id !== 'string' || seen.has(e.id)) continue;
|
|
1948
|
+
seen.add(e.id);
|
|
1949
|
+
out.push(e);
|
|
1950
|
+
}
|
|
1951
|
+
// Related claims sit BELOW every direct hit and carry a marker,
|
|
1952
|
+
// so a role can tell "the KB matched this" from "the KB says
|
|
1953
|
+
// something about what it matched".
|
|
1954
|
+
for (const e of related) {
|
|
1955
|
+
if (!e || typeof e.id !== 'string' || seen.has(e.id)) continue;
|
|
1956
|
+
seen.add(e.id);
|
|
1957
|
+
out.push({ ...e, via: 'kb-graph' });
|
|
1958
|
+
}
|
|
1959
|
+
return out.slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
|
|
1960
|
+
} catch (err) {
|
|
1961
|
+
log(`[kb-work] kb_query failed for ${repoPath} (non-fatal): ${err.message}`);
|
|
1962
|
+
return [];
|
|
1963
|
+
}
|
|
1964
|
+
},
|
|
1965
|
+
async apply(role, repoPath, result) {
|
|
1966
|
+
const { captures, promotions, refused } = vetKbWork(role, result);
|
|
1967
|
+
|
|
1968
|
+
for (const r of refused) log(`[kb-work] refused -- ${r}`);
|
|
1969
|
+
// Log every promotion with its stated evidence BEFORE attempting it.
|
|
1970
|
+
// This log is the audit trail the bible never had.
|
|
1971
|
+
for (const p of promotions) log(`[kb-work] promote ${p.id} (${role}): ${p.reason}`);
|
|
1972
|
+
|
|
1973
|
+
// Without a repo path a capture would land in whichever KB the fleet
|
|
1974
|
+
// server's cwd resolves to -- the tm7 defect. Refuse rather than guess.
|
|
1975
|
+
if (!active || !repoPath) {
|
|
1976
|
+
if ((captures.length || promotions.length) && !repoPath) {
|
|
1977
|
+
log(`[kb-work] no repo path for ${role} -- ${captures.length} capture(s) and ${promotions.length} promotion(s) dropped`);
|
|
1978
|
+
}
|
|
1979
|
+
return { captured: 0, promoted: 0, refused: refused.length };
|
|
1980
|
+
}
|
|
1981
|
+
|
|
1982
|
+
let captured = 0;
|
|
1983
|
+
let promoted = 0;
|
|
1984
|
+
for (const c of captures) {
|
|
1985
|
+
try {
|
|
1986
|
+
const res = await callTool('kb_capture', { ...c, repo_path: repoPath, ...scopeOf(repoPath) });
|
|
1987
|
+
// apra-fleet-23c: an MCP client RESOLVES with {isError:true} on a
|
|
1988
|
+
// tool-level failure rather than throwing, so counting every
|
|
1989
|
+
// non-throwing call as a success reported captures that never
|
|
1990
|
+
// persisted ("captured 3" against a KB that stayed empty).
|
|
1991
|
+
if (isToolError(res)) {
|
|
1992
|
+
log(`[kb-work] kb_capture rejected for "${c.title}" (non-fatal): ${toolErrorText(res)}`);
|
|
1993
|
+
continue;
|
|
1994
|
+
}
|
|
1995
|
+
captured++;
|
|
1996
|
+
} catch (err) {
|
|
1997
|
+
log(`[kb-work] kb_capture failed for "${c.title}" (non-fatal): ${err.message}`);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
for (const p of promotions) {
|
|
2001
|
+
try {
|
|
2002
|
+
// apra-fleet-0ef: repo_path is REQUIRED here, exactly as on
|
|
2003
|
+
// the kb_capture call above. Omitting it resolved the
|
|
2004
|
+
// promotion against the fleet server's cwd -- a different
|
|
2005
|
+
// project's KB, where the id does not exist -- so every
|
|
2006
|
+
// promotion would have failed "Entry not found" (the
|
|
2007
|
+
// apra-fleet-tm7 repo-blindness class, fixed for capture
|
|
2008
|
+
// but missed here).
|
|
2009
|
+
const res = await callTool('kb_promote', { id: p.id, reason: p.reason, repo_path: repoPath, ...scopeOf(repoPath) });
|
|
2010
|
+
if (isToolError(res)) {
|
|
2011
|
+
log(`[kb-work] kb_promote rejected for ${p.id} (non-fatal): ${toolErrorText(res)}`);
|
|
2012
|
+
continue;
|
|
2013
|
+
}
|
|
2014
|
+
promoted++;
|
|
2015
|
+
} catch (err) {
|
|
2016
|
+
log(`[kb-work] kb_promote failed for ${p.id} (non-fatal): ${err.message}`);
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
if (captured || promoted) log(`[kb-work] ${role}: captured ${captured}, promoted ${promoted}`);
|
|
2020
|
+
return { captured, promoted, refused: refused.length };
|
|
2021
|
+
},
|
|
2022
|
+
|
|
2023
|
+
/**
|
|
2024
|
+
* KB audit 2026-08-11: publish this repo's CONFIRMED set to its
|
|
2025
|
+
* canonical bible (<repo>/.fleet/kb-canonical.json).
|
|
2026
|
+
*
|
|
2027
|
+
* Nothing in the pipeline had ever called kb_export, so a bible existed
|
|
2028
|
+
* only where an operator had run the tool by hand -- 1 of 17 repos on
|
|
2029
|
+
* the audited machine. Promotion therefore ended at the local sqlite
|
|
2030
|
+
* store: a teammate, a fresh clone, or a member on another host saw
|
|
2031
|
+
* none of it, and kb_session_prime's cold-seed (which reads exactly
|
|
2032
|
+
* this file) had nothing to fall back on. Promotion is the sprint's
|
|
2033
|
+
* work; publishing it is the step that makes the work leave the
|
|
2034
|
+
* machine.
|
|
2035
|
+
*
|
|
2036
|
+
* Called once, AFTER the final review's promotions have been applied,
|
|
2037
|
+
* so the bible reflects everything this sprint confirmed. Best-effort
|
|
2038
|
+
* like every other KB call here: a sprint must never fail over an
|
|
2039
|
+
* export, and the tool itself is a no-op when the entry set is
|
|
2040
|
+
* unchanged. Committing/pushing the file stays a separate, opt-in
|
|
2041
|
+
* decision (kb_export's own autoCommit config) -- this does not widen
|
|
2042
|
+
* the engine's git authority.
|
|
2043
|
+
*/
|
|
2044
|
+
async exportBible(repoPath) {
|
|
2045
|
+
// Same repo-blindness guard as every other call here: without a
|
|
2046
|
+
// path kb_export would resolve against the fleet server's cwd and
|
|
2047
|
+
// write an unrelated project's bible.
|
|
2048
|
+
if (!active || !repoPath) return false;
|
|
2049
|
+
try {
|
|
2050
|
+
const res = await callTool('kb_export', { repo_path: repoPath, ...scopeOf(repoPath) });
|
|
2051
|
+
if (isToolError(res)) {
|
|
2052
|
+
log(`[kb-work] kb_export rejected for ${repoPath} (non-fatal): ${toolErrorText(res)}`);
|
|
2053
|
+
return false;
|
|
2054
|
+
}
|
|
2055
|
+
log(`[kb-work] exported the canonical bible for ${repoPath}`);
|
|
2056
|
+
return true;
|
|
2057
|
+
} catch (err) {
|
|
2058
|
+
log(`[kb-work] kb_export failed for ${repoPath} (non-fatal): ${err.message}`);
|
|
2059
|
+
return false;
|
|
2060
|
+
}
|
|
2061
|
+
},
|
|
2062
|
+
};
|
|
2063
|
+
}
|
|
2064
|
+
|
|
1470
2065
|
export function createMemberReservationClient(opts = {}) {
|
|
1471
2066
|
const { callTool, members = [], sprintId, log = () => {} } = opts;
|
|
1472
2067
|
const active = typeof callTool === 'function' && typeof sprintId === 'string' && sprintId.length > 0 && members.length > 0;
|
|
@@ -1479,26 +2074,97 @@ export function createMemberReservationClient(opts = {}) {
|
|
|
1479
2074
|
return '';
|
|
1480
2075
|
}
|
|
1481
2076
|
|
|
2077
|
+
// Returns { ok, text } rather than throwing so BOTH the best-effort callers
|
|
2078
|
+
// (reserveAll/releaseAll, which ignore the outcome) and the owner-checked
|
|
2079
|
+
// resume caller (reReserveForResume, which MUST know per-member whether the
|
|
2080
|
+
// reserve was granted or rejected) can share one call path. `ok` is false
|
|
2081
|
+
// on a tool rejection ("already reserved by X") OR a transport throw; the
|
|
2082
|
+
// caller decides what a failure means for its own contract.
|
|
1482
2083
|
async function callFor(action, member) {
|
|
1483
2084
|
try {
|
|
1484
2085
|
const result = await callTool('member_reservation', { member_name: member, action, sprint_id: sprintId });
|
|
1485
2086
|
const text = resultText(result);
|
|
1486
2087
|
if ((result && result.isError) || text.startsWith('[-]')) {
|
|
1487
2088
|
log(`[member-reservation] ${action} rejected for member '${member}': ${text || '(no detail)'}`);
|
|
2089
|
+
return { ok: false, text };
|
|
1488
2090
|
}
|
|
2091
|
+
return { ok: true, text };
|
|
1489
2092
|
} catch (err) {
|
|
1490
2093
|
log(`[member-reservation] ${action} failed for member '${member}' (non-fatal; execute_prompt's dispatch-time reservedBy check still applies): ${err.message}`);
|
|
2094
|
+
return { ok: false, text: err.message };
|
|
1491
2095
|
}
|
|
1492
2096
|
}
|
|
1493
2097
|
|
|
2098
|
+
async function releaseAll() {
|
|
2099
|
+
if (!active) return;
|
|
2100
|
+
for (const member of members) await callFor('release', member);
|
|
2101
|
+
}
|
|
2102
|
+
|
|
1494
2103
|
return {
|
|
1495
2104
|
async reserveAll() {
|
|
1496
2105
|
if (!active) return;
|
|
1497
2106
|
for (const member of members) await callFor('reserve', member);
|
|
1498
2107
|
},
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
2108
|
+
releaseAll,
|
|
2109
|
+
|
|
2110
|
+
// (apra-fleet-p2to.4.2) Pause hand-back: release EVERY member so a
|
|
2111
|
+
// different sprint may claim it while this one is parked at a
|
|
2112
|
+
// cooperative pause. Best-effort per member, exactly like releaseAll()
|
|
2113
|
+
// -- a pause must never fail on a release hiccup, and execute_prompt's
|
|
2114
|
+
// dispatch-time reservedBy check still fails loudly on any member this
|
|
2115
|
+
// sprint later dispatches to without holding.
|
|
2116
|
+
//
|
|
2117
|
+
// (apra-fleet-p2to.4.4.1) releaseForPause() is intentionally the SAME
|
|
2118
|
+
// operation as releaseAll() -- both release every member,
|
|
2119
|
+
// best-effort, with no distinct behavior of their own -- so this
|
|
2120
|
+
// calls straight through to releaseAll() rather than keeping a
|
|
2121
|
+
// byte-identical second copy of the loop to drift out of sync. The
|
|
2122
|
+
// two names stay separate call sites (not aliased) because they mean
|
|
2123
|
+
// different things to a caller even though today they do the same
|
|
2124
|
+
// work: this is intended to change independently if a pause hand-back
|
|
2125
|
+
// ever needs behavior releaseAll() should not have (e.g. skipping a
|
|
2126
|
+
// member expected back imminently).
|
|
2127
|
+
releaseForPause: releaseAll,
|
|
2128
|
+
|
|
2129
|
+
// (apra-fleet-p2to.4.2) Resume re-acquire, OWNER-CHECKED: re-reserve
|
|
2130
|
+
// every member released at pause. A member is "unavailable" when its
|
|
2131
|
+
// reserve is rejected -- another sprint claimed it while we were paused,
|
|
2132
|
+
// so it is no longer ours. We refuse to silently continue on top of a
|
|
2133
|
+
// member some other sprint now owns: collect every unavailable member
|
|
2134
|
+
// and, if any, fail the resume with a single clean error that NAMES
|
|
2135
|
+
// them (MemberReservationResumeError) so the operator knows exactly what
|
|
2136
|
+
// to free before retrying the resume.
|
|
2137
|
+
//
|
|
2138
|
+
// Every successfully re-acquired member then runs `resyncMember` (git
|
|
2139
|
+
// fetch + decideEnsureBranchAction probe + bd dolt pull) UNCONDITIONALLY
|
|
2140
|
+
// before any work continues -- while paused, origin and the beads DB can
|
|
2141
|
+
// have moved (another sprint, a human push), so the re-sync is never
|
|
2142
|
+
// gated on a "looks unchanged" heuristic.
|
|
2143
|
+
//
|
|
2144
|
+
// @param {{ resyncMember?: (member: string) => Promise<void> }} [opts]
|
|
2145
|
+
// @returns {Promise<{ reacquired: string[] }>}
|
|
2146
|
+
async reReserveForResume({ resyncMember } = {}) {
|
|
2147
|
+
if (!active) return { reacquired: [] };
|
|
2148
|
+
const reacquired = [];
|
|
2149
|
+
const unavailable = [];
|
|
2150
|
+
for (const member of members) {
|
|
2151
|
+
const res = await callFor('reserve', member);
|
|
2152
|
+
if (res.ok) reacquired.push(member);
|
|
2153
|
+
else unavailable.push(member);
|
|
2154
|
+
}
|
|
2155
|
+
if (unavailable.length > 0) {
|
|
2156
|
+
// Hand back the ones we DID re-grab so a failed resume does not
|
|
2157
|
+
// leave this sprint holding a partial, unusable reservation set
|
|
2158
|
+
// that blocks the very members another operator may need to free
|
|
2159
|
+
// up the unavailable ones. Best-effort -- the resume is failing
|
|
2160
|
+
// regardless.
|
|
2161
|
+
for (const member of reacquired) await callFor('release', member);
|
|
2162
|
+
throw new MemberReservationResumeError(unavailable);
|
|
2163
|
+
}
|
|
2164
|
+
if (typeof resyncMember === 'function') {
|
|
2165
|
+
for (const member of reacquired) await resyncMember(member);
|
|
2166
|
+
}
|
|
2167
|
+
return { reacquired };
|
|
1502
2168
|
},
|
|
1503
2169
|
};
|
|
1504
2170
|
}
|
|
@@ -1579,6 +2245,100 @@ export function parseOwnerRepoFromRemoteUrl(url) {
|
|
|
1579
2245
|
return null;
|
|
1580
2246
|
}
|
|
1581
2247
|
|
|
2248
|
+
/**
|
|
2249
|
+
* Resolve the `repos` scope for a member's git remote (apra-fleet-5co8.1.2).
|
|
2250
|
+
*
|
|
2251
|
+
* The two-line-generic parse above cannot express every provider's repository
|
|
2252
|
+
* identity: Azure DevOps' is org/project/repo behind a '_git' marker, which
|
|
2253
|
+
* the owner/repo regexes score as "unrecognized" (null) and therefore silently
|
|
2254
|
+
* drop the repos scope. So the URL is first offered to whichever registered
|
|
2255
|
+
* provider CLAIMS its host, via VCSModule.parseProviderRepoRef() -> that
|
|
2256
|
+
* provider's own parseRepoRef hook, and only falls back to the generic parse
|
|
2257
|
+
* when no provider claims the host or the claiming one has no hook. Every
|
|
2258
|
+
* provider-specific rule (legal URL shapes, coordinate names, remedy text)
|
|
2259
|
+
* stays in the provider file: this function -- and runner.js as a whole --
|
|
2260
|
+
* never names or branches on a provider.
|
|
2261
|
+
*
|
|
2262
|
+
* A host CLAIMED by a provider whose hook rejects the URL is a different
|
|
2263
|
+
* failure from an unrecognized one: the remote is malformed, and proceeding
|
|
2264
|
+
* with no scope would provision credentials against the wrong (or no) repo.
|
|
2265
|
+
* That case returns a typed `error` naming the shape the provider expects, for
|
|
2266
|
+
* the caller to raise as a PREFLIGHT failure -- not a stderr classification.
|
|
2267
|
+
*
|
|
2268
|
+
* `ref` carries the provider's full coordinate object when one was produced
|
|
2269
|
+
* (null otherwise), so a caller can hand it back to that same provider's other
|
|
2270
|
+
* hooks -- e.g. buildProvisionArgs, which derives an org URL from it
|
|
2271
|
+
* (apra-fleet-5co8.2.1) -- without re-parsing or interpreting it here.
|
|
2272
|
+
*
|
|
2273
|
+
* @param {string|null|undefined} url
|
|
2274
|
+
* @returns {{ repo: string|null, ref: object|null, error: string|null }}
|
|
2275
|
+
*/
|
|
2276
|
+
export function parseRepoScopeFromRemoteUrl(url) {
|
|
2277
|
+
const text = String(url == null ? '' : url).trim();
|
|
2278
|
+
if (!text) return { repo: null, ref: null, error: null };
|
|
2279
|
+
|
|
2280
|
+
const providerRef = parseProviderRepoRef(text);
|
|
2281
|
+
if (providerRef && providerRef.error) return { repo: null, ref: null, error: providerRef.error };
|
|
2282
|
+
if (providerRef && providerRef.canonical) return { repo: providerRef.canonical, ref: providerRef.ref, error: null };
|
|
2283
|
+
|
|
2284
|
+
return { repo: parseOwnerRepoFromRemoteUrl(text), ref: null, error: null };
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
/**
|
|
2288
|
+
* Read the credential-store entry NAMES (never values) currently registered on
|
|
2289
|
+
* the hub, for a provider hook that needs to fail fast when the secret it
|
|
2290
|
+
* intends to reference as a {{secure.NAME}} placeholder does not exist
|
|
2291
|
+
* (apra-fleet-5co8.2.1).
|
|
2292
|
+
*
|
|
2293
|
+
* Returns null -- not an empty list -- when the store cannot be read or its
|
|
2294
|
+
* response cannot be parsed, so a hook can tell "the store definitely lacks
|
|
2295
|
+
* this entry" apart from "unknown" and skip the check rather than emit a
|
|
2296
|
+
* false, sprint-stopping ERROR. A genuinely missing secret still fails loudly
|
|
2297
|
+
* hub-side when placeholder resolution runs.
|
|
2298
|
+
*
|
|
2299
|
+
* @param {object} fleetApi
|
|
2300
|
+
* @returns {Promise<string[]|null>}
|
|
2301
|
+
*/
|
|
2302
|
+
async function listCredentialStoreNames(fleetApi) {
|
|
2303
|
+
if (!fleetApi || typeof fleetApi.credentialStoreList !== 'function') return null;
|
|
2304
|
+
try {
|
|
2305
|
+
const parsed = JSON.parse(selfHealResultText(await fleetApi.credentialStoreList()));
|
|
2306
|
+
if (!Array.isArray(parsed)) return null;
|
|
2307
|
+
return parsed
|
|
2308
|
+
.map((entry) => (entry && typeof entry.name === 'string' ? entry.name : null))
|
|
2309
|
+
.filter((name) => name !== null);
|
|
2310
|
+
} catch {
|
|
2311
|
+
return null;
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2315
|
+
/**
|
|
2316
|
+
* Build the provision_vcs_auth arguments for a member, dispatched through the
|
|
2317
|
+
* resolved provider's OPTIONAL buildProvisionArgs hook (apra-fleet-5co8.2.1).
|
|
2318
|
+
*
|
|
2319
|
+
* A provider with no hook gets `base` verbatim -- the GitHub-App-shaped
|
|
2320
|
+
* `git_access`/`repos` arguments this function has always sent -- so nothing
|
|
2321
|
+
* changes for GitHub or any other existing provider. A provider WITH a hook
|
|
2322
|
+
* owns its own argument shape entirely, including which credential-store entry
|
|
2323
|
+
* it references and what remedy text a missing one prints. No provider name,
|
|
2324
|
+
* no auth-mode knowledge and no raw credential value appears here.
|
|
2325
|
+
*
|
|
2326
|
+
* @param {{ provider: string, base: object, repoRef: object|null, fleetApi: object }} ctx
|
|
2327
|
+
* @returns {Promise<object>} the arguments to send
|
|
2328
|
+
*/
|
|
2329
|
+
async function buildProvisionArgsForProvider({ provider, base, repoRef, fleetApi, secretName }) {
|
|
2330
|
+
const impl = getVcsProvider(provider);
|
|
2331
|
+
if (!impl || typeof impl.buildProvisionArgs !== 'function') return base;
|
|
2332
|
+
|
|
2333
|
+
const availableSecrets = await listCredentialStoreNames(fleetApi);
|
|
2334
|
+
const built = impl.buildProvisionArgs({ base, repoRef, availableSecrets, secretName });
|
|
2335
|
+
if (built && typeof built.error === 'string') throw new Error(built.error);
|
|
2336
|
+
if (!built || !built.args || typeof built.args !== 'object') {
|
|
2337
|
+
throw new Error(`ERROR: VCS provider '${provider}' returned no provision arguments for member '${base.member_name}'.`);
|
|
2338
|
+
}
|
|
2339
|
+
return built.args;
|
|
2340
|
+
}
|
|
2341
|
+
|
|
1582
2342
|
// Shared MCP tool-result-to-text extractor for the self-heal callbacks below.
|
|
1583
2343
|
// The provision_* tools do not throw on failure: they return plain
|
|
1584
2344
|
// human-readable text with a leading status emoji (check mark = success,
|
|
@@ -1611,23 +2371,49 @@ function selfHealResultText(result) {
|
|
|
1611
2371
|
// the just-in-time credential-scoping ADR (docs/adr-server-never-acts-on-repo.md)
|
|
1612
2372
|
// for the rogue-dispatch blast-radius rationale: widening this default would
|
|
1613
2373
|
// give every member standing pull_requests:write for the whole sprint.
|
|
1614
|
-
// @param {{ fleetApi: object, command: Function, member: string, log?: Function, logPrefix: string, gitAccess?: string }} opts
|
|
2374
|
+
// @param {{ fleetApi: object, command: Function, member: string, log?: Function, logPrefix: string, gitAccess?: string, resolvedProvider?: { provider: string, authMode: string|null } }} opts
|
|
1615
2375
|
// @returns {Promise<{ expiresAt: Date|null, repo: string|null }>}
|
|
1616
|
-
async function provisionVcsAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, gitAccess = 'push' }) {
|
|
2376
|
+
async function provisionVcsAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, gitAccess = 'push', azdevopsPatSecretName, remoteUrlOverride, resolvedProvider }) {
|
|
1617
2377
|
let repos;
|
|
1618
2378
|
let derivedRepo = null;
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
2379
|
+
let derivedRef = null;
|
|
2380
|
+
// Reading the remote is best-effort (a failure here just means no explicit
|
|
2381
|
+
// repos scope), but PARSING it is not: a malformed remote on a host some
|
|
2382
|
+
// provider claims is a preflight ERROR that must escape this function
|
|
2383
|
+
// rather than be swallowed by the read's catch -- hence the parse sits
|
|
2384
|
+
// outside the try. See parseRepoScopeFromRemoteUrl (apra-fleet-5co8.1.2).
|
|
2385
|
+
let remoteUrl = '';
|
|
2386
|
+
let remoteReadFailed = false;
|
|
2387
|
+
// apra-fleet-8zr3-adjacent: a caller that already resolved the sprint's
|
|
2388
|
+
// origin remote via a real git-capable member (e.g. Publish PR's
|
|
2389
|
+
// publishGitMember) passes it here instead of making THIS function shell
|
|
2390
|
+
// out its own 'git remote get-url origin' to `member` -- which matters
|
|
2391
|
+
// when `member` is orchestratorMember and may be a git-less/shared member
|
|
2392
|
+
// with no checkout to read a remote from at all. Skips the read entirely,
|
|
2393
|
+
// never the parse below.
|
|
2394
|
+
if (remoteUrlOverride) {
|
|
2395
|
+
remoteUrl = String(remoteUrlOverride).trim();
|
|
2396
|
+
} else {
|
|
2397
|
+
try {
|
|
2398
|
+
const remoteRes = await command('git remote get-url origin', { member_name: member, silent: true, failSoft: true });
|
|
2399
|
+
remoteUrl = remoteRes && remoteRes.ok ? String(remoteRes.output || '').trim() : '';
|
|
2400
|
+
} catch (remoteErr) {
|
|
2401
|
+
remoteReadFailed = true;
|
|
2402
|
+
log(`${logPrefix}: failed to read member '${member}' git remote to derive 'repos' (continuing without an explicit repos scope): ${remoteErr.message}`);
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
if (!remoteReadFailed) {
|
|
2406
|
+
const scope = parseRepoScopeFromRemoteUrl(remoteUrl);
|
|
2407
|
+
if (scope.error) {
|
|
2408
|
+
throw new Error(`${logPrefix}: cannot provision VCS auth for member '${member}': ${scope.error}`);
|
|
2409
|
+
}
|
|
2410
|
+
derivedRef = scope.ref;
|
|
2411
|
+
if (scope.repo) {
|
|
2412
|
+
repos = [scope.repo];
|
|
2413
|
+
derivedRepo = scope.repo;
|
|
1626
2414
|
} else {
|
|
1627
|
-
log(`${logPrefix}: could not derive an owner/repo from member '${member}' git remote (raw: '${
|
|
2415
|
+
log(`${logPrefix}: could not derive an owner/repo from member '${member}' git remote (raw: '${remoteUrl}'); calling provision_vcs_auth without an explicit repos scope.`);
|
|
1628
2416
|
}
|
|
1629
|
-
} catch (remoteErr) {
|
|
1630
|
-
log(`${logPrefix}: failed to read member '${member}' git remote to derive 'repos' (continuing without an explicit repos scope): ${remoteErr.message}`);
|
|
1631
2417
|
}
|
|
1632
2418
|
|
|
1633
2419
|
// apra-fleet-647.1.2.1: provider and auth-mode are resolved from the
|
|
@@ -1638,14 +2424,29 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
|
|
|
1638
2424
|
// providers: null, no separate mode axis) and is only forwarded as
|
|
1639
2425
|
// `<provider>_mode` when non-null, matching provision_vcs_auth's own
|
|
1640
2426
|
// `github_mode` field name for the one provider that has one today.
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
2427
|
+
// apra-fleet-5co8.13: a caller that already resolved the provider (e.g.
|
|
2428
|
+
// the self-heal callback's authRemedy hint lookup) can thread it through
|
|
2429
|
+
// via `resolvedProvider`, saving a second member_detail round trip. Falls
|
|
2430
|
+
// back to this function's own lookup when not supplied.
|
|
2431
|
+
const { provider, authMode } = resolvedProvider || await resolveProvider(member, { fleetApi });
|
|
2432
|
+
// apra-fleet-5co8.2.1: the argument shape itself is now provider-owned.
|
|
2433
|
+
// What follows is the DEFAULT (GitHub-App) shape; a provider that declares
|
|
2434
|
+
// a buildProvisionArgs hook replaces it wholesale -- see
|
|
2435
|
+
// buildProvisionArgsForProvider above.
|
|
2436
|
+
const provisionArgs = await buildProvisionArgsForProvider({
|
|
1644
2437
|
provider,
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
2438
|
+
base: {
|
|
2439
|
+
member_name: member,
|
|
2440
|
+
provider,
|
|
2441
|
+
...(authMode ? { [`${provider}_mode`]: authMode } : {}),
|
|
2442
|
+
git_access: gitAccess,
|
|
2443
|
+
...(repos ? { repos } : {}),
|
|
2444
|
+
},
|
|
2445
|
+
repoRef: derivedRef,
|
|
2446
|
+
fleetApi,
|
|
2447
|
+
secretName: azdevopsPatSecretName,
|
|
1648
2448
|
});
|
|
2449
|
+
const provisionRes = await fleetApi.provisionVcsAuth(provisionArgs);
|
|
1649
2450
|
const provisionText = selfHealResultText(provisionRes);
|
|
1650
2451
|
// provision_vcs_auth NEVER throws on failure -- it returns a string
|
|
1651
2452
|
// starting with the failure emoji. A failed provision must never be
|
|
@@ -1673,17 +2474,36 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
|
|
|
1673
2474
|
// learn the repo VCSModule needs to build the PR-creation command.
|
|
1674
2475
|
// @param {{ fleetApi: object, command: Function, member: string, log?: Function, logPrefix: string }} opts
|
|
1675
2476
|
// @returns {Promise<{ expiresAt: Date|null, repo: string|null }>}
|
|
1676
|
-
async function provisionPrCapableAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix }) {
|
|
1677
|
-
return provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix, gitAccess: 'push+pr' });
|
|
2477
|
+
async function provisionPrCapableAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, remoteUrlOverride }) {
|
|
2478
|
+
return provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix, gitAccess: 'push+pr', remoteUrlOverride });
|
|
1678
2479
|
}
|
|
1679
2480
|
|
|
1680
2481
|
// Default credential label provision_vcs_auth deploys under when no explicit
|
|
1681
2482
|
// `label` is passed (src/tools/provision-vcs-auth.ts: `label = input.label ??
|
|
1682
2483
|
// input.provider`) -- the PR-raising call sites never pass a label either, so
|
|
1683
2484
|
// the deployed git-credential-helper file is always
|
|
1684
|
-
// $HOME/.fleet-git-credential-github for the 'github' provider
|
|
2485
|
+
// $HOME/.fleet-git-credential-github for the 'github' provider on POSIX
|
|
2486
|
+
// (src/os/linux.ts gitCredentialHelperWrite), and
|
|
2487
|
+
// $env:USERPROFILE\.fleet-git-credential-github.bat on Windows
|
|
2488
|
+
// (src/os/windows.ts:279-294).
|
|
1685
2489
|
const GITHUB_VCS_CREDENTIAL_LABEL = 'github';
|
|
1686
2490
|
|
|
2491
|
+
// The credential-helper label provision_vcs_auth deploys a member's VCS
|
|
2492
|
+
// credential under, for the PR-raising call sites to read it back from:
|
|
2493
|
+
// `label = input.label ?? input.provider` server-side, and no fleet-sprint
|
|
2494
|
+
// caller (neither the shared GitHub-App-shaped arguments in
|
|
2495
|
+
// provisionVcsAuthForMember nor a provider's buildProvisionArgs hook) ever
|
|
2496
|
+
// sends an explicit `label`, so the label IS the provider name -- 'github'
|
|
2497
|
+
// -> $HOME/.fleet-git-credential-github, 'azure-devops' ->
|
|
2498
|
+
// $HOME/.fleet-git-credential-azure-devops, etc. A member with no
|
|
2499
|
+
// resolvable provider keeps the historical GitHub default.
|
|
2500
|
+
// @param {string|null|undefined} provider
|
|
2501
|
+
// @returns {string}
|
|
2502
|
+
export function vcsCredentialLabelForProvider(provider) {
|
|
2503
|
+
const name = typeof provider === 'string' ? provider.trim() : '';
|
|
2504
|
+
return name || GITHUB_VCS_CREDENTIAL_LABEL;
|
|
2505
|
+
}
|
|
2506
|
+
|
|
1687
2507
|
// Typed marker returned by finalizeAbort() (and logged by the Publish PR step)
|
|
1688
2508
|
// when the callTool-absent graceful-degradation path is taken: PR creation was
|
|
1689
2509
|
// intentionally skipped because no MCP client was wired to mint the push+pr
|
|
@@ -1692,9 +2512,174 @@ const GITHUB_VCS_CREDENTIAL_LABEL = 'github';
|
|
|
1692
2512
|
// this exact reason string. See apra-fleet-tfx.8.1.
|
|
1693
2513
|
const PR_SKIPPED_NO_MCP_CLIENT = 'pr-skipped-no-mcp-client';
|
|
1694
2514
|
|
|
2515
|
+
// memberName -> resolved { os, shell } ('windows' | 'linux' | 'darwin' | ...
|
|
2516
|
+
// and '' | 'gitbash' | ... respectively), cached for the lifetime of the
|
|
2517
|
+
// runner process: a member's OS/shell never changes mid-sprint, and
|
|
2518
|
+
// member_detail performs a live connectivity check, so this must not be
|
|
2519
|
+
// re-dispatched per credential read (raiseVcsPrForMember can call it twice
|
|
2520
|
+
// on the auth-retry path alone).
|
|
2521
|
+
const memberOsCache = new Map();
|
|
2522
|
+
|
|
2523
|
+
// Test seam: the OS cache is process-lifetime state, so a test exercising two
|
|
2524
|
+
// different member OSes for the same member name must be able to clear it.
|
|
2525
|
+
export function clearMemberOsCache() {
|
|
2526
|
+
memberOsCache.clear();
|
|
2527
|
+
}
|
|
2528
|
+
|
|
2529
|
+
// Resolves `member`'s { os, shell } from the fleet member registry via
|
|
2530
|
+
// fleetApi.memberDetail() ('member_detail' is the only MCP surface exposing
|
|
2531
|
+
// Agent.os/Agent's registered shell -- src/tools/member-detail.ts; it does
|
|
2532
|
+
// NOT expose a homeDir). Mirrors VCSModule.resolveProvider()'s member_detail
|
|
2533
|
+
// JSON-parsing shape.
|
|
2534
|
+
//
|
|
2535
|
+
// Unlike resolveProvider, an unresolvable OS is NOT a hard error here: the
|
|
2536
|
+
// ONLY behavioral difference it drives is which shell string the credential
|
|
2537
|
+
// read is built as, and the historical (POSIX) string must stay byte-identical
|
|
2538
|
+
// for every non-Windows member and for any caller that has no memberDetail
|
|
2539
|
+
// wired. So a missing/unparseable/absent-`os` response degrades to 'linux'
|
|
2540
|
+
// (the pre-existing behavior) and is logged, never thrown. A windows member
|
|
2541
|
+
// whose record carries no `shell` (or an unrecognized one) resolves to '' --
|
|
2542
|
+
// getSeCommands() treats that as the PowerShell implementation, matching what
|
|
2543
|
+
// every Windows member was assumed to be before shells were recorded.
|
|
2544
|
+
// @param {{ fleetApi?: object, member: string, log?: Function }} opts
|
|
2545
|
+
// @returns {Promise<{ os: string, shell: string }>}
|
|
2546
|
+
async function resolveMemberTarget({ fleetApi, member, log = () => {} }) {
|
|
2547
|
+
if (memberOsCache.has(member)) return memberOsCache.get(member);
|
|
2548
|
+
try {
|
|
2549
|
+
if (!fleetApi || typeof fleetApi.memberDetail !== 'function') {
|
|
2550
|
+
throw new Error('no fleetApi.memberDetail() injected');
|
|
2551
|
+
}
|
|
2552
|
+
const res = await fleetApi.memberDetail({ member_name: member, format: 'json' });
|
|
2553
|
+
const text = typeof res === 'string'
|
|
2554
|
+
? res
|
|
2555
|
+
: (res && Array.isArray(res.content) && res.content[0] && typeof res.content[0].text === 'string')
|
|
2556
|
+
? res.content[0].text
|
|
2557
|
+
: '';
|
|
2558
|
+
const parsed = JSON.parse(text);
|
|
2559
|
+
if (parsed && typeof parsed.os === 'string' && parsed.os.trim()) {
|
|
2560
|
+
const os = parsed.os.trim().toLowerCase();
|
|
2561
|
+
const shell = (parsed && typeof parsed.shell === 'string') ? parsed.shell.trim().toLowerCase() : '';
|
|
2562
|
+
const target = { os, shell };
|
|
2563
|
+
// Only a genuine member_detail-derived OS/shell is cached. Caching
|
|
2564
|
+
// the 'linux' fallback below would permanently pin a member that
|
|
2565
|
+
// hit a transient failure (asleep, flaky SSH, MCP hiccup) to
|
|
2566
|
+
// POSIX command construction for the rest of the runner process
|
|
2567
|
+
// -- including the auth-retry credential read at
|
|
2568
|
+
// raiseVcsPrForMember, whose entire purpose is to recover from
|
|
2569
|
+
// exactly this kind of transient failure. See apra-fleet-ot2z.13.
|
|
2570
|
+
memberOsCache.set(member, target);
|
|
2571
|
+
return target;
|
|
2572
|
+
}
|
|
2573
|
+
throw new Error('member_detail response carried no "os" field');
|
|
2574
|
+
} catch (err) {
|
|
2575
|
+
log(`Could not resolve OS for member '${member}' from member_detail (${err && err.message ? err.message : err}); assuming POSIX ('linux') for member-bound command construction.`);
|
|
2576
|
+
return { os: 'linux', shell: '' };
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
// Back-compat wrapper: existing callers (and tests) that only need the OS
|
|
2581
|
+
// string keep working unchanged. Resolves and caches both os and shell (see
|
|
2582
|
+
// resolveMemberTarget above); callers that also need the shell (e.g. the VCS
|
|
2583
|
+
// credential-read path) should call resolveMemberTarget directly.
|
|
2584
|
+
// @param {{ fleetApi?: object, member: string, log?: Function }} opts
|
|
2585
|
+
// @returns {Promise<string>}
|
|
2586
|
+
export async function resolveMemberOs(opts) {
|
|
2587
|
+
const { os } = await resolveMemberTarget(opts);
|
|
2588
|
+
return os;
|
|
2589
|
+
}
|
|
2590
|
+
|
|
2591
|
+
/**
|
|
2592
|
+
* Resolve a member's registered shell for a buildSettleCallback call site,
|
|
2593
|
+
* guarded on the presence of a callTool the same way the original
|
|
2594
|
+
* pre-dispatch wiring at runSprintCycle's dispatch bracket is (apra-
|
|
2595
|
+
* fleet-7dir.16) -- so a mock-sprint scenario with no MCP client wired keeps
|
|
2596
|
+
* its pre-shell-aware default ('', PowerShell dialect on Windows) instead of
|
|
2597
|
+
* throwing or hanging on a fleetApi call that has nothing to answer it.
|
|
2598
|
+
* Shared by every remaining buildSettleCallback call site so each one does
|
|
2599
|
+
* not have to re-implement the guard (apra-fleet-7dir.24).
|
|
2600
|
+
* @param {{ args?: { callTool?: Function }, member: string, log?: Function }} opts
|
|
2601
|
+
* @returns {Promise<string>}
|
|
2602
|
+
*/
|
|
2603
|
+
async function resolveSettleShell({ args, member, log = () => {} }) {
|
|
2604
|
+
if (!(args && typeof args.callTool === 'function')) return '';
|
|
2605
|
+
const target = await resolveMemberTarget({ fleetApi: new ApraFleet({ callTool: args.callTool }), member, log });
|
|
2606
|
+
return target.shell;
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
// Builds the member-bound command that RUNS the deployed git-credential-helper
|
|
2610
|
+
// and the human-readable descriptor used in this function's error messages
|
|
2611
|
+
// (the descriptor must stay readable -- the Windows command itself is an
|
|
2612
|
+
// opaque base64 blob).
|
|
2613
|
+
//
|
|
2614
|
+
// SHELL CONTRACT (confirmed, not assumed -- apra-fleet-ot2z.1):
|
|
2615
|
+
// execute_command hands the caller's string to
|
|
2616
|
+
// cmds.wrapPidCapture(cmds.wrapInWorkFolder(folder, cmd)) and then straight
|
|
2617
|
+
// to the strategy's execCommand (src/tools/execute-command.ts:273 ->
|
|
2618
|
+
// src/services/ssh.ts execCommand, which does NO shell branching of its
|
|
2619
|
+
// own). wrapInWorkFolder/wrapPidCapture (src/os/windows.ts:328-335) still
|
|
2620
|
+
// emit RAW PowerShell text (`Set-Location "<folder>"; ...`,
|
|
2621
|
+
// `Write-Output "FLEET_PID:$pid"; ...`), NOT shell-normalized/encoded --
|
|
2622
|
+
// they are NOT wrapped with -EncodedCommand, so on a Windows member whose
|
|
2623
|
+
// sshd default shell is cmd.exe (not PowerShell) that outer wrapping is
|
|
2624
|
+
// still garbage regardless of what this function returns. This function's
|
|
2625
|
+
// own return value (the inner payload wrapPidCapture/wrapInWorkFolder wrap
|
|
2626
|
+
// around) IS explicitly -EncodedCommand and is valid to launch from either
|
|
2627
|
+
// PowerShell or cmd.exe on its own -- but that only protects the inner
|
|
2628
|
+
// payload, not the outer Set-Location/Write-Output wrapper the codebase
|
|
2629
|
+
// composes around it. Correctness end-to-end still depends on the target
|
|
2630
|
+
// member's default shell being PowerShell.
|
|
2631
|
+
// TODO: normalize wrapInWorkFolder/wrapPidCapture (and
|
|
2632
|
+
// gitCredentialHelperWrite/gitCredentialHelperRemove/deploySSHPublicKey,
|
|
2633
|
+
// which have the same raw-PowerShell issue on the write side) through a
|
|
2634
|
+
// single shell-detecting wrapper so the whole composite string -- not just
|
|
2635
|
+
// this function's inner payload -- is shell-agnostic.
|
|
2636
|
+
//
|
|
2637
|
+
// WHY $env:USERPROFILE AND NOT A JS-RESOLVED HOME PATH: the WRITE side
|
|
2638
|
+
// (src/os/windows.ts:289 gitCredentialHelperWrite) writes the helper to
|
|
2639
|
+
// `"$env:USERPROFILE\.fleet-git-credential-<label>.bat"` -- expanded ON THE
|
|
2640
|
+
// MEMBER at write time. The read must resolve the home directory the same way
|
|
2641
|
+
// the write did, or an independently-probed home could point somewhere the
|
|
2642
|
+
// file was never written. This mirrors member-home.ts probeCommandFor(), which
|
|
2643
|
+
// likewise resolves the OS in JS and interpolates a shell-appropriate string
|
|
2644
|
+
// that still contains $env:USERPROFILE.
|
|
2645
|
+
// RUNNER-WIDE POSIX-EXPANSION SWEEP (apra-fleet-ot2z.1, WORK item 2): every
|
|
2646
|
+
// runner.js string passed to command()/execute_command was audited for `$VAR`,
|
|
2647
|
+
// `~/`, backticks, `$( )` and POSIX-only shell plumbing (`&&`/`||` chains,
|
|
2648
|
+
// `2>/dev/null`, `test -f`, pipes). Result: the credential read below was the
|
|
2649
|
+
// ONLY member-bound string carrying a shell expansion. The surviving `$`
|
|
2650
|
+
// occurrences in this file are all justified in place --
|
|
2651
|
+
// - NOT_DONE_STATUSES (~line 278): quoting note about PowerShell's $OFS, a
|
|
2652
|
+
// comment, not an expansion in the dispatched string;
|
|
2653
|
+
// - the Windows branch below: deliberately PowerShell, base64-encoded (via
|
|
2654
|
+
// se-os-commands.mjs's SeWindowsCommands#wrapForMember) so no host shell
|
|
2655
|
+
// ever re-parses it;
|
|
2656
|
+
// - the POSIX branch below: `$HOME` expanded by the POSIX member's own
|
|
2657
|
+
// shell, matching what src/os/linux.ts wrote.
|
|
2658
|
+
// Everything else dispatched to a member is plain `git`/`bd`/`node -e`
|
|
2659
|
+
// argv-shaped text (see stageCommandBodyMemberSide ~line 2195 and the
|
|
2660
|
+
// two-sequential-calls note at ~line 5685, which already document why they
|
|
2661
|
+
// avoid `&&` and `$`), inert across POSIX, PowerShell and cmd.exe.
|
|
2662
|
+
//
|
|
2663
|
+
// `target` is whatever se-os-commands.mjs's getSeCommands() accepts: a bare
|
|
2664
|
+
// OS string (back-compat -- resolves to the PowerShell implementation for
|
|
2665
|
+
// 'windows', matching pre-shell-aware behavior) or a { os, shell } record
|
|
2666
|
+
// (resolveMemberTarget's shape), so a Windows member whose shell is
|
|
2667
|
+
// Git-for-Windows bash gets the bash-flavored credential-read command instead
|
|
2668
|
+
// of a PowerShell one. Label validation and byte-identical string shapes are
|
|
2669
|
+
// now owned by the SePosixCommands/SeWindowsCommands/SeWindowsGitbashCommands
|
|
2670
|
+
// classes themselves -- see se-os-commands.mjs.
|
|
2671
|
+
// @param {{ os?: string, shell?: string }|string} target
|
|
2672
|
+
// @param {string} label
|
|
2673
|
+
// @returns {{ command: string, descriptor: string }}
|
|
2674
|
+
export function buildCredentialReadCommand(target, label) {
|
|
2675
|
+
return getSeCommands(target).readCredentialHelper(label);
|
|
2676
|
+
}
|
|
2677
|
+
|
|
1695
2678
|
// Reads the raw token back out of the git-credential-helper script
|
|
1696
2679
|
// provision_vcs_auth just deployed onto `member`'s filesystem
|
|
1697
|
-
// ($HOME/.fleet-git-credential-<label
|
|
2680
|
+
// ($HOME/.fleet-git-credential-<label> on POSIX, or
|
|
2681
|
+
// $env:USERPROFILE\.fleet-git-credential-<label>.bat on Windows -- see
|
|
2682
|
+
// buildCredentialReadCommand above; an executable script that PRINTS
|
|
1698
2683
|
// "protocol=...\nhost=...\nusername=...\npassword=<token>\n" when run -- see
|
|
1699
2684
|
// src/os/linux.ts gitCredentialHelperWrite()/src/os/windows.ts). This is the
|
|
1700
2685
|
// ONLY way an orchestrator-side caller (VCSModule's runner.js callers) can
|
|
@@ -1706,11 +2691,14 @@ const PR_SKIPPED_NO_MCP_CLIENT = 'pr-skipped-no-mcp-client';
|
|
|
1706
2691
|
// itself is never logged/echoed anywhere (the token value briefly transits
|
|
1707
2692
|
// this one command's captured stdout, held only in-process, and is used
|
|
1708
2693
|
// immediately to build the VCSModule command).
|
|
1709
|
-
//
|
|
2694
|
+
// Both the POSIX helper script and the Windows .bat print the same
|
|
2695
|
+
// "password=<token>" line, so the extraction regex below is OS-independent.
|
|
2696
|
+
// @param {{ command: Function, member: string, label?: string, fleetApi?: object, log?: Function }} opts
|
|
1710
2697
|
// @returns {Promise<string>}
|
|
1711
|
-
async function readMemberVcsCredentialToken({ command, member, label = GITHUB_VCS_CREDENTIAL_LABEL }) {
|
|
1712
|
-
const
|
|
1713
|
-
const
|
|
2698
|
+
async function readMemberVcsCredentialToken({ command, member, label = GITHUB_VCS_CREDENTIAL_LABEL, fleetApi, log = () => {} }) {
|
|
2699
|
+
const target = await resolveMemberTarget({ fleetApi, member, log });
|
|
2700
|
+
const { command: credCommand, descriptor: credFile } = buildCredentialReadCommand(target, label);
|
|
2701
|
+
const res = await command(credCommand, {
|
|
1714
2702
|
member_name: member,
|
|
1715
2703
|
silent: true,
|
|
1716
2704
|
failSoft: true,
|
|
@@ -1787,17 +2775,97 @@ function isPrAuthFailure(status, errorText) {
|
|
|
1787
2775
|
// token is never logged, only `built.logSafeCommand`.
|
|
1788
2776
|
// @param {{ fleetApi: object, command: Function, member: string, base: string, head: string, title: string, body?: string, log?: Function, logPrefix: string }} opts
|
|
1789
2777
|
// @returns {Promise<{ ok: boolean, alreadyExists: boolean, prUrl: string|null, error: string|null, authFailure: boolean }>}
|
|
1790
|
-
async function raiseVcsPrForMember({ fleetApi, command, member, base, head, title, body, log = () => {}, logPrefix }) {
|
|
1791
|
-
let
|
|
2778
|
+
async function raiseVcsPrForMember({ fleetApi, command, member, base, head, title, body, log = () => {}, logPrefix, remoteUrlOverride }) {
|
|
2779
|
+
let repo;
|
|
2780
|
+
try {
|
|
2781
|
+
({ repo } = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride }));
|
|
2782
|
+
} catch (provisionErr) {
|
|
2783
|
+
// apra-fleet-5co8.15: provisionPrCapableAuthForMember has no failSoft
|
|
2784
|
+
// of its own (by design -- see its doc comment above), so a
|
|
2785
|
+
// provisioning failure that happens BEFORE any PR-creation attempt
|
|
2786
|
+
// (e.g. a missing Azure DevOps PAT credential-store entry) used to
|
|
2787
|
+
// escape here as the raw provision_vcs_auth failure text and abort
|
|
2788
|
+
// the whole sprint. Degrade it the same way the reactive
|
|
2789
|
+
// auth-self-heal retry below already degrades a mid-retry failure:
|
|
2790
|
+
// log the provider's own authRemedy hint (never a wording duplicated
|
|
2791
|
+
// here) and return authFailure:true instead of throwing, so a caller
|
|
2792
|
+
// (Publish PR, finalizeAbort) can report clean, actionable guidance
|
|
2793
|
+
// and keep going rather than aborting on this condition.
|
|
2794
|
+
let remedyHint = null;
|
|
2795
|
+
try {
|
|
2796
|
+
const { provider } = await resolveProvider(member, { fleetApi });
|
|
2797
|
+
const impl = getVcsProvider(provider);
|
|
2798
|
+
if (impl && impl.authRemedy && impl.authRemedy.hint) remedyHint = impl.authRemedy.hint;
|
|
2799
|
+
} catch (resolveErr) {
|
|
2800
|
+
log(`${logPrefix}: could not resolve member '${member}'s VCS provider to look up an auth remedy hint (falling back to the raw provisioning error): ${resolveErr.message}`);
|
|
2801
|
+
}
|
|
2802
|
+
const message = remedyHint
|
|
2803
|
+
? `Could not provision a push+pr credential for member '${member}': ${remedyHint}`
|
|
2804
|
+
: provisionErr.message;
|
|
2805
|
+
log(`${logPrefix}: PR-capable credential provisioning failed for member '${member}'; degrading (not throwing): ${message}`);
|
|
2806
|
+
return { ok: false, alreadyExists: false, prUrl: null, error: message, authFailure: true };
|
|
2807
|
+
}
|
|
1792
2808
|
if (!repo) {
|
|
1793
2809
|
throw new Error(`Could not derive an owner/repo from member '${member}' git remote -- cannot build a VCSModule create-pull-request command without one.`);
|
|
1794
2810
|
}
|
|
1795
|
-
|
|
2811
|
+
// apra-fleet-lzfv.5: resolve the member's OWN registered VCS provider
|
|
2812
|
+
// (VCSModule.resolveProvider(), never a hardcoded 'github' literal --
|
|
2813
|
+
// same rule provisionVcsAuthForMember already follows) so
|
|
2814
|
+
// buildCreatePrCommand dispatches to the right REST dialect for a
|
|
2815
|
+
// dev.azure.com (or any other) remote, not just GitHub.
|
|
2816
|
+
//
|
|
2817
|
+
// Resolved BEFORE the credential read below because the read is keyed
|
|
2818
|
+
// by provider too: provision_vcs_auth deploys the credential helper
|
|
2819
|
+
// under `label = input.label ?? input.provider`
|
|
2820
|
+
// (src/tools/provision-vcs-auth.ts), and neither the shared
|
|
2821
|
+
// GitHub-App-shaped arguments nor a provider's buildProvisionArgs hook
|
|
2822
|
+
// sends an explicit label -- so the file to read back is
|
|
2823
|
+
// $HOME/.fleet-git-credential-<provider>. Reading the 'github'-labelled
|
|
2824
|
+
// file unconditionally (the pre-fix default of
|
|
2825
|
+
// readMemberVcsCredentialToken) made every Azure DevOps member's PR
|
|
2826
|
+
// raise fail with "Failed to read VCS credential token ... from
|
|
2827
|
+
// '$HOME/.fleet-git-credential-github'" (or, worse, silently reuse a
|
|
2828
|
+
// stale GitHub token left over from an earlier provider and send it to
|
|
2829
|
+
// dev.azure.com).
|
|
2830
|
+
const { provider } = await resolveProvider(member, { fleetApi });
|
|
2831
|
+
const credentialLabel = vcsCredentialLabelForProvider(provider);
|
|
2832
|
+
|
|
2833
|
+
let token = await readMemberVcsCredentialToken({ command, member, label: credentialLabel, fleetApi, log });
|
|
2834
|
+
// Both os AND shell feed the command builder: os picks the curl binary
|
|
2835
|
+
// token (curl.exe vs curl), shell picks the quoting dialect. A Windows
|
|
2836
|
+
// member whose registered shell is gitbash needs POSIX quoting, not
|
|
2837
|
+
// PowerShell doubled-quote escaping -- resolving only the OS here fed
|
|
2838
|
+
// shell-less params to shQuote and corrupted the curl -d JSON payload
|
|
2839
|
+
// (observed live: GitHub 400 "Problems parsing JSON" on the create-PR
|
|
2840
|
+
// endpoint for a windows+gitbash member).
|
|
2841
|
+
const { os, shell } = await resolveMemberTarget({ fleetApi, member, log });
|
|
2842
|
+
|
|
2843
|
+
// The provider's own coordinate shape (e.g. Azure DevOps' org/project/repo
|
|
2844
|
+
// -- see VCSModule.parseProviderRepoRef()/that provider's parseRepoRef
|
|
2845
|
+
// hook) when one exists; null for a provider with no such hook (GitHub),
|
|
2846
|
+
// which keeps using the two-part `repo` string above unchanged. Only ONE
|
|
2847
|
+
// of `repo`/`repoRef` is ever sent below: passing both would let the
|
|
2848
|
+
// (possibly provider-specific, e.g. 3-part) canonical `repo` string
|
|
2849
|
+
// silently override repoRef's own coordinates and mis-encode the request
|
|
2850
|
+
// URL (see azure-devops.mjs's assertRepoCoords doc comment). Both real
|
|
2851
|
+
// call sites (Publish PR, [ABORTED] PR) already resolve and pass
|
|
2852
|
+
// `remoteUrlOverride` themselves (see their own comments), so this never
|
|
2853
|
+
// needs a git-remote read of its own; a caller that omits it simply gets
|
|
2854
|
+
// no repoRef (falls back to `repo`, unchanged from before this task).
|
|
2855
|
+
const providerRef = remoteUrlOverride ? parseProviderRepoRef(remoteUrlOverride) : null;
|
|
2856
|
+
if (providerRef && providerRef.error) {
|
|
2857
|
+
throw new Error(providerRef.error);
|
|
2858
|
+
}
|
|
2859
|
+
const repoRef = providerRef ? providerRef.ref : null;
|
|
1796
2860
|
|
|
1797
2861
|
let authHealAttempted = false;
|
|
1798
2862
|
// eslint-disable-next-line no-constant-condition
|
|
1799
2863
|
while (true) {
|
|
1800
|
-
const built = buildCreatePrCommand({
|
|
2864
|
+
const built = buildCreatePrCommand({
|
|
2865
|
+
provider,
|
|
2866
|
+
...(repoRef ? { repoRef } : { repo }),
|
|
2867
|
+
base, head, title, body, token, os, shell,
|
|
2868
|
+
});
|
|
1801
2869
|
|
|
1802
2870
|
const res = await command(built.command, {
|
|
1803
2871
|
member_name: member,
|
|
@@ -1812,8 +2880,19 @@ async function raiseVcsPrForMember({ fleetApi, command, member, base, head, titl
|
|
|
1812
2880
|
const { status, body: respBody, bodyText } = parseVcsCurlOutput(res.output);
|
|
1813
2881
|
const [lo, hi] = built.interpret.successStatusRange;
|
|
1814
2882
|
if (status !== null && status >= lo && status <= hi) {
|
|
1815
|
-
|
|
1816
|
-
|
|
2883
|
+
// apra-fleet-lzfv.5: read the created PR's id/url through the
|
|
2884
|
+
// provider's OWN pullRequestResponse.map hook (declared on its
|
|
2885
|
+
// descriptor -- see vcs-providers/github.mjs and
|
|
2886
|
+
// vcs-providers/azure-devops.mjs) instead of a GitHub-dialect
|
|
2887
|
+
// `html_url` field literal here. A provider with no mapping
|
|
2888
|
+
// (should not happen for an auth-backend provider, but never
|
|
2889
|
+
// throws) yields prUrl: null rather than crashing on an
|
|
2890
|
+
// otherwise-successful PR.
|
|
2891
|
+
const impl = getVcsProvider(provider);
|
|
2892
|
+
const mapped = (impl && impl.pullRequestResponse && typeof impl.pullRequestResponse.map === 'function')
|
|
2893
|
+
? impl.pullRequestResponse.map(respBody, repoRef ? { repoRef } : { repo })
|
|
2894
|
+
: { id: null, url: null };
|
|
2895
|
+
return { ok: true, alreadyExists: false, prUrl: mapped.url, error: null, authFailure: false };
|
|
1817
2896
|
}
|
|
1818
2897
|
|
|
1819
2898
|
const errorMessages = [];
|
|
@@ -1835,9 +2914,9 @@ async function raiseVcsPrForMember({ fleetApi, command, member, base, head, titl
|
|
|
1835
2914
|
authHealAttempted = true;
|
|
1836
2915
|
log(`${logPrefix}: PR creation returned an auth-classified failure (HTTP ${status ?? '(unknown)'}) for member '${member}'; re-provisioning a push+pr credential and retrying once (command: ${built.logSafeCommand}): ${errorText}`);
|
|
1837
2916
|
try {
|
|
1838
|
-
const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix });
|
|
2917
|
+
const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride });
|
|
1839
2918
|
if (reprov.repo) repo = reprov.repo;
|
|
1840
|
-
token = await readMemberVcsCredentialToken({ command, member });
|
|
2919
|
+
token = await readMemberVcsCredentialToken({ command, member, label: credentialLabel, fleetApi, log });
|
|
1841
2920
|
} catch (healErr) {
|
|
1842
2921
|
log(`${logPrefix}: PR auth self-heal failed for member '${member}'; not retrying further: ${healErr.message}`);
|
|
1843
2922
|
return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}`, authFailure: true };
|
|
@@ -1908,6 +2987,130 @@ export function createMemberVcsProviderResolver(opts = {}) {
|
|
|
1908
2987
|
};
|
|
1909
2988
|
}
|
|
1910
2989
|
|
|
2990
|
+
/**
|
|
2991
|
+
* Best-effort provisions a member for unattended execution (`unattended:
|
|
2992
|
+
* 'auto'`) before dispatching it as deployer, integ-test-runner, or
|
|
2993
|
+
* regression-test-runner -- roles that run real deploy commands and test
|
|
2994
|
+
* suites via a runbook and must never stall on an interactive permission
|
|
2995
|
+
* prompt. Provisioning is a one-way member-registration change and is
|
|
2996
|
+
* deliberately NOT reverted after the dispatch: `unattended` lives on the
|
|
2997
|
+
* member (update_member), not on the dispatch, so there is nothing to revert
|
|
2998
|
+
* to without also clobbering whatever the user set intentionally. In a
|
|
2999
|
+
* single-member sprint the same member also plays doer/reviewer/etc, so it
|
|
3000
|
+
* ends up unattended='auto' too -- accepted, not a bug.
|
|
3001
|
+
*
|
|
3002
|
+
* Cached per member for the lifetime of the returned function, so a sprint
|
|
3003
|
+
* with many deploy/integ/regression dispatches across cycles calls
|
|
3004
|
+
* update_member at most once per member. A failure (fleet unreachable,
|
|
3005
|
+
* member not found) is logged and swallowed -- exactly like
|
|
3006
|
+
* createMemberVcsProviderResolver above -- so a provisioning hiccup degrades
|
|
3007
|
+
* to whatever permission mode the member already had, rather than aborting
|
|
3008
|
+
* the phase.
|
|
3009
|
+
*
|
|
3010
|
+
* `callTool` is injected (the caller's MCP client), so this stays
|
|
3011
|
+
* transport-agnostic and unit-testable without a live fleet server.
|
|
3012
|
+
*
|
|
3013
|
+
* @param {{ callTool: (name: string, args: object) => Promise<any>, log?: Function }} opts
|
|
3014
|
+
* @returns {(member: string) => Promise<void>}
|
|
3015
|
+
*/
|
|
3016
|
+
export function createUnattendedAutoProvisioner(opts = {}) {
|
|
3017
|
+
const { callTool, log = () => {} } = opts;
|
|
3018
|
+
const fleetApi = new ApraFleet({ callTool });
|
|
3019
|
+
/** @type {Set<string>} members already confirmed unattended='auto' this run. */
|
|
3020
|
+
const provisioned = new Set();
|
|
3021
|
+
|
|
3022
|
+
return async function ensureUnattendedAuto(member) {
|
|
3023
|
+
if (provisioned.has(member)) return;
|
|
3024
|
+
try {
|
|
3025
|
+
await fleetApi.updateMember({ member_name: member, unattended: 'auto' });
|
|
3026
|
+
provisioned.add(member);
|
|
3027
|
+
log(`[unattended] member '${member}' set to unattended='auto' for this dispatch.`);
|
|
3028
|
+
} catch (err) {
|
|
3029
|
+
log(`[unattended] could not set unattended='auto' on member '${member}' (continuing with its existing permission mode): ${err.message}`);
|
|
3030
|
+
}
|
|
3031
|
+
};
|
|
3032
|
+
}
|
|
3033
|
+
|
|
3034
|
+
/**
|
|
3035
|
+
* Best-effort, self-heals the "Missing permission" class of deploy/integ/
|
|
3036
|
+
* regression-test failure BEFORE it happens: reads deploy.md's own
|
|
3037
|
+
* `## Permissions` section -- the exact list the deployer/integ-test-runner/
|
|
3038
|
+
* regression-test-runner agent prompts already cross-check at their own
|
|
3039
|
+
* Step 0a/0 -- and proactively grants every listed prefix to the target
|
|
3040
|
+
* member via compose_permissions. Without this, a runbook permissions
|
|
3041
|
+
* change (e.g. the `apra-fleet start` -> `apra-fleet run` swap, #395) only
|
|
3042
|
+
* gets noticed when a dispatch fails, and only gets fixed once an operator
|
|
3043
|
+
* greps deploy.md by hand and runs compose_permissions manually -- exactly
|
|
3044
|
+
* the failure mode this closes the loop on.
|
|
3045
|
+
*
|
|
3046
|
+
* Reads deploy.md via `command()` against the FIRST target member it is asked
|
|
3047
|
+
* to provision (that member is about to be dispatched as deployer/
|
|
3048
|
+
* integ-test-runner/regression-test-runner, so its own checkout is the source
|
|
3049
|
+
* of truth for what it is about to run) and caches the parsed prefix list for
|
|
3050
|
+
* the lifetime of the returned function -- one read per sprint run, since
|
|
3051
|
+
* deploy.md does not change mid-run on a healthy pipeline. Also caches per
|
|
3052
|
+
* TARGET member, like createUnattendedAutoProvisioner above, so repeat cycles
|
|
3053
|
+
* don't re-grant. Deliberately does NOT read via a separate orchestrator
|
|
3054
|
+
* member: the orchestrator role may be shared/unreservable across concurrent
|
|
3055
|
+
* sprints and carries no git checkout of its own to read from.
|
|
3056
|
+
*
|
|
3057
|
+
* Failure at any step (probe fails, deploy.md missing/unparseable,
|
|
3058
|
+
* compose_permissions unreachable, a listed prefix hitting the
|
|
3059
|
+
* NEVER_AUTO_GRANT denylist) is logged and swallowed. This is pure
|
|
3060
|
+
* best-effort acceleration -- the deployer's own Step 0a check remains the
|
|
3061
|
+
* authoritative, fail-closed backstop regardless of whether this succeeds.
|
|
3062
|
+
*
|
|
3063
|
+
* @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function }} opts
|
|
3064
|
+
* @returns {(member: string) => Promise<void>}
|
|
3065
|
+
*/
|
|
3066
|
+
export function createDeployPermissionsProvisioner(opts = {}) {
|
|
3067
|
+
const { callTool, command, log = () => {} } = opts;
|
|
3068
|
+
const fleetApi = new ApraFleet({ callTool });
|
|
3069
|
+
/** @type {Set<string>} members already granted deploy.md's permissions this run. */
|
|
3070
|
+
const provisioned = new Set();
|
|
3071
|
+
/** @type {string[] | null | undefined} undefined = not yet attempted. */
|
|
3072
|
+
let cachedPrefixes;
|
|
3073
|
+
|
|
3074
|
+
async function loadRequiredPrefixes(targetMember) {
|
|
3075
|
+
if (cachedPrefixes !== undefined) return cachedPrefixes;
|
|
3076
|
+
try {
|
|
3077
|
+
const res = await command(
|
|
3078
|
+
`node -e "const fs=require('fs'); if(fs.existsSync('deploy.md')) process.stdout.write(fs.readFileSync('deploy.md','utf8'))"`,
|
|
3079
|
+
{ member_name: targetMember, silent: true, label: `Read deploy.md permissions`, failSoft: true },
|
|
3080
|
+
);
|
|
3081
|
+
if (!res.ok || !res.output) {
|
|
3082
|
+
cachedPrefixes = null;
|
|
3083
|
+
} else {
|
|
3084
|
+
const section = res.output.split(/^## Permissions/m)[1]?.split(/^## /m)[0] ?? '';
|
|
3085
|
+
const prefixes = [...section.matchAll(/^-\s*`([^`]+)`/gm)].map(m => m[1]);
|
|
3086
|
+
cachedPrefixes = prefixes.length ? prefixes : null;
|
|
3087
|
+
}
|
|
3088
|
+
} catch (err) {
|
|
3089
|
+
log(`[deploy-permissions] could not read deploy.md's Permissions section (continuing without auto-provisioning): ${err.message}`);
|
|
3090
|
+
cachedPrefixes = null;
|
|
3091
|
+
}
|
|
3092
|
+
return cachedPrefixes;
|
|
3093
|
+
}
|
|
3094
|
+
|
|
3095
|
+
return async function ensureDeployPermissions(member) {
|
|
3096
|
+
if (!member || provisioned.has(member)) return;
|
|
3097
|
+
const prefixes = await loadRequiredPrefixes(member);
|
|
3098
|
+
if (!prefixes) return;
|
|
3099
|
+
try {
|
|
3100
|
+
const result = await fleetApi.composePermissions({
|
|
3101
|
+
member_name: member,
|
|
3102
|
+
role: 'doer',
|
|
3103
|
+
grant: prefixes,
|
|
3104
|
+
grant_reason: "deploy.md's declared Permissions section, auto-provisioned before dispatch",
|
|
3105
|
+
});
|
|
3106
|
+
provisioned.add(member);
|
|
3107
|
+
log(`[deploy-permissions] ensured deploy.md's required permissions on '${member}': ${result}`);
|
|
3108
|
+
} catch (err) {
|
|
3109
|
+
log(`[deploy-permissions] could not auto-provision deploy.md permissions on '${member}' (continuing -- the deployer's own Step 0a check remains the backstop): ${err.message}`);
|
|
3110
|
+
}
|
|
3111
|
+
};
|
|
3112
|
+
}
|
|
3113
|
+
|
|
1911
3114
|
/**
|
|
1912
3115
|
* Builds the REACTIVE `onAuthFailure` self-heal callback runGitStep and
|
|
1913
3116
|
* runDoltStep invoke on an 'auth' classification: re-provisions the failing
|
|
@@ -1924,13 +3127,41 @@ export function createMemberVcsProviderResolver(opts = {}) {
|
|
|
1924
3127
|
* @returns {(info: { member: string, label: string, cmd?: string, error: string, kind: 'git'|'dolt' }) => Promise<void>}
|
|
1925
3128
|
*/
|
|
1926
3129
|
export function createVcsAuthSelfHealCallback(opts = {}) {
|
|
1927
|
-
const { callTool, command, log = () => {} } = opts;
|
|
3130
|
+
const { callTool, command, log = () => {}, azdevopsPatSecretName } = opts;
|
|
1928
3131
|
const fleetApi = new ApraFleet({ callTool });
|
|
1929
3132
|
|
|
1930
3133
|
return async function onAuthFailure({ member, label, error }) {
|
|
1931
3134
|
log(`[Sync] self-heal: auth failure detected for member '${member}' (${label}); calling provision_vcs_auth to re-provision credentials: ${error}`);
|
|
1932
3135
|
|
|
1933
|
-
|
|
3136
|
+
// apra-fleet-5co8.4.2: some providers (e.g. Azure DevOps PATs) can
|
|
3137
|
+
// never be fixed by this reactive re-provisioning call alone -- it
|
|
3138
|
+
// only redeploys the SAME stored secret, it never mints a new one.
|
|
3139
|
+
// Print that provider's own remedy hint via the generic
|
|
3140
|
+
// `authRemedy` descriptor field (no provider-name conditional here,
|
|
3141
|
+
// see vcs-providers/index.mjs) BEFORE attempting the self-heal below,
|
|
3142
|
+
// so the operator has the real remedy even if that attempt also
|
|
3143
|
+
// fails. A provider that declares no `authRemedy` (or
|
|
3144
|
+
// `serverSideReMintable: true`, e.g. GitHub's App-minted token) prints
|
|
3145
|
+
// nothing extra here -- unchanged from before this task.
|
|
3146
|
+
// apra-fleet-5co8.13: resolve the provider ONCE here and thread it into
|
|
3147
|
+
// provisionVcsAuthForMember below via `resolvedProvider`, so a single
|
|
3148
|
+
// self-heal attempt makes exactly one member_detail round trip instead
|
|
3149
|
+
// of two. A resolution failure here must NOT short-circuit the
|
|
3150
|
+
// self-heal attempt -- `resolved` simply stays undefined and
|
|
3151
|
+
// provisionVcsAuthForMember falls back to its own lookup.
|
|
3152
|
+
let resolved;
|
|
3153
|
+
try {
|
|
3154
|
+
resolved = await resolveProvider(member, { fleetApi });
|
|
3155
|
+
const { provider } = resolved;
|
|
3156
|
+
const impl = getVcsProvider(provider);
|
|
3157
|
+
if (impl && impl.authRemedy && impl.authRemedy.serverSideReMintable === false) {
|
|
3158
|
+
log(`[Sync] self-heal: member '${member}' (${label}) uses '${provider}', whose credentials cannot be re-minted server-side. ${impl.authRemedy.hint}`);
|
|
3159
|
+
}
|
|
3160
|
+
} catch (resolveErr) {
|
|
3161
|
+
log(`[Sync] self-heal: could not resolve member '${member}' (${label})'s VCS provider to check for an auth remedy hint (continuing with the self-heal attempt): ${resolveErr.message}`);
|
|
3162
|
+
}
|
|
3163
|
+
|
|
3164
|
+
await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] self-heal', azdevopsPatSecretName, resolvedProvider: resolved });
|
|
1934
3165
|
|
|
1935
3166
|
log(`[Sync] self-heal: provision_vcs_auth succeeded for member '${member}' (${label}); the failed command will be retried once.`);
|
|
1936
3167
|
};
|
|
@@ -1969,7 +3200,7 @@ const VCS_AUTH_EXPIRY_PREFLIGHT_MS = 10 * 60 * 1000; // 10 minutes
|
|
|
1969
3200
|
* @returns {(member: string) => Promise<void>}
|
|
1970
3201
|
*/
|
|
1971
3202
|
export function createVcsAuthPreflightCallback(opts = {}) {
|
|
1972
|
-
const { callTool, command, log = () => {}, now = () => Date.now() } = opts;
|
|
3203
|
+
const { callTool, command, log = () => {}, now = () => Date.now(), azdevopsPatSecretName } = opts;
|
|
1973
3204
|
const fleetApi = new ApraFleet({ callTool });
|
|
1974
3205
|
/** @type {Map<string, Date|null>} member -> last-known expiresAt (null = no expiry tracked, e.g. PAT mode). */
|
|
1975
3206
|
const knownGoodUntil = new Map();
|
|
@@ -1986,7 +3217,7 @@ export function createVcsAuthPreflightCallback(opts = {}) {
|
|
|
1986
3217
|
}
|
|
1987
3218
|
log(`[Sync] preflight: ensuring member '${member}' has a fresh VCS credential before dispatch; calling provision_vcs_auth.`);
|
|
1988
3219
|
try {
|
|
1989
|
-
const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight' });
|
|
3220
|
+
const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight', azdevopsPatSecretName });
|
|
1990
3221
|
knownGoodUntil.set(member, expiresAt);
|
|
1991
3222
|
log(`[Sync] preflight: provision_vcs_auth succeeded for member '${member}'${expiresAt ? ` (expires ${expiresAt.toISOString()})` : ''}.`);
|
|
1992
3223
|
} catch (err) {
|
|
@@ -2236,15 +3467,19 @@ export async function persistNewTaskBestEffort({ createFn, command, member, pare
|
|
|
2236
3467
|
* Returns the ids that are NOT closed after the D-pull-then-read. An empty
|
|
2237
3468
|
* array means the streak genuinely closed everything it was assigned.
|
|
2238
3469
|
*
|
|
2239
|
-
* @param {{ command: Function, orchestratorMember: string, beadIds: string[], log?: Function }} opts
|
|
3470
|
+
* @param {{ command: Function, orchestratorMember: string, beadIds: string[], log?: Function, args?: { callTool?: Function } }} opts
|
|
2240
3471
|
* @returns {Promise<string[]>} the still-unclosed bead ids
|
|
2241
3472
|
*/
|
|
2242
|
-
export async function verifyDoerStreakClosed({ command, orchestratorMember, beadIds, log = () => {} }) {
|
|
3473
|
+
export async function verifyDoerStreakClosed({ command, orchestratorMember, beadIds, log = () => {}, args }) {
|
|
2243
3474
|
// D-pull FIRST so the orchestrator's clone observes the doer's just-pushed
|
|
2244
3475
|
// closes. Routed through the single dolt-sync module's purpose-based BEFORE
|
|
2245
3476
|
// bracket (apra-fleet-417.2.1); behavior is identical to the previous
|
|
2246
3477
|
// direct doltPullBefore() call.
|
|
2247
|
-
|
|
3478
|
+
// Thread the orchestrator member's REGISTERED shell into dolt-settle,
|
|
3479
|
+
// guarded on args.callTool the same way the pre-dispatch bracket is
|
|
3480
|
+
// (apra-fleet-7dir.24).
|
|
3481
|
+
const shell = await resolveSettleShell({ args, member: orchestratorMember, log });
|
|
3482
|
+
await DoltSync.syncBefore(orchestratorMember, { command, log, fatal: true, settle: buildSettleCallback(orchestratorMember, { command, log, shell }) });
|
|
2248
3483
|
const label = `bd show ${beadIds.join(' ')} --json`;
|
|
2249
3484
|
const showRes = await command(label, { member_name: orchestratorMember, silent: true });
|
|
2250
3485
|
const showBeads = parseBdJson(showRes, label);
|
|
@@ -2252,6 +3487,71 @@ export async function verifyDoerStreakClosed({ command, orchestratorMember, bead
|
|
|
2252
3487
|
return beadIds.filter((id) => statusById.get(id) !== 'closed');
|
|
2253
3488
|
}
|
|
2254
3489
|
|
|
3490
|
+
/**
|
|
3491
|
+
* Batched per-streak work-claiming (apra-fleet-7h6n.7, audit R6): claims
|
|
3492
|
+
* every id in `beadIds` with ONE `bd update <id...> --claim --json`
|
|
3493
|
+
* invocation instead of one `bd update <id> --claim` call per bead.
|
|
3494
|
+
*
|
|
3495
|
+
* RESEARCH FINDING this batching relies on (verified against real `bd`
|
|
3496
|
+
* 1.1.0, both by reading `bd update --help`'s `Usage: bd update [id...]`
|
|
3497
|
+
* and by exercising a scratch sandbox DB): `bd update` DOES accept a
|
|
3498
|
+
* variadic id list, and `--claim --json` on a MULTI-id invocation returns a
|
|
3499
|
+
* JSON array containing ONLY the issues that were successfully claimed --
|
|
3500
|
+
* an id that fails to resolve, or is already claimed by a DIFFERENT
|
|
3501
|
+
* assignee, is silently dropped from the array (its error goes to stderr,
|
|
3502
|
+
* not stdout) rather than aborting the whole call. Two non-obvious
|
|
3503
|
+
* consequences, both load-bearing for this function's design:
|
|
3504
|
+
* 1. This is NOT atomic in the transactional sense -- ids before a
|
|
3505
|
+
* failing one are still committed, there is no all-or-nothing
|
|
3506
|
+
* rollback. It IS enough to cut the streak's claim step from N
|
|
3507
|
+
* subprocess spawns to 1, which is this bead's actual goal.
|
|
3508
|
+
* 2. The process exit code stays 0 even when SOME ids in the batch
|
|
3509
|
+
* failed to claim (verified: a lone failing id exits 1, but the exact
|
|
3510
|
+
* same failure mixed into a multi-id batch with a succeeding id exits
|
|
3511
|
+
* 0) -- so, unlike the old single-id-per-call loop, success can NEVER
|
|
3512
|
+
* be inferred from "command() did not throw". The returned JSON array
|
|
3513
|
+
* is the only reliable signal, which is why this function always
|
|
3514
|
+
* diffs `beadIds` against the parsed array rather than relying on a
|
|
3515
|
+
* catch block.
|
|
3516
|
+
*
|
|
3517
|
+
* A total call failure (command() itself throws -- e.g. a transient
|
|
3518
|
+
* dispatch/network fault reaching the member) is treated the same way the
|
|
3519
|
+
* old loop treated "every id failed": every id is reported skipped, never
|
|
3520
|
+
* thrown, so one bad batch degrades the streak (all its beads stay
|
|
3521
|
+
* unclaimed, caller decides whether to skip the streak) rather than
|
|
3522
|
+
* crashing the sprint.
|
|
3523
|
+
*
|
|
3524
|
+
* @param {{ command: Function, orchestratorMember: string, beadIds: string[], log?: Function }} opts
|
|
3525
|
+
* @returns {Promise<{ claimedBeadIds: string[], skippedBeadIds: string[] }>}
|
|
3526
|
+
*/
|
|
3527
|
+
export async function claimBeadsBatched({ command, orchestratorMember, beadIds, log = () => {} }) {
|
|
3528
|
+
if (!Array.isArray(beadIds) || beadIds.length === 0) {
|
|
3529
|
+
return { claimedBeadIds: [], skippedBeadIds: [] };
|
|
3530
|
+
}
|
|
3531
|
+
const label = `bd update ${beadIds.join(' ')} --claim --json`;
|
|
3532
|
+
let raw;
|
|
3533
|
+
try {
|
|
3534
|
+
raw = await command(label, { member_name: orchestratorMember, silent: true });
|
|
3535
|
+
} catch (err) {
|
|
3536
|
+
// A dispatch/exec-level failure (member unreachable, transient
|
|
3537
|
+
// network fault) degrades gracefully -- every id in this batch
|
|
3538
|
+
// stays unclaimed, same as the old per-id loop's catch-and-skip.
|
|
3539
|
+
// This is DISTINCT from a malformed-JSON parse failure below, which
|
|
3540
|
+
// stays fatal (per parseBdJson's own doc comment: a parse failure
|
|
3541
|
+
// must be LOUD, never silently swallowed as "everything skipped").
|
|
3542
|
+
log(`Batched claim failed for [${beadIds.join(', ')}]: ${err.message}`);
|
|
3543
|
+
return { claimedBeadIds: [], skippedBeadIds: [...beadIds] };
|
|
3544
|
+
}
|
|
3545
|
+
const claimed = parseBdJson(raw, label);
|
|
3546
|
+
const claimedIds = new Set((Array.isArray(claimed) ? claimed : []).map((b) => b && b.id).filter(Boolean));
|
|
3547
|
+
const claimedBeadIds = beadIds.filter((id) => claimedIds.has(id));
|
|
3548
|
+
const skippedBeadIds = beadIds.filter((id) => !claimedIds.has(id));
|
|
3549
|
+
if (skippedBeadIds.length > 0) {
|
|
3550
|
+
log(`Batched claim: claimed ${claimedBeadIds.length} bead(s) [${claimedBeadIds.join(', ')}]; skipped ${skippedBeadIds.length} already-claimed/unresolvable bead(s) [${skippedBeadIds.join(', ')}].`);
|
|
3551
|
+
}
|
|
3552
|
+
return { claimedBeadIds, skippedBeadIds };
|
|
3553
|
+
}
|
|
3554
|
+
|
|
2255
3555
|
/**
|
|
2256
3556
|
* Validates and normalizes the args object passed into main(context).
|
|
2257
3557
|
* Rejects unknown keys and missing/malformed required keys loudly.
|
|
@@ -2362,6 +3662,12 @@ export function validateArgs(args) {
|
|
|
2362
3662
|
throw new Error(`[Arg Contract] Invalid budget "${args.budget}": must be a non-negative finite number (USD ceiling).`);
|
|
2363
3663
|
}
|
|
2364
3664
|
|
|
3665
|
+
// --- run_id (optional) -------------------------------------------------
|
|
3666
|
+
// Free-form supervisor-generated identity; only its shape is checked here.
|
|
3667
|
+
if (args.run_id !== undefined && (typeof args.run_id !== 'string' || args.run_id.length === 0)) {
|
|
3668
|
+
throw new Error('[Arg Contract] Invalid run_id: must be a non-empty string.');
|
|
3669
|
+
}
|
|
3670
|
+
|
|
2365
3671
|
// --- serviceUrl (optional) --------------------------------------------
|
|
2366
3672
|
// The always-on supervisor's base HTTP URL. Validated as an http(s) URL so
|
|
2367
3673
|
// a malformed value fails fast rather than silently disabling the
|
|
@@ -2394,16 +3700,20 @@ export function validateArgs(args) {
|
|
|
2394
3700
|
}
|
|
2395
3701
|
}
|
|
2396
3702
|
|
|
2397
|
-
// --- dispatch_timeout_s (optional, default
|
|
3703
|
+
// --- dispatch_timeout_s (optional, default 9000 = 150min/2.5h) ---------
|
|
2398
3704
|
// Per-dispatch time budget in seconds, applied as BOTH timeout_s and
|
|
2399
3705
|
// max_total_s on every agent dispatch: `claude -p` emits nothing until the
|
|
2400
3706
|
// turn completes, so inactivity equals total runtime and the two timers
|
|
2401
3707
|
// must be equal for the ceiling to be reachable. The integ-test dispatch
|
|
2402
|
-
// ceiling is 2x this value
|
|
2403
|
-
//
|
|
2404
|
-
//
|
|
2405
|
-
//
|
|
2406
|
-
|
|
3708
|
+
// ceiling is 2x this value and the regression-test ceiling is 3x, since
|
|
3709
|
+
// those suites legitimately run past one budget. Raised from the earlier
|
|
3710
|
+
// 3600s default: an hour was tight enough to misclassify a slow-but-alive
|
|
3711
|
+
// turn (a large diff, a chatty tool loop) as a stall, which is a false
|
|
3712
|
+
// positive, not the genuine-hang protection this timer exists for.
|
|
3713
|
+
// Lowering it still bounds the cost of a live-but-silent member hang,
|
|
3714
|
+
// which no timer can otherwise distinguish from work. Floor 60: below
|
|
3715
|
+
// that even healthy dispatches cannot complete a single turn.
|
|
3716
|
+
const dispatchTimeoutS = args.dispatch_timeout_s === undefined ? 9000 : args.dispatch_timeout_s;
|
|
2407
3717
|
if (typeof dispatchTimeoutS !== 'number' || !Number.isInteger(dispatchTimeoutS) || dispatchTimeoutS < 60) {
|
|
2408
3718
|
throw new Error(`[Arg Contract] Invalid dispatch_timeout_s "${dispatchTimeoutS}": must be an integer >= 60 (seconds).`);
|
|
2409
3719
|
}
|
|
@@ -2430,6 +3740,15 @@ export function validateArgs(args) {
|
|
|
2430
3740
|
throw new Error(`[Arg Contract] Invalid worklist_effort_budget "${args.worklist_effort_budget}": must be a positive finite number (effort points).`);
|
|
2431
3741
|
}
|
|
2432
3742
|
|
|
3743
|
+
// --- azdevops_pat_secret_name (optional) --------------------------------
|
|
3744
|
+
// Override for the default Azure DevOps PAT secret name. When provided, this
|
|
3745
|
+
// credential store entry name is used instead of the documented default
|
|
3746
|
+
// (azdevops_pat). Validated as a credential-store name at contract-validation
|
|
3747
|
+
// time, not mid-sprint, so invalid values fail fast and clearly.
|
|
3748
|
+
if (args.azdevops_pat_secret_name !== undefined) {
|
|
3749
|
+
validateCredentialStoreName(args.azdevops_pat_secret_name, 'azdevops_pat_secret_name');
|
|
3750
|
+
}
|
|
3751
|
+
|
|
2433
3752
|
return {
|
|
2434
3753
|
targetIssues,
|
|
2435
3754
|
members: args.members,
|
|
@@ -2441,8 +3760,10 @@ export function validateArgs(args) {
|
|
|
2441
3760
|
roleMap: normalizedRoleMap,
|
|
2442
3761
|
budget: args.budget,
|
|
2443
3762
|
serviceUrl: args.serviceUrl,
|
|
3763
|
+
runId: args.run_id,
|
|
2444
3764
|
assignee: args.assignee,
|
|
2445
3765
|
dispatchTimeoutS,
|
|
3766
|
+
azdevopsPatSecretName: args.azdevops_pat_secret_name,
|
|
2446
3767
|
doerWorklistMode,
|
|
2447
3768
|
resumeModelSwitch,
|
|
2448
3769
|
worklistEffortBudget: args.worklist_effort_budget,
|
|
@@ -3460,10 +4781,13 @@ export function assignDoerWorklists(streaks, doerCount, opts = {}) {
|
|
|
3460
4781
|
* sprint track branch and is always spelled out: doer.md requires it, and a
|
|
3461
4782
|
* doer dispatched without one must return "BLOCKED" rather than guess whatever
|
|
3462
4783
|
* branch happens to be checked out.
|
|
3463
|
-
*
|
|
4784
|
+
* `kbKnowledge` carries the entries kb_session_prime returned for this member
|
|
4785
|
+
* (see kbKnowledgeBlock): the doer cannot read the KB itself on a member
|
|
4786
|
+
* dispatch, so this prompt is its only route to prior knowledge.
|
|
4787
|
+
* @param {{ beadIds: string[], branch: string, feedback: string|null, kbKnowledge?: object[] }} opts
|
|
3464
4788
|
* @returns {string}
|
|
3465
4789
|
*/
|
|
3466
|
-
export function buildDoerPrompt({ beadIds, branch, feedback }) {
|
|
4790
|
+
export function buildDoerPrompt({ beadIds, branch, feedback, kbKnowledge }) {
|
|
3467
4791
|
const lines = [
|
|
3468
4792
|
`Sprint track branch to work on: ${branch}. Work on this branch only; do not push to the base branch.`,
|
|
3469
4793
|
`Assigned bead ids (comma-separated): ${beadIds.join(', ')}`,
|
|
@@ -3480,6 +4804,7 @@ export function buildDoerPrompt({ beadIds, branch, feedback }) {
|
|
|
3480
4804
|
'workaround whose purpose is to bypass the block, even for a brand-new file and ' +
|
|
3481
4805
|
'even if you judge the underlying operation safe. This matches this repo\'s ' +
|
|
3482
4806
|
'CLAUDE.md permission-block policy.',
|
|
4807
|
+
...kbKnowledgeBlock(kbKnowledge),
|
|
3483
4808
|
];
|
|
3484
4809
|
if (feedback) {
|
|
3485
4810
|
lines.push(
|
|
@@ -3497,29 +4822,204 @@ export function buildDoerPrompt({ beadIds, branch, feedback }) {
|
|
|
3497
4822
|
* ids just worked, their full `bd show` detail (acceptance criteria), the diff
|
|
3498
4823
|
* range, and the sprint goal priority are all spelled out rather than assumed.
|
|
3499
4824
|
*
|
|
3500
|
-
*
|
|
3501
|
-
*
|
|
3502
|
-
*
|
|
3503
|
-
*
|
|
4825
|
+
* CRITICAL: explicitly, redundantly forbids the reviewer from mutating
|
|
4826
|
+
* beads itself. agents/reviewer.md's own prose (Step 5, Rules) already
|
|
4827
|
+
* states this same prohibition -- prose and dispatch prompt agree today --
|
|
4828
|
+
* but the schema alone doesn't stop the reviewer from shelling out `bd`
|
|
4829
|
+
* commands on the member side regardless of what either document says, so
|
|
4830
|
+
* the prohibition is stated here too as defense in depth, not because of
|
|
4831
|
+
* any known prose/code divergence.
|
|
4832
|
+
* apra-fleet-s6d: `beadIds` may legitimately be EMPTY. The Cycle Evaluation
|
|
4833
|
+
* re-review asks a scope-wide question ("no goal-priority beads are open --
|
|
4834
|
+
* is the sprint actually done?"), so it has no bead ids to name. Rendering
|
|
4835
|
+
* the per-bead framing anyway produced the literal dangling sentence
|
|
4836
|
+
* "...for the following bead id(s): ." plus a SPRINT SCOPE block ordering the
|
|
4837
|
+
* reviewer to judge "ONLY against the named bead id(s) above" -- against an
|
|
4838
|
+
* empty set. The reviewer answered honestly (CHANGES_NEEDED with nothing to
|
|
4839
|
+
* reopen and nothing to create), which is exactly what
|
|
4840
|
+
* isReviewerContractViolation flags; the retry re-sent the identical
|
|
4841
|
+
* incoherent prompt, so the sprint aborted on ReviewerContractViolationError.
|
|
4842
|
+
* The empty case therefore gets its own coherent scope-wide framing.
|
|
4843
|
+
*
|
|
4844
|
+
* @param {{ beadIds: string[], acceptanceCriteriaJson: string, baseBranch: string, branch: string, goal?: string, kbCandidates?: object[] }} opts
|
|
3504
4845
|
* @returns {string}
|
|
3505
4846
|
*/
|
|
3506
|
-
|
|
4847
|
+
/**
|
|
4848
|
+
* apra-fleet-0ef / apra-fleet-nx7: the "KNOWLEDGE BANK -- promotion candidates"
|
|
4849
|
+
* block, shared verbatim by the per-round reviewer prompt and the Final Review
|
|
4850
|
+
* prompt.
|
|
4851
|
+
*
|
|
4852
|
+
* It lives in one function because the two prompts must state the SAME evidence
|
|
4853
|
+
* bar. Duplicating the text invites them to drift, and a drifted bar is
|
|
4854
|
+
* invisible: both sides would still "work", just to different standards, and the
|
|
4855
|
+
* only symptom would be inconsistent CONFIRMED quality months later.
|
|
4856
|
+
*
|
|
4857
|
+
* Returns a single-element array (or an empty one) so callers can spread it into
|
|
4858
|
+
* their prompt-section list.
|
|
4859
|
+
*
|
|
4860
|
+
* @param {object[]|undefined} kbCandidates
|
|
4861
|
+
* @returns {string[]}
|
|
4862
|
+
*/
|
|
4863
|
+
/**
|
|
4864
|
+
* KB audit 2026-08-11: the "KNOWLEDGE BANK -- what this repo already knows"
|
|
4865
|
+
* block, shared by the doer and reviewer dispatch prompts.
|
|
4866
|
+
*
|
|
4867
|
+
* WHY THIS EXISTS AT ALL. Every role contract's Step 0 tells the role to call
|
|
4868
|
+
* kb_session_prime itself. On a fleet-member dispatch it cannot: the member's
|
|
4869
|
+
* composed permission config disables the apra-fleet MCP server outright
|
|
4870
|
+
* (src/providers/claude.ts composePermissionConfig), so the tool is not merely
|
|
4871
|
+
* unlisted, it is unreachable. That is the same wall kb_promotions hit, and
|
|
4872
|
+
* this is the same fix -- the engine performs the read and hands the result
|
|
4873
|
+
* over as prompt content. Step 0 stays correct for the OTHER execution path
|
|
4874
|
+
* (an apra-pm orchestrator session running these contracts as local subagents,
|
|
4875
|
+
* where the MCP server is present), so both paths now get knowledge.
|
|
4876
|
+
*
|
|
4877
|
+
* The trust ladder is restated here rather than assumed: these entries are
|
|
4878
|
+
* agent-authored claims from earlier sprints, and CONFIRMED means a reviewer
|
|
4879
|
+
* verified the claim, not that it is currently true of this branch's tree.
|
|
4880
|
+
*
|
|
4881
|
+
* Returns a single-element array (or an empty one) so callers can spread it
|
|
4882
|
+
* into their prompt-section list, matching kbPromotionBlock.
|
|
4883
|
+
*
|
|
4884
|
+
* @param {object[]|undefined} entries
|
|
4885
|
+
* @returns {string[]}
|
|
4886
|
+
*/
|
|
4887
|
+
/**
|
|
4888
|
+
* Roles whose prompt BUILDER places the knowledge block itself, at a position
|
|
4889
|
+
* that carries meaning. Everything else receives it from the agent() wrapper.
|
|
4890
|
+
* Listing them here (rather than inside the wrapper) keeps the two halves of
|
|
4891
|
+
* that split visible from the block's own definition -- a role added to one
|
|
4892
|
+
* side and forgotten on the other either gets the block twice or never.
|
|
4893
|
+
*/
|
|
4894
|
+
export const KB_SELF_INJECTING_ROLES = Object.freeze(new Set([ROLE_DOER, ROLE_REVIEWER]));
|
|
4895
|
+
|
|
4896
|
+
/**
|
|
4897
|
+
* FTS terms for a dispatch's kb_query, drawn from what the engine already
|
|
4898
|
+
* holds: the beads being worked and their ids.
|
|
4899
|
+
*
|
|
4900
|
+
* Bead TITLES are the useful half -- they are prose about the change ("stop
|
|
4901
|
+
* collapsing unknown_zone into unbound_roi"), which is what matches an entry's
|
|
4902
|
+
* title/summary/content. Ids are included because a bead id occasionally
|
|
4903
|
+
* appears verbatim in a captured entry, and query() OR-joins its terms, so a
|
|
4904
|
+
* term that matches nothing costs a little ranking noise rather than filtering
|
|
4905
|
+
* the result to empty. Non-string and blank values are dropped so a partially
|
|
4906
|
+
* populated bead cannot produce a malformed query.
|
|
4907
|
+
*
|
|
4908
|
+
* @param {Array<{id?: string, title?: string}>} beads
|
|
4909
|
+
* @param {string[]} beadIds
|
|
4910
|
+
* @returns {string[]}
|
|
4911
|
+
*/
|
|
4912
|
+
export function kbQueryTerms(beads, beadIds) {
|
|
4913
|
+
const terms = [];
|
|
4914
|
+
for (const b of Array.isArray(beads) ? beads : []) {
|
|
4915
|
+
if (b && typeof b.title === 'string' && b.title.trim()) terms.push(b.title.trim());
|
|
4916
|
+
}
|
|
4917
|
+
for (const id of Array.isArray(beadIds) ? beadIds : []) {
|
|
4918
|
+
if (typeof id === 'string' && id.trim()) terms.push(id.trim());
|
|
4919
|
+
}
|
|
4920
|
+
return terms;
|
|
4921
|
+
}
|
|
4922
|
+
|
|
4923
|
+
export function kbKnowledgeBlock(entries) {
|
|
4924
|
+
if (!Array.isArray(entries) || entries.length === 0) return [];
|
|
4925
|
+
return [
|
|
4926
|
+
'KNOWLEDGE BANK -- what this repo already knows. These entries were captured and '
|
|
4927
|
+
+ 'verified during earlier work on this repository, and are provided so you do not '
|
|
4928
|
+
+ 'rediscover them the hard way. Read them BEFORE you start.\n'
|
|
4929
|
+
+ 'CONFIRMED entries were independently verified by a reviewer: trust them. INFERRED '
|
|
4930
|
+
+ 'entries are unverified hints: treat them as leads to check, not as facts. An entry '
|
|
4931
|
+
+ 'describes the tree it was captured against, so if one contradicts what you actually '
|
|
4932
|
+
+ 'observe in the code right now, the code wins -- say so in your notes rather than '
|
|
4933
|
+
+ 'bending your work to fit the entry.\n'
|
|
4934
|
+
+ 'You do not need to call any kb_* tool to read these. If you discover something '
|
|
4935
|
+
+ 'non-obvious and durable while working, report it in the `kb_captures` field of your '
|
|
4936
|
+
+ 'structured output and the orchestrator will record it.\n'
|
|
4937
|
+
+ wrapUntrustedBlock('kb_session_prime --top_entries', JSON.stringify(
|
|
4938
|
+
entries.map((e) => ({
|
|
4939
|
+
confidence: e.confidence,
|
|
4940
|
+
title: e.title,
|
|
4941
|
+
summary: e.summary,
|
|
4942
|
+
source_files: e.source_files,
|
|
4943
|
+
})),
|
|
4944
|
+
null,
|
|
4945
|
+
2
|
|
4946
|
+
)),
|
|
4947
|
+
];
|
|
4948
|
+
}
|
|
4949
|
+
|
|
4950
|
+
export function kbPromotionBlock(kbCandidates) {
|
|
4951
|
+
if (!Array.isArray(kbCandidates) || kbCandidates.length === 0) return [];
|
|
4952
|
+
return [
|
|
4953
|
+
'KNOWLEDGE BANK -- promotion candidates. These entries were captured during this '
|
|
4954
|
+
+ 'sprint and sit at INFERRED. You are the only role that can promote them to '
|
|
4955
|
+
+ 'CONFIRMED. Do NOT call any kb_* tool yourself: return your decisions in the '
|
|
4956
|
+
+ '`kb_promotions` field of your structured output as [{id, reason}] and the '
|
|
4957
|
+
+ 'orchestrator executes them.\n'
|
|
4958
|
+
+ 'Promote ONLY entries whose claim you independently verified during THIS review '
|
|
4959
|
+
+ '-- by reading the diff, running the tests, or checking the cited files yourself. '
|
|
4960
|
+
+ 'The `reason` must state that evidence (at least 20 characters, e.g. "verified '
|
|
4961
|
+
+ 'against server/transit.js:88 and the reopen test"). Evidence, not plausibility: '
|
|
4962
|
+
+ 'if an entry merely looks correct, leave it INFERRED -- that is a perfectly good '
|
|
4963
|
+
+ 'resting state, and a wrong CONFIRMED entry is worse than no entry. Never '
|
|
4964
|
+
+ 'blanket-promote, and never promote by module, tag or timestamp. Promoting '
|
|
4965
|
+
+ 'nothing is a valid outcome; return [] in that case.\n'
|
|
4966
|
+
+ wrapUntrustedBlock('kb_list --confidence INFERRED', JSON.stringify(
|
|
4967
|
+
kbCandidates.map((e) => ({
|
|
4968
|
+
id: e.id,
|
|
4969
|
+
title: e.title,
|
|
4970
|
+
summary: e.summary,
|
|
4971
|
+
source_files: e.source_files,
|
|
4972
|
+
})),
|
|
4973
|
+
null,
|
|
4974
|
+
2
|
|
4975
|
+
)),
|
|
4976
|
+
];
|
|
4977
|
+
}
|
|
4978
|
+
|
|
4979
|
+
export function buildReviewerPrompt({ beadIds, acceptanceCriteriaJson, baseBranch, branch, goal, kbCandidates, kbKnowledge }) {
|
|
4980
|
+
const ids = Array.isArray(beadIds) ? beadIds : [];
|
|
4981
|
+
const scopeWide = ids.length === 0;
|
|
4982
|
+
// Scope-wide re-reviews are fed `bd list --json` (the whole remaining
|
|
4983
|
+
// scope); per-bead reviews are fed `bd show --json`. Label the untrusted
|
|
4984
|
+
// block with the command that actually produced it.
|
|
4985
|
+
const scopeCommand = scopeWide ? 'bd list --json' : 'bd show --json';
|
|
3507
4986
|
return [
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
4987
|
+
scopeWide
|
|
4988
|
+
? 'Re-review the CURRENT state of the entire sprint scope. No bead ids are named '
|
|
4989
|
+
+ 'because no goal-priority beads remain open -- that is precisely the question you '
|
|
4990
|
+
+ 'are being asked to settle: judge the delivered work as a whole and decide whether '
|
|
4991
|
+
+ 'this sprint is genuinely complete.'
|
|
4992
|
+
: `Review the work just done for the following bead id(s): ${ids.join(', ')}.`,
|
|
4993
|
+
scopeWide
|
|
4994
|
+
? 'The full sprint scope, from `bd list --json`:'
|
|
4995
|
+
: 'Full task detail (including acceptance criteria), from `bd show --json`:',
|
|
4996
|
+
wrapUntrustedBlock(scopeCommand, acceptanceCriteriaJson),
|
|
3511
4997
|
`Diff range to review: ${baseBranch}..${branch} (base_branch..branch).`,
|
|
3512
4998
|
// Without an explicit scope clause a reviewer can withhold APPROVED
|
|
3513
4999
|
// over below-goal work the sprint deliberately defers, which starves
|
|
3514
5000
|
// the completion gate (zero open goal beads AND an APPROVED verdict).
|
|
3515
5001
|
...(goal ? [
|
|
3516
5002
|
`SPRINT SCOPE: this sprint's goal priority is ${goal}. Judge your verdict ` +
|
|
3517
|
-
|
|
3518
|
-
|
|
5003
|
+
(scopeWide
|
|
5004
|
+
? `ONLY against work at or above that goal priority. `
|
|
5005
|
+
: `ONLY against the named bead id(s) above and other work at or above that `
|
|
5006
|
+
+ `goal priority. `) +
|
|
5007
|
+
`Features/beads BELOW the goal priority (e.g. P3 when the ` +
|
|
3519
5008
|
`goal is P1/P2) are DEFERRED BY DESIGN to a later sprint: their absence ` +
|
|
3520
5009
|
`from the diff is correct, must not block APPROVED, must not appear in ` +
|
|
3521
5010
|
`reopenIds, and may be mentioned in notes only.`,
|
|
3522
5011
|
] : []),
|
|
5012
|
+
// apra-fleet-0ef: the reviewer is the ONLY role permitted to mint
|
|
5013
|
+
// CONFIRMED, but a KB entry id can only come from the KB, and the
|
|
5014
|
+
// reviewer subagent has no apra-fleet MCP tools to look one up. Without
|
|
5015
|
+
// this block it could never name an id, so `kb_promotions` came back
|
|
5016
|
+
// empty on every round and nothing was ever promoted. The engine reads
|
|
5017
|
+
// the candidates and executes; the judgment stays with the reviewer.
|
|
5018
|
+
// Prior knowledge FIRST, then the promotion candidates: the reviewer
|
|
5019
|
+
// judges the work against what the repo already knows before it decides
|
|
5020
|
+
// which of this sprint's captures earned CONFIRMED.
|
|
5021
|
+
...kbKnowledgeBlock(kbKnowledge),
|
|
5022
|
+
...kbPromotionBlock(kbCandidates),
|
|
3523
5023
|
'Do NOT run any `bd` command yourself and do NOT mutate beads directly in any way ' +
|
|
3524
5024
|
'(no bd update, bd close, bd create, etc.) -- the orchestrator applies your ' +
|
|
3525
5025
|
'`reopenIds` via `bd update <id> --status=open` and creates your `newTasks` via ' +
|
|
@@ -3594,29 +5094,34 @@ export function extractContestedBeadIds(verdict) {
|
|
|
3594
5094
|
// diff/commit could try to steer it into emitting text crafted to break out of
|
|
3595
5095
|
// a shell command.
|
|
3596
5096
|
//
|
|
3597
|
-
// SAFE_TEXT_RE
|
|
3598
|
-
//
|
|
3599
|
-
//
|
|
3600
|
-
//
|
|
3601
|
-
//
|
|
3602
|
-
//
|
|
5097
|
+
// SAFE_TEXT_RE (title only) deliberately excludes: backtick, `$`,
|
|
5098
|
+
// double-quote (the command's own quoting delimiter -- allowing it back in
|
|
5099
|
+
// would let a title close the quote early regardless of any other
|
|
5100
|
+
// restriction), and backslash (blocks a trailing-backslash "escape the
|
|
5101
|
+
// closing quote" trick as well as any other backslash-based escape
|
|
5102
|
+
// sequence). The allowed punctuation (`.,:;!?()'-_/+[]` plus space) covers
|
|
5103
|
+
// realistic task titles while remaining inert as shell syntax in both POSIX
|
|
5104
|
+
// and Windows member shells.
|
|
3603
5105
|
//
|
|
3604
|
-
//
|
|
3605
|
-
//
|
|
3606
|
-
//
|
|
3607
|
-
//
|
|
3608
|
-
//
|
|
3609
|
-
//
|
|
3610
|
-
//
|
|
5106
|
+
// apra-fleet-v75: `[`, `]` and `+` are allowed. The title is interpolated as
|
|
5107
|
+
// `bd create "${title}"` -- inside double quotes, brackets never glob and `+`
|
|
5108
|
+
// has no meaning, in POSIX shells or PowerShell. Excluding them rejected this
|
|
5109
|
+
// project's own bead-title convention ([bug]/[epic]/[test] prefixes), which
|
|
5110
|
+
// `bd create` itself accepts; a real reviewer follow-up was dropped mid-sprint
|
|
5111
|
+
// on exactly that. The characters that ARE live inside double quotes --
|
|
5112
|
+
// `"`, `\`, backtick, `$` -- remain excluded, which is what this guard is for.
|
|
3611
5113
|
//
|
|
3612
|
-
// `description`
|
|
3613
|
-
//
|
|
3614
|
-
//
|
|
3615
|
-
//
|
|
3616
|
-
//
|
|
3617
|
-
//
|
|
3618
|
-
//
|
|
3619
|
-
|
|
5114
|
+
// `description` no longer reaches this shell-interpolation risk at all
|
|
5115
|
+
// (apra-fleet-eft.56.1, transport hardened in eft.73.1):
|
|
5116
|
+
// createChildBeadWithAllocatedId() stages it to a member-local temp file
|
|
5117
|
+
// (base64-carried, member-side) and hands that path to `bd create
|
|
5118
|
+
// --body-file`, never interpolating it into a command string. That removed
|
|
5119
|
+
// the injection
|
|
5120
|
+
// surface SAFE_TEXT_RE existed to close for descriptions, so
|
|
5121
|
+
// SAFE_DESCRIPTION_RE only enforces the repo's own ASCII-only convention
|
|
5122
|
+
// (plus non-empty) -- legitimate technical characters ('=', '&', '+', '"',
|
|
5123
|
+
// backticks-as-text, '%', '#', '[', ']', etc.) are allowed again.
|
|
5124
|
+
const SAFE_TEXT_RE = /^[A-Za-z0-9 .,:;!?()'_/+[\]-]+$/;
|
|
3620
5125
|
const SAFE_DESCRIPTION_RE = /^[\t\n\r\x20-\x7E]+$/;
|
|
3621
5126
|
const SAFE_PRIORITY_RE = /^P[0-4]$/;
|
|
3622
5127
|
|
|
@@ -3646,8 +5151,8 @@ export function normalizeTierToken(raw) {
|
|
|
3646
5151
|
* validation, so a description is not rejected wholesale over characters that
|
|
3647
5152
|
* lose no meaning when normalized. This is a fixed substitution table, not a
|
|
3648
5153
|
* general Unicode stripper: anything still outside the allowlist afterwards is
|
|
3649
|
-
* still a hard rejection.
|
|
3650
|
-
*
|
|
5154
|
+
* still a hard rejection. See sanitizeNewTaskTitle() below for title's own,
|
|
5155
|
+
* stricter table.
|
|
3651
5156
|
* @param {string} description
|
|
3652
5157
|
* @returns {string}
|
|
3653
5158
|
*/
|
|
@@ -3659,6 +5164,38 @@ export function sanitizeNewTaskDescription(description) {
|
|
|
3659
5164
|
.replace(/\u2026/g, '...'); // horizontal ellipsis (\u2026)
|
|
3660
5165
|
}
|
|
3661
5166
|
|
|
5167
|
+
/**
|
|
5168
|
+
* Same idea as sanitizeNewTaskDescription() above, for title -- but with a
|
|
5169
|
+
* STRICTER substitution table, since title still has to pass the tighter
|
|
5170
|
+
* SAFE_TEXT_RE shell-safety allowlist afterwards (it is interpolated inline
|
|
5171
|
+
* into a `bd create "..."` command; description is not). Every substitution
|
|
5172
|
+
* here maps to a character SAFE_TEXT_RE already admits, so this never
|
|
5173
|
+
* reopens the injection surface that allowlist exists to close -- it only
|
|
5174
|
+
* rescues titles that would otherwise be needlessly rejected over benign,
|
|
5175
|
+
* common LLM punctuation choices. Observed live (apra-fleet-vk0a's sibling
|
|
5176
|
+
* finding): a reviewer wrote a title referencing a CLI command in backticks
|
|
5177
|
+
* (`` `apra-fleet status` ``, ordinary Markdown inline-code style), which
|
|
5178
|
+
* SAFE_TEXT_RE rejects outright (backtick is excluded as a POSIX
|
|
5179
|
+
* command-substitution risk) -- the finding was then silently demoted to a
|
|
5180
|
+
* freetext note on the parent bead instead of becoming its own actionable
|
|
5181
|
+
* task. Backtick has no special meaning in a bd title (bd has no
|
|
5182
|
+
* code-formatting concept), so it is rewritten to a single quote here rather
|
|
5183
|
+
* than dropped or preserved. A literal `"`/`$`/backslash in a title is NOT
|
|
5184
|
+
* rewritten (there is no safe ASCII stand-in that preserves meaning without
|
|
5185
|
+
* reopening the injection question) -- those still hard-reject via
|
|
5186
|
+
* SAFE_TEXT_RE below, exactly as before this function existed.
|
|
5187
|
+
* @param {string} title
|
|
5188
|
+
* @returns {string}
|
|
5189
|
+
*/
|
|
5190
|
+
export function sanitizeNewTaskTitle(title) {
|
|
5191
|
+
return String(title ?? '')
|
|
5192
|
+
.replace(/[\u2014\u2013]/g, '--') // em dash (\u2014), en dash (\u2013)
|
|
5193
|
+
.replace(/[\u2018\u2019]/g, "'") // curly single quotes (\u2018 \u2019)
|
|
5194
|
+
.replace(/[\u201C\u201D]/g, "'") // curly double quotes -> single quote (a literal `"` stays disallowed in title, unlike description)
|
|
5195
|
+
.replace(/\u2026/g, '...') // horizontal ellipsis (\u2026)
|
|
5196
|
+
.replace(/`/g, "'"); // backtick (Markdown inline-code marker) -> single quote
|
|
5197
|
+
}
|
|
5198
|
+
|
|
3662
5199
|
/**
|
|
3663
5200
|
* Validates one reviewer-authored newTask entry. `title` is checked against
|
|
3664
5201
|
* SAFE_TEXT_RE because it is interpolated inline into a `bd create` command
|
|
@@ -3676,7 +5213,7 @@ export function validateNewTask(newTask) {
|
|
|
3676
5213
|
if (!SAFE_PRIORITY_RE.test(priority)) {
|
|
3677
5214
|
return { ok: false, reason: `priority '${priority}' does not match required pattern ${SAFE_PRIORITY_RE}` };
|
|
3678
5215
|
}
|
|
3679
|
-
const title =
|
|
5216
|
+
const title = sanitizeNewTaskTitle(newTask && newTask.title);
|
|
3680
5217
|
if (!title || !SAFE_TEXT_RE.test(title)) {
|
|
3681
5218
|
return { ok: false, reason: `title fails safe-character allowlist ${SAFE_TEXT_RE} (or is empty): ${JSON.stringify(title)}` };
|
|
3682
5219
|
}
|
|
@@ -3888,7 +5425,7 @@ export function sanitizePrText(text) {
|
|
|
3888
5425
|
* }} opts
|
|
3889
5426
|
* @returns {string}
|
|
3890
5427
|
*/
|
|
3891
|
-
export function buildFinalVerdictPrompt({ targetIssues, branch, baseBranch, goal, cyclesRun, closedCount, openAtGoalCount, deployFailures, integFailures, rejectedNewTasks = [], unclosedVerifyIds = [] }) {
|
|
5428
|
+
export function buildFinalVerdictPrompt({ targetIssues, branch, baseBranch, goal, cyclesRun, closedCount, openAtGoalCount, deployFailures, integFailures, rejectedNewTasks = [], unclosedVerifyIds = [], kbCandidates, kbKnowledge }) {
|
|
3892
5429
|
const lines = [
|
|
3893
5430
|
`Final review for sprint scope issue id(s): ${targetIssues.join(', ')}.`,
|
|
3894
5431
|
`Branch: ${branch} (base: ${baseBranch}). Goal priority: ${goal}. The sprint ran ${cyclesRun} cycle(s).`,
|
|
@@ -3955,6 +5492,15 @@ export function buildFinalVerdictPrompt({ targetIssues, branch, baseBranch, goal
|
|
|
3955
5492
|
'NEVER touch beads yourself (no bd create/update/reopen) -- the orchestrator applies your ' +
|
|
3956
5493
|
'newTasks and reopenIds.'
|
|
3957
5494
|
);
|
|
5495
|
+
// apra-fleet-nx7: the Final Review is the best-positioned promoter in the
|
|
5496
|
+
// whole run -- it has read the entire diff, run the full suite and judged the
|
|
5497
|
+
// sprint as a whole, which is exactly the evidence standard reviewer.md
|
|
5498
|
+
// demands before minting CONFIRMED. It used to receive no candidate block at
|
|
5499
|
+
// all (0ef wired kbCandidates through buildReviewerPrompt only), so anything
|
|
5500
|
+
// captured in a sprint's LAST round reached this reviewer and nobody else,
|
|
5501
|
+
// and was stranded at INFERRED forever.
|
|
5502
|
+
lines.push(...kbKnowledgeBlock(kbKnowledge));
|
|
5503
|
+
lines.push(...kbPromotionBlock(kbCandidates));
|
|
3958
5504
|
return lines.join('\n\n');
|
|
3959
5505
|
}
|
|
3960
5506
|
|
|
@@ -4468,6 +6014,11 @@ export async function finalizeAbort({ error, branch, baseBranch, member, command
|
|
|
4468
6014
|
body: prBody,
|
|
4469
6015
|
log,
|
|
4470
6016
|
logPrefix: '[Publish Abort PR]',
|
|
6017
|
+
// Already resolved just above (the origin-remote PR-capability gate)
|
|
6018
|
+
// via a real git-capable member -- skip re-deriving it a second time
|
|
6019
|
+
// by shelling out to `member`, which may be orchestratorMember and
|
|
6020
|
+
// have no git checkout of its own to read a remote from.
|
|
6021
|
+
remoteUrlOverride: originUrl,
|
|
4471
6022
|
});
|
|
4472
6023
|
|
|
4473
6024
|
if (!prResult.ok) {
|
|
@@ -4633,8 +6184,212 @@ export function decideEnsureBranchAction({ branch, baseBranch, branchFetchOk, br
|
|
|
4633
6184
|
};
|
|
4634
6185
|
}
|
|
4635
6186
|
|
|
6187
|
+
/**
|
|
6188
|
+
* (apra-fleet-p2to.4.2) Map an `execute_command` tool result to the SOFT git
|
|
6189
|
+
* runner contract resyncReacquiredMember() consumes:
|
|
6190
|
+
* { ok: boolean, stdout?: string, error?: string }
|
|
6191
|
+
*
|
|
6192
|
+
* `ok` MUST be derived from the command's real EXIT CODE, never from an
|
|
6193
|
+
* `isError` flag: the fleet server's `execute_command` tool does NOT set
|
|
6194
|
+
* `isError` on a non-zero exit (see src/services/tool-registry.ts wrapTool() --
|
|
6195
|
+
* it returns `{ content, structuredContent: { exitCode } }` with no isError,
|
|
6196
|
+
* and src/tools/execute-command.ts formats the text as `Exit code: N\n...`).
|
|
6197
|
+
* Reading `isError` here would make EVERY git command look successful, which is
|
|
6198
|
+
* catastrophic for `git merge-base --is-ancestor` where the whole point is that
|
|
6199
|
+
* a NON-zero exit (1 = "not an ancestor") is the meaningful signal: misreading
|
|
6200
|
+
* it as ok=true collapses 'ahead'/'diverged' into 'behind-or-equal' and lets
|
|
6201
|
+
* resyncReacquiredMember() run `git checkout -B <branch> origin/<branch>`,
|
|
6202
|
+
* resetting away committed-but-unpushed work. So: prefer the structured
|
|
6203
|
+
* `exitCode`, else parse the `Exit code: N` line out of the text, and only as a
|
|
6204
|
+
* last resort (no exit code recoverable at all -- e.g. a transport-level string
|
|
6205
|
+
* failure from the tool) fall back to the `isError` flag.
|
|
6206
|
+
*
|
|
6207
|
+
* @param {any} res - an `execute_command` MCP result (`{ content, structuredContent }`),
|
|
6208
|
+
* a plain string, or `{ isError, ... }`.
|
|
6209
|
+
* @returns {{ ok: boolean, stdout: string, error: string|undefined }}
|
|
6210
|
+
*/
|
|
6211
|
+
export function commandResultToSoftGit(res) {
|
|
6212
|
+
let text = '';
|
|
6213
|
+
if (typeof res === 'string') {
|
|
6214
|
+
text = res;
|
|
6215
|
+
} else if (res && Array.isArray(res.content)) {
|
|
6216
|
+
text = res.content
|
|
6217
|
+
.map((c) => (c && typeof c.text === 'string' ? c.text : ''))
|
|
6218
|
+
.join('\n');
|
|
6219
|
+
} else if (res && typeof res.text === 'string') {
|
|
6220
|
+
text = res.text;
|
|
6221
|
+
}
|
|
6222
|
+
|
|
6223
|
+
let exitCode;
|
|
6224
|
+
if (res && res.structuredContent && typeof res.structuredContent.exitCode === 'number') {
|
|
6225
|
+
exitCode = res.structuredContent.exitCode;
|
|
6226
|
+
} else {
|
|
6227
|
+
const m = /Exit code:\s*(-?\d+)/.exec(text);
|
|
6228
|
+
if (m) exitCode = Number(m[1]);
|
|
6229
|
+
}
|
|
6230
|
+
|
|
6231
|
+
const ok = exitCode !== undefined ? exitCode === 0 : !(res && res.isError);
|
|
6232
|
+
return { ok, stdout: text, error: ok ? undefined : (text || 'unknown error') };
|
|
6233
|
+
}
|
|
6234
|
+
|
|
6235
|
+
/**
|
|
6236
|
+
* (apra-fleet-p2to.4.2) Re-sync ONE member that was just re-acquired on resume.
|
|
6237
|
+
* Runs -- UNCONDITIONALLY, never gated on a "looks unchanged" heuristic -- the
|
|
6238
|
+
* same three reconciliation steps a fresh dispatch would rely on, because while
|
|
6239
|
+
* this sprint was paused both origin and the beads DB can have moved (another
|
|
6240
|
+
* sprint, a human push) on top of the released member:
|
|
6241
|
+
*
|
|
6242
|
+
* 1. `git fetch` (base branch, then the sprint branch soft -- a brand-new
|
|
6243
|
+
* branch legitimately has no remote ref yet).
|
|
6244
|
+
* 2. The pure decideEnsureBranchAction() probe: fetch outcome + a local-branch
|
|
6245
|
+
* existence probe + (when both tips exist) a two-way ancestor comparison,
|
|
6246
|
+
* fed into the SAME decision helper the Ensure Sprint Branch phase uses.
|
|
6247
|
+
* An 'abort' decision (fetch failed for a non-"missing ref" reason, or the
|
|
6248
|
+
* tips diverged) THROWS rather than touch git -- resuming onto a diverged
|
|
6249
|
+
* branch could silently discard real pushed work. A 'checkout' decision is
|
|
6250
|
+
* executed so the member's working branch is reconciled to origin's new
|
|
6251
|
+
* tip before work continues.
|
|
6252
|
+
* 3. `bd dolt pull` -- re-sync the beads clone to whatever landed while paused.
|
|
6253
|
+
*
|
|
6254
|
+
* All I/O is injected so this stays transport-agnostic and unit-testable:
|
|
6255
|
+
* - `runGit(cmd)` -> Promise<{ ok: boolean, stdout?: string, error?: string }>
|
|
6256
|
+
* (a SOFT git runner: it never throws; this function decides which failures
|
|
6257
|
+
* are fatal).
|
|
6258
|
+
* - `doltPull(member)` -> Promise<any> (runs `bd dolt pull` on the member).
|
|
6259
|
+
*
|
|
6260
|
+
* @param {{ member: string, branch: string, baseBranch: string,
|
|
6261
|
+
* runGit: (cmd: string) => Promise<{ ok: boolean, stdout?: string, error?: string }>,
|
|
6262
|
+
* doltPull: (member: string) => Promise<any>, log?: Function }} opts
|
|
6263
|
+
* @returns {Promise<void>}
|
|
6264
|
+
*/
|
|
6265
|
+
export async function resyncReacquiredMember(opts = {}) {
|
|
6266
|
+
const { member, branch, baseBranch, runGit, doltPull, log = () => {} } = opts;
|
|
6267
|
+
if (typeof runGit !== 'function' || typeof doltPull !== 'function') {
|
|
6268
|
+
throw new TypeError('resyncReacquiredMember requires runGit() and doltPull() to be injected');
|
|
6269
|
+
}
|
|
6270
|
+
|
|
6271
|
+
async function gitStep(cmd, { failSoft = false } = {}) {
|
|
6272
|
+
const res = await runGit(cmd);
|
|
6273
|
+
if (!failSoft && !(res && res.ok)) {
|
|
6274
|
+
throw new Error(
|
|
6275
|
+
`[resume-resync] '${cmd}' failed on member '${member}': ${(res && (res.error || res.stdout)) || 'unknown error'}`
|
|
6276
|
+
);
|
|
6277
|
+
}
|
|
6278
|
+
return res || { ok: false };
|
|
6279
|
+
}
|
|
6280
|
+
|
|
6281
|
+
// 1. git fetch: base (hard -- a missing base is a real problem) then the
|
|
6282
|
+
// sprint branch (soft -- a brand-new branch has no remote ref yet).
|
|
6283
|
+
await gitStep(`git fetch origin ${baseBranch} --quiet`);
|
|
6284
|
+
const branchFetch = await gitStep(`git fetch origin ${branch} --quiet`, { failSoft: true });
|
|
6285
|
+
|
|
6286
|
+
// 2. decideEnsureBranchAction probe: local-branch existence + tip comparison.
|
|
6287
|
+
const localProbe = await gitStep(`git rev-parse --verify --quiet refs/heads/${branch}`, { failSoft: true });
|
|
6288
|
+
const localBranchExists = localProbe.ok;
|
|
6289
|
+
let localTipStatus;
|
|
6290
|
+
if (branchFetch.ok && localBranchExists) {
|
|
6291
|
+
const localIsAncestorOfRemote = await gitStep(
|
|
6292
|
+
`git merge-base --is-ancestor ${branch} origin/${branch}`, { failSoft: true }
|
|
6293
|
+
);
|
|
6294
|
+
const remoteIsAncestorOfLocal = await gitStep(
|
|
6295
|
+
`git merge-base --is-ancestor origin/${branch} ${branch}`, { failSoft: true }
|
|
6296
|
+
);
|
|
6297
|
+
if (localIsAncestorOfRemote.ok) {
|
|
6298
|
+
localTipStatus = 'behind-or-equal';
|
|
6299
|
+
} else if (remoteIsAncestorOfLocal.ok) {
|
|
6300
|
+
localTipStatus = 'ahead';
|
|
6301
|
+
} else {
|
|
6302
|
+
localTipStatus = 'diverged';
|
|
6303
|
+
}
|
|
6304
|
+
}
|
|
6305
|
+
const decision = decideEnsureBranchAction({
|
|
6306
|
+
branch,
|
|
6307
|
+
baseBranch,
|
|
6308
|
+
branchFetchOk: branchFetch.ok,
|
|
6309
|
+
branchFetchError: branchFetch.error,
|
|
6310
|
+
localBranchExists,
|
|
6311
|
+
localTipStatus,
|
|
6312
|
+
});
|
|
6313
|
+
if (decision.action === 'abort') {
|
|
6314
|
+
throw new Error(`[resume-resync] ${decision.message} (member '${member}')`);
|
|
6315
|
+
}
|
|
6316
|
+
// Reconcile the member's working branch to origin's (possibly moved) tip.
|
|
6317
|
+
await gitStep(decision.command);
|
|
6318
|
+
|
|
6319
|
+
// 3. bd dolt pull: re-sync the beads clone.
|
|
6320
|
+
await doltPull(member);
|
|
6321
|
+
|
|
6322
|
+
log(`[resume-resync] member '${member}' re-synced (git fetch + branch reconcile + beads D-pull) before work resumed`);
|
|
6323
|
+
}
|
|
6324
|
+
|
|
4636
6325
|
async function runSprintCycle(context) {
|
|
4637
|
-
const { agent: agentRaw, command: rawCommand, parallel, log, phase: rawPhase, group, endGroup, publishState, args, budget } = context;
|
|
6326
|
+
const { agent: agentRaw, command: rawCommand, parallel, log, phase: rawPhase, group, endGroup, publishState, args, budget, setPauseGuard } = context;
|
|
6327
|
+
|
|
6328
|
+
// Validate BEFORE any agent()/command() dispatch: a rejected/malformed arg
|
|
6329
|
+
// must result in zero fleet dispatches. This must happen early so the
|
|
6330
|
+
// validated result is available to setup code that builds callbacks below.
|
|
6331
|
+
const validated = validateArgs(args);
|
|
6332
|
+
|
|
6333
|
+
// (apra-fleet-p2to.4.1) Clean-state pause guard: this is runner.js's OWN
|
|
6334
|
+
// pause-awareness -- the engine's cooperative pause primitive
|
|
6335
|
+
// (apra-fleet-p2to.1's requestPause()/setPauseGuard()) only ever engages
|
|
6336
|
+
// a pending pause at a zero-in-flight-activity boundary that ALSO passes
|
|
6337
|
+
// this predicate, so registering it here is what keeps a pause from
|
|
6338
|
+
// landing mid-git/mid-dolt-sync (e.g. between a pull and its matching
|
|
6339
|
+
// push, or mid-D-push) and leaving the workspace/beads clone in an
|
|
6340
|
+
// inconsistent state to resume from. `openSyncBracketCount` counts every
|
|
6341
|
+
// currently-open "bracket": withGitSync()'s FULL body (pre-dispatch sync
|
|
6342
|
+
// through post-dispatch sync, wrapped as a single bracket below) and
|
|
6343
|
+
// every standalone DoltSync.syncBefore()/syncAfter() call elsewhere in
|
|
6344
|
+
// this file that is NOT already nested inside a withGitSync bracket (a
|
|
6345
|
+
// nested one is harmless double-counting, never a leak, since
|
|
6346
|
+
// withOpenSyncBracket()'s increment/decrement is always paired). The
|
|
6347
|
+
// guard itself is trivial and adds NO behavior when no pause is pending
|
|
6348
|
+
// -- the engine only ever consults it while a pause is deferred (see
|
|
6349
|
+
// FleetWorkflow._guardPermitsPause(), packages/apra-fleet-workflow/src/
|
|
6350
|
+
// workflow/index.mjs), so a clean run with setPauseGuard registered but
|
|
6351
|
+
// no pause ever requested behaves identically to one with no guard at
|
|
6352
|
+
// all. `setPauseGuard` is only present on `context` when this script
|
|
6353
|
+
// runs through WorkflowEngine.executeFile() (see that module's
|
|
6354
|
+
// _bindPrimitives()) -- guarded so direct/legacy callers of
|
|
6355
|
+
// runSprintCycle() that never go through the engine (existing tests)
|
|
6356
|
+
// keep working unchanged.
|
|
6357
|
+
let openSyncBracketCount = 0;
|
|
6358
|
+
if (typeof setPauseGuard === 'function') {
|
|
6359
|
+
setPauseGuard(() => openSyncBracketCount === 0);
|
|
6360
|
+
}
|
|
6361
|
+
/**
|
|
6362
|
+
* Runs `fn` with the open-sync-bracket counter incremented for its
|
|
6363
|
+
* duration, decrementing again on EVERY exit path (success or throw) via
|
|
6364
|
+
* `finally` -- never leaves a stale increment behind on an error.
|
|
6365
|
+
* @template T
|
|
6366
|
+
* @param {() => Promise<T>} fn
|
|
6367
|
+
* @returns {Promise<T>}
|
|
6368
|
+
*/
|
|
6369
|
+
async function withOpenSyncBracket(fn) {
|
|
6370
|
+
openSyncBracketCount += 1;
|
|
6371
|
+
try {
|
|
6372
|
+
return await fn();
|
|
6373
|
+
} finally {
|
|
6374
|
+
openSyncBracketCount -= 1;
|
|
6375
|
+
// (apra-fleet-p2to.4.4.1) Closing the LAST open sync bracket is
|
|
6376
|
+
// itself a clean-state boundary a deferred pause may complete at,
|
|
6377
|
+
// but the engine only re-checks its pause-engage condition
|
|
6378
|
+
// (WorkflowEngine._maybeEngagePause()) at specific trigger points
|
|
6379
|
+
// -- requestPause(), an in-flight activity draining to zero, the
|
|
6380
|
+
// gate at the next agent()/command() dispatch, or setPauseGuard()
|
|
6381
|
+
// itself (which re-checks as a side effect of registering). None
|
|
6382
|
+
// of those necessarily fire here: this bracket can close with no
|
|
6383
|
+
// further dispatch immediately following. Re-registering the SAME
|
|
6384
|
+
// guard predicate is a deliberate poke -- it engages a pause
|
|
6385
|
+
// requested while sync brackets were open the instant this guard
|
|
6386
|
+
// opens, rather than leaving it stranded until some later
|
|
6387
|
+
// dispatch happens to hit the gate.
|
|
6388
|
+
if (openSyncBracketCount === 0 && typeof setPauseGuard === 'function') {
|
|
6389
|
+
setPauseGuard(() => openSyncBracketCount === 0);
|
|
6390
|
+
}
|
|
6391
|
+
}
|
|
6392
|
+
}
|
|
4638
6393
|
|
|
4639
6394
|
// The shared full-DB beads snapshot served by fetchAllBeadsShared(), plus
|
|
4640
6395
|
// the two choke points that keep it correct. Both wrappers are installed
|
|
@@ -4645,13 +6400,34 @@ async function runSprintCycle(context) {
|
|
|
4645
6400
|
// variable -- transparently goes through the wrapped version.
|
|
4646
6401
|
//
|
|
4647
6402
|
// The snapshot MUST be invalidated the instant the underlying data can
|
|
4648
|
-
// have changed, so invalidation fires on
|
|
6403
|
+
// have changed, so invalidation fires on ALL of:
|
|
4649
6404
|
// 1. every `phase()` call -- a new step must never inherit a stale view
|
|
4650
|
-
// from the step before it,
|
|
6405
|
+
// from the step before it,
|
|
4651
6406
|
// 2. every bd command that is not a known read (list/show/ready/config).
|
|
4652
6407
|
// Update/create/close/note/dep/dolt-pull are all mutations, and an
|
|
4653
6408
|
// unrecognized bd subcommand is conservatively assumed to mutate: the
|
|
4654
|
-
// failure mode is a redundant full fetch, never silently stale data
|
|
6409
|
+
// failure mode is a redundant full fetch, never silently stale data,
|
|
6410
|
+
// and
|
|
6411
|
+
// 3. every PLANNER dispatch that returns successfully (see the explicit
|
|
6412
|
+
// invalidateAllBeadsCache() calls right after dispatchPlanner()
|
|
6413
|
+
// below, in both the main Planning Loop and the in-cycle scoped
|
|
6414
|
+
// replan). The planner mutates beads on ITS OWN clone via its own
|
|
6415
|
+
// `bd create` tool calls, never through this orchestrator-side
|
|
6416
|
+
// `command()` wrapper -- so (2) alone cannot see it, and Execution
|
|
6417
|
+
// Prep runs later in the SAME "Plan C{cycle} R{round}" phase (no
|
|
6418
|
+
// intervening phase() call), so (1) cannot see it either. Without
|
|
6419
|
+
// (3), a planner that creates its task DAG inside one dispatch
|
|
6420
|
+
// leaves the very next Execution Prep step looking at the pre-plan
|
|
6421
|
+
// snapshot, which filters those tasks' still-unseen parent features
|
|
6422
|
+
// out as non-target features and finds nothing ready -- silently
|
|
6423
|
+
// skipping Develop for that whole cycle (apra-fleet-zmqm).
|
|
6424
|
+
// Deliberately scoped to the planner only, NOT every dispatch: an
|
|
6425
|
+
// unconditional per-dispatch invalidation was tried and reverted --
|
|
6426
|
+
// it defeats the "one full-DB fetch per phase" cost control
|
|
6427
|
+
// full-db-fetch-tripwire.test.mjs pins, for every OTHER role
|
|
6428
|
+
// (doer/reviewer/deployer/...) that has no same-phase reader
|
|
6429
|
+
// depending on its bead mutations the way Execution Prep depends on
|
|
6430
|
+
// the planner's.
|
|
4655
6431
|
// Non-bd commands (git, node probes) never touch beads state.
|
|
4656
6432
|
let allBeadsSnapshot = null; // { beads } -- cleared by invalidateAllBeadsCache()
|
|
4657
6433
|
function invalidateAllBeadsCache() { allBeadsSnapshot = null; }
|
|
@@ -4682,7 +6458,27 @@ async function runSprintCycle(context) {
|
|
|
4682
6458
|
// shared fleet HTTP singleton with no per-sprint identity of its own. One
|
|
4683
6459
|
// wrapper covers every call site in this file; an explicit `sprint_id` in an
|
|
4684
6460
|
// individual call's opts wins via the spread order.
|
|
4685
|
-
|
|
6461
|
+
//
|
|
6462
|
+
// KB audit follow-up: this wrapper is also where the KNOWLEDGE BANK block
|
|
6463
|
+
// reaches the roles whose prompt builders do not place it themselves.
|
|
6464
|
+
//
|
|
6465
|
+
// Every one of the ten role contracts carries a Step 0 telling it to call
|
|
6466
|
+
// kb_session_prime, and on a member dispatch NONE of them can (the fleet MCP
|
|
6467
|
+
// server is disabled there) -- so the engine has to hand the knowledge over
|
|
6468
|
+
// as prompt text. buildDoerPrompt / buildReviewerPrompt / buildFinalVerdict-
|
|
6469
|
+
// Prompt already do that at a position that matters (the reviewer's block
|
|
6470
|
+
// must precede its promotion candidates), so those roles are excluded here
|
|
6471
|
+
// and handled there. Everyone else -- planner, plan-reviewer, deployer, the
|
|
6472
|
+
// two test runners, harvester -- got nothing at all until now, which is
|
|
6473
|
+
// exactly the population most likely to benefit from a `runbook` entry.
|
|
6474
|
+
const agent = (prompt, opts = {}) => {
|
|
6475
|
+
let finalPrompt = prompt;
|
|
6476
|
+
if (opts.agentType && !KB_SELF_INJECTING_ROLES.has(opts.agentType) && opts.member_name) {
|
|
6477
|
+
const [block] = kbKnowledgeBlock(kbPriming.knowledgeOf(opts.member_name));
|
|
6478
|
+
if (block) finalPrompt = prompt + '\n\n' + block;
|
|
6479
|
+
}
|
|
6480
|
+
return agentRaw(finalPrompt, { sprint_id: sprintMutexId, ...opts });
|
|
6481
|
+
};
|
|
4686
6482
|
|
|
4687
6483
|
// The global dolt push mutex client. Every D-push below serializes through
|
|
4688
6484
|
// it so two sprints never push at the same time. Four sources, in
|
|
@@ -4782,7 +6578,7 @@ async function runSprintCycle(context) {
|
|
|
4782
6578
|
// 'function'`.
|
|
4783
6579
|
const onAuthFailure = context.onAuthFailure ?? (
|
|
4784
6580
|
(args && typeof args.callTool === 'function')
|
|
4785
|
-
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log })
|
|
6581
|
+
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log, azdevopsPatSecretName: validated.azdevopsPatSecretName })
|
|
4786
6582
|
: undefined
|
|
4787
6583
|
);
|
|
4788
6584
|
|
|
@@ -4834,7 +6630,7 @@ async function runSprintCycle(context) {
|
|
|
4834
6630
|
// auth-recovery path.
|
|
4835
6631
|
const ensureVcsAuthFresh = context.ensureVcsAuthFresh ?? (
|
|
4836
6632
|
(args && typeof args.callTool === 'function')
|
|
4837
|
-
? createVcsAuthPreflightCallback({ callTool: args.callTool, command, log })
|
|
6633
|
+
? createVcsAuthPreflightCallback({ callTool: args.callTool, command, log, azdevopsPatSecretName: validated.azdevopsPatSecretName })
|
|
4838
6634
|
: async () => {}
|
|
4839
6635
|
);
|
|
4840
6636
|
|
|
@@ -4849,9 +6645,23 @@ async function runSprintCycle(context) {
|
|
|
4849
6645
|
: undefined
|
|
4850
6646
|
);
|
|
4851
6647
|
|
|
4852
|
-
//
|
|
4853
|
-
//
|
|
4854
|
-
|
|
6648
|
+
// Provisions a member unattended='auto' right before its deployer /
|
|
6649
|
+
// integ-test-runner / regression-test-runner dispatch, so those
|
|
6650
|
+
// real-command/real-suite roles never stall on an interactive permission
|
|
6651
|
+
// prompt. See createUnattendedAutoProvisioner's doc comment for why this
|
|
6652
|
+
// is one-way (never reverted) and safe in a single-member sprint.
|
|
6653
|
+
// 1. `context.ensureUnattendedAuto` -- an explicitly-injected function
|
|
6654
|
+
// (tests wire an in-process one to prove the call site fires
|
|
6655
|
+
// without a live fleet server).
|
|
6656
|
+
// 2. `args.callTool` -- the real update_member call via
|
|
6657
|
+
// createUnattendedAutoProvisioner (this file).
|
|
6658
|
+
// 3. neither -- a no-op: no provisioning call is made and the member
|
|
6659
|
+
// dispatches under whatever permission mode it already has.
|
|
6660
|
+
const ensureUnattendedAuto = context.ensureUnattendedAuto ?? (
|
|
6661
|
+
(args && typeof args.callTool === 'function')
|
|
6662
|
+
? createUnattendedAutoProvisioner({ callTool: args.callTool, log })
|
|
6663
|
+
: async () => {}
|
|
6664
|
+
);
|
|
4855
6665
|
|
|
4856
6666
|
// The per-dispatch time budget used for BOTH timeout_s and max_total_s:
|
|
4857
6667
|
// silent-until-done CLIs make inactivity indistinguishable from total
|
|
@@ -4882,11 +6692,60 @@ async function runSprintCycle(context) {
|
|
|
4882
6692
|
const roundSessions = createRoundSessionRegistry({ log });
|
|
4883
6693
|
|
|
4884
6694
|
const targetIssues = validated.targetIssues;
|
|
4885
|
-
|
|
6695
|
+
// Display-only label for error/diagnostic text -- NEVER fed to an actual
|
|
6696
|
+
// `bd` invocation (bdListScoped below builds scope structurally, via an
|
|
6697
|
+
// in-memory BFS over `bd list --all`, not via a `bd list --parent` call).
|
|
6698
|
+
// `--parent` is only an accurate description of that BFS for the
|
|
6699
|
+
// single-target case (one root + all its descendants); for 2+ target
|
|
6700
|
+
// ids with no shared parent -- e.g. a flat batch of independent leaf
|
|
6701
|
+
// beads -- comma-joining them after a single `--parent` flag misdescribes
|
|
6702
|
+
// the scope as "all these ids are children of one parent" (they are not)
|
|
6703
|
+
// and, worse, LOOKS like a real, directly-runnable `bd` invocation that a
|
|
6704
|
+
// human debugging a "Nothing to do" failure will paste verbatim -- `bd
|
|
6705
|
+
// list --parent <id1>,<id2>,...` does not do a multi-root union; `bd`
|
|
6706
|
+
// treats a comma-joined value as one (nonexistent) parent id and returns
|
|
6707
|
+
// `[]`, which reads as "confirms the sprint's own finding" and sends
|
|
6708
|
+
// debugging in exactly the wrong direction (this shape was mistaken for
|
|
6709
|
+
// the root cause of a real "Nothing to do" incident before this comment
|
|
6710
|
+
// was added -- see the multi-id flat-leaf-scope bug writeup).
|
|
6711
|
+
const sprintFilter = targetIssues.length === 0
|
|
6712
|
+
? ''
|
|
6713
|
+
: targetIssues.length === 1
|
|
6714
|
+
? `--parent ${targetIssues[0]}`
|
|
6715
|
+
: `sprint targets (each root + its descendants): ${targetIssues.join(', ')}`;
|
|
4886
6716
|
|
|
4887
6717
|
// Member mapping resolution
|
|
4888
6718
|
const physicalMembers = validated.members;
|
|
4889
6719
|
|
|
6720
|
+
// apra-fleet-e28: prime each member's own project KB before any dispatch, so
|
|
6721
|
+
// the Step 0 Knowledge Bank block in every role contract has something warm
|
|
6722
|
+
// to read. This engine had no KB priming at all -- it lived only in the
|
|
6723
|
+
// Claude workflow copy. Best-effort: a cold KB never fails a sprint.
|
|
6724
|
+
const kbPriming = context.kbPriming ?? createKbPrimingClient({
|
|
6725
|
+
callTool: (args && typeof args.callTool === 'function') ? args.callTool : undefined,
|
|
6726
|
+
members: physicalMembers,
|
|
6727
|
+
log,
|
|
6728
|
+
});
|
|
6729
|
+
await kbPriming.primeAll();
|
|
6730
|
+
|
|
6731
|
+
// The role output schemas are shared with apra-pm, so every role dispatched
|
|
6732
|
+
// below is now asked for kb_captures (and the reviewer for kb_promotions).
|
|
6733
|
+
// This is the consumer: without it those fields would be gathered and
|
|
6734
|
+
// silently dropped. Unlike apra-pm's workflow script, this engine has a real
|
|
6735
|
+
// callTool, so the kb_capture/kb_promote calls are made directly.
|
|
6736
|
+
const kbWork = context.kbWork ?? createKbWorkClient({
|
|
6737
|
+
callTool: (args && typeof args.callTool === 'function') ? args.callTool : undefined,
|
|
6738
|
+
log,
|
|
6739
|
+
// Scope every kb_* call below to the member's OWN project KB. The repo
|
|
6740
|
+
// path each call site already threads is a path on the MEMBER's host,
|
|
6741
|
+
// so the server cannot derive a slug from it -- without this lookup a
|
|
6742
|
+
// remote member's reads and writes all land in the shared 'default' KB
|
|
6743
|
+
// (apra-fleet-b4g.15). Resolved through the path rather than passed
|
|
6744
|
+
// per call site so no site can thread the path and forget the scope.
|
|
6745
|
+
// context.kbPriming above is an injection seam; a stub that predates
|
|
6746
|
+
// remoteUrlForPath degrades to no scope rather than crashing a sprint.
|
|
6747
|
+
remoteUrlFor: (repoPath) => (typeof kbPriming.remoteUrlForPath === 'function' ? kbPriming.remoteUrlForPath(repoPath) : null),
|
|
6748
|
+
});
|
|
4890
6749
|
// A member named in ANY roleMap value is a "specialist" for whatever
|
|
4891
6750
|
// role(s) named it -- e.g. a member pinned to roleMap.reviewer has been
|
|
4892
6751
|
// deliberately reserved for review. Without this, a role the caller left
|
|
@@ -4907,9 +6766,32 @@ async function runSprintCycle(context) {
|
|
|
4907
6766
|
if (Array.isArray(list)) for (const m of list) roleMapSpecialists.add(m);
|
|
4908
6767
|
}
|
|
4909
6768
|
}
|
|
6769
|
+
// apra-fleet: roleMap.orchestrator members are excluded from BOTH the
|
|
6770
|
+
// generalist pool and its degenerate physicalMembers fallback -- not just
|
|
6771
|
+
// from the generalist filter -- because the orchestrator role may be a
|
|
6772
|
+
// shared/unreservable, git-less member (docs/design-orchestrator-
|
|
6773
|
+
// worktree-model-v2.md). Without this, the "every member is a specialist"
|
|
6774
|
+
// degradation re-selects the orchestrator for OTHER unmapped roles
|
|
6775
|
+
// (harvester/planner/deployer/etc.), silently undoing the branchEnsureMembers
|
|
6776
|
+
// removal and every probeFileExists/publishGitMember fix elsewhere in this
|
|
6777
|
+
// file: those call getMemberForRole()/getMembersForRole() for roles that
|
|
6778
|
+
// still expect a real git checkout.
|
|
6779
|
+
const orchestratorRoleMapMembers = new Set(
|
|
6780
|
+
(validated.roleMap && Array.isArray(validated.roleMap[ROLE_ORCHESTRATOR]))
|
|
6781
|
+
? validated.roleMap[ROLE_ORCHESTRATOR]
|
|
6782
|
+
: []
|
|
6783
|
+
);
|
|
4910
6784
|
const unmappedRoleFallbackPool = (() => {
|
|
4911
|
-
const
|
|
4912
|
-
|
|
6785
|
+
const eligible = physicalMembers.filter((m) => !orchestratorRoleMapMembers.has(m));
|
|
6786
|
+
const generalists = eligible.filter((m) => !roleMapSpecialists.has(m));
|
|
6787
|
+
if (generalists.length > 0) return generalists;
|
|
6788
|
+
if (eligible.length > 0) return eligible;
|
|
6789
|
+
// Every physical member IS the mapped orchestrator (e.g. a single-member
|
|
6790
|
+
// launch that role-maps the same member as both a dispatch role and
|
|
6791
|
+
// orchestrator): there is no other member to fall back to, so this
|
|
6792
|
+
// degrades to the original physicalMembers behavior rather than
|
|
6793
|
+
// resolving to an empty pool.
|
|
6794
|
+
return physicalMembers;
|
|
4913
6795
|
})();
|
|
4914
6796
|
|
|
4915
6797
|
const getMemberForRole = (role) => {
|
|
@@ -4935,8 +6817,32 @@ async function runSprintCycle(context) {
|
|
|
4935
6817
|
// Uses the canonical ROLE_ORCHESTRATOR constant, not a literal -- see its
|
|
4936
6818
|
// doc comment for why 'orchestrator' is an application-level pseudo-role
|
|
4937
6819
|
// deliberately outside contracts.ROLES.
|
|
6820
|
+
//
|
|
6821
|
+
// apra-fleet-TODO(orchestrator-hard-fail): an unmapped orchestrator
|
|
6822
|
+
// silently falling back to unmappedRoleFallbackPool[0] is a known defect
|
|
6823
|
+
// (docs/design-orchestrator-worktree-model-v2.md section 1/6.4) -- it has
|
|
6824
|
+
// repeatedly caused the orchestrator to run against a stale/wrong-scope bd
|
|
6825
|
+
// clone. Making this a hard launch-time failure is the intended fix, but
|
|
6826
|
+
// it cannot land in isolation: it requires the supervisor to
|
|
6827
|
+
// auto-inject roleMap.orchestrator on every launch first (section 6.2,
|
|
6828
|
+
// not yet implemented) -- otherwise every existing caller that relies on
|
|
6829
|
+
// the implicit fallback (including this file's own test harness) breaks.
|
|
6830
|
+
// Land 6.2, update callers, THEN make this throw.
|
|
4938
6831
|
const orchestratorMember = getMemberForRole(ROLE_ORCHESTRATOR);
|
|
4939
6832
|
|
|
6833
|
+
// Self-heals deploy.md's declared Permissions onto the deployer /
|
|
6834
|
+
// integ-test-runner / regression-test-runner member before each of
|
|
6835
|
+
// those dispatches -- see createDeployPermissionsProvisioner's doc
|
|
6836
|
+
// comment. Same three-way precedence shape as ensureUnattendedAuto
|
|
6837
|
+
// above: an explicitly-injected `context.ensureDeployPermissions` (for
|
|
6838
|
+
// tests), else the real compose_permissions-backed provisioner built
|
|
6839
|
+
// from `args.callTool`, else a no-op when neither is available.
|
|
6840
|
+
const ensureDeployPermissions = context.ensureDeployPermissions ?? (
|
|
6841
|
+
(args && typeof args.callTool === 'function')
|
|
6842
|
+
? createDeployPermissionsProvisioner({ callTool: args.callTool, command, log })
|
|
6843
|
+
: async () => {}
|
|
6844
|
+
);
|
|
6845
|
+
|
|
4940
6846
|
// ONE shared bracket wrapping EVERY role-identified agent() dispatch below
|
|
4941
6847
|
// -- planner, plan-reviewer, doer, reviewer, deployer, integ-test-runner,
|
|
4942
6848
|
// harvester. No phase-based exemptions: a deployer or integ-test-runner
|
|
@@ -4997,6 +6903,16 @@ async function runSprintCycle(context) {
|
|
|
4997
6903
|
// agent-with-runbook resolution before failing the streak (a no-op for
|
|
4998
6904
|
// non-code-writing roles; never fires for a plain divergence).
|
|
4999
6905
|
async function withGitSync(member, pushCode, dispatchFn, { pushBeads = false, needsVcsAuth = pushCode || pushBeads, skipPreDispatchSync = false, skipPreDispatchDoltPull = false, resumeOntoRemoteTip = false } = {}) {
|
|
6906
|
+
// (apra-fleet-p2to.4.1) The WHOLE withGitSync bracket -- pre-dispatch
|
|
6907
|
+
// G-pull/D-pull, the dispatch itself, and post-dispatch G-push/D-push
|
|
6908
|
+
// -- counts as ONE open sync bracket for the clean-state pause guard
|
|
6909
|
+
// above: a pause must never land between, say, a pre-dispatch pull and
|
|
6910
|
+
// its matching post-dispatch push, which would leave the workspace/
|
|
6911
|
+
// beads clone mid-cycle. `finally` guarantees the decrement fires on
|
|
6912
|
+
// every exit path (the normal return, or any of the throws below),
|
|
6913
|
+
// never leaving a stale increment behind.
|
|
6914
|
+
openSyncBracketCount += 1;
|
|
6915
|
+
try {
|
|
5000
6916
|
if (skipPreDispatchSync) {
|
|
5001
6917
|
log(`[Sync] Skipping pre-dispatch G-pull/D-pull for member '${member}' on a retry after a terminal no-mutation dispatch failure (prior attempt published nothing -- workspace unchanged since the last pull).`);
|
|
5002
6918
|
} else {
|
|
@@ -5023,7 +6939,19 @@ async function runSprintCycle(context) {
|
|
|
5023
6939
|
// EXPLICITLY FATAL (apra-fleet-417.3.1): a pre-dispatch D-pull that
|
|
5024
6940
|
// silently degraded would hand the agent a STALE beads clone and
|
|
5025
6941
|
// let it act on it -- worse than not dispatching at all.
|
|
5026
|
-
|
|
6942
|
+
//
|
|
6943
|
+
// Thread this member's REGISTERED shell into dolt-settle
|
|
6944
|
+
// (apra-fleet-7dir.16) so a settle triggered for a Windows member
|
|
6945
|
+
// whose shell is Git-for-Windows bash gets bash-dialect dolt
|
|
6946
|
+
// commands instead of being force-assumed PowerShell.
|
|
6947
|
+
// resolveMemberTarget never throws (degrades to { os: 'linux',
|
|
6948
|
+
// shell: '' } on any lookup failure), and is a no-op when no
|
|
6949
|
+
// callTool is wired (e.g. a mock-sprint scenario with no MCP
|
|
6950
|
+
// client), matching this call site's pre-existing behavior.
|
|
6951
|
+
const settleTarget = (args && typeof args.callTool === 'function')
|
|
6952
|
+
? await resolveMemberTarget({ fleetApi: new ApraFleet({ callTool: args.callTool }), member, log })
|
|
6953
|
+
: { os: 'linux', shell: '' };
|
|
6954
|
+
await DoltSync.syncBefore(member, { command, log, skipRefresh: skipPreDispatchDoltPull, onAuthFailure, fatal: true, settle: buildSettleCallback(member, { command, log, shell: settleTarget.shell }) });
|
|
5027
6955
|
}
|
|
5028
6956
|
// The teardown is deliberately NOT a `finally`. A throw out of a
|
|
5029
6957
|
// `finally` replaces the (successful) dispatch result and is
|
|
@@ -5069,7 +6997,7 @@ async function runSprintCycle(context) {
|
|
|
5069
6997
|
await syncMemberAfterOrdered(member, {
|
|
5070
6998
|
command, pushCode, pushBeads, log, branch: validated.branch,
|
|
5071
6999
|
mutex: doltPushMutex, sprintId: sprintMutexId, agent, onAuthFailure,
|
|
5072
|
-
resolveMemberProvider: resolveMemberVcsProvider,
|
|
7000
|
+
resolveMemberProvider: resolveMemberVcsProvider, args,
|
|
5073
7001
|
});
|
|
5074
7002
|
syncErr = null;
|
|
5075
7003
|
break;
|
|
@@ -5090,6 +7018,18 @@ async function runSprintCycle(context) {
|
|
|
5090
7018
|
}
|
|
5091
7019
|
if (dispatchThrew) throw dispatchThrew;
|
|
5092
7020
|
return dispatchResult;
|
|
7021
|
+
} finally {
|
|
7022
|
+
openSyncBracketCount -= 1;
|
|
7023
|
+
// (apra-fleet-p2to.4.4.1) See withOpenSyncBracket()'s matching
|
|
7024
|
+
// comment above: poke the engine's pause-engage check by
|
|
7025
|
+
// re-registering the same guard predicate the instant this bracket
|
|
7026
|
+
// -- the whole pre-dispatch sync/dispatch/post-dispatch sync unit --
|
|
7027
|
+
// closes, so a pause deferred for its duration engages right away
|
|
7028
|
+
// rather than waiting on whatever dispatch happens to come next.
|
|
7029
|
+
if (openSyncBracketCount === 0 && typeof setPauseGuard === 'function') {
|
|
7030
|
+
setPauseGuard(() => openSyncBracketCount === 0);
|
|
7031
|
+
}
|
|
7032
|
+
}
|
|
5093
7033
|
}
|
|
5094
7034
|
|
|
5095
7035
|
// Scope discovery cannot be built on `bd list --parent`: it accepts exactly
|
|
@@ -5335,13 +7275,32 @@ async function runSprintCycle(context) {
|
|
|
5335
7275
|
*/
|
|
5336
7276
|
async function dispatchReview({ beadIds, acceptanceCriteriaJson }) {
|
|
5337
7277
|
const reviewerPool = getMembersForRole(ROLE_REVIEWER);
|
|
7278
|
+
// apra-fleet-0ef: fetch the INFERRED entries this reviewer may promote
|
|
7279
|
+
// and hand them to it in the prompt. The reviewer has no MCP kb_* tools
|
|
7280
|
+
// of its own, so without this it can never name an entry id and
|
|
7281
|
+
// `kb_promotions` comes back empty every round -- which is exactly why
|
|
7282
|
+
// kb_promote had never once fired. Scoped to the reviewer's OWN work
|
|
7283
|
+
// folder (same source kbWork.apply uses to route the writes), and
|
|
7284
|
+
// best-effort: a cold KB must not fail the review.
|
|
7285
|
+
const reviewerRepoPath = kbPriming.folderOf(reviewerPool[0]);
|
|
7286
|
+
const kbCandidates = await kbWork.promotionCandidates(reviewerRepoPath);
|
|
7287
|
+
if (kbCandidates.length > 0) {
|
|
7288
|
+
log(`[kb-work] offering ${kbCandidates.length} INFERRED entr(ies) to the reviewer for promotion.`);
|
|
7289
|
+
}
|
|
7290
|
+
// What the KB knows about the beads UNDER REVIEW, not just whatever the
|
|
7291
|
+
// sprint-start prime happened to surface. Falls back to the primed set
|
|
7292
|
+
// when the query returns nothing (a KB with no matching rows yet).
|
|
7293
|
+
const reviewerQueried = await kbWork.relevantKnowledge(reviewerRepoPath, kbQueryTerms([], beadIds));
|
|
7294
|
+
const reviewerKnowledge = reviewerQueried.length > 0
|
|
7295
|
+
? reviewerQueried
|
|
7296
|
+
: kbPriming.knowledgeOf(reviewerPool[0]);
|
|
5338
7297
|
// A full-cycle review can genuinely exhaust the fleet's default turn
|
|
5339
7298
|
// budget, and a fresh retry deterministically hits the same wall. Make
|
|
5340
7299
|
// the budget explicit and, on max_turns exhaustion, RESUME the same
|
|
5341
7300
|
// session at a doubled budget: the session already holds the full
|
|
5342
7301
|
// review context, so a continue-nudge finishes the job instead of
|
|
5343
7302
|
// restarting it.
|
|
5344
|
-
const BASE_REVIEWER_MAX_TURNS =
|
|
7303
|
+
const BASE_REVIEWER_MAX_TURNS = 500;
|
|
5345
7304
|
const reviewerDispatchOpts = {
|
|
5346
7305
|
member_name: reviewerPool[0],
|
|
5347
7306
|
agentType: 'reviewer',
|
|
@@ -5369,6 +7328,8 @@ async function runSprintCycle(context) {
|
|
|
5369
7328
|
baseBranch: validated.baseBranch,
|
|
5370
7329
|
branch: validated.branch,
|
|
5371
7330
|
goal: validated.goal,
|
|
7331
|
+
kbCandidates,
|
|
7332
|
+
kbKnowledge: reviewerKnowledge,
|
|
5372
7333
|
}),
|
|
5373
7334
|
// member_name is repeated literally here -- not only via the
|
|
5374
7335
|
// shared opts object -- so the source-level call-site parse in
|
|
@@ -5379,7 +7340,14 @@ async function runSprintCycle(context) {
|
|
|
5379
7340
|
// Restate the review scope: a resumed dispatch replaces the
|
|
5380
7341
|
// delivered prompt artifact, so the scope must be repeated inline.
|
|
5381
7342
|
'Continue your review exactly where you left off in this same session -- do not restart or re-read the diff from scratch. ' +
|
|
5382
|
-
|
|
7343
|
+
// apra-fleet-s6d: same empty-beadIds case as buildReviewerPrompt --
|
|
7344
|
+
// a scope-wide re-review has no ids to restate, and "bead id(s)
|
|
7345
|
+
// under review on branch..." reads as a dropped value.
|
|
7346
|
+
`Your scope, restated so a resumed dispatch never loses it: `
|
|
7347
|
+
+ (Array.isArray(beadIds) && beadIds.length > 0
|
|
7348
|
+
? `bead id(s) under review ${beadIds.join(', ')} `
|
|
7349
|
+
: `the entire sprint scope (no individual bead ids -- you are judging whether the sprint as a whole is complete) `)
|
|
7350
|
+
+ `on branch ${validated.branch} against base ${validated.baseBranch}. ` +
|
|
5383
7351
|
'Finish evaluating the remaining acceptance criteria and return your final verdict now.',
|
|
5384
7352
|
{
|
|
5385
7353
|
...reviewerDispatchOpts,
|
|
@@ -5501,10 +7469,29 @@ async function runSprintCycle(context) {
|
|
|
5501
7469
|
}
|
|
5502
7470
|
|
|
5503
7471
|
// The sprint branch must be git-ensured on EVERY member that will operate
|
|
5504
|
-
// on it, not just the orchestrator: doers round-robin across the doer pool
|
|
5505
|
-
//
|
|
5506
|
-
//
|
|
5507
|
-
//
|
|
7472
|
+
// on it, not just the orchestrator: doers round-robin across the doer pool,
|
|
7473
|
+
// the reviewer runs from the reviewer pool, and every other role dispatched
|
|
7474
|
+
// through withGitSync's shared bracket (planner, plan-reviewer, deployer,
|
|
7475
|
+
// integ-test-runner, regression-test-runner, harvester -- see that bracket's
|
|
7476
|
+
// own doc comment a few hundred lines up) gets a pre-dispatch G-pull that
|
|
7477
|
+
// ASSUMES the correct branch is already checked out. On a real multi-member
|
|
7478
|
+
// fleet each role can resolve to its own independent checkout, so ensure on
|
|
7479
|
+
// the union of every role's member pool before the first doer round -- not
|
|
7480
|
+
// just doer/reviewer.
|
|
7481
|
+
//
|
|
7482
|
+
// Without this, a role pinned via roleMap to a member that was never
|
|
7483
|
+
// branch-ensured (e.g. deployer isolated onto its own machine, per the
|
|
7484
|
+
// fleet-supervisor skill's own recommended layout) can pass its G-pull's
|
|
7485
|
+
// `git merge --ff-only origin/<branch>` silently: a fast-forward merge does
|
|
7486
|
+
// not care what branch HEAD is currently on, only that HEAD is an ancestor
|
|
7487
|
+
// of the fetched tip. If that member happens to be sitting on a branch
|
|
7488
|
+
// (e.g. main) that is still fast-forward-compatible with the sprint branch,
|
|
7489
|
+
// the merge succeeds and silently advances THAT branch's pointer instead of
|
|
7490
|
+
// checking out/creating a correctly-named local branch -- the deploy/test
|
|
7491
|
+
// dispatch still gets the right code, but the member's local branch bookkeeping
|
|
7492
|
+
// ends up mislabeled. See apra-fleet-ivxi/u1qw/69pp sprint run
|
|
7493
|
+
// (fleet-sprint/ivxi-u1qw-69pp), where fleet-win-deploy's local `main`
|
|
7494
|
+
// silently absorbed the sprint branch's commits this way.
|
|
5508
7495
|
//
|
|
5509
7496
|
// SUPPORTED-TOPOLOGY NOTE: there is no cross-member bd/git sync layer here.
|
|
5510
7497
|
// Every `bd` command below runs against the orchestrator member's beads DB
|
|
@@ -5514,10 +7501,22 @@ async function runSprintCycle(context) {
|
|
|
5514
7501
|
// sprint starts; this ensure-everywhere is the git half of the same "every
|
|
5515
7502
|
// member starts from the same state" guarantee. See docs/architecture.md
|
|
5516
7503
|
// "Multi-member topology (fleet-sprint)".
|
|
7504
|
+
// apra-fleet: orchestratorMember is deliberately NOT included here -- the
|
|
7505
|
+
// orchestrator role issues only bd/Dolt commands (never git), and a
|
|
7506
|
+
// shared/unreservable orchestrator member used across concurrent sprints
|
|
7507
|
+
// cannot be checked out onto N different branches at once. If an operator
|
|
7508
|
+
// explicitly role-maps a dispatch member (doer/reviewer/planner/etc.) as
|
|
7509
|
+
// orchestrator too, that member is still included below via its dispatch
|
|
7510
|
+
// role, so the ensure-everywhere guarantee is unaffected for that case.
|
|
5517
7511
|
const branchEnsureMembers = [...new Set([
|
|
5518
|
-
orchestratorMember,
|
|
5519
7512
|
...getMembersForRole(ROLE_DOER),
|
|
5520
7513
|
...getMembersForRole(ROLE_REVIEWER),
|
|
7514
|
+
...getMembersForRole('planner'),
|
|
7515
|
+
...getMembersForRole('plan-reviewer'),
|
|
7516
|
+
...getMembersForRole('deployer'),
|
|
7517
|
+
...getMembersForRole('integ-test-runner'),
|
|
7518
|
+
...getMembersForRole('regression-test-runner'),
|
|
7519
|
+
...getMembersForRole('harvester'),
|
|
5521
7520
|
])];
|
|
5522
7521
|
|
|
5523
7522
|
// Read the requirementsFile (if any) once, up front, so its content can
|
|
@@ -5542,7 +7541,12 @@ async function runSprintCycle(context) {
|
|
|
5542
7541
|
// Routed through the single dolt-sync module (apra-fleet-417.2.1):
|
|
5543
7542
|
// readinessGate (apra-fleet-417.5 rename of healthGate) selects the
|
|
5544
7543
|
// pre-flight variant of the BEFORE bracket.
|
|
5545
|
-
|
|
7544
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
7545
|
+
// Thread the orchestrator member's REGISTERED shell into dolt-settle,
|
|
7546
|
+
// guarded on args.callTool the same way the pre-dispatch bracket is
|
|
7547
|
+
// (apra-fleet-7dir.24).
|
|
7548
|
+
const preflightSettleShell = await resolveSettleShell({ args, member: orchestratorMember, log });
|
|
7549
|
+
await withOpenSyncBracket(() => DoltSync.syncBefore(orchestratorMember, { command, log, readinessGate: true, settle: buildSettleCallback(orchestratorMember, { command, log, shell: preflightSettleShell }) }));
|
|
5546
7550
|
|
|
5547
7551
|
// =======================
|
|
5548
7552
|
// 0. Git Setup: ensure the sprint branch exists off base_branch
|
|
@@ -5807,6 +7811,23 @@ async function runSprintCycle(context) {
|
|
|
5807
7811
|
const { sprintTasks: sprintPlaced, backlogTasks } = partitionByGoalMembership(sprintTasks, validated.goal);
|
|
5808
7812
|
const payload = { sprintTasks: sprintPlaced };
|
|
5809
7813
|
if (backlogTasks.length > 0) payload.backlogTasks = backlogTasks;
|
|
7814
|
+
// apra-fleet-x8r.4: plumbs the SAME two axes runner.js's own
|
|
7815
|
+
// completion gate (~line 8134: bdListScoped(--priority-max=
|
|
7816
|
+
// goalMax) MINUS decomposedParentIds()) filters on, so the
|
|
7817
|
+
// viewer's computeSprintProgress() required/closed counts match
|
|
7818
|
+
// what actually gates sprint exit -- never re-derived
|
|
7819
|
+
// client-side. Not `const goalMax` from the outer closure: this
|
|
7820
|
+
// function's FIRST call happens before that `const` initializes
|
|
7821
|
+
// (TDZ), so the numeric max is derived fresh here instead, from
|
|
7822
|
+
// the same pure goalPriorityMax() helper.
|
|
7823
|
+
payload.goalMax = Number(goalPriorityMax(validated.goal).slice(1));
|
|
7824
|
+
// sprintTasks is already this cycle's `bdListScoped('')` result
|
|
7825
|
+
// (any status, full scope) -- decomposedParentIds() re-derives
|
|
7826
|
+
// from that same no-args query, so building the set directly off
|
|
7827
|
+
// sprintTasks here is identical output with no extra `bd` call.
|
|
7828
|
+
payload.decomposedParentIds = [...new Set(
|
|
7829
|
+
sprintTasks.filter((b) => b && b.parent).map((b) => b.parent)
|
|
7830
|
+
)];
|
|
5810
7831
|
publishState('beads', payload);
|
|
5811
7832
|
}
|
|
5812
7833
|
}
|
|
@@ -5816,10 +7837,13 @@ async function runSprintCycle(context) {
|
|
|
5816
7837
|
// single-quoted JS literals inside a double-quoted shell argument (no
|
|
5817
7838
|
// escaped-quote-inside-quote traps). failSoft, so a probe failure can never
|
|
5818
7839
|
// throw and kill the sprint -- it just means "skip the dependent phase".
|
|
5819
|
-
|
|
7840
|
+
// Runs on `member` -- the role member about to consume the probed file --
|
|
7841
|
+
// never on orchestratorMember: a shared/unreservable orchestrator member
|
|
7842
|
+
// carries no git checkout to probe.
|
|
7843
|
+
async function probeFileExists(filename, member) {
|
|
5820
7844
|
const res = await command(
|
|
5821
7845
|
`node -e "console.log(require('fs').existsSync('${filename}') ? 'found' : 'not found')"`,
|
|
5822
|
-
{ member_name:
|
|
7846
|
+
{ member_name: member, silent: true, label: `Probe for '${filename}'`, failSoft: true }
|
|
5823
7847
|
);
|
|
5824
7848
|
if (!res.ok) {
|
|
5825
7849
|
log(`Probe for '${filename}' failed (treating as not-found, skipping the dependent phase): ${res.error}`);
|
|
@@ -5833,7 +7857,12 @@ async function runSprintCycle(context) {
|
|
|
5833
7857
|
// doer's work, so pull again immediately before the verification read.
|
|
5834
7858
|
// DoltSync.syncBefore() is a benign no-op when the clone is current and
|
|
5835
7859
|
// when no dolt remote is configured at all.
|
|
5836
|
-
|
|
7860
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
7861
|
+
// Thread the orchestrator member's REGISTERED shell into dolt-settle,
|
|
7862
|
+
// guarded on args.callTool the same way the pre-dispatch bracket is
|
|
7863
|
+
// (apra-fleet-7dir.24).
|
|
7864
|
+
const verifyReadSettleShell = await resolveSettleShell({ args, member: orchestratorMember, log });
|
|
7865
|
+
await withOpenSyncBracket(() => DoltSync.syncBefore(orchestratorMember, { command, log, fatal: true, settle: buildSettleCallback(orchestratorMember, { command, log, shell: verifyReadSettleShell }) }));
|
|
5837
7866
|
|
|
5838
7867
|
await updateDashboard();
|
|
5839
7868
|
|
|
@@ -5884,6 +7913,31 @@ async function runSprintCycle(context) {
|
|
|
5884
7913
|
|
|
5885
7914
|
if (initialBeads.length === 0) {
|
|
5886
7915
|
if (notDoneBeads.length === 0) {
|
|
7916
|
+
// Distinguish "every target issue is genuinely done" from "one
|
|
7917
|
+
// or more target ids are not visible to this orchestrator
|
|
7918
|
+
// member's own bd clone AT ALL" -- the latter reads
|
|
7919
|
+
// identically as "Nothing to do" without this check (an empty
|
|
7920
|
+
// `notDoneBeads` either way), but is a completely different
|
|
7921
|
+
// problem: those beads are not closed, they are invisible
|
|
7922
|
+
// here, most commonly because they were created/mutated on a
|
|
7923
|
+
// different clone that was never `bd dolt push`ed to the
|
|
7924
|
+
// shared remote before this sprint launched, or because a
|
|
7925
|
+
// members-persistent-across-sprints orchestrator (see
|
|
7926
|
+
// DoltSync.syncBefore's fatal:true D-pull above) still hasn't
|
|
7927
|
+
// synced them for some other reason. Reusing the already-
|
|
7928
|
+
// fetched project-wide snapshot -- no extra bd call.
|
|
7929
|
+
const allBeadsForVisibilityCheck = await fetchAllBeadsShared();
|
|
7930
|
+
const knownIds = new Set(allBeadsForVisibilityCheck.map((b) => b.id));
|
|
7931
|
+
const invisibleTargets = targetIssues.filter((id) => !knownIds.has(id));
|
|
7932
|
+
if (invisibleTargets.length > 0) {
|
|
7933
|
+
throw new Error(
|
|
7934
|
+
`Pre-sprint validation failed: ${invisibleTargets.length} of ${targetIssues.length} target issue id(s) ` +
|
|
7935
|
+
`are not visible to the orchestrator member ('${orchestratorMember}')'s bd clone at all: ` +
|
|
7936
|
+
`${invisibleTargets.join(', ')}. This is NOT the same as those beads being closed/done -- it usually ` +
|
|
7937
|
+
`means they were created/updated on a different clone that was never synced to the shared Dolt remote ` +
|
|
7938
|
+
`(dolt-push it there first) or this member's clone has not picked them up yet. Scope: '${sprintFilter}'.`
|
|
7939
|
+
);
|
|
7940
|
+
}
|
|
5887
7941
|
throw new Error(`Pre-sprint validation failed: No open/in-progress/blocked/deferred beads found for scope '${sprintFilter}'. Nothing to do.`);
|
|
5888
7942
|
}
|
|
5889
7943
|
|
|
@@ -6149,7 +8203,7 @@ async function runSprintCycle(context) {
|
|
|
6149
8203
|
// meaningful gap. Like every dispatch site, max_turns exhaustion is
|
|
6150
8204
|
// answered with a same-session resume at doubled turns; the planner
|
|
6151
8205
|
// gets a doer-sized base because it builds the whole epic DAG.
|
|
6152
|
-
const PLANNER_MAX_TURNS =
|
|
8206
|
+
const PLANNER_MAX_TURNS = 500;
|
|
6153
8207
|
const plannerDispatchOpts = {
|
|
6154
8208
|
member_name: getMemberForRole('planner'),
|
|
6155
8209
|
agentType: 'planner',
|
|
@@ -6250,6 +8304,27 @@ async function runSprintCycle(context) {
|
|
|
6250
8304
|
const skipPreDispatchDoltPull =
|
|
6251
8305
|
i === 0 && cycle === 1 && planningRounds === 1 && plannerSharesOrchestratorClone;
|
|
6252
8306
|
await dispatchPlanner({ skipPreDispatchSync: skipPreDispatchSyncNext, skipPreDispatchDoltPull });
|
|
8307
|
+
// apra-fleet-jxdf.1: when the planner runs on a DIFFERENT
|
|
8308
|
+
// clone than the orchestrator, its newly-created/mutated
|
|
8309
|
+
// beads are invisible to the orchestrator's own Dolt clone
|
|
8310
|
+
// until that clone is actually pulled -- invalidating the
|
|
8311
|
+
// JS-level cache below is not enough, since the cache's
|
|
8312
|
+
// NEXT read still hits stale on-disk data. Fatal on
|
|
8313
|
+
// failure: proceeding to Execution Prep against a plan the
|
|
8314
|
+
// orchestrator cannot actually see reproduces exactly the
|
|
8315
|
+
// "epic looks like a childless ready leaf" failure this
|
|
8316
|
+
// fix exists to close.
|
|
8317
|
+
if (!plannerSharesOrchestratorClone) {
|
|
8318
|
+
const postPlanSettleShell = await resolveSettleShell({ args, member: orchestratorMember, log });
|
|
8319
|
+
await withOpenSyncBracket(() => DoltSync.syncBefore(orchestratorMember, { command, log, fatal: true, settle: buildSettleCallback(orchestratorMember, { command, log, shell: postPlanSettleShell }) }));
|
|
8320
|
+
}
|
|
8321
|
+
// apra-fleet-zmqm: the planner just created/mutated beads on
|
|
8322
|
+
// its own clone via its own bd tool calls -- invisible to
|
|
8323
|
+
// this orchestrator's command()-wrapper invalidation (see
|
|
8324
|
+
// fetchAllBeadsShared()'s doc comment, point 3). Execution
|
|
8325
|
+
// Prep runs later in this SAME phase, so without this the
|
|
8326
|
+
// cache built before Plan silently survives into it.
|
|
8327
|
+
invalidateAllBeadsCache();
|
|
6253
8328
|
plannerErr = null;
|
|
6254
8329
|
break;
|
|
6255
8330
|
} catch (err) {
|
|
@@ -6323,7 +8398,7 @@ async function runSprintCycle(context) {
|
|
|
6323
8398
|
let verdict;
|
|
6324
8399
|
// Reviewer-sized turn base, with the same same-session
|
|
6325
8400
|
// turn-exhaustion resume every dispatch site uses.
|
|
6326
|
-
const PLAN_REVIEWER_MAX_TURNS =
|
|
8401
|
+
const PLAN_REVIEWER_MAX_TURNS = 500;
|
|
6327
8402
|
const planReviewerDispatchOpts = {
|
|
6328
8403
|
member_name: getMemberForRole('plan-reviewer'),
|
|
6329
8404
|
agentType: 'plan-reviewer',
|
|
@@ -6499,7 +8574,8 @@ async function runSprintCycle(context) {
|
|
|
6499
8574
|
{ member_name: orchestratorMember, silent: true, label: `Attach plan-cap deferral finding to ${id}` }
|
|
6500
8575
|
);
|
|
6501
8576
|
}
|
|
6502
|
-
|
|
8577
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
8578
|
+
await withOpenSyncBracket(() => DoltSync.syncAfter(orchestratorMember, { command, pushBeads: true, log, mutex: doltPushMutex, sprintId: sprintMutexId }));
|
|
6503
8579
|
planCapDeferredIds = contestedIds;
|
|
6504
8580
|
}
|
|
6505
8581
|
|
|
@@ -6670,7 +8746,7 @@ async function runSprintCycle(context) {
|
|
|
6670
8746
|
for (const id of replanScopeIds) replannedThisCycle.add(id);
|
|
6671
8747
|
|
|
6672
8748
|
// --- Scoped planner pass ---
|
|
6673
|
-
const SCOPED_REPLAN_PLANNER_MAX_TURNS =
|
|
8749
|
+
const SCOPED_REPLAN_PLANNER_MAX_TURNS = 500;
|
|
6674
8750
|
let scopedPlannerOk = true;
|
|
6675
8751
|
try {
|
|
6676
8752
|
const scopedPlannerRes = await withGitSync(getMemberForRole('planner'), false, () => withDispatchWatchdog(
|
|
@@ -6702,6 +8778,14 @@ async function runSprintCycle(context) {
|
|
|
6702
8778
|
{ timeoutS: DISPATCH_TIMEOUT_S, member: getMemberForRole('planner'), label: 'Scoped Replan Plan (interactive)', log }
|
|
6703
8779
|
), { pushBeads: true });
|
|
6704
8780
|
log(`Scoped Replan Planner: ${scopedPlannerRes}`);
|
|
8781
|
+
// apra-fleet-zmqm: same reasoning as the main Planning
|
|
8782
|
+
// Loop's invalidateAllBeadsCache() call -- this dispatch
|
|
8783
|
+
// mutated beads on its own clone, and everything after it
|
|
8784
|
+
// in this same "Replan C{cycle} R{devRounds}" phase (the
|
|
8785
|
+
// scoped plan-reviewer, the resumed develop round) must
|
|
8786
|
+
// see those mutations, not the pre-replan snapshot taken
|
|
8787
|
+
// when this phase() started.
|
|
8788
|
+
invalidateAllBeadsCache();
|
|
6705
8789
|
} catch (err) {
|
|
6706
8790
|
scopedPlannerOk = false;
|
|
6707
8791
|
// Self-heal an LLM-auth failure so the next cycle's planner
|
|
@@ -6716,7 +8800,7 @@ async function runSprintCycle(context) {
|
|
|
6716
8800
|
// --- Scoped plan-review pass ---
|
|
6717
8801
|
let scopedReplanApproved = false;
|
|
6718
8802
|
if (scopedPlannerOk) {
|
|
6719
|
-
const SCOPED_REPLAN_REVIEWER_MAX_TURNS =
|
|
8803
|
+
const SCOPED_REPLAN_REVIEWER_MAX_TURNS = 500;
|
|
6720
8804
|
try {
|
|
6721
8805
|
const scopedVerdict = await withGitSync(getMemberForRole('plan-reviewer'), false, () => agent(
|
|
6722
8806
|
buildPlanReviewerPrompt({ targetIssues, goal: validated.goal, replanScope: replanScopeIds, verifyExcluded: verifySetThisCycle }),
|
|
@@ -6766,7 +8850,8 @@ async function runSprintCycle(context) {
|
|
|
6766
8850
|
// and refresh the dashboard before re-evaluating the loop top.
|
|
6767
8851
|
// Routed through the single dolt-sync module's AFTER bracket
|
|
6768
8852
|
// (apra-fleet-417.2.1); behavior is identical.
|
|
6769
|
-
|
|
8853
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
8854
|
+
await withOpenSyncBracket(() => DoltSync.syncAfter(orchestratorMember, { command, pushBeads: true, log, mutex: doltPushMutex, sprintId: sprintMutexId }));
|
|
6770
8855
|
await updateDashboard();
|
|
6771
8856
|
continue;
|
|
6772
8857
|
}
|
|
@@ -6996,7 +9081,7 @@ async function runSprintCycle(context) {
|
|
|
6996
9081
|
// default) so the max-turns-exhaustion resume path below has a
|
|
6997
9082
|
// known baseline to escalate from. Sized so a typical streak
|
|
6998
9083
|
// finishes in one dispatch and resume stays the exception.
|
|
6999
|
-
const BASE_DOER_MAX_TURNS =
|
|
9084
|
+
const BASE_DOER_MAX_TURNS = 500;
|
|
7000
9085
|
// Bounded resume-and-continue attempts after a max_turns
|
|
7001
9086
|
// exhaustion, each doubling the turn budget. An identical retry
|
|
7002
9087
|
// is pointless (the doer would deterministically run out of
|
|
@@ -7024,24 +9109,18 @@ async function runSprintCycle(context) {
|
|
|
7024
9109
|
// FIRST attempt passes nothing and keeps plain ff-only
|
|
7025
9110
|
// pre-dispatch sync.
|
|
7026
9111
|
const dispatchDoer = (syncOpts = {}) => withGitSync(doerMember, true, async () => {
|
|
7027
|
-
// Claim once per streak turn, after the D-pull.
|
|
9112
|
+
// Claim once per streak turn, after the D-pull. Batched into ONE
|
|
9113
|
+
// bd update id-list --claim --json call (apra-fleet-7h6n.7)
|
|
9114
|
+
// instead of one bd update id --claim call per bead -- see the
|
|
9115
|
+
// claimBeadsBatched doc comment above for the verified
|
|
9116
|
+
// multi-id --claim contract (non-atomic, JSON-array-only
|
|
9117
|
+
// success signal) this relies on.
|
|
7028
9118
|
if (!hasClaimedBeads) {
|
|
7029
9119
|
hasClaimedBeads = true;
|
|
7030
9120
|
if (validated.assignee) {
|
|
7031
|
-
const claimedBeadIds =
|
|
7032
|
-
|
|
7033
|
-
|
|
7034
|
-
try {
|
|
7035
|
-
const claimLabel = `bd update ${beadId} --claim`;
|
|
7036
|
-
await command(claimLabel, { member_name: orchestratorMember, silent: true });
|
|
7037
|
-
claimedBeadIds.push(beadId);
|
|
7038
|
-
} catch (claimErr) {
|
|
7039
|
-
// A claim can fail if the bead is already claimed by another
|
|
7040
|
-
// sprint/assignee. Skip this bead instead of crashing.
|
|
7041
|
-
skippedBeadIds.push(beadId);
|
|
7042
|
-
log(`Doer streak: bead ${beadId} already claimed (skipping): ${claimErr.message}`);
|
|
7043
|
-
}
|
|
7044
|
-
}
|
|
9121
|
+
const { claimedBeadIds, skippedBeadIds } = await claimBeadsBatched({
|
|
9122
|
+
command, orchestratorMember, beadIds: actualBeadIds, log,
|
|
9123
|
+
});
|
|
7045
9124
|
if (claimedBeadIds.length === 0) {
|
|
7046
9125
|
// All beads in this streak are already claimed by other sprints.
|
|
7047
9126
|
// Skip this streak entirely.
|
|
@@ -7052,7 +9131,6 @@ async function runSprintCycle(context) {
|
|
|
7052
9131
|
);
|
|
7053
9132
|
}
|
|
7054
9133
|
if (skippedBeadIds.length > 0) {
|
|
7055
|
-
log(`Doer streak: claimed ${claimedBeadIds.length} bead(s) [${claimedBeadIds.join(', ')}]; skipped ${skippedBeadIds.length} already-claimed bead(s) [${skippedBeadIds.join(', ')}].`);
|
|
7056
9134
|
actualBeadIds = claimedBeadIds; // Update to only the successfully claimed ones
|
|
7057
9135
|
}
|
|
7058
9136
|
}
|
|
@@ -7123,7 +9201,22 @@ async function runSprintCycle(context) {
|
|
|
7123
9201
|
);
|
|
7124
9202
|
}
|
|
7125
9203
|
|
|
7126
|
-
|
|
9204
|
+
// The doer cannot read the KB itself (the member's composed
|
|
9205
|
+
// permission config disables the fleet MCP server), so the
|
|
9206
|
+
// entries primed for THIS member travel in its prompt.
|
|
9207
|
+
// Relevance-ranked read for THESE beads, falling back to the
|
|
9208
|
+
// sprint-start primed set when the query returns nothing.
|
|
9209
|
+
// The query terms are the bead ids and titles the engine
|
|
9210
|
+
// already holds; expand_related on that call is what
|
|
9211
|
+
// traverses the refines/contradiction_of edges.
|
|
9212
|
+
const doerRepoPath = kbPriming.folderOf(doerMember);
|
|
9213
|
+
const doerKnowledge = await kbWork.relevantKnowledge(doerRepoPath, kbQueryTerms(streak, actualBeadIds));
|
|
9214
|
+
const basePrompt = buildDoerPrompt({
|
|
9215
|
+
beadIds: actualBeadIds,
|
|
9216
|
+
branch: validated.branch,
|
|
9217
|
+
feedback: feedbackForStreak || null,
|
|
9218
|
+
kbKnowledge: doerKnowledge.length > 0 ? doerKnowledge : kbPriming.knowledgeOf(doerMember),
|
|
9219
|
+
});
|
|
7127
9220
|
let doerPrompt = basePrompt;
|
|
7128
9221
|
if (batchStreaks) {
|
|
7129
9222
|
// Mode (i) BATCH: one dispatch carries the whole ordered
|
|
@@ -7242,9 +9335,11 @@ async function runSprintCycle(context) {
|
|
|
7242
9335
|
// SUCCEEDED: resuming it wastes a dispatch on a session with
|
|
7243
9336
|
// nothing left to do, and classifying it 'failed' would
|
|
7244
9337
|
// falsely re-lane already-completed work.
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
9338
|
+
// (apra-fleet-p2to.4.1) verifyDoerStreakClosed() D-pulls internally
|
|
9339
|
+
// (DoltSync.syncBefore) -- treat the whole call as one sync bracket.
|
|
9340
|
+
const preResumeUnclosed = await withOpenSyncBracket(() => verifyDoerStreakClosed({
|
|
9341
|
+
command, orchestratorMember, beadIds: actualBeadIds, log, args,
|
|
9342
|
+
}));
|
|
7248
9343
|
if (preResumeUnclosed.length === 0) {
|
|
7249
9344
|
log(`Doer streak [${actualBeadIds.join(', ')}] on member '${doerMember}' exhausted its turn limit (max_turns), but all assigned bead id(s) are already closed -- WARNING: the doer missed the VERIFY checkpoint (kept running after its last bd close instead of stopping). Treating this streak as a successful completion, not a failure; issuing NO resume dispatch.`);
|
|
7250
9345
|
dispatchError = null;
|
|
@@ -7339,9 +9434,11 @@ async function runSprintCycle(context) {
|
|
|
7339
9434
|
// assuming every bead in the streak is still open, so
|
|
7340
9435
|
// completed work is never discarded because a sibling in the
|
|
7341
9436
|
// same streak was never reached.
|
|
7342
|
-
|
|
7343
|
-
|
|
7344
|
-
|
|
9437
|
+
// (apra-fleet-p2to.4.1) verifyDoerStreakClosed() D-pulls internally
|
|
9438
|
+
// (DoltSync.syncBefore) -- treat the whole call as one sync bracket.
|
|
9439
|
+
const unclosedIds = await withOpenSyncBracket(() => verifyDoerStreakClosed({
|
|
9440
|
+
command, orchestratorMember, beadIds: actualBeadIds, log, args,
|
|
9441
|
+
}));
|
|
7345
9442
|
const closedIds = actualBeadIds.filter((id) => !unclosedIds.includes(id));
|
|
7346
9443
|
log(`Doer streak attribution [${actualBeadIds.join(', ')}]: closed=[${closedIds.join(', ')}] failed=[${unclosedIds.join(', ')}] (dispatch error: ${dispatchError.message}).`);
|
|
7347
9444
|
if (batchStreaks) {
|
|
@@ -7392,16 +9489,25 @@ async function runSprintCycle(context) {
|
|
|
7392
9489
|
// D-pull this read sees stale (still-open) status and EVERY
|
|
7393
9490
|
// remote doer streak is falsely marked FAILED -- the single most
|
|
7394
9491
|
// divergence-sensitive read in the file.
|
|
7395
|
-
|
|
7396
|
-
|
|
7397
|
-
|
|
9492
|
+
// (apra-fleet-p2to.4.1) verifyDoerStreakClosed() D-pulls internally
|
|
9493
|
+
// (DoltSync.syncBefore) -- treat the whole call as one sync bracket.
|
|
9494
|
+
const unclosedIds = await withOpenSyncBracket(() => verifyDoerStreakClosed({
|
|
9495
|
+
command, orchestratorMember, beadIds: actualBeadIds, log, args,
|
|
9496
|
+
}));
|
|
7398
9497
|
const closedIds = actualBeadIds.filter((id) => !unclosedIds.includes(id));
|
|
7399
9498
|
|
|
7400
|
-
//
|
|
7401
|
-
//
|
|
7402
|
-
//
|
|
7403
|
-
//
|
|
7404
|
-
|
|
9499
|
+
// KB trust pipeline Phase 2: the doer decides what to capture,
|
|
9500
|
+
// the engine executes it against the repo THAT doer worked in.
|
|
9501
|
+
// Captures are honoured regardless of the streak outcome -- a
|
|
9502
|
+
// gotcha found on the way to a failed streak is still true.
|
|
9503
|
+
await kbWork.apply(ROLE_DOER, kbPriming.folderOf(doerMember), report);
|
|
9504
|
+
|
|
9505
|
+
// apra-fleet-eft.76.4: per-bead failure attribution -- always
|
|
9506
|
+
// emitted (not only when something failed) so every streak's
|
|
9507
|
+
// report leaves an audit trail of exactly which beads closed
|
|
9508
|
+
// vs which stayed open. Closed beads stay closed regardless
|
|
9509
|
+
// of a sibling bead in the same streak being refused; only
|
|
9510
|
+
// the still-open ones are eligible for re-laning next round
|
|
7405
9511
|
// (the next dev round's `currentReady` query naturally omits
|
|
7406
9512
|
// whatever already closed here).
|
|
7407
9513
|
log(`Doer streak attribution [${actualBeadIds.join(', ')}]: closed=[${closedIds.join(', ')}] failed=[${unclosedIds.join(', ')}].`);
|
|
@@ -7530,7 +9636,10 @@ async function runSprintCycle(context) {
|
|
|
7530
9636
|
// both reopenIds and newTasks empty is self-contradictory and must
|
|
7531
9637
|
// never be treated as an ordinary "more work needed" round.
|
|
7532
9638
|
const verdict = await dispatchReview({ beadIds: assignedBeadIds, acceptanceCriteriaJson });
|
|
7533
|
-
//
|
|
9639
|
+
// KB trust pipeline Phase 2: the reviewer decides, the engine executes.
|
|
9640
|
+
// Reviewer is the ONLY role whose kb_promotions are honoured.
|
|
9641
|
+
await kbWork.apply(ROLE_REVIEWER, kbPriming.folderOf(getMembersForRole(ROLE_REVIEWER)[0]), verdict);
|
|
9642
|
+
// A5: the last reviewer verdict seen THIS cycle feeds the Cycle
|
|
7534
9643
|
// Evaluation section's completion check below -- goal-priority
|
|
7535
9644
|
// completion requires this to be exactly 'APPROVED', not just
|
|
7536
9645
|
// an empty ready-bead list.
|
|
@@ -7686,7 +9795,8 @@ async function runSprintCycle(context) {
|
|
|
7686
9795
|
// The orchestrator just MUTATED beads (reopens + newTask creates) in
|
|
7687
9796
|
// its own clone -- D-push so members observe them on their next
|
|
7688
9797
|
// dispatch's D-pull.
|
|
7689
|
-
|
|
9798
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
9799
|
+
await withOpenSyncBracket(() => DoltSync.syncAfter(orchestratorMember, { command, pushBeads: true, log, mutex: doltPushMutex, sprintId: sprintMutexId }));
|
|
7690
9800
|
} // end assignedBeadIds.length > 0 (Review dispatch + orchestrator-applied transitions)
|
|
7691
9801
|
|
|
7692
9802
|
await updateDashboard();
|
|
@@ -7724,18 +9834,36 @@ async function runSprintCycle(context) {
|
|
|
7724
9834
|
// error, portability quirk on a given member, etc.) SKIPS the dependent
|
|
7725
9835
|
// phase with a logged warning -- it must never throw and kill the
|
|
7726
9836
|
// sprint.
|
|
7727
|
-
const hasDeploy = await probeFileExists('deploy.md');
|
|
7728
|
-
const hasPlaybook = await probeFileExists('integ-test-playbook.md');
|
|
9837
|
+
const hasDeploy = await probeFileExists('deploy.md', getMemberForRole('deployer'));
|
|
9838
|
+
const hasPlaybook = await probeFileExists('integ-test-playbook.md', getMemberForRole('integ-test-runner'));
|
|
7729
9839
|
|
|
7730
9840
|
let deployedThisCycle = false;
|
|
7731
9841
|
|
|
7732
9842
|
if (hasDeploy) {
|
|
7733
9843
|
phase(`Deploy C${cycle}`);
|
|
9844
|
+
await ensureUnattendedAuto(getMemberForRole('deployer'));
|
|
9845
|
+
await ensureDeployPermissions(getMemberForRole('deployer'));
|
|
7734
9846
|
let deployResult;
|
|
7735
9847
|
// Turn budget for the deployer, with the same-session
|
|
7736
9848
|
// turn-exhaustion resume below: a source-build fallback deploy runs
|
|
7737
9849
|
// npm ci plus two builds, comfortably beyond a small default budget.
|
|
7738
|
-
const DEPLOYER_MAX_TURNS =
|
|
9850
|
+
const DEPLOYER_MAX_TURNS = 500;
|
|
9851
|
+
// apra-fleet-5co8.37: hand the deployer THIS sprint's own reservation
|
|
9852
|
+
// identity so deploy.md's active-sprints gate can tell this sprint's
|
|
9853
|
+
// OWN ledger entry (a sprint is always reserved while it runs, so the
|
|
9854
|
+
// entry is ALWAYS there) from a genuinely foreign one. Without it the
|
|
9855
|
+
// gate stopped on every deploy and no sprint could deploy its own
|
|
9856
|
+
// work. `sprintSelfId` is the SAME string the supervisor keys the
|
|
9857
|
+
// reservation by: the forwarded --run-id, or the branch name for a
|
|
9858
|
+
// direct/standalone launch (bin/cli.mjs reserves under the branch
|
|
9859
|
+
// name in that case).
|
|
9860
|
+
const sprintSelfId = validated.runId || validated.branch;
|
|
9861
|
+
const deployerPrompt =
|
|
9862
|
+
'Deploy to test env using deploy.md.\n' +
|
|
9863
|
+
`Your dispatching sprint's own supervisor reservation id (sprintId): ${sprintSelfId}\n` +
|
|
9864
|
+
"Use it for deploy.md's active-sprints gate: a reservation whose sprintId is EXACTLY " +
|
|
9865
|
+
'this string is your own sprint, not a foreign one, so the deploy proceeds. Stop only ' +
|
|
9866
|
+
'for a reservation with a different sprintId.';
|
|
7739
9867
|
const deployerDispatchOpts = {
|
|
7740
9868
|
member_name: getMemberForRole('deployer'),
|
|
7741
9869
|
agentType: 'deployer',
|
|
@@ -7753,7 +9881,7 @@ async function runSprintCycle(context) {
|
|
|
7753
9881
|
// diff, so it still gets the pre-dispatch G-pull.
|
|
7754
9882
|
try {
|
|
7755
9883
|
deployResult = await withGitSync(getMemberForRole('deployer'), false, () => agent(
|
|
7756
|
-
|
|
9884
|
+
deployerPrompt,
|
|
7757
9885
|
{ ...deployerDispatchOpts, member_name: getMemberForRole('deployer') }
|
|
7758
9886
|
));
|
|
7759
9887
|
} catch (err) {
|
|
@@ -7813,6 +9941,8 @@ async function runSprintCycle(context) {
|
|
|
7813
9941
|
let verifySetForIntegTest = [];
|
|
7814
9942
|
if (hasPlaybook && deployedThisCycle) {
|
|
7815
9943
|
phase(`Integ Test C${cycle}`);
|
|
9944
|
+
await ensureUnattendedAuto(getMemberForRole('integ-test-runner'));
|
|
9945
|
+
await ensureDeployPermissions(getMemberForRole('integ-test-runner'));
|
|
7816
9946
|
// apra-fleet-nwh.1: snapshot the running total BEFORE this
|
|
7817
9947
|
// cycle's Integ Test dispatch(es) so the delta after (below) is
|
|
7818
9948
|
// this phase's own spend, not the whole run's. budget.spent()
|
|
@@ -7925,7 +10055,7 @@ async function runSprintCycle(context) {
|
|
|
7925
10055
|
// re-runs, respect the poll cadence) a normal cycle needs far
|
|
7926
10056
|
// fewer than 300 turns. The resume ladder below still doubles from
|
|
7927
10057
|
// here (to 600) when a run legitimately needs more.
|
|
7928
|
-
const INTEG_TEST_MAX_TURNS =
|
|
10058
|
+
const INTEG_TEST_MAX_TURNS = 500;
|
|
7929
10059
|
const integDispatchOpts = {
|
|
7930
10060
|
member_name: getMemberForRole('integ-test-runner'),
|
|
7931
10061
|
agentType: 'integ-test-runner',
|
|
@@ -8079,7 +10209,7 @@ async function runSprintCycle(context) {
|
|
|
8079
10209
|
if (gapCount > VERIFY_GAP_LIMIT) {
|
|
8080
10210
|
log(`Verify-route bounce cap: ${parentId} has failed verification ${gapCount} time(s) this sprint (limit ${VERIFY_GAP_LIMIT}) -- deferring rather than bouncing again.`);
|
|
8081
10211
|
await command(
|
|
8082
|
-
`bd update ${parentId} --status=deferred --append-notes "Deferred by
|
|
10212
|
+
`bd update ${parentId} --status=deferred --append-notes "Deferred by the verify-route bounce cap: failed integration-test verification ${gapCount} times this sprint (limit ${VERIFY_GAP_LIMIT}). Latest gap: ${bugId}."`,
|
|
8083
10213
|
{ member_name: orchestratorMember, silent: true }
|
|
8084
10214
|
);
|
|
8085
10215
|
} else {
|
|
@@ -8121,7 +10251,12 @@ async function runSprintCycle(context) {
|
|
|
8121
10251
|
// counts so the completion/stall math reads the current cross-member
|
|
8122
10252
|
// beads state (every member's D-pushed closes) rather than the
|
|
8123
10253
|
// orchestrator's stale local copy.
|
|
8124
|
-
|
|
10254
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
10255
|
+
// Thread the orchestrator member's REGISTERED shell into dolt-settle,
|
|
10256
|
+
// guarded on args.callTool the same way the pre-dispatch bracket is
|
|
10257
|
+
// (apra-fleet-7dir.24).
|
|
10258
|
+
const cycleEvalSettleShell = await resolveSettleShell({ args, member: orchestratorMember, log });
|
|
10259
|
+
await withOpenSyncBracket(() => DoltSync.syncBefore(orchestratorMember, { command, log, fatal: true, settle: buildSettleCallback(orchestratorMember, { command, log, shell: cycleEvalSettleShell }) }));
|
|
8125
10260
|
// A decomposed parent (any bead that is itself someone's --parent,
|
|
8126
10261
|
// including a childful --issue target) is excluded here the same way
|
|
8127
10262
|
// readyLeafBeads() excludes it from dispatch: its own "done" status
|
|
@@ -8191,6 +10326,13 @@ async function runSprintCycle(context) {
|
|
|
8191
10326
|
|
|
8192
10327
|
if (staleCycles >= STALL_CYCLE_LIMIT) {
|
|
8193
10328
|
const thrashIds = thrashingBeadIds();
|
|
10329
|
+
// apra-fleet-mjo: counts alone ("history: [9, 14, 14, 14]") do not
|
|
10330
|
+
// tell an operator WHAT is holding the sprint open, which is
|
|
10331
|
+
// precisely what they need to intervene. Name the blocking beads.
|
|
10332
|
+
const blockerIds = openAtGoal.map((b) => b.id);
|
|
10333
|
+
const blockerSuffix = blockerIds.length > 0
|
|
10334
|
+
? ` Still open at/above goal priority ${goalMax}: [${blockerIds.join(', ')}].`
|
|
10335
|
+
: ' No beads remain open at/above goal priority -- the stall is in closing out the sprint, not in the work itself.';
|
|
8194
10336
|
const thrashSuffix = thrashIds.length > 0
|
|
8195
10337
|
? ` Reopen-thrash detected on bead(s) [${thrashIds.join(', ')}] (reopened more than ${REOPEN_THRASH_LIMIT} times) -- ` +
|
|
8196
10338
|
`likely cause of the oscillation.`
|
|
@@ -8220,9 +10362,9 @@ async function runSprintCycle(context) {
|
|
|
8220
10362
|
`Sprint stalled: ${staleCycles} consecutive cycle(s) made no new high-water-mark progress ` +
|
|
8221
10363
|
`(closed beads + verify-routed beads) in scope '${sprintFilter}'. Closed-count history: ` +
|
|
8222
10364
|
`[${closedCountHistory.join(', ')}] (high-water mark on progress score: ${highWaterClosedCount}).` +
|
|
8223
|
-
thrashSuffix + verifySuffix +
|
|
10365
|
+
blockerSuffix + thrashSuffix + verifySuffix +
|
|
8224
10366
|
` Aborting rather than burning the remaining cycles.`,
|
|
8225
|
-
{ staleCycles, closedCountHistory, highWaterClosedCount, thrashIds, reopenCounts: Object.fromEntries(reopenCounts), verifyEverIds: [...verifyEverIds], cycle }
|
|
10367
|
+
{ staleCycles, closedCountHistory, highWaterClosedCount, blockerIds, thrashIds, reopenCounts: Object.fromEntries(reopenCounts), verifyEverIds: [...verifyEverIds], cycle }
|
|
8226
10368
|
);
|
|
8227
10369
|
}
|
|
8228
10370
|
|
|
@@ -8270,6 +10412,7 @@ async function runSprintCycle(context) {
|
|
|
8270
10412
|
// verdict in; acceptanceCriteriaJson still carries the full scope
|
|
8271
10413
|
// for context.
|
|
8272
10414
|
const reReviewVerdict = await dispatchReview({ beadIds: targetIssues, acceptanceCriteriaJson: JSON.stringify(reReviewScope) });
|
|
10415
|
+
await kbWork.apply(ROLE_REVIEWER, kbPriming.folderOf(getMembersForRole(ROLE_REVIEWER)[0]), reReviewVerdict);
|
|
8273
10416
|
lastReviewVerdict = reReviewVerdict.verdict;
|
|
8274
10417
|
reviewedThisCycle = true;
|
|
8275
10418
|
|
|
@@ -8342,7 +10485,8 @@ async function runSprintCycle(context) {
|
|
|
8342
10485
|
|
|
8343
10486
|
// D-push the orchestrator's applied re-review reopens/newTask
|
|
8344
10487
|
// creates, same as the Develop/Review transition site above.
|
|
8345
|
-
|
|
10488
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
10489
|
+
await withOpenSyncBracket(() => DoltSync.syncAfter(orchestratorMember, { command, pushBeads: true, log, mutex: doltPushMutex, sprintId: sprintMutexId }));
|
|
8346
10490
|
}
|
|
8347
10491
|
|
|
8348
10492
|
// apra-fleet-jfo.2: verify-routed beads are decomposed parents, so
|
|
@@ -8401,7 +10545,12 @@ async function runSprintCycle(context) {
|
|
|
8401
10545
|
// the sprint's closing evidence (finalOpenAtGoal / finalClosedCount)
|
|
8402
10546
|
// reflects every member's D-pushed beads state, not the orchestrator's
|
|
8403
10547
|
// stale local copy.
|
|
8404
|
-
|
|
10548
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
10549
|
+
// Thread the orchestrator member's REGISTERED shell into dolt-settle,
|
|
10550
|
+
// guarded on args.callTool the same way the pre-dispatch bracket is
|
|
10551
|
+
// (apra-fleet-7dir.24).
|
|
10552
|
+
const finalReviewSettleShell = await resolveSettleShell({ args, member: orchestratorMember, log });
|
|
10553
|
+
await withOpenSyncBracket(() => DoltSync.syncBefore(orchestratorMember, { command, log, fatal: true, settle: buildSettleCallback(orchestratorMember, { command, log, shell: finalReviewSettleShell }) }));
|
|
8405
10554
|
const [finalOpenAtGoalRaw, finalOpenAtGoalParentIds, finalClosedBeads] = await Promise.all([
|
|
8406
10555
|
bdListScoped(`--status=${NOT_DONE_STATUSES} --priority-max=${goalMax} --json`),
|
|
8407
10556
|
decomposedParentIds(),
|
|
@@ -8433,7 +10582,7 @@ async function runSprintCycle(context) {
|
|
|
8433
10582
|
// reviewer. Without it a large sprint's final review dies at the default
|
|
8434
10583
|
// turn limit and flips the whole sprint to a FAIL whose notes carry no
|
|
8435
10584
|
// findings at all.
|
|
8436
|
-
const FINAL_REVIEW_MAX_TURNS =
|
|
10585
|
+
const FINAL_REVIEW_MAX_TURNS = 500;
|
|
8437
10586
|
// Final Review is the same 'reviewer' role as dispatchReview above
|
|
8438
10587
|
// (read-side, pushCode: false) -- G-pull before, no-op G-push after every
|
|
8439
10588
|
// attempt (including the retry below).
|
|
@@ -8450,6 +10599,15 @@ async function runSprintCycle(context) {
|
|
|
8450
10599
|
max_total_s: DISPATCH_TIMEOUT_S,
|
|
8451
10600
|
max_turns: FINAL_REVIEW_MAX_TURNS,
|
|
8452
10601
|
};
|
|
10602
|
+
// apra-fleet-nx7: offer the final reviewer the same INFERRED candidates a
|
|
10603
|
+
// per-round reviewer gets. Fetched once, before the dispatch, so the retry
|
|
10604
|
+
// and resume paths below reuse the identical block rather than re-querying a
|
|
10605
|
+
// KB that its own earlier promotions may have already changed.
|
|
10606
|
+
const finalReviewRepoPath = kbPriming.folderOf(getMemberForRole('reviewer'));
|
|
10607
|
+
const finalKbCandidates = await kbWork.promotionCandidates(finalReviewRepoPath);
|
|
10608
|
+
if (finalKbCandidates.length > 0) {
|
|
10609
|
+
log(`[kb-work] offering ${finalKbCandidates.length} INFERRED entr(ies) to the final reviewer for promotion.`);
|
|
10610
|
+
}
|
|
8453
10611
|
const dispatchFinalReview = () => withGitSync(getMemberForRole('reviewer'), false, () => agent(
|
|
8454
10612
|
buildFinalVerdictPrompt({
|
|
8455
10613
|
targetIssues,
|
|
@@ -8463,6 +10621,8 @@ async function runSprintCycle(context) {
|
|
|
8463
10621
|
integFailures,
|
|
8464
10622
|
rejectedNewTasks,
|
|
8465
10623
|
unclosedVerifyIds: finalUnclosedVerifyIds,
|
|
10624
|
+
kbCandidates: finalKbCandidates,
|
|
10625
|
+
kbKnowledge: kbPriming.knowledgeOf(getMemberForRole('reviewer')),
|
|
8466
10626
|
}),
|
|
8467
10627
|
// member_name is repeated literally here -- not only via the
|
|
8468
10628
|
// shared opts object -- so the source-level call-site parse in
|
|
@@ -8568,6 +10728,20 @@ async function runSprintCycle(context) {
|
|
|
8568
10728
|
// see src/viewer/index.mjs), a second independent reason a raw JSON
|
|
8569
10729
|
// re-print here would be redundant.
|
|
8570
10730
|
|
|
10731
|
+
// apra-fleet-nx7: execute the final reviewer's KB decisions through the same
|
|
10732
|
+
// path every per-round review uses. Deliberately NOT gated on the verdict --
|
|
10733
|
+
// a fact can be verified even when the sprint as a whole fails, and reviewer
|
|
10734
|
+
// contract already says as much ("Not tied to the verdict"). Placed before
|
|
10735
|
+
// the beads/PR work below and kept non-fatal by kbWork.apply itself, so a KB
|
|
10736
|
+
// problem can never change a sprint's outcome.
|
|
10737
|
+
await kbWork.apply(ROLE_REVIEWER, finalReviewRepoPath, finalVerdictResult);
|
|
10738
|
+
|
|
10739
|
+
// Publish what this sprint confirmed. Immediately after the LAST promotion
|
|
10740
|
+
// of the run, so the bible carries every CONFIRMED entry including the ones
|
|
10741
|
+
// minted a line above. Without this the sprint's knowledge never left the
|
|
10742
|
+
// member's local sqlite store -- see createKbWorkClient.exportBible.
|
|
10743
|
+
await kbWork.exportBible(finalReviewRepoPath);
|
|
10744
|
+
|
|
8571
10745
|
// Persist the Final Review's actionable findings to BEADS -- the only
|
|
8572
10746
|
// artifact the next sprint's planner reads (notes reach only the PR body
|
|
8573
10747
|
// and the analysis doc). NOT gated to FAIL: a PASS can still surface real
|
|
@@ -8721,14 +10895,16 @@ async function runSprintCycle(context) {
|
|
|
8721
10895
|
// part 2 provisions its own fresh sandbox install, so neither depends on
|
|
8722
10896
|
// the per-cycle Deploy target.
|
|
8723
10897
|
let regressionResult = null;
|
|
8724
|
-
const hasRegressionPlaybook = await probeFileExists('regression-test-playbook.md');
|
|
10898
|
+
const hasRegressionPlaybook = await probeFileExists('regression-test-playbook.md', getMemberForRole('regression-test-runner'));
|
|
8725
10899
|
if (hasRegressionPlaybook) {
|
|
8726
10900
|
phase(`Regression Test C${finalCycleLabel}`);
|
|
10901
|
+
await ensureUnattendedAuto(getMemberForRole('regression-test-runner'));
|
|
10902
|
+
await ensureDeployPermissions(getMemberForRole('regression-test-runner'));
|
|
8727
10903
|
// The real functional suite alone spends roughly one turn per liveness
|
|
8728
10904
|
// poll for the better part of an hour, and this single dispatch carries
|
|
8729
10905
|
// both it and the sandbox smoke sprint -- hence the large turn budget
|
|
8730
10906
|
// and the wider hard ceiling.
|
|
8731
|
-
const REGRESSION_TEST_MAX_TURNS =
|
|
10907
|
+
const REGRESSION_TEST_MAX_TURNS = 500;
|
|
8732
10908
|
const REGRESSION_TEST_MAX_TOTAL_S = DISPATCH_TIMEOUT_S * 3;
|
|
8733
10909
|
const regressionPrompt =
|
|
8734
10910
|
`Run the full regression pass using regression-test-playbook.md at the repo root: part 1 ` +
|
|
@@ -8897,7 +11073,7 @@ async function runSprintCycle(context) {
|
|
|
8897
11073
|
let harvesterResult = null;
|
|
8898
11074
|
// Turn budget for the harvester, with the same-session turn-exhaustion
|
|
8899
11075
|
// resume below: it writes docs/changelog across the whole epic.
|
|
8900
|
-
const HARVESTER_MAX_TURNS =
|
|
11076
|
+
const HARVESTER_MAX_TURNS = 500;
|
|
8901
11077
|
const harvesterDispatchOpts = {
|
|
8902
11078
|
member_name: getMemberForRole('harvester'),
|
|
8903
11079
|
agentType: 'harvester',
|
|
@@ -8943,6 +11119,13 @@ async function runSprintCycle(context) {
|
|
|
8943
11119
|
// path itself IS worth a line: it is the durable, committed record of
|
|
8944
11120
|
// the Final Review verdict (and everything else in analysisText) --
|
|
8945
11121
|
// unlike the verdict object, it survives after this process exits.
|
|
11122
|
+
// harvester-output.json declares kb_captures, and until now nothing
|
|
11123
|
+
// consumed it: the harvester filled the field and the engine dropped it
|
|
11124
|
+
// -- the same "gathered and thrown away" shape kbWork was built to fix
|
|
11125
|
+
// for the doer and reviewer. The harvester is a good capturer precisely
|
|
11126
|
+
// because it has just read the whole sprint's evidence. Capture only:
|
|
11127
|
+
// vetKbWork refuses kb_promotions from any role but the reviewer.
|
|
11128
|
+
await kbWork.apply('harvester', kbPriming.folderOf(getMemberForRole('harvester')), harvesterResult);
|
|
8946
11129
|
if (harvesterResult.status !== 'OK') {
|
|
8947
11130
|
log(`Harvester reported FAILED: ${harvesterResult.notes}`);
|
|
8948
11131
|
} else {
|
|
@@ -8988,32 +11171,44 @@ async function runSprintCycle(context) {
|
|
|
8988
11171
|
// closing the sprint's target issue would advertise a completion nobody can
|
|
8989
11172
|
// see. This is the deliberately MINIMAL hardening -- the pluggable-publish
|
|
8990
11173
|
// restructure is apra-fleet-647.2, which supersedes it.
|
|
11174
|
+
// apra-fleet: this push and the origin-remote read just below it run on
|
|
11175
|
+
// publishGitMember -- a real dispatch member with an actual git checkout
|
|
11176
|
+
// (harvester, falling back to the fallback pool like every other role
|
|
11177
|
+
// resolution in this file) -- NEVER orchestratorMember, which may be a
|
|
11178
|
+
// shared/unreservable, git-less member (docs/design-orchestrator-
|
|
11179
|
+
// worktree-model-v2.md section 4.3/4.5). raiseVcsPrForMember() below
|
|
11180
|
+
// stays on orchestratorMember: it is a credential-file read + REST call,
|
|
11181
|
+
// not git, and is explicitly designed to stay there (section 4.6).
|
|
11182
|
+
const publishGitMember = getMemberForRole('harvester');
|
|
8991
11183
|
let pushed = false;
|
|
8992
11184
|
let lastPushError = '';
|
|
8993
|
-
|
|
8994
|
-
|
|
8995
|
-
|
|
8996
|
-
|
|
8997
|
-
|
|
8998
|
-
|
|
8999
|
-
|
|
9000
|
-
|
|
9001
|
-
|
|
9002
|
-
|
|
9003
|
-
|
|
9004
|
-
|
|
9005
|
-
|
|
9006
|
-
|
|
9007
|
-
|
|
9008
|
-
|
|
9009
|
-
|
|
9010
|
-
|
|
9011
|
-
|
|
9012
|
-
|
|
9013
|
-
|
|
11185
|
+
// apra-fleet-9wdh-adjacent (Publish-PR push self-heal): this used to retry
|
|
11186
|
+
// the byte-identical `git push` up to 3 times with no fetch/rebase step in
|
|
11187
|
+
// between -- fine for a transient/busy-remote failure, but a genuine
|
|
11188
|
+
// non-fast-forward rejection ("fetch first") is deterministic, so all 3
|
|
11189
|
+
// attempts failed identically and the branch's work was stranded local-
|
|
11190
|
+
// only. syncMemberAfter() (this file, above) already implements the
|
|
11191
|
+
// correct self-heal for exactly this failure shape -- bounded transient
|
|
11192
|
+
// retry, then one pull-rebase-then-re-push on a genuine non-fast-forward
|
|
11193
|
+
// divergence, never a blind force-push -- and every OTHER post-dispatch
|
|
11194
|
+
// G-push in this file already routes through it. Publish PR is the one
|
|
11195
|
+
// push site that bypassed it. Route through it here too instead of the
|
|
11196
|
+
// raw retry loop. NOTE: no `agent` is passed here, so a real content
|
|
11197
|
+
// conflict during the rebase (not just a plain non-FF race) throws
|
|
11198
|
+
// GitDivergedError directly rather than getting syncMemberAfter's
|
|
11199
|
+
// optional Tier 2 conflict-resolution-agent dispatch -- same as the old
|
|
11200
|
+
// loop, which had no Tier 2 either; not a regression.
|
|
11201
|
+
try {
|
|
11202
|
+
await syncMemberAfter(publishGitMember, {
|
|
11203
|
+
command, log, branch: validated.branch, remote: 'origin', setUpstream: true,
|
|
11204
|
+
onAuthFailure, resolveMemberProvider: resolveMemberVcsProvider,
|
|
11205
|
+
});
|
|
11206
|
+
pushed = true;
|
|
11207
|
+
} catch (pushErr) {
|
|
11208
|
+
lastPushError = pushErr.message;
|
|
9014
11209
|
}
|
|
9015
11210
|
if (!pushed) {
|
|
9016
|
-
log(`[Publish Push Failed] Could not push sprint branch '${validated.branch}' to origin
|
|
11211
|
+
log(`[Publish Push Failed] Could not push sprint branch '${validated.branch}' to origin (bounded transient retry, and a rebase-then-re-push if diverged, both exhausted) -- the sprint's work is COMMITTED LOCALLY ONLY and is NOT on the remote. Skipping PR creation and target-issue closure (neither is meaningful for an unpushed branch); the sprint's own computed verdict (${finalVerdictResult.verdict}) is preserved and returned with pushed:false. Push the branch by hand and raise the PR, or re-run finalization once the remote is reachable. Last error: ${lastPushError}`);
|
|
9017
11212
|
endGroup();
|
|
9018
11213
|
return {
|
|
9019
11214
|
status: finalVerdictResult.verdict === 'PASS' ? 'success' : 'failed',
|
|
@@ -9044,7 +11239,7 @@ async function runSprintCycle(context) {
|
|
|
9044
11239
|
// capabilities()'s own contract -- so a probe hiccup here can never kill
|
|
9045
11240
|
// the sprint.
|
|
9046
11241
|
const originUrlRes = await command('git remote get-url origin', {
|
|
9047
|
-
member_name:
|
|
11242
|
+
member_name: publishGitMember,
|
|
9048
11243
|
silent: true,
|
|
9049
11244
|
failSoft: true,
|
|
9050
11245
|
label: 'Resolve origin remote URL',
|
|
@@ -9075,7 +11270,8 @@ async function runSprintCycle(context) {
|
|
|
9075
11270
|
log(`Publish PR: failed to close target issue '${id}' directly (non-fatal, continuing): ${closeRes.error}`);
|
|
9076
11271
|
}
|
|
9077
11272
|
}
|
|
9078
|
-
|
|
11273
|
+
// (apra-fleet-p2to.4.1) standalone sync bracket -- see openSyncBracketCount's doc comment above.
|
|
11274
|
+
await withOpenSyncBracket(() => DoltSync.syncAfter(orchestratorMember, { command, pushBeads: true, log, mutex: doltPushMutex, sprintId: sprintMutexId }));
|
|
9079
11275
|
} else {
|
|
9080
11276
|
log('Publish PR: final verdict is FAIL -- leaving target issue(s) open (not closing on a non-PASS verdict).');
|
|
9081
11277
|
}
|
|
@@ -9139,14 +11335,33 @@ async function runSprintCycle(context) {
|
|
|
9139
11335
|
body: prBody,
|
|
9140
11336
|
log,
|
|
9141
11337
|
logPrefix: '[Publish PR]',
|
|
11338
|
+
// Already resolved above via publishGitMember (a real
|
|
11339
|
+
// git-capable member) for the PR-capability gate -- skip
|
|
11340
|
+
// re-deriving it a second time by shelling out to
|
|
11341
|
+
// orchestratorMember, which may have no git checkout of its
|
|
11342
|
+
// own to read a remote from (docs/design-orchestrator-
|
|
11343
|
+
// worktree-model-v2.md section 4.6: this call stays workspace-
|
|
11344
|
+
// independent by design, credential-file-read + REST only).
|
|
11345
|
+
remoteUrlOverride: originUrl,
|
|
9142
11346
|
});
|
|
9143
11347
|
if (!prResult.ok) {
|
|
9144
|
-
|
|
9145
|
-
|
|
9146
|
-
|
|
9147
|
-
|
|
9148
|
-
|
|
9149
|
-
|
|
11348
|
+
if (prResult.authFailure) {
|
|
11349
|
+
// apra-fleet-5co8.15: an auth failure raiseVcsPrForMember
|
|
11350
|
+
// could not clear -- including one that never got past
|
|
11351
|
+
// credential provisioning, e.g. a missing Azure DevOps PAT
|
|
11352
|
+
// credential-store entry -- degrades the publish phase
|
|
11353
|
+
// instead of aborting the sprint, same policy
|
|
11354
|
+
// finalizeAbort() already applies to its own authFailure
|
|
11355
|
+
// outcome (see above). The branch is already pushed; only
|
|
11356
|
+
// the PR itself is skipped.
|
|
11357
|
+
log(`[Publish PR Skipped] could not raise a PR for branch '${validated.branch}' -> '${validated.baseBranch}' (branch is pushed) due to an unrecoverable VCS auth failure: ${prResult.error}`);
|
|
11358
|
+
} else {
|
|
11359
|
+
throw new CommandError(
|
|
11360
|
+
`[Publish PR Failed] VCSModule create-pull-request failed for branch '${validated.branch}' -> '${validated.baseBranch}': ${prResult.error}`,
|
|
11361
|
+
{ details: { branch: validated.branch, baseBranch: validated.baseBranch, error: prResult.error } }
|
|
11362
|
+
);
|
|
11363
|
+
}
|
|
11364
|
+
} else if (prResult.alreadyExists) {
|
|
9150
11365
|
log(`Publish PR: a PR for branch '${validated.branch}' already exists -- treating as idempotent success.`);
|
|
9151
11366
|
}
|
|
9152
11367
|
}
|
|
@@ -9347,7 +11562,7 @@ export async function main(context) {
|
|
|
9347
11562
|
// through to finalizeAbort()'s existing throw-and-fall-back path.
|
|
9348
11563
|
const abortOnAuthFailure = context.onAuthFailure ?? (
|
|
9349
11564
|
(args && typeof args.callTool === 'function')
|
|
9350
|
-
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log })
|
|
11565
|
+
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log, azdevopsPatSecretName: validatedForLock.azdevopsPatSecretName })
|
|
9351
11566
|
: undefined
|
|
9352
11567
|
);
|
|
9353
11568
|
|
|
@@ -9389,9 +11604,25 @@ export async function main(context) {
|
|
|
9389
11604
|
// the watchdog needs a reason either way.
|
|
9390
11605
|
if (isTypedAbortError(err)) {
|
|
9391
11606
|
try {
|
|
9392
|
-
|
|
9393
|
-
|
|
9394
|
-
|
|
11607
|
+
// apra-fleet: finalizeAbort() runs `git fetch`/`git push` against
|
|
11608
|
+
// this member's LOCAL checkout, which the orchestrator role no
|
|
11609
|
+
// longer has (it may be a shared/unreservable, git-less member --
|
|
11610
|
+
// see docs/design-orchestrator-worktree-model-v2.md section 4.5).
|
|
11611
|
+
// Resolve a git-capable DISPATCH member instead: the harvester's
|
|
11612
|
+
// member (the last code-writing role, so its clone pushed most
|
|
11613
|
+
// recently), falling back to the first doer, never
|
|
11614
|
+
// roleMap.orchestrator and never a bare validatedForLock.members[0]
|
|
11615
|
+
// pick (that silent pick is the original bug this closes).
|
|
11616
|
+
const roleMap = validatedForLock.roleMap;
|
|
11617
|
+
const harvesterMembers = (roleMap && Array.isArray(roleMap['harvester'])) ? roleMap['harvester'] : [];
|
|
11618
|
+
const doerMembers = (roleMap && Array.isArray(roleMap[ROLE_DOER])) ? roleMap[ROLE_DOER] : [];
|
|
11619
|
+
const member = harvesterMembers[0]
|
|
11620
|
+
?? doerMembers[0]
|
|
11621
|
+
?? validatedForLock.members.find((m) => !roleMap || !roleMap[ROLE_ORCHESTRATOR] || !roleMap[ROLE_ORCHESTRATOR].includes(m));
|
|
11622
|
+
if (!member) {
|
|
11623
|
+
log('[Terminal History] finalizeAbort() skipped: no harvester/doer/dispatch member could be resolved to push the aborted branch.');
|
|
11624
|
+
throw new Error('no git-capable member resolved for finalizeAbort');
|
|
11625
|
+
}
|
|
9395
11626
|
abortResult = await finalizeAbort({
|
|
9396
11627
|
error: err,
|
|
9397
11628
|
branch,
|