@apralabs/apra-fleet 0.4.1 → 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 +16 -8
- package/dist/agents/backlog-groomer.md +17 -21
- package/dist/agents/ci-watcher.md +3 -0
- package/dist/agents/deployer.md +22 -44
- package/dist/agents/doer.md +131 -132
- package/dist/agents/harvester.md +20 -32
- package/dist/agents/integ-test-runner.md +81 -113
- package/dist/agents/kb-reconciler.md +31 -42
- package/dist/agents/plan-reviewer.md +32 -44
- package/dist/agents/planner.md +51 -63
- package/dist/agents/regression-test-runner.md +65 -80
- package/dist/agents/reviewer.md +56 -83
- package/dist/agents/schemas/integ-test-runner-output.json +1 -1
- package/dist/agents/schemas/regression-test-runner-output.json +4 -17
- 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.map +1 -1
- package/dist/cli/install.js +5 -39
- package/dist/cli/install.js.map +1 -1
- 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 +5 -3
- package/dist/cli/uninstall.js.map +1 -1
- package/dist/cli/watch.d.ts +26 -3
- package/dist/cli/watch.d.ts.map +1 -1
- package/dist/cli/watch.js +41 -9
- package/dist/cli/watch.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.js +1 -1
- package/dist/os/linux.js.map +1 -1
- package/dist/os/os-commands.d.ts +7 -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.map +1 -1
- package/dist/os/windows.js +27 -5
- package/dist/os/windows.js.map +1 -1
- package/dist/providers/agy.d.ts +3 -2
- package/dist/providers/agy.d.ts.map +1 -1
- package/dist/providers/agy.js +11 -2
- package/dist/providers/agy.js.map +1 -1
- package/dist/providers/claude.d.ts +3 -2
- package/dist/providers/claude.d.ts.map +1 -1
- package/dist/providers/claude.js +22 -3
- package/dist/providers/claude.js.map +1 -1
- package/dist/providers/codex.d.ts +3 -2
- package/dist/providers/codex.d.ts.map +1 -1
- package/dist/providers/codex.js +5 -2
- package/dist/providers/codex.js.map +1 -1
- package/dist/providers/copilot.d.ts +3 -2
- package/dist/providers/copilot.d.ts.map +1 -1
- package/dist/providers/copilot.js +7 -2
- package/dist/providers/copilot.js.map +1 -1
- 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 +3 -2
- package/dist/providers/none.d.ts.map +1 -1
- package/dist/providers/none.js +5 -2
- package/dist/providers/none.js.map +1 -1
- package/dist/providers/opencode.d.ts +3 -2
- package/dist/providers/opencode.d.ts.map +1 -1
- package/dist/providers/opencode.js +5 -2
- package/dist/providers/opencode.js.map +1 -1
- package/dist/providers/provider.d.ts +16 -7
- package/dist/providers/provider.d.ts.map +1 -1
- package/dist/providers/provider.js +2 -2
- package/dist/providers/provider.js.map +1 -1
- package/dist/services/agent-provisioner.js +2 -2
- 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/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/member-home.d.ts +1 -1
- package/dist/services/member-home.d.ts.map +1 -1
- package/dist/services/member-home.js +15 -12
- package/dist/services/member-home.js.map +1 -1
- 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 +6 -3
- package/dist/services/orphan-recovery.d.ts.map +1 -1
- package/dist/services/orphan-recovery.js +17 -14
- package/dist/services/orphan-recovery.js.map +1 -1
- package/dist/services/preflight-check.js +2 -2
- package/dist/services/preflight-check.js.map +1 -1
- 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/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-poller.d.ts.map +1 -1
- package/dist/services/stall/stall-poller.js +35 -42
- 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 +40 -6
- package/dist/services/strategy.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 +24 -0
- 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/skills/fleet-sprint-cli/SKILL.md +2 -1
- package/dist/skills/pm/SKILL.md +0 -1
- package/dist/skills/pm/cost.md +0 -1
- package/dist/skills/pm/fleet-addendum.md +0 -1
- package/dist/tools/check-status.js +3 -3
- package/dist/tools/check-status.js.map +1 -1
- package/dist/tools/cloud-control.js +2 -2
- package/dist/tools/cloud-control.js.map +1 -1
- package/dist/tools/compose-permissions.d.ts.map +1 -1
- package/dist/tools/compose-permissions.js +37 -24
- package/dist/tools/compose-permissions.js.map +1 -1
- package/dist/tools/execute-command.d.ts.map +1 -1
- package/dist/tools/execute-command.js +28 -12
- package/dist/tools/execute-command.js.map +1 -1
- package/dist/tools/execute-prompt.d.ts.map +1 -1
- package/dist/tools/execute-prompt.js +55 -18
- package/dist/tools/execute-prompt.js.map +1 -1
- 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 +5 -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 +17 -2
- package/dist/tools/monitor-task.js.map +1 -1
- package/dist/tools/provision-auth.js +5 -5
- 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 +18 -12
- package/dist/tools/register-member.d.ts.map +1 -1
- package/dist/tools/register-member.js +42 -4
- package/dist/tools/register-member.js.map +1 -1
- package/dist/tools/remove-member.js +2 -2
- package/dist/tools/remove-member.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/setup-ssh-key.d.ts.map +1 -1
- package/dist/tools/setup-ssh-key.js +2 -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 +18 -12
- package/dist/tools/update-member.d.ts.map +1 -1
- package/dist/tools/update-member.js +18 -1
- package/dist/tools/update-member.js.map +1 -1
- package/dist/types.d.ts +11 -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/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 +4 -17
- package/package.json +2 -2
- package/packages/apra-fleet-client/src/client/api.mjs +92 -3
- package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +17 -21
- package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +3 -0
- package/packages/apra-fleet-se/apra-pm/agents/deployer.md +22 -44
- package/packages/apra-fleet-se/apra-pm/agents/doer.md +131 -132
- package/packages/apra-fleet-se/apra-pm/agents/harvester.md +20 -32
- package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +81 -113
- package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +31 -42
- package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +32 -44
- package/packages/apra-fleet-se/apra-pm/agents/planner.md +51 -63
- package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +65 -80
- package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +56 -83
- package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +1 -1
- package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +4 -17
- package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +0 -1
- 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 +0 -1
- package/packages/apra-fleet-se/bin/cli.mjs +132 -3
- package/packages/apra-fleet-se/bin/serve.mjs +36 -1
- package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +151 -33
- package/packages/apra-fleet-se/fleet-sprint/docs/README.md +22 -7
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-manual-recovery-verified.md +10 -8
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +9 -4
- package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +2 -2
- package/packages/apra-fleet-se/fleet-sprint/docs/shared-orchestrator-reservation-design.md +12 -12
- package/packages/apra-fleet-se/fleet-sprint/docs/stabilization-log.md +14 -4
- package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +275 -99
- package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +67 -16
- package/packages/apra-fleet-se/fleet-sprint/errors.mjs +41 -0
- package/packages/apra-fleet-se/fleet-sprint/runner.js +1140 -209
- 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 +2 -1
- 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 -43
- 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 +92 -37
- package/packages/apra-fleet-workflow/src/viewer/index.mjs +167 -1
- package/packages/apra-fleet-workflow/src/workflow/index.mjs +435 -31
- 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/onboarding.md +4 -4
- package/skills/fleet/permissions.md +6 -6
- 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 -52
- package/dist/providers/gemini.d.ts.map +0 -1
- package/dist/providers/gemini.js +0 -236
- package/dist/providers/gemini.js.map +0 -1
- package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +0 -23
|
@@ -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
|
|
@@ -32,7 +33,8 @@ import { parseUnmergedPaths, detectAndAbortRebaseConflict, dispatchConflictResol
|
|
|
32
33
|
// hard-aborting the run at its readiness gate.
|
|
33
34
|
import { buildSettleCallback } from './dolt-settle.mjs';
|
|
34
35
|
import { acquireSprintLock } from './sprint-lock.mjs';
|
|
35
|
-
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';
|
|
36
38
|
|
|
37
39
|
// Re-exported so importers of parseUnmergedPaths from runner.js keep working;
|
|
38
40
|
// conflict-ladder.mjs is the single source of truth for its implementation.
|
|
@@ -322,6 +324,13 @@ const KNOWN_ARG_KEYS = new Set([
|
|
|
322
324
|
// and per-bead work-claiming. All three are no-ops without it -- a lone
|
|
323
325
|
// sprint has no sibling to coordinate with.
|
|
324
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',
|
|
325
334
|
// The assignee identity this sprint claims beads as and filters ready work
|
|
326
335
|
// by (`bd update --claim` / `bd ready --assignee`). Nothing sets this
|
|
327
336
|
// today; the claiming layer stays dormant and bead selection uses the
|
|
@@ -355,6 +364,11 @@ const KNOWN_ARG_KEYS = new Set([
|
|
|
355
364
|
// `import()`, never across a subprocess boundary). Absent for direct
|
|
356
365
|
// runSprintCycle()/main() test calls, where the guard is a no-op.
|
|
357
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',
|
|
358
372
|
]);
|
|
359
373
|
|
|
360
374
|
/**
|
|
@@ -910,7 +924,7 @@ export async function syncMemberBefore(member, opts = {}) {
|
|
|
910
924
|
export async function syncMemberAfter(member, opts = {}) {
|
|
911
925
|
const {
|
|
912
926
|
command, pushCode = true, log = () => {}, maxTransientRetries = 1, remote = 'origin', branch,
|
|
913
|
-
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider,
|
|
927
|
+
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider, setUpstream = false,
|
|
914
928
|
} = opts;
|
|
915
929
|
if (typeof command !== 'function') {
|
|
916
930
|
throw new Error("syncMemberAfter requires an injected command() in opts");
|
|
@@ -921,7 +935,15 @@ export async function syncMemberAfter(member, opts = {}) {
|
|
|
921
935
|
}
|
|
922
936
|
const provider = await resolveGitProviderForClassification(resolveMemberProvider, member, log);
|
|
923
937
|
|
|
924
|
-
|
|
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';
|
|
925
947
|
|
|
926
948
|
let push = await runGitStep({
|
|
927
949
|
command, member, cmd: pushCmd,
|
|
@@ -1090,6 +1112,7 @@ export {
|
|
|
1090
1112
|
* remote?: string, agent?: Function, resolveConflictModel?: string,
|
|
1091
1113
|
* onAuthFailure?: Function,
|
|
1092
1114
|
* resolveMemberProvider?: (member: string) => Promise<string|undefined>,
|
|
1115
|
+
* args?: { callTool?: Function },
|
|
1093
1116
|
* }} opts
|
|
1094
1117
|
* @returns {Promise<{ ok: true, member: string, gPush: object, dPush: object }>}
|
|
1095
1118
|
*/
|
|
@@ -1097,7 +1120,7 @@ export async function syncMemberAfterOrdered(member, opts = {}) {
|
|
|
1097
1120
|
const {
|
|
1098
1121
|
command, pushCode = true, pushBeads = true, log = () => {},
|
|
1099
1122
|
mutex, sprintId, branch, maxTransientRetries = 1, remote = 'origin',
|
|
1100
|
-
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider,
|
|
1123
|
+
agent, resolveConflictModel, onAuthFailure, resolveMemberProvider, args,
|
|
1101
1124
|
} = opts;
|
|
1102
1125
|
|
|
1103
1126
|
let gPush;
|
|
@@ -1130,7 +1153,12 @@ export async function syncMemberAfterOrdered(member, opts = {}) {
|
|
|
1130
1153
|
// and re-bootstraps a clone, so an arbitrary multi-command dispatch's bead
|
|
1131
1154
|
// mutations cannot be silently thrown away here. There is no pendingMutation
|
|
1132
1155
|
// to capture and replay because nothing is ever dropped.
|
|
1133
|
-
|
|
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 });
|
|
1134
1162
|
const dPush = await DoltSync.syncAfter(member, { command, pushBeads, log, mutex, sprintId, onAuthFailure, fatal: true, settle });
|
|
1135
1163
|
return { ok: true, member, gPush, dPush };
|
|
1136
1164
|
}
|
|
@@ -2046,26 +2074,97 @@ export function createMemberReservationClient(opts = {}) {
|
|
|
2046
2074
|
return '';
|
|
2047
2075
|
}
|
|
2048
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.
|
|
2049
2083
|
async function callFor(action, member) {
|
|
2050
2084
|
try {
|
|
2051
2085
|
const result = await callTool('member_reservation', { member_name: member, action, sprint_id: sprintId });
|
|
2052
2086
|
const text = resultText(result);
|
|
2053
2087
|
if ((result && result.isError) || text.startsWith('[-]')) {
|
|
2054
2088
|
log(`[member-reservation] ${action} rejected for member '${member}': ${text || '(no detail)'}`);
|
|
2089
|
+
return { ok: false, text };
|
|
2055
2090
|
}
|
|
2091
|
+
return { ok: true, text };
|
|
2056
2092
|
} catch (err) {
|
|
2057
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 };
|
|
2058
2095
|
}
|
|
2059
2096
|
}
|
|
2060
2097
|
|
|
2098
|
+
async function releaseAll() {
|
|
2099
|
+
if (!active) return;
|
|
2100
|
+
for (const member of members) await callFor('release', member);
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2061
2103
|
return {
|
|
2062
2104
|
async reserveAll() {
|
|
2063
2105
|
if (!active) return;
|
|
2064
2106
|
for (const member of members) await callFor('reserve', member);
|
|
2065
2107
|
},
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
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 };
|
|
2069
2168
|
},
|
|
2070
2169
|
};
|
|
2071
2170
|
}
|
|
@@ -2146,6 +2245,100 @@ export function parseOwnerRepoFromRemoteUrl(url) {
|
|
|
2146
2245
|
return null;
|
|
2147
2246
|
}
|
|
2148
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
|
+
|
|
2149
2342
|
// Shared MCP tool-result-to-text extractor for the self-heal callbacks below.
|
|
2150
2343
|
// The provision_* tools do not throw on failure: they return plain
|
|
2151
2344
|
// human-readable text with a leading status emoji (check mark = success,
|
|
@@ -2178,23 +2371,49 @@ function selfHealResultText(result) {
|
|
|
2178
2371
|
// the just-in-time credential-scoping ADR (docs/adr-server-never-acts-on-repo.md)
|
|
2179
2372
|
// for the rogue-dispatch blast-radius rationale: widening this default would
|
|
2180
2373
|
// give every member standing pull_requests:write for the whole sprint.
|
|
2181
|
-
// @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
|
|
2182
2375
|
// @returns {Promise<{ expiresAt: Date|null, repo: string|null }>}
|
|
2183
|
-
async function provisionVcsAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, gitAccess = 'push' }) {
|
|
2376
|
+
async function provisionVcsAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix, gitAccess = 'push', azdevopsPatSecretName, remoteUrlOverride, resolvedProvider }) {
|
|
2184
2377
|
let repos;
|
|
2185
2378
|
let derivedRepo = null;
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
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;
|
|
2193
2414
|
} else {
|
|
2194
|
-
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.`);
|
|
2195
2416
|
}
|
|
2196
|
-
} catch (remoteErr) {
|
|
2197
|
-
log(`${logPrefix}: failed to read member '${member}' git remote to derive 'repos' (continuing without an explicit repos scope): ${remoteErr.message}`);
|
|
2198
2417
|
}
|
|
2199
2418
|
|
|
2200
2419
|
// apra-fleet-647.1.2.1: provider and auth-mode are resolved from the
|
|
@@ -2205,14 +2424,29 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
|
|
|
2205
2424
|
// providers: null, no separate mode axis) and is only forwarded as
|
|
2206
2425
|
// `<provider>_mode` when non-null, matching provision_vcs_auth's own
|
|
2207
2426
|
// `github_mode` field name for the one provider that has one today.
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
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({
|
|
2211
2437
|
provider,
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
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,
|
|
2215
2448
|
});
|
|
2449
|
+
const provisionRes = await fleetApi.provisionVcsAuth(provisionArgs);
|
|
2216
2450
|
const provisionText = selfHealResultText(provisionRes);
|
|
2217
2451
|
// provision_vcs_auth NEVER throws on failure -- it returns a string
|
|
2218
2452
|
// starting with the failure emoji. A failed provision must never be
|
|
@@ -2240,8 +2474,8 @@ async function provisionVcsAuthForMember({ fleetApi, command, member, log = () =
|
|
|
2240
2474
|
// learn the repo VCSModule needs to build the PR-creation command.
|
|
2241
2475
|
// @param {{ fleetApi: object, command: Function, member: string, log?: Function, logPrefix: string }} opts
|
|
2242
2476
|
// @returns {Promise<{ expiresAt: Date|null, repo: string|null }>}
|
|
2243
|
-
async function provisionPrCapableAuthForMember({ fleetApi, command, member, log = () => {}, logPrefix }) {
|
|
2244
|
-
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 });
|
|
2245
2479
|
}
|
|
2246
2480
|
|
|
2247
2481
|
// Default credential label provision_vcs_auth deploys under when no explicit
|
|
@@ -2254,6 +2488,22 @@ async function provisionPrCapableAuthForMember({ fleetApi, command, member, log
|
|
|
2254
2488
|
// (src/os/windows.ts:279-294).
|
|
2255
2489
|
const GITHUB_VCS_CREDENTIAL_LABEL = 'github';
|
|
2256
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
|
+
|
|
2257
2507
|
// Typed marker returned by finalizeAbort() (and logged by the Publish PR step)
|
|
2258
2508
|
// when the callTool-absent graceful-degradation path is taken: PR creation was
|
|
2259
2509
|
// intentionally skipped because no MCP client was wired to mint the push+pr
|
|
@@ -2262,11 +2512,12 @@ const GITHUB_VCS_CREDENTIAL_LABEL = 'github';
|
|
|
2262
2512
|
// this exact reason string. See apra-fleet-tfx.8.1.
|
|
2263
2513
|
const PR_SKIPPED_NO_MCP_CLIENT = 'pr-skipped-no-mcp-client';
|
|
2264
2514
|
|
|
2265
|
-
// memberName -> resolved
|
|
2266
|
-
//
|
|
2267
|
-
//
|
|
2268
|
-
//
|
|
2269
|
-
//
|
|
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).
|
|
2270
2521
|
const memberOsCache = new Map();
|
|
2271
2522
|
|
|
2272
2523
|
// Test seam: the OS cache is process-lifetime state, so a test exercising two
|
|
@@ -2275,20 +2526,24 @@ export function clearMemberOsCache() {
|
|
|
2275
2526
|
memberOsCache.clear();
|
|
2276
2527
|
}
|
|
2277
2528
|
|
|
2278
|
-
// Resolves `member`'s
|
|
2529
|
+
// Resolves `member`'s { os, shell } from the fleet member registry via
|
|
2279
2530
|
// fleetApi.memberDetail() ('member_detail' is the only MCP surface exposing
|
|
2280
|
-
// Agent.os -- src/tools/member-detail.ts
|
|
2281
|
-
// Mirrors VCSModule.resolveProvider()'s member_detail
|
|
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.
|
|
2282
2534
|
//
|
|
2283
2535
|
// Unlike resolveProvider, an unresolvable OS is NOT a hard error here: the
|
|
2284
2536
|
// ONLY behavioral difference it drives is which shell string the credential
|
|
2285
2537
|
// read is built as, and the historical (POSIX) string must stay byte-identical
|
|
2286
2538
|
// for every non-Windows member and for any caller that has no memberDetail
|
|
2287
2539
|
// wired. So a missing/unparseable/absent-`os` response degrades to 'linux'
|
|
2288
|
-
// (the pre-existing behavior) and is logged, never thrown.
|
|
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.
|
|
2289
2544
|
// @param {{ fleetApi?: object, member: string, log?: Function }} opts
|
|
2290
|
-
// @returns {Promise<string>}
|
|
2291
|
-
|
|
2545
|
+
// @returns {Promise<{ os: string, shell: string }>}
|
|
2546
|
+
async function resolveMemberTarget({ fleetApi, member, log = () => {} }) {
|
|
2292
2547
|
if (memberOsCache.has(member)) return memberOsCache.get(member);
|
|
2293
2548
|
try {
|
|
2294
2549
|
if (!fleetApi || typeof fleetApi.memberDetail !== 'function') {
|
|
@@ -2303,39 +2558,52 @@ export async function resolveMemberOs({ fleetApi, member, log = () => {} }) {
|
|
|
2303
2558
|
const parsed = JSON.parse(text);
|
|
2304
2559
|
if (parsed && typeof parsed.os === 'string' && parsed.os.trim()) {
|
|
2305
2560
|
const os = parsed.os.trim().toLowerCase();
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
//
|
|
2309
|
-
//
|
|
2310
|
-
//
|
|
2311
|
-
//
|
|
2312
|
-
//
|
|
2313
|
-
|
|
2314
|
-
|
|
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;
|
|
2315
2572
|
}
|
|
2316
2573
|
throw new Error('member_detail response carried no "os" field');
|
|
2317
2574
|
} catch (err) {
|
|
2318
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.`);
|
|
2319
|
-
return 'linux';
|
|
2576
|
+
return { os: 'linux', shell: '' };
|
|
2320
2577
|
}
|
|
2321
2578
|
}
|
|
2322
2579
|
|
|
2323
|
-
//
|
|
2324
|
-
//
|
|
2325
|
-
//
|
|
2326
|
-
// -
|
|
2327
|
-
//
|
|
2328
|
-
//
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
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;
|
|
2339
2607
|
}
|
|
2340
2608
|
|
|
2341
2609
|
// Builds the member-bound command that RUNS the deployed git-credential-helper
|
|
@@ -2382,38 +2650,29 @@ function wrapPowerShellEncodedForMember(psScript) {
|
|
|
2382
2650
|
// occurrences in this file are all justified in place --
|
|
2383
2651
|
// - NOT_DONE_STATUSES (~line 278): quoting note about PowerShell's $OFS, a
|
|
2384
2652
|
// comment, not an expansion in the dispatched string;
|
|
2385
|
-
// -
|
|
2386
|
-
//
|
|
2387
|
-
// re-parses
|
|
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;
|
|
2388
2656
|
// - the POSIX branch below: `$HOME` expanded by the POSIX member's own
|
|
2389
2657
|
// shell, matching what src/os/linux.ts wrote.
|
|
2390
2658
|
// Everything else dispatched to a member is plain `git`/`bd`/`node -e`
|
|
2391
2659
|
// argv-shaped text (see stageCommandBodyMemberSide ~line 2195 and the
|
|
2392
2660
|
// two-sequential-calls note at ~line 5685, which already document why they
|
|
2393
2661
|
// avoid `&&` and `$`), inert across POSIX, PowerShell and cmd.exe.
|
|
2394
|
-
//
|
|
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
|
|
2395
2672
|
// @param {string} label
|
|
2396
2673
|
// @returns {{ command: string, descriptor: string }}
|
|
2397
|
-
export function buildCredentialReadCommand(
|
|
2398
|
-
|
|
2399
|
-
// The label is interpolated into a PowerShell double-quoted string and
|
|
2400
|
-
// a filename; the POSIX branch below is unvalidated for byte-identical
|
|
2401
|
-
// back-compat, but there is no reason to admit shell metacharacters on
|
|
2402
|
-
// the branch being introduced here.
|
|
2403
|
-
if (!/^[A-Za-z0-9._-]+$/.test(String(label))) {
|
|
2404
|
-
throw new Error(`Refusing to build a Windows credential-read command for unsafe VCS credential label '${label}' (allowed: letters, digits, '.', '_', '-').`);
|
|
2405
|
-
}
|
|
2406
|
-
const descriptor = `$env:USERPROFILE\\.fleet-git-credential-${label}.bat`;
|
|
2407
|
-
// `& "<path>"` -- the call operator, so PowerShell EXECUTES the batch
|
|
2408
|
-
// file (and its "password=<token>" line reaches stdout) instead of
|
|
2409
|
-
// echoing the path as a string.
|
|
2410
|
-
return { command: wrapPowerShellEncodedForMember(`& "$env:USERPROFILE\\.fleet-git-credential-${label}.bat"`), descriptor };
|
|
2411
|
-
}
|
|
2412
|
-
// POSIX (linux/darwin): byte-identical to the pre-apra-fleet-ot2z.1
|
|
2413
|
-
// string. $HOME (not `~`) matches what src/os/linux.ts
|
|
2414
|
-
// gitCredentialHelperWrite() wrote and chmod +x'd.
|
|
2415
|
-
const credFile = `$HOME/.fleet-git-credential-${label}`;
|
|
2416
|
-
return { command: credFile, descriptor: credFile };
|
|
2674
|
+
export function buildCredentialReadCommand(target, label) {
|
|
2675
|
+
return getSeCommands(target).readCredentialHelper(label);
|
|
2417
2676
|
}
|
|
2418
2677
|
|
|
2419
2678
|
// Reads the raw token back out of the git-credential-helper script
|
|
@@ -2437,8 +2696,8 @@ export function buildCredentialReadCommand(os, label) {
|
|
|
2437
2696
|
// @param {{ command: Function, member: string, label?: string, fleetApi?: object, log?: Function }} opts
|
|
2438
2697
|
// @returns {Promise<string>}
|
|
2439
2698
|
async function readMemberVcsCredentialToken({ command, member, label = GITHUB_VCS_CREDENTIAL_LABEL, fleetApi, log = () => {} }) {
|
|
2440
|
-
const
|
|
2441
|
-
const { command: credCommand, descriptor: credFile } = buildCredentialReadCommand(
|
|
2699
|
+
const target = await resolveMemberTarget({ fleetApi, member, log });
|
|
2700
|
+
const { command: credCommand, descriptor: credFile } = buildCredentialReadCommand(target, label);
|
|
2442
2701
|
const res = await command(credCommand, {
|
|
2443
2702
|
member_name: member,
|
|
2444
2703
|
silent: true,
|
|
@@ -2516,18 +2775,97 @@ function isPrAuthFailure(status, errorText) {
|
|
|
2516
2775
|
// token is never logged, only `built.logSafeCommand`.
|
|
2517
2776
|
// @param {{ fleetApi: object, command: Function, member: string, base: string, head: string, title: string, body?: string, log?: Function, logPrefix: string }} opts
|
|
2518
2777
|
// @returns {Promise<{ ok: boolean, alreadyExists: boolean, prUrl: string|null, error: string|null, authFailure: boolean }>}
|
|
2519
|
-
async function raiseVcsPrForMember({ fleetApi, command, member, base, head, title, body, log = () => {}, logPrefix }) {
|
|
2520
|
-
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
|
+
}
|
|
2521
2808
|
if (!repo) {
|
|
2522
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.`);
|
|
2523
2810
|
}
|
|
2524
|
-
|
|
2525
|
-
|
|
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;
|
|
2526
2860
|
|
|
2527
2861
|
let authHealAttempted = false;
|
|
2528
2862
|
// eslint-disable-next-line no-constant-condition
|
|
2529
2863
|
while (true) {
|
|
2530
|
-
const built = buildCreatePrCommand({
|
|
2864
|
+
const built = buildCreatePrCommand({
|
|
2865
|
+
provider,
|
|
2866
|
+
...(repoRef ? { repoRef } : { repo }),
|
|
2867
|
+
base, head, title, body, token, os, shell,
|
|
2868
|
+
});
|
|
2531
2869
|
|
|
2532
2870
|
const res = await command(built.command, {
|
|
2533
2871
|
member_name: member,
|
|
@@ -2542,8 +2880,19 @@ async function raiseVcsPrForMember({ fleetApi, command, member, base, head, titl
|
|
|
2542
2880
|
const { status, body: respBody, bodyText } = parseVcsCurlOutput(res.output);
|
|
2543
2881
|
const [lo, hi] = built.interpret.successStatusRange;
|
|
2544
2882
|
if (status !== null && status >= lo && status <= hi) {
|
|
2545
|
-
|
|
2546
|
-
|
|
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 };
|
|
2547
2896
|
}
|
|
2548
2897
|
|
|
2549
2898
|
const errorMessages = [];
|
|
@@ -2565,9 +2914,9 @@ async function raiseVcsPrForMember({ fleetApi, command, member, base, head, titl
|
|
|
2565
2914
|
authHealAttempted = true;
|
|
2566
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}`);
|
|
2567
2916
|
try {
|
|
2568
|
-
const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix });
|
|
2917
|
+
const reprov = await provisionPrCapableAuthForMember({ fleetApi, command, member, log, logPrefix, remoteUrlOverride });
|
|
2569
2918
|
if (reprov.repo) repo = reprov.repo;
|
|
2570
|
-
token = await readMemberVcsCredentialToken({ command, member, fleetApi, log });
|
|
2919
|
+
token = await readMemberVcsCredentialToken({ command, member, label: credentialLabel, fleetApi, log });
|
|
2571
2920
|
} catch (healErr) {
|
|
2572
2921
|
log(`${logPrefix}: PR auth self-heal failed for member '${member}'; not retrying further: ${healErr.message}`);
|
|
2573
2922
|
return { ok: false, alreadyExists: false, prUrl: null, error: `HTTP ${status ?? '(unknown)'}: ${errorText}`, authFailure: true };
|
|
@@ -2694,12 +3043,16 @@ export function createUnattendedAutoProvisioner(opts = {}) {
|
|
|
2694
3043
|
* greps deploy.md by hand and runs compose_permissions manually -- exactly
|
|
2695
3044
|
* the failure mode this closes the loop on.
|
|
2696
3045
|
*
|
|
2697
|
-
* Reads deploy.md via `command()` against the
|
|
2698
|
-
*
|
|
2699
|
-
*
|
|
2700
|
-
*
|
|
2701
|
-
*
|
|
2702
|
-
*
|
|
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.
|
|
2703
3056
|
*
|
|
2704
3057
|
* Failure at any step (probe fails, deploy.md missing/unparseable,
|
|
2705
3058
|
* compose_permissions unreachable, a listed prefix hitting the
|
|
@@ -2707,23 +3060,23 @@ export function createUnattendedAutoProvisioner(opts = {}) {
|
|
|
2707
3060
|
* best-effort acceleration -- the deployer's own Step 0a check remains the
|
|
2708
3061
|
* authoritative, fail-closed backstop regardless of whether this succeeds.
|
|
2709
3062
|
*
|
|
2710
|
-
* @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function,
|
|
3063
|
+
* @param {{ callTool: (name: string, args: object) => Promise<any>, command: Function, log?: Function }} opts
|
|
2711
3064
|
* @returns {(member: string) => Promise<void>}
|
|
2712
3065
|
*/
|
|
2713
3066
|
export function createDeployPermissionsProvisioner(opts = {}) {
|
|
2714
|
-
const { callTool, command,
|
|
3067
|
+
const { callTool, command, log = () => {} } = opts;
|
|
2715
3068
|
const fleetApi = new ApraFleet({ callTool });
|
|
2716
3069
|
/** @type {Set<string>} members already granted deploy.md's permissions this run. */
|
|
2717
3070
|
const provisioned = new Set();
|
|
2718
3071
|
/** @type {string[] | null | undefined} undefined = not yet attempted. */
|
|
2719
3072
|
let cachedPrefixes;
|
|
2720
3073
|
|
|
2721
|
-
async function loadRequiredPrefixes() {
|
|
3074
|
+
async function loadRequiredPrefixes(targetMember) {
|
|
2722
3075
|
if (cachedPrefixes !== undefined) return cachedPrefixes;
|
|
2723
3076
|
try {
|
|
2724
3077
|
const res = await command(
|
|
2725
3078
|
`node -e "const fs=require('fs'); if(fs.existsSync('deploy.md')) process.stdout.write(fs.readFileSync('deploy.md','utf8'))"`,
|
|
2726
|
-
{ member_name:
|
|
3079
|
+
{ member_name: targetMember, silent: true, label: `Read deploy.md permissions`, failSoft: true },
|
|
2727
3080
|
);
|
|
2728
3081
|
if (!res.ok || !res.output) {
|
|
2729
3082
|
cachedPrefixes = null;
|
|
@@ -2741,7 +3094,7 @@ export function createDeployPermissionsProvisioner(opts = {}) {
|
|
|
2741
3094
|
|
|
2742
3095
|
return async function ensureDeployPermissions(member) {
|
|
2743
3096
|
if (!member || provisioned.has(member)) return;
|
|
2744
|
-
const prefixes = await loadRequiredPrefixes();
|
|
3097
|
+
const prefixes = await loadRequiredPrefixes(member);
|
|
2745
3098
|
if (!prefixes) return;
|
|
2746
3099
|
try {
|
|
2747
3100
|
const result = await fleetApi.composePermissions({
|
|
@@ -2774,13 +3127,41 @@ export function createDeployPermissionsProvisioner(opts = {}) {
|
|
|
2774
3127
|
* @returns {(info: { member: string, label: string, cmd?: string, error: string, kind: 'git'|'dolt' }) => Promise<void>}
|
|
2775
3128
|
*/
|
|
2776
3129
|
export function createVcsAuthSelfHealCallback(opts = {}) {
|
|
2777
|
-
const { callTool, command, log = () => {} } = opts;
|
|
3130
|
+
const { callTool, command, log = () => {}, azdevopsPatSecretName } = opts;
|
|
2778
3131
|
const fleetApi = new ApraFleet({ callTool });
|
|
2779
3132
|
|
|
2780
3133
|
return async function onAuthFailure({ member, label, error }) {
|
|
2781
3134
|
log(`[Sync] self-heal: auth failure detected for member '${member}' (${label}); calling provision_vcs_auth to re-provision credentials: ${error}`);
|
|
2782
3135
|
|
|
2783
|
-
|
|
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 });
|
|
2784
3165
|
|
|
2785
3166
|
log(`[Sync] self-heal: provision_vcs_auth succeeded for member '${member}' (${label}); the failed command will be retried once.`);
|
|
2786
3167
|
};
|
|
@@ -2819,7 +3200,7 @@ const VCS_AUTH_EXPIRY_PREFLIGHT_MS = 10 * 60 * 1000; // 10 minutes
|
|
|
2819
3200
|
* @returns {(member: string) => Promise<void>}
|
|
2820
3201
|
*/
|
|
2821
3202
|
export function createVcsAuthPreflightCallback(opts = {}) {
|
|
2822
|
-
const { callTool, command, log = () => {}, now = () => Date.now() } = opts;
|
|
3203
|
+
const { callTool, command, log = () => {}, now = () => Date.now(), azdevopsPatSecretName } = opts;
|
|
2823
3204
|
const fleetApi = new ApraFleet({ callTool });
|
|
2824
3205
|
/** @type {Map<string, Date|null>} member -> last-known expiresAt (null = no expiry tracked, e.g. PAT mode). */
|
|
2825
3206
|
const knownGoodUntil = new Map();
|
|
@@ -2836,7 +3217,7 @@ export function createVcsAuthPreflightCallback(opts = {}) {
|
|
|
2836
3217
|
}
|
|
2837
3218
|
log(`[Sync] preflight: ensuring member '${member}' has a fresh VCS credential before dispatch; calling provision_vcs_auth.`);
|
|
2838
3219
|
try {
|
|
2839
|
-
const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight' });
|
|
3220
|
+
const { expiresAt } = await provisionVcsAuthForMember({ fleetApi, command, member, log, logPrefix: '[Sync] preflight', azdevopsPatSecretName });
|
|
2840
3221
|
knownGoodUntil.set(member, expiresAt);
|
|
2841
3222
|
log(`[Sync] preflight: provision_vcs_auth succeeded for member '${member}'${expiresAt ? ` (expires ${expiresAt.toISOString()})` : ''}.`);
|
|
2842
3223
|
} catch (err) {
|
|
@@ -3086,15 +3467,19 @@ export async function persistNewTaskBestEffort({ createFn, command, member, pare
|
|
|
3086
3467
|
* Returns the ids that are NOT closed after the D-pull-then-read. An empty
|
|
3087
3468
|
* array means the streak genuinely closed everything it was assigned.
|
|
3088
3469
|
*
|
|
3089
|
-
* @param {{ command: Function, orchestratorMember: string, beadIds: string[], log?: Function }} opts
|
|
3470
|
+
* @param {{ command: Function, orchestratorMember: string, beadIds: string[], log?: Function, args?: { callTool?: Function } }} opts
|
|
3090
3471
|
* @returns {Promise<string[]>} the still-unclosed bead ids
|
|
3091
3472
|
*/
|
|
3092
|
-
export async function verifyDoerStreakClosed({ command, orchestratorMember, beadIds, log = () => {} }) {
|
|
3473
|
+
export async function verifyDoerStreakClosed({ command, orchestratorMember, beadIds, log = () => {}, args }) {
|
|
3093
3474
|
// D-pull FIRST so the orchestrator's clone observes the doer's just-pushed
|
|
3094
3475
|
// closes. Routed through the single dolt-sync module's purpose-based BEFORE
|
|
3095
3476
|
// bracket (apra-fleet-417.2.1); behavior is identical to the previous
|
|
3096
3477
|
// direct doltPullBefore() call.
|
|
3097
|
-
|
|
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 }) });
|
|
3098
3483
|
const label = `bd show ${beadIds.join(' ')} --json`;
|
|
3099
3484
|
const showRes = await command(label, { member_name: orchestratorMember, silent: true });
|
|
3100
3485
|
const showBeads = parseBdJson(showRes, label);
|
|
@@ -3102,6 +3487,71 @@ export async function verifyDoerStreakClosed({ command, orchestratorMember, bead
|
|
|
3102
3487
|
return beadIds.filter((id) => statusById.get(id) !== 'closed');
|
|
3103
3488
|
}
|
|
3104
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
|
+
|
|
3105
3555
|
/**
|
|
3106
3556
|
* Validates and normalizes the args object passed into main(context).
|
|
3107
3557
|
* Rejects unknown keys and missing/malformed required keys loudly.
|
|
@@ -3212,6 +3662,12 @@ export function validateArgs(args) {
|
|
|
3212
3662
|
throw new Error(`[Arg Contract] Invalid budget "${args.budget}": must be a non-negative finite number (USD ceiling).`);
|
|
3213
3663
|
}
|
|
3214
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
|
+
|
|
3215
3671
|
// --- serviceUrl (optional) --------------------------------------------
|
|
3216
3672
|
// The always-on supervisor's base HTTP URL. Validated as an http(s) URL so
|
|
3217
3673
|
// a malformed value fails fast rather than silently disabling the
|
|
@@ -3284,6 +3740,15 @@ export function validateArgs(args) {
|
|
|
3284
3740
|
throw new Error(`[Arg Contract] Invalid worklist_effort_budget "${args.worklist_effort_budget}": must be a positive finite number (effort points).`);
|
|
3285
3741
|
}
|
|
3286
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
|
+
|
|
3287
3752
|
return {
|
|
3288
3753
|
targetIssues,
|
|
3289
3754
|
members: args.members,
|
|
@@ -3295,8 +3760,10 @@ export function validateArgs(args) {
|
|
|
3295
3760
|
roleMap: normalizedRoleMap,
|
|
3296
3761
|
budget: args.budget,
|
|
3297
3762
|
serviceUrl: args.serviceUrl,
|
|
3763
|
+
runId: args.run_id,
|
|
3298
3764
|
assignee: args.assignee,
|
|
3299
3765
|
dispatchTimeoutS,
|
|
3766
|
+
azdevopsPatSecretName: args.azdevops_pat_secret_name,
|
|
3300
3767
|
doerWorklistMode,
|
|
3301
3768
|
resumeModelSwitch,
|
|
3302
3769
|
worklistEffortBudget: args.worklist_effort_budget,
|
|
@@ -5547,6 +6014,11 @@ export async function finalizeAbort({ error, branch, baseBranch, member, command
|
|
|
5547
6014
|
body: prBody,
|
|
5548
6015
|
log,
|
|
5549
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,
|
|
5550
6022
|
});
|
|
5551
6023
|
|
|
5552
6024
|
if (!prResult.ok) {
|
|
@@ -5712,8 +6184,212 @@ export function decideEnsureBranchAction({ branch, baseBranch, branchFetchOk, br
|
|
|
5712
6184
|
};
|
|
5713
6185
|
}
|
|
5714
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
|
+
|
|
5715
6325
|
async function runSprintCycle(context) {
|
|
5716
|
-
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
|
+
}
|
|
5717
6393
|
|
|
5718
6394
|
// The shared full-DB beads snapshot served by fetchAllBeadsShared(), plus
|
|
5719
6395
|
// the two choke points that keep it correct. Both wrappers are installed
|
|
@@ -5724,13 +6400,34 @@ async function runSprintCycle(context) {
|
|
|
5724
6400
|
// variable -- transparently goes through the wrapped version.
|
|
5725
6401
|
//
|
|
5726
6402
|
// The snapshot MUST be invalidated the instant the underlying data can
|
|
5727
|
-
// have changed, so invalidation fires on
|
|
6403
|
+
// have changed, so invalidation fires on ALL of:
|
|
5728
6404
|
// 1. every `phase()` call -- a new step must never inherit a stale view
|
|
5729
|
-
// from the step before it,
|
|
6405
|
+
// from the step before it,
|
|
5730
6406
|
// 2. every bd command that is not a known read (list/show/ready/config).
|
|
5731
6407
|
// Update/create/close/note/dep/dolt-pull are all mutations, and an
|
|
5732
6408
|
// unrecognized bd subcommand is conservatively assumed to mutate: the
|
|
5733
|
-
// 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.
|
|
5734
6431
|
// Non-bd commands (git, node probes) never touch beads state.
|
|
5735
6432
|
let allBeadsSnapshot = null; // { beads } -- cleared by invalidateAllBeadsCache()
|
|
5736
6433
|
function invalidateAllBeadsCache() { allBeadsSnapshot = null; }
|
|
@@ -5881,7 +6578,7 @@ async function runSprintCycle(context) {
|
|
|
5881
6578
|
// 'function'`.
|
|
5882
6579
|
const onAuthFailure = context.onAuthFailure ?? (
|
|
5883
6580
|
(args && typeof args.callTool === 'function')
|
|
5884
|
-
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log })
|
|
6581
|
+
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log, azdevopsPatSecretName: validated.azdevopsPatSecretName })
|
|
5885
6582
|
: undefined
|
|
5886
6583
|
);
|
|
5887
6584
|
|
|
@@ -5933,7 +6630,7 @@ async function runSprintCycle(context) {
|
|
|
5933
6630
|
// auth-recovery path.
|
|
5934
6631
|
const ensureVcsAuthFresh = context.ensureVcsAuthFresh ?? (
|
|
5935
6632
|
(args && typeof args.callTool === 'function')
|
|
5936
|
-
? createVcsAuthPreflightCallback({ callTool: args.callTool, command, log })
|
|
6633
|
+
? createVcsAuthPreflightCallback({ callTool: args.callTool, command, log, azdevopsPatSecretName: validated.azdevopsPatSecretName })
|
|
5937
6634
|
: async () => {}
|
|
5938
6635
|
);
|
|
5939
6636
|
|
|
@@ -5966,10 +6663,6 @@ async function runSprintCycle(context) {
|
|
|
5966
6663
|
: async () => {}
|
|
5967
6664
|
);
|
|
5968
6665
|
|
|
5969
|
-
// Validate BEFORE any agent()/command() dispatch: a rejected/malformed arg
|
|
5970
|
-
// must result in zero fleet dispatches.
|
|
5971
|
-
const validated = validateArgs(args);
|
|
5972
|
-
|
|
5973
6666
|
// The per-dispatch time budget used for BOTH timeout_s and max_total_s:
|
|
5974
6667
|
// silent-until-done CLIs make inactivity indistinguishable from total
|
|
5975
6668
|
// runtime, so the two must be equal. The integ-test dispatch alone gets a
|
|
@@ -5999,7 +6692,27 @@ async function runSprintCycle(context) {
|
|
|
5999
6692
|
const roundSessions = createRoundSessionRegistry({ log });
|
|
6000
6693
|
|
|
6001
6694
|
const targetIssues = validated.targetIssues;
|
|
6002
|
-
|
|
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(', ')}`;
|
|
6003
6716
|
|
|
6004
6717
|
// Member mapping resolution
|
|
6005
6718
|
const physicalMembers = validated.members;
|
|
@@ -6053,9 +6766,32 @@ async function runSprintCycle(context) {
|
|
|
6053
6766
|
if (Array.isArray(list)) for (const m of list) roleMapSpecialists.add(m);
|
|
6054
6767
|
}
|
|
6055
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
|
+
);
|
|
6056
6784
|
const unmappedRoleFallbackPool = (() => {
|
|
6057
|
-
const
|
|
6058
|
-
|
|
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;
|
|
6059
6795
|
})();
|
|
6060
6796
|
|
|
6061
6797
|
const getMemberForRole = (role) => {
|
|
@@ -6081,6 +6817,17 @@ async function runSprintCycle(context) {
|
|
|
6081
6817
|
// Uses the canonical ROLE_ORCHESTRATOR constant, not a literal -- see its
|
|
6082
6818
|
// doc comment for why 'orchestrator' is an application-level pseudo-role
|
|
6083
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.
|
|
6084
6831
|
const orchestratorMember = getMemberForRole(ROLE_ORCHESTRATOR);
|
|
6085
6832
|
|
|
6086
6833
|
// Self-heals deploy.md's declared Permissions onto the deployer /
|
|
@@ -6092,7 +6839,7 @@ async function runSprintCycle(context) {
|
|
|
6092
6839
|
// from `args.callTool`, else a no-op when neither is available.
|
|
6093
6840
|
const ensureDeployPermissions = context.ensureDeployPermissions ?? (
|
|
6094
6841
|
(args && typeof args.callTool === 'function')
|
|
6095
|
-
? createDeployPermissionsProvisioner({ callTool: args.callTool, command,
|
|
6842
|
+
? createDeployPermissionsProvisioner({ callTool: args.callTool, command, log })
|
|
6096
6843
|
: async () => {}
|
|
6097
6844
|
);
|
|
6098
6845
|
|
|
@@ -6156,6 +6903,16 @@ async function runSprintCycle(context) {
|
|
|
6156
6903
|
// agent-with-runbook resolution before failing the streak (a no-op for
|
|
6157
6904
|
// non-code-writing roles; never fires for a plain divergence).
|
|
6158
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 {
|
|
6159
6916
|
if (skipPreDispatchSync) {
|
|
6160
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).`);
|
|
6161
6918
|
} else {
|
|
@@ -6182,7 +6939,19 @@ async function runSprintCycle(context) {
|
|
|
6182
6939
|
// EXPLICITLY FATAL (apra-fleet-417.3.1): a pre-dispatch D-pull that
|
|
6183
6940
|
// silently degraded would hand the agent a STALE beads clone and
|
|
6184
6941
|
// let it act on it -- worse than not dispatching at all.
|
|
6185
|
-
|
|
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 }) });
|
|
6186
6955
|
}
|
|
6187
6956
|
// The teardown is deliberately NOT a `finally`. A throw out of a
|
|
6188
6957
|
// `finally` replaces the (successful) dispatch result and is
|
|
@@ -6228,7 +6997,7 @@ async function runSprintCycle(context) {
|
|
|
6228
6997
|
await syncMemberAfterOrdered(member, {
|
|
6229
6998
|
command, pushCode, pushBeads, log, branch: validated.branch,
|
|
6230
6999
|
mutex: doltPushMutex, sprintId: sprintMutexId, agent, onAuthFailure,
|
|
6231
|
-
resolveMemberProvider: resolveMemberVcsProvider,
|
|
7000
|
+
resolveMemberProvider: resolveMemberVcsProvider, args,
|
|
6232
7001
|
});
|
|
6233
7002
|
syncErr = null;
|
|
6234
7003
|
break;
|
|
@@ -6249,6 +7018,18 @@ async function runSprintCycle(context) {
|
|
|
6249
7018
|
}
|
|
6250
7019
|
if (dispatchThrew) throw dispatchThrew;
|
|
6251
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
|
+
}
|
|
6252
7033
|
}
|
|
6253
7034
|
|
|
6254
7035
|
// Scope discovery cannot be built on `bd list --parent`: it accepts exactly
|
|
@@ -6720,8 +7501,14 @@ async function runSprintCycle(context) {
|
|
|
6720
7501
|
// sprint starts; this ensure-everywhere is the git half of the same "every
|
|
6721
7502
|
// member starts from the same state" guarantee. See docs/architecture.md
|
|
6722
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.
|
|
6723
7511
|
const branchEnsureMembers = [...new Set([
|
|
6724
|
-
orchestratorMember,
|
|
6725
7512
|
...getMembersForRole(ROLE_DOER),
|
|
6726
7513
|
...getMembersForRole(ROLE_REVIEWER),
|
|
6727
7514
|
...getMembersForRole('planner'),
|
|
@@ -6754,7 +7541,12 @@ async function runSprintCycle(context) {
|
|
|
6754
7541
|
// Routed through the single dolt-sync module (apra-fleet-417.2.1):
|
|
6755
7542
|
// readinessGate (apra-fleet-417.5 rename of healthGate) selects the
|
|
6756
7543
|
// pre-flight variant of the BEFORE bracket.
|
|
6757
|
-
|
|
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 }) }));
|
|
6758
7550
|
|
|
6759
7551
|
// =======================
|
|
6760
7552
|
// 0. Git Setup: ensure the sprint branch exists off base_branch
|
|
@@ -7045,10 +7837,13 @@ async function runSprintCycle(context) {
|
|
|
7045
7837
|
// single-quoted JS literals inside a double-quoted shell argument (no
|
|
7046
7838
|
// escaped-quote-inside-quote traps). failSoft, so a probe failure can never
|
|
7047
7839
|
// throw and kill the sprint -- it just means "skip the dependent phase".
|
|
7048
|
-
|
|
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) {
|
|
7049
7844
|
const res = await command(
|
|
7050
7845
|
`node -e "console.log(require('fs').existsSync('${filename}') ? 'found' : 'not found')"`,
|
|
7051
|
-
{ member_name:
|
|
7846
|
+
{ member_name: member, silent: true, label: `Probe for '${filename}'`, failSoft: true }
|
|
7052
7847
|
);
|
|
7053
7848
|
if (!res.ok) {
|
|
7054
7849
|
log(`Probe for '${filename}' failed (treating as not-found, skipping the dependent phase): ${res.error}`);
|
|
@@ -7062,7 +7857,12 @@ async function runSprintCycle(context) {
|
|
|
7062
7857
|
// doer's work, so pull again immediately before the verification read.
|
|
7063
7858
|
// DoltSync.syncBefore() is a benign no-op when the clone is current and
|
|
7064
7859
|
// when no dolt remote is configured at all.
|
|
7065
|
-
|
|
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 }) }));
|
|
7066
7866
|
|
|
7067
7867
|
await updateDashboard();
|
|
7068
7868
|
|
|
@@ -7113,6 +7913,31 @@ async function runSprintCycle(context) {
|
|
|
7113
7913
|
|
|
7114
7914
|
if (initialBeads.length === 0) {
|
|
7115
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
|
+
}
|
|
7116
7941
|
throw new Error(`Pre-sprint validation failed: No open/in-progress/blocked/deferred beads found for scope '${sprintFilter}'. Nothing to do.`);
|
|
7117
7942
|
}
|
|
7118
7943
|
|
|
@@ -7479,6 +8304,27 @@ async function runSprintCycle(context) {
|
|
|
7479
8304
|
const skipPreDispatchDoltPull =
|
|
7480
8305
|
i === 0 && cycle === 1 && planningRounds === 1 && plannerSharesOrchestratorClone;
|
|
7481
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();
|
|
7482
8328
|
plannerErr = null;
|
|
7483
8329
|
break;
|
|
7484
8330
|
} catch (err) {
|
|
@@ -7728,7 +8574,8 @@ async function runSprintCycle(context) {
|
|
|
7728
8574
|
{ member_name: orchestratorMember, silent: true, label: `Attach plan-cap deferral finding to ${id}` }
|
|
7729
8575
|
);
|
|
7730
8576
|
}
|
|
7731
|
-
|
|
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 }));
|
|
7732
8579
|
planCapDeferredIds = contestedIds;
|
|
7733
8580
|
}
|
|
7734
8581
|
|
|
@@ -7931,6 +8778,14 @@ async function runSprintCycle(context) {
|
|
|
7931
8778
|
{ timeoutS: DISPATCH_TIMEOUT_S, member: getMemberForRole('planner'), label: 'Scoped Replan Plan (interactive)', log }
|
|
7932
8779
|
), { pushBeads: true });
|
|
7933
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();
|
|
7934
8789
|
} catch (err) {
|
|
7935
8790
|
scopedPlannerOk = false;
|
|
7936
8791
|
// Self-heal an LLM-auth failure so the next cycle's planner
|
|
@@ -7995,7 +8850,8 @@ async function runSprintCycle(context) {
|
|
|
7995
8850
|
// and refresh the dashboard before re-evaluating the loop top.
|
|
7996
8851
|
// Routed through the single dolt-sync module's AFTER bracket
|
|
7997
8852
|
// (apra-fleet-417.2.1); behavior is identical.
|
|
7998
|
-
|
|
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 }));
|
|
7999
8855
|
await updateDashboard();
|
|
8000
8856
|
continue;
|
|
8001
8857
|
}
|
|
@@ -8253,24 +9109,18 @@ async function runSprintCycle(context) {
|
|
|
8253
9109
|
// FIRST attempt passes nothing and keeps plain ff-only
|
|
8254
9110
|
// pre-dispatch sync.
|
|
8255
9111
|
const dispatchDoer = (syncOpts = {}) => withGitSync(doerMember, true, async () => {
|
|
8256
|
-
// 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.
|
|
8257
9118
|
if (!hasClaimedBeads) {
|
|
8258
9119
|
hasClaimedBeads = true;
|
|
8259
9120
|
if (validated.assignee) {
|
|
8260
|
-
const claimedBeadIds =
|
|
8261
|
-
|
|
8262
|
-
|
|
8263
|
-
try {
|
|
8264
|
-
const claimLabel = `bd update ${beadId} --claim`;
|
|
8265
|
-
await command(claimLabel, { member_name: orchestratorMember, silent: true });
|
|
8266
|
-
claimedBeadIds.push(beadId);
|
|
8267
|
-
} catch (claimErr) {
|
|
8268
|
-
// A claim can fail if the bead is already claimed by another
|
|
8269
|
-
// sprint/assignee. Skip this bead instead of crashing.
|
|
8270
|
-
skippedBeadIds.push(beadId);
|
|
8271
|
-
log(`Doer streak: bead ${beadId} already claimed (skipping): ${claimErr.message}`);
|
|
8272
|
-
}
|
|
8273
|
-
}
|
|
9121
|
+
const { claimedBeadIds, skippedBeadIds } = await claimBeadsBatched({
|
|
9122
|
+
command, orchestratorMember, beadIds: actualBeadIds, log,
|
|
9123
|
+
});
|
|
8274
9124
|
if (claimedBeadIds.length === 0) {
|
|
8275
9125
|
// All beads in this streak are already claimed by other sprints.
|
|
8276
9126
|
// Skip this streak entirely.
|
|
@@ -8281,7 +9131,6 @@ async function runSprintCycle(context) {
|
|
|
8281
9131
|
);
|
|
8282
9132
|
}
|
|
8283
9133
|
if (skippedBeadIds.length > 0) {
|
|
8284
|
-
log(`Doer streak: claimed ${claimedBeadIds.length} bead(s) [${claimedBeadIds.join(', ')}]; skipped ${skippedBeadIds.length} already-claimed bead(s) [${skippedBeadIds.join(', ')}].`);
|
|
8285
9134
|
actualBeadIds = claimedBeadIds; // Update to only the successfully claimed ones
|
|
8286
9135
|
}
|
|
8287
9136
|
}
|
|
@@ -8486,9 +9335,11 @@ async function runSprintCycle(context) {
|
|
|
8486
9335
|
// SUCCEEDED: resuming it wastes a dispatch on a session with
|
|
8487
9336
|
// nothing left to do, and classifying it 'failed' would
|
|
8488
9337
|
// falsely re-lane already-completed work.
|
|
8489
|
-
|
|
8490
|
-
|
|
8491
|
-
|
|
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
|
+
}));
|
|
8492
9343
|
if (preResumeUnclosed.length === 0) {
|
|
8493
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.`);
|
|
8494
9345
|
dispatchError = null;
|
|
@@ -8583,9 +9434,11 @@ async function runSprintCycle(context) {
|
|
|
8583
9434
|
// assuming every bead in the streak is still open, so
|
|
8584
9435
|
// completed work is never discarded because a sibling in the
|
|
8585
9436
|
// same streak was never reached.
|
|
8586
|
-
|
|
8587
|
-
|
|
8588
|
-
|
|
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
|
+
}));
|
|
8589
9442
|
const closedIds = actualBeadIds.filter((id) => !unclosedIds.includes(id));
|
|
8590
9443
|
log(`Doer streak attribution [${actualBeadIds.join(', ')}]: closed=[${closedIds.join(', ')}] failed=[${unclosedIds.join(', ')}] (dispatch error: ${dispatchError.message}).`);
|
|
8591
9444
|
if (batchStreaks) {
|
|
@@ -8636,9 +9489,11 @@ async function runSprintCycle(context) {
|
|
|
8636
9489
|
// D-pull this read sees stale (still-open) status and EVERY
|
|
8637
9490
|
// remote doer streak is falsely marked FAILED -- the single most
|
|
8638
9491
|
// divergence-sensitive read in the file.
|
|
8639
|
-
|
|
8640
|
-
|
|
8641
|
-
|
|
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
|
+
}));
|
|
8642
9497
|
const closedIds = actualBeadIds.filter((id) => !unclosedIds.includes(id));
|
|
8643
9498
|
|
|
8644
9499
|
// KB trust pipeline Phase 2: the doer decides what to capture,
|
|
@@ -8940,7 +9795,8 @@ async function runSprintCycle(context) {
|
|
|
8940
9795
|
// The orchestrator just MUTATED beads (reopens + newTask creates) in
|
|
8941
9796
|
// its own clone -- D-push so members observe them on their next
|
|
8942
9797
|
// dispatch's D-pull.
|
|
8943
|
-
|
|
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 }));
|
|
8944
9800
|
} // end assignedBeadIds.length > 0 (Review dispatch + orchestrator-applied transitions)
|
|
8945
9801
|
|
|
8946
9802
|
await updateDashboard();
|
|
@@ -8978,8 +9834,8 @@ async function runSprintCycle(context) {
|
|
|
8978
9834
|
// error, portability quirk on a given member, etc.) SKIPS the dependent
|
|
8979
9835
|
// phase with a logged warning -- it must never throw and kill the
|
|
8980
9836
|
// sprint.
|
|
8981
|
-
const hasDeploy = await probeFileExists('deploy.md');
|
|
8982
|
-
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'));
|
|
8983
9839
|
|
|
8984
9840
|
let deployedThisCycle = false;
|
|
8985
9841
|
|
|
@@ -8992,6 +9848,22 @@ async function runSprintCycle(context) {
|
|
|
8992
9848
|
// turn-exhaustion resume below: a source-build fallback deploy runs
|
|
8993
9849
|
// npm ci plus two builds, comfortably beyond a small default budget.
|
|
8994
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.';
|
|
8995
9867
|
const deployerDispatchOpts = {
|
|
8996
9868
|
member_name: getMemberForRole('deployer'),
|
|
8997
9869
|
agentType: 'deployer',
|
|
@@ -9009,7 +9881,7 @@ async function runSprintCycle(context) {
|
|
|
9009
9881
|
// diff, so it still gets the pre-dispatch G-pull.
|
|
9010
9882
|
try {
|
|
9011
9883
|
deployResult = await withGitSync(getMemberForRole('deployer'), false, () => agent(
|
|
9012
|
-
|
|
9884
|
+
deployerPrompt,
|
|
9013
9885
|
{ ...deployerDispatchOpts, member_name: getMemberForRole('deployer') }
|
|
9014
9886
|
));
|
|
9015
9887
|
} catch (err) {
|
|
@@ -9379,7 +10251,12 @@ async function runSprintCycle(context) {
|
|
|
9379
10251
|
// counts so the completion/stall math reads the current cross-member
|
|
9380
10252
|
// beads state (every member's D-pushed closes) rather than the
|
|
9381
10253
|
// orchestrator's stale local copy.
|
|
9382
|
-
|
|
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 }) }));
|
|
9383
10260
|
// A decomposed parent (any bead that is itself someone's --parent,
|
|
9384
10261
|
// including a childful --issue target) is excluded here the same way
|
|
9385
10262
|
// readyLeafBeads() excludes it from dispatch: its own "done" status
|
|
@@ -9608,7 +10485,8 @@ async function runSprintCycle(context) {
|
|
|
9608
10485
|
|
|
9609
10486
|
// D-push the orchestrator's applied re-review reopens/newTask
|
|
9610
10487
|
// creates, same as the Develop/Review transition site above.
|
|
9611
|
-
|
|
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 }));
|
|
9612
10490
|
}
|
|
9613
10491
|
|
|
9614
10492
|
// apra-fleet-jfo.2: verify-routed beads are decomposed parents, so
|
|
@@ -9667,7 +10545,12 @@ async function runSprintCycle(context) {
|
|
|
9667
10545
|
// the sprint's closing evidence (finalOpenAtGoal / finalClosedCount)
|
|
9668
10546
|
// reflects every member's D-pushed beads state, not the orchestrator's
|
|
9669
10547
|
// stale local copy.
|
|
9670
|
-
|
|
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 }) }));
|
|
9671
10554
|
const [finalOpenAtGoalRaw, finalOpenAtGoalParentIds, finalClosedBeads] = await Promise.all([
|
|
9672
10555
|
bdListScoped(`--status=${NOT_DONE_STATUSES} --priority-max=${goalMax} --json`),
|
|
9673
10556
|
decomposedParentIds(),
|
|
@@ -10012,7 +10895,7 @@ async function runSprintCycle(context) {
|
|
|
10012
10895
|
// part 2 provisions its own fresh sandbox install, so neither depends on
|
|
10013
10896
|
// the per-cycle Deploy target.
|
|
10014
10897
|
let regressionResult = null;
|
|
10015
|
-
const hasRegressionPlaybook = await probeFileExists('regression-test-playbook.md');
|
|
10898
|
+
const hasRegressionPlaybook = await probeFileExists('regression-test-playbook.md', getMemberForRole('regression-test-runner'));
|
|
10016
10899
|
if (hasRegressionPlaybook) {
|
|
10017
10900
|
phase(`Regression Test C${finalCycleLabel}`);
|
|
10018
10901
|
await ensureUnattendedAuto(getMemberForRole('regression-test-runner'));
|
|
@@ -10288,32 +11171,44 @@ async function runSprintCycle(context) {
|
|
|
10288
11171
|
// closing the sprint's target issue would advertise a completion nobody can
|
|
10289
11172
|
// see. This is the deliberately MINIMAL hardening -- the pluggable-publish
|
|
10290
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');
|
|
10291
11183
|
let pushed = false;
|
|
10292
11184
|
let lastPushError = '';
|
|
10293
|
-
|
|
10294
|
-
|
|
10295
|
-
|
|
10296
|
-
|
|
10297
|
-
|
|
10298
|
-
|
|
10299
|
-
|
|
10300
|
-
|
|
10301
|
-
|
|
10302
|
-
|
|
10303
|
-
|
|
10304
|
-
|
|
10305
|
-
|
|
10306
|
-
|
|
10307
|
-
|
|
10308
|
-
|
|
10309
|
-
|
|
10310
|
-
|
|
10311
|
-
|
|
10312
|
-
|
|
10313
|
-
|
|
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;
|
|
10314
11209
|
}
|
|
10315
11210
|
if (!pushed) {
|
|
10316
|
-
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}`);
|
|
10317
11212
|
endGroup();
|
|
10318
11213
|
return {
|
|
10319
11214
|
status: finalVerdictResult.verdict === 'PASS' ? 'success' : 'failed',
|
|
@@ -10344,7 +11239,7 @@ async function runSprintCycle(context) {
|
|
|
10344
11239
|
// capabilities()'s own contract -- so a probe hiccup here can never kill
|
|
10345
11240
|
// the sprint.
|
|
10346
11241
|
const originUrlRes = await command('git remote get-url origin', {
|
|
10347
|
-
member_name:
|
|
11242
|
+
member_name: publishGitMember,
|
|
10348
11243
|
silent: true,
|
|
10349
11244
|
failSoft: true,
|
|
10350
11245
|
label: 'Resolve origin remote URL',
|
|
@@ -10375,7 +11270,8 @@ async function runSprintCycle(context) {
|
|
|
10375
11270
|
log(`Publish PR: failed to close target issue '${id}' directly (non-fatal, continuing): ${closeRes.error}`);
|
|
10376
11271
|
}
|
|
10377
11272
|
}
|
|
10378
|
-
|
|
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 }));
|
|
10379
11275
|
} else {
|
|
10380
11276
|
log('Publish PR: final verdict is FAIL -- leaving target issue(s) open (not closing on a non-PASS verdict).');
|
|
10381
11277
|
}
|
|
@@ -10439,14 +11335,33 @@ async function runSprintCycle(context) {
|
|
|
10439
11335
|
body: prBody,
|
|
10440
11336
|
log,
|
|
10441
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,
|
|
10442
11346
|
});
|
|
10443
11347
|
if (!prResult.ok) {
|
|
10444
|
-
|
|
10445
|
-
|
|
10446
|
-
|
|
10447
|
-
|
|
10448
|
-
|
|
10449
|
-
|
|
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) {
|
|
10450
11365
|
log(`Publish PR: a PR for branch '${validated.branch}' already exists -- treating as idempotent success.`);
|
|
10451
11366
|
}
|
|
10452
11367
|
}
|
|
@@ -10647,7 +11562,7 @@ export async function main(context) {
|
|
|
10647
11562
|
// through to finalizeAbort()'s existing throw-and-fall-back path.
|
|
10648
11563
|
const abortOnAuthFailure = context.onAuthFailure ?? (
|
|
10649
11564
|
(args && typeof args.callTool === 'function')
|
|
10650
|
-
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log })
|
|
11565
|
+
? createVcsAuthSelfHealCallback({ callTool: args.callTool, command, log, azdevopsPatSecretName: validatedForLock.azdevopsPatSecretName })
|
|
10651
11566
|
: undefined
|
|
10652
11567
|
);
|
|
10653
11568
|
|
|
@@ -10689,9 +11604,25 @@ export async function main(context) {
|
|
|
10689
11604
|
// the watchdog needs a reason either way.
|
|
10690
11605
|
if (isTypedAbortError(err)) {
|
|
10691
11606
|
try {
|
|
10692
|
-
|
|
10693
|
-
|
|
10694
|
-
|
|
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
|
+
}
|
|
10695
11626
|
abortResult = await finalizeAbort({
|
|
10696
11627
|
error: err,
|
|
10697
11628
|
branch,
|