gsd-pi 2.38.0-dev.eeb3520 → 2.39.0-dev.64cd3ed
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 +15 -11
- package/dist/app-paths.js +1 -1
- package/dist/cli.js +9 -0
- package/dist/extension-discovery.d.ts +5 -3
- package/dist/extension-discovery.js +14 -9
- package/dist/extension-registry.js +2 -2
- package/dist/remote-questions-config.js +2 -2
- package/dist/resource-loader.js +34 -1
- package/dist/resources/extensions/async-jobs/index.js +10 -0
- package/dist/resources/extensions/browser-tools/index.js +3 -1
- package/dist/resources/extensions/browser-tools/package.json +3 -1
- package/dist/resources/extensions/browser-tools/tools/verify.js +97 -0
- package/dist/resources/extensions/cmux/index.js +55 -1
- package/dist/resources/extensions/context7/package.json +1 -1
- package/dist/resources/extensions/env-utils.js +29 -0
- package/dist/resources/extensions/get-secrets-from-user.js +5 -24
- package/dist/resources/extensions/github-sync/cli.js +284 -0
- package/dist/resources/extensions/github-sync/index.js +73 -0
- package/dist/resources/extensions/github-sync/mapping.js +67 -0
- package/dist/resources/extensions/github-sync/sync.js +424 -0
- package/dist/resources/extensions/github-sync/templates.js +118 -0
- package/dist/resources/extensions/github-sync/types.js +7 -0
- package/dist/resources/extensions/google-search/package.json +3 -1
- package/dist/resources/extensions/gsd/auto/session.js +6 -23
- package/dist/resources/extensions/gsd/auto-dispatch.js +8 -9
- package/dist/resources/extensions/gsd/auto-loop.js +650 -588
- package/dist/resources/extensions/gsd/auto-post-unit.js +99 -70
- package/dist/resources/extensions/gsd/auto-prompts.js +202 -48
- package/dist/resources/extensions/gsd/auto-start.js +13 -2
- package/dist/resources/extensions/gsd/auto-worktree-sync.js +13 -5
- package/dist/resources/extensions/gsd/auto-worktree.js +3 -3
- package/dist/resources/extensions/gsd/auto.js +143 -96
- package/dist/resources/extensions/gsd/captures.js +9 -1
- package/dist/resources/extensions/gsd/commands-extensions.js +3 -2
- package/dist/resources/extensions/gsd/commands-handlers.js +16 -3
- package/dist/resources/extensions/gsd/commands-prefs-wizard.js +1 -1
- package/dist/resources/extensions/gsd/commands.js +24 -3
- package/dist/resources/extensions/gsd/context-budget.js +2 -10
- package/dist/resources/extensions/gsd/detection.js +1 -2
- package/dist/resources/extensions/gsd/docs/preferences-reference.md +0 -2
- package/dist/resources/extensions/gsd/doctor-checks.js +82 -0
- package/dist/resources/extensions/gsd/doctor-environment.js +78 -0
- package/dist/resources/extensions/gsd/doctor-format.js +15 -0
- package/dist/resources/extensions/gsd/doctor-providers.js +30 -11
- package/dist/resources/extensions/gsd/doctor.js +204 -12
- package/dist/resources/extensions/gsd/exit-command.js +2 -1
- package/dist/resources/extensions/gsd/export.js +1 -1
- package/dist/resources/extensions/gsd/files.js +48 -9
- package/dist/resources/extensions/gsd/forensics.js +1 -1
- package/dist/resources/extensions/gsd/git-service.js +30 -12
- package/dist/resources/extensions/gsd/gitignore.js +16 -3
- package/dist/resources/extensions/gsd/guided-flow.js +149 -38
- package/dist/resources/extensions/gsd/health-widget-core.js +32 -70
- package/dist/resources/extensions/gsd/health-widget.js +3 -86
- package/dist/resources/extensions/gsd/index.js +24 -20
- package/dist/resources/extensions/gsd/migrate/parsers.js +1 -1
- package/dist/resources/extensions/gsd/migrate-external.js +18 -1
- package/dist/resources/extensions/gsd/native-git-bridge.js +37 -0
- package/dist/resources/extensions/gsd/package.json +1 -1
- package/dist/resources/extensions/gsd/paths.js +3 -0
- package/dist/resources/extensions/gsd/preferences-models.js +0 -12
- package/dist/resources/extensions/gsd/preferences-types.js +1 -1
- package/dist/resources/extensions/gsd/preferences-validation.js +59 -11
- package/dist/resources/extensions/gsd/preferences.js +22 -11
- package/dist/resources/extensions/gsd/prompt-loader.js +6 -2
- package/dist/resources/extensions/gsd/prompts/complete-milestone.md +1 -1
- package/dist/resources/extensions/gsd/prompts/complete-slice.md +1 -1
- package/dist/resources/extensions/gsd/prompts/discuss.md +11 -14
- package/dist/resources/extensions/gsd/prompts/execute-task.md +5 -3
- package/dist/resources/extensions/gsd/prompts/guided-complete-slice.md +1 -1
- package/dist/resources/extensions/gsd/prompts/guided-discuss-milestone.md +11 -12
- package/dist/resources/extensions/gsd/prompts/guided-discuss-slice.md +8 -10
- package/dist/resources/extensions/gsd/prompts/guided-execute-task.md +1 -1
- package/dist/resources/extensions/gsd/prompts/guided-plan-milestone.md +1 -1
- package/dist/resources/extensions/gsd/prompts/guided-plan-slice.md +1 -1
- package/dist/resources/extensions/gsd/prompts/guided-research-slice.md +1 -1
- package/dist/resources/extensions/gsd/prompts/guided-resume-task.md +1 -1
- package/dist/resources/extensions/gsd/prompts/plan-milestone.md +1 -1
- package/dist/resources/extensions/gsd/prompts/plan-slice.md +1 -1
- package/dist/resources/extensions/gsd/prompts/queue.md +4 -8
- package/dist/resources/extensions/gsd/prompts/reactive-execute.md +11 -8
- package/dist/resources/extensions/gsd/prompts/reassess-roadmap.md +1 -1
- package/dist/resources/extensions/gsd/prompts/research-milestone.md +1 -1
- package/dist/resources/extensions/gsd/prompts/research-slice.md +1 -1
- package/dist/resources/extensions/gsd/prompts/run-uat.md +28 -11
- package/dist/resources/extensions/gsd/prompts/workflow-start.md +2 -2
- package/dist/resources/extensions/gsd/repo-identity.js +21 -4
- package/dist/resources/extensions/gsd/resource-version.js +2 -1
- package/dist/resources/extensions/gsd/roadmap-mutations.js +24 -0
- package/dist/resources/extensions/gsd/state.js +42 -23
- package/dist/resources/extensions/gsd/templates/runtime.md +21 -0
- package/dist/resources/extensions/gsd/templates/task-plan.md +3 -0
- package/dist/resources/extensions/gsd/visualizer-data.js +1 -1
- package/dist/resources/extensions/gsd/worktree.js +35 -16
- package/dist/resources/extensions/mcp-client/index.js +14 -1
- package/dist/resources/extensions/remote-questions/status.js +4 -1
- package/dist/resources/extensions/remote-questions/store.js +4 -1
- package/dist/resources/extensions/search-the-web/provider.js +2 -1
- package/dist/resources/extensions/shared/frontmatter.js +1 -1
- package/dist/resources/extensions/subagent/index.js +12 -3
- package/dist/resources/extensions/subagent/isolation.js +2 -1
- package/dist/resources/extensions/ttsr/rule-loader.js +2 -1
- package/dist/resources/extensions/universal-config/package.json +1 -1
- package/dist/welcome-screen.d.ts +12 -0
- package/dist/welcome-screen.js +53 -0
- package/package.json +1 -1
- package/packages/pi-ai/dist/utils/oauth/anthropic.js +2 -2
- package/packages/pi-ai/dist/utils/oauth/anthropic.js.map +1 -1
- package/packages/pi-ai/src/utils/oauth/anthropic.ts +2 -2
- package/packages/pi-coding-agent/dist/core/extensions/loader.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/extensions/loader.js +205 -7
- package/packages/pi-coding-agent/dist/core/extensions/loader.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/package-manager.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/package-manager.js +8 -4
- package/packages/pi-coding-agent/dist/core/package-manager.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/skills.d.ts +1 -0
- package/packages/pi-coding-agent/dist/core/skills.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/skills.js +6 -1
- package/packages/pi-coding-agent/dist/core/skills.js.map +1 -1
- package/packages/pi-coding-agent/dist/index.d.ts +1 -1
- package/packages/pi-coding-agent/dist/index.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/index.js +1 -1
- package/packages/pi-coding-agent/dist/index.js.map +1 -1
- package/packages/pi-coding-agent/package.json +1 -1
- package/packages/pi-coding-agent/src/core/extensions/loader.ts +223 -7
- package/packages/pi-coding-agent/src/core/package-manager.ts +8 -4
- package/packages/pi-coding-agent/src/core/skills.ts +9 -1
- package/packages/pi-coding-agent/src/index.ts +1 -0
- package/pkg/package.json +1 -1
- package/src/resources/extensions/async-jobs/index.ts +11 -0
- package/src/resources/extensions/browser-tools/index.ts +3 -0
- package/src/resources/extensions/browser-tools/tools/verify.ts +117 -0
- package/src/resources/extensions/cmux/index.ts +57 -1
- package/src/resources/extensions/env-utils.ts +31 -0
- package/src/resources/extensions/get-secrets-from-user.ts +5 -24
- package/src/resources/extensions/github-sync/cli.ts +364 -0
- package/src/resources/extensions/github-sync/index.ts +93 -0
- package/src/resources/extensions/github-sync/mapping.ts +81 -0
- package/src/resources/extensions/github-sync/sync.ts +556 -0
- package/src/resources/extensions/github-sync/templates.ts +183 -0
- package/src/resources/extensions/github-sync/tests/cli.test.ts +20 -0
- package/src/resources/extensions/github-sync/tests/commit-linking.test.ts +39 -0
- package/src/resources/extensions/github-sync/tests/mapping.test.ts +104 -0
- package/src/resources/extensions/github-sync/tests/templates.test.ts +110 -0
- package/src/resources/extensions/github-sync/types.ts +47 -0
- package/src/resources/extensions/gsd/auto/session.ts +7 -25
- package/src/resources/extensions/gsd/auto-dispatch.ts +7 -9
- package/src/resources/extensions/gsd/auto-loop.ts +553 -546
- package/src/resources/extensions/gsd/auto-post-unit.ts +80 -44
- package/src/resources/extensions/gsd/auto-prompts.ts +247 -50
- package/src/resources/extensions/gsd/auto-start.ts +18 -2
- package/src/resources/extensions/gsd/auto-worktree-sync.ts +15 -4
- package/src/resources/extensions/gsd/auto-worktree.ts +3 -3
- package/src/resources/extensions/gsd/auto.ts +139 -101
- package/src/resources/extensions/gsd/captures.ts +10 -1
- package/src/resources/extensions/gsd/commands-extensions.ts +4 -2
- package/src/resources/extensions/gsd/commands-handlers.ts +17 -2
- package/src/resources/extensions/gsd/commands-prefs-wizard.ts +1 -1
- package/src/resources/extensions/gsd/commands.ts +26 -4
- package/src/resources/extensions/gsd/context-budget.ts +2 -12
- package/src/resources/extensions/gsd/detection.ts +2 -2
- package/src/resources/extensions/gsd/docs/preferences-reference.md +0 -2
- package/src/resources/extensions/gsd/doctor-checks.ts +75 -0
- package/src/resources/extensions/gsd/doctor-environment.ts +82 -1
- package/src/resources/extensions/gsd/doctor-format.ts +20 -0
- package/src/resources/extensions/gsd/doctor-providers.ts +30 -9
- package/src/resources/extensions/gsd/doctor-types.ts +16 -1
- package/src/resources/extensions/gsd/doctor.ts +199 -14
- package/src/resources/extensions/gsd/exit-command.ts +2 -2
- package/src/resources/extensions/gsd/export.ts +1 -1
- package/src/resources/extensions/gsd/files.ts +51 -11
- package/src/resources/extensions/gsd/forensics.ts +1 -1
- package/src/resources/extensions/gsd/git-service.ts +44 -10
- package/src/resources/extensions/gsd/gitignore.ts +17 -3
- package/src/resources/extensions/gsd/guided-flow.ts +177 -44
- package/src/resources/extensions/gsd/health-widget-core.ts +28 -80
- package/src/resources/extensions/gsd/health-widget.ts +3 -89
- package/src/resources/extensions/gsd/index.ts +24 -17
- package/src/resources/extensions/gsd/migrate/parsers.ts +1 -1
- package/src/resources/extensions/gsd/migrate-external.ts +18 -1
- package/src/resources/extensions/gsd/native-git-bridge.ts +37 -0
- package/src/resources/extensions/gsd/paths.ts +4 -0
- package/src/resources/extensions/gsd/preferences-models.ts +0 -12
- package/src/resources/extensions/gsd/preferences-types.ts +4 -4
- package/src/resources/extensions/gsd/preferences-validation.ts +51 -11
- package/src/resources/extensions/gsd/preferences.ts +25 -11
- package/src/resources/extensions/gsd/prompt-loader.ts +7 -2
- package/src/resources/extensions/gsd/prompts/complete-milestone.md +1 -1
- package/src/resources/extensions/gsd/prompts/complete-slice.md +1 -1
- package/src/resources/extensions/gsd/prompts/discuss.md +11 -14
- package/src/resources/extensions/gsd/prompts/execute-task.md +5 -3
- package/src/resources/extensions/gsd/prompts/guided-complete-slice.md +1 -1
- package/src/resources/extensions/gsd/prompts/guided-discuss-milestone.md +11 -12
- package/src/resources/extensions/gsd/prompts/guided-discuss-slice.md +8 -10
- package/src/resources/extensions/gsd/prompts/guided-execute-task.md +1 -1
- package/src/resources/extensions/gsd/prompts/guided-plan-milestone.md +1 -1
- package/src/resources/extensions/gsd/prompts/guided-plan-slice.md +1 -1
- package/src/resources/extensions/gsd/prompts/guided-research-slice.md +1 -1
- package/src/resources/extensions/gsd/prompts/guided-resume-task.md +1 -1
- package/src/resources/extensions/gsd/prompts/plan-milestone.md +1 -1
- package/src/resources/extensions/gsd/prompts/plan-slice.md +1 -1
- package/src/resources/extensions/gsd/prompts/queue.md +4 -8
- package/src/resources/extensions/gsd/prompts/reactive-execute.md +11 -8
- package/src/resources/extensions/gsd/prompts/reassess-roadmap.md +1 -1
- package/src/resources/extensions/gsd/prompts/research-milestone.md +1 -1
- package/src/resources/extensions/gsd/prompts/research-slice.md +1 -1
- package/src/resources/extensions/gsd/prompts/run-uat.md +28 -11
- package/src/resources/extensions/gsd/prompts/workflow-start.md +2 -2
- package/src/resources/extensions/gsd/repo-identity.ts +23 -4
- package/src/resources/extensions/gsd/resource-version.ts +3 -1
- package/src/resources/extensions/gsd/roadmap-mutations.ts +29 -0
- package/src/resources/extensions/gsd/state.ts +39 -21
- package/src/resources/extensions/gsd/templates/runtime.md +21 -0
- package/src/resources/extensions/gsd/templates/task-plan.md +3 -0
- package/src/resources/extensions/gsd/tests/agent-end-retry.test.ts +21 -18
- package/src/resources/extensions/gsd/tests/auto-loop.test.ts +122 -68
- package/src/resources/extensions/gsd/tests/auto-worktree-milestone-merge.test.ts +4 -3
- package/src/resources/extensions/gsd/tests/cmux.test.ts +93 -0
- package/src/resources/extensions/gsd/tests/derive-state.test.ts +43 -0
- package/src/resources/extensions/gsd/tests/doctor-enhancements.test.ts +266 -0
- package/src/resources/extensions/gsd/tests/doctor-providers.test.ts +86 -3
- package/src/resources/extensions/gsd/tests/gitignore-tracked-gsd.test.ts +50 -0
- package/src/resources/extensions/gsd/tests/health-widget.test.ts +16 -54
- package/src/resources/extensions/gsd/tests/parsers.test.ts +131 -14
- package/src/resources/extensions/gsd/tests/plan-slice-prompt.test.ts +209 -0
- package/src/resources/extensions/gsd/tests/preferences.test.ts +2 -7
- package/src/resources/extensions/gsd/tests/prompt-contracts.test.ts +59 -0
- package/src/resources/extensions/gsd/tests/repo-identity-worktree.test.ts +21 -1
- package/src/resources/extensions/gsd/tests/run-uat.test.ts +16 -4
- package/src/resources/extensions/gsd/tests/skill-activation.test.ts +140 -0
- package/src/resources/extensions/gsd/tests/worktree.test.ts +47 -0
- package/src/resources/extensions/gsd/types.ts +18 -1
- package/src/resources/extensions/gsd/verification-evidence.ts +16 -0
- package/src/resources/extensions/gsd/visualizer-data.ts +1 -1
- package/src/resources/extensions/gsd/worktree.ts +35 -15
- package/src/resources/extensions/mcp-client/index.ts +17 -1
- package/src/resources/extensions/remote-questions/status.ts +5 -1
- package/src/resources/extensions/remote-questions/store.ts +5 -1
- package/src/resources/extensions/search-the-web/provider.ts +2 -1
- package/src/resources/extensions/shared/frontmatter.ts +1 -1
- package/src/resources/extensions/subagent/index.ts +12 -3
- package/src/resources/extensions/subagent/isolation.ts +3 -1
- package/src/resources/extensions/ttsr/rule-loader.ts +3 -1
- package/dist/resources/extensions/gsd/prompt-compressor.js +0 -393
- package/dist/resources/extensions/gsd/semantic-chunker.js +0 -254
- package/dist/resources/extensions/gsd/summary-distiller.js +0 -212
- package/src/resources/extensions/gsd/prompt-compressor.ts +0 -508
- package/src/resources/extensions/gsd/semantic-chunker.ts +0 -336
- package/src/resources/extensions/gsd/summary-distiller.ts +0 -258
- package/src/resources/extensions/gsd/tests/context-compression.test.ts +0 -193
- package/src/resources/extensions/gsd/tests/prompt-compressor.test.ts +0 -529
- package/src/resources/extensions/gsd/tests/semantic-chunker.test.ts +0 -426
- package/src/resources/extensions/gsd/tests/summary-distiller.test.ts +0 -323
- package/src/resources/extensions/gsd/tests/token-optimization-benchmark.test.ts +0 -1272
- package/src/resources/extensions/gsd/tests/token-optimization-prefs.test.ts +0 -164
|
@@ -5,12 +5,16 @@
|
|
|
5
5
|
* pattern with a while loop. The agent_end event resolves a promise instead
|
|
6
6
|
* of recursing.
|
|
7
7
|
*
|
|
8
|
-
* MAINTENANCE RULE:
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* MAINTENANCE RULE: Module-level mutable state is limited to `_currentResolve`
|
|
9
|
+
* (per-unit one-shot resolver) and `_sessionSwitchInFlight` (guard for
|
|
10
|
+
* session rotation). No queue — stale agent_end events are dropped.
|
|
11
11
|
*/
|
|
12
|
+
import { importExtensionModule } from "@gsd/pi-coding-agent";
|
|
12
13
|
import { NEW_SESSION_TIMEOUT_MS } from "./auto/session.js";
|
|
13
14
|
import { debugLog } from "./debug-logger.js";
|
|
15
|
+
import { gsdRoot } from "./paths.js";
|
|
16
|
+
import { atomicWriteSync } from "./atomic-write.js";
|
|
17
|
+
import { join } from "node:path";
|
|
14
18
|
/**
|
|
15
19
|
* Maximum total loop iterations before forced stop. Prevents runaway loops
|
|
16
20
|
* when units alternate IDs (bypassing the same-unit stuck detector).
|
|
@@ -18,71 +22,114 @@ import { debugLog } from "./debug-logger.js";
|
|
|
18
22
|
* generous headroom including retries and sidecar work.
|
|
19
23
|
*/
|
|
20
24
|
const MAX_LOOP_ITERATIONS = 500;
|
|
21
|
-
|
|
25
|
+
/** Maximum characters of failure/crash context included in recovery prompts. */
|
|
26
|
+
const MAX_RECOVERY_CHARS = 50_000;
|
|
27
|
+
/** Data-driven budget threshold notifications (descending). The 100% entry
|
|
28
|
+
* triggers special enforcement logic (halt/pause/warn); sub-100 entries fire
|
|
29
|
+
* a simple notification. */
|
|
30
|
+
const BUDGET_THRESHOLDS = [
|
|
31
|
+
{ pct: 100, label: "Budget ceiling reached", notifyLevel: "error", cmuxLevel: "error" },
|
|
32
|
+
{ pct: 90, label: "Budget 90%", notifyLevel: "warning", cmuxLevel: "warning" },
|
|
33
|
+
{ pct: 80, label: "Approaching budget ceiling — 80%", notifyLevel: "warning", cmuxLevel: "warning" },
|
|
34
|
+
{ pct: 75, label: "Budget 75%", notifyLevel: "info", cmuxLevel: "progress" },
|
|
35
|
+
];
|
|
36
|
+
// ─── Per-unit one-shot promise state ────────────────────────────────────────
|
|
22
37
|
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
*/
|
|
30
|
-
let _activeSession = null;
|
|
38
|
+
// A single module-level resolve function scoped to the current unit execution.
|
|
39
|
+
// No queue — if an agent_end arrives with no pending resolver, it is dropped
|
|
40
|
+
// (logged as warning). This is simpler and safer than the previous session-
|
|
41
|
+
// scoped pendingResolve + pendingAgentEndQueue pattern.
|
|
42
|
+
let _currentResolve = null;
|
|
43
|
+
let _sessionSwitchInFlight = false;
|
|
31
44
|
// ─── resolveAgentEnd ─────────────────────────────────────────────────────────
|
|
32
45
|
/**
|
|
33
46
|
* Called from the agent_end event handler in index.ts to resolve the
|
|
34
47
|
* in-flight unit promise. One-shot: the resolver is nulled before calling
|
|
35
48
|
* to prevent double-resolution from model fallback retries.
|
|
36
49
|
*
|
|
37
|
-
* If no
|
|
38
|
-
* the event is
|
|
50
|
+
* If no resolver exists (event arrived between loop iterations or during
|
|
51
|
+
* session switch), the event is dropped with a debug warning.
|
|
39
52
|
*/
|
|
40
53
|
export function resolveAgentEnd(event) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
debugLog("resolveAgentEnd", {
|
|
44
|
-
status: "no-active-session",
|
|
45
|
-
warning: "agent_end with no active loop session",
|
|
46
|
-
});
|
|
54
|
+
if (_sessionSwitchInFlight) {
|
|
55
|
+
debugLog("resolveAgentEnd", { status: "ignored-during-switch" });
|
|
47
56
|
return;
|
|
48
57
|
}
|
|
49
|
-
if (
|
|
58
|
+
if (_currentResolve) {
|
|
50
59
|
debugLog("resolveAgentEnd", { status: "resolving", hasEvent: true });
|
|
51
|
-
const r =
|
|
52
|
-
|
|
60
|
+
const r = _currentResolve;
|
|
61
|
+
_currentResolve = null;
|
|
53
62
|
r({ status: "completed", event });
|
|
54
63
|
}
|
|
55
64
|
else {
|
|
56
|
-
// Queue the event so the next runUnit picks it up immediately
|
|
57
65
|
debugLog("resolveAgentEnd", {
|
|
58
|
-
status: "
|
|
59
|
-
|
|
60
|
-
warning: "agent_end arrived between loop iterations — queued for next runUnit",
|
|
66
|
+
status: "no-pending-resolve",
|
|
67
|
+
warning: "agent_end with no pending unit",
|
|
61
68
|
});
|
|
62
|
-
s.pendingAgentEndQueue.push(event);
|
|
63
69
|
}
|
|
64
70
|
}
|
|
65
71
|
export function isSessionSwitchInFlight() {
|
|
66
|
-
return
|
|
72
|
+
return _sessionSwitchInFlight;
|
|
67
73
|
}
|
|
68
74
|
// ─── resetPendingResolve (test helper) ───────────────────────────────────────
|
|
69
75
|
/**
|
|
70
|
-
* Reset
|
|
71
|
-
* should never call this.
|
|
76
|
+
* Reset module-level promise state. Only exported for test cleanup —
|
|
77
|
+
* production code should never call this.
|
|
72
78
|
*/
|
|
73
79
|
export function _resetPendingResolve() {
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
80
|
+
_currentResolve = null;
|
|
81
|
+
_sessionSwitchInFlight = false;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* No-op for backward compatibility with tests that previously set the
|
|
85
|
+
* active session. The module no longer holds a session reference.
|
|
86
|
+
*/
|
|
87
|
+
export function _setActiveSession(_session) {
|
|
88
|
+
// No-op — kept for test backward compatibility
|
|
79
89
|
}
|
|
80
90
|
/**
|
|
81
|
-
*
|
|
82
|
-
*
|
|
91
|
+
* Analyze a sliding window of recent unit dispatches for stuck patterns.
|
|
92
|
+
* Returns a signal with reason if stuck, null otherwise.
|
|
93
|
+
*
|
|
94
|
+
* Rule 1: Same error string twice in a row → stuck immediately.
|
|
95
|
+
* Rule 2: Same unit key 3+ consecutive times → stuck (preserves prior behavior).
|
|
96
|
+
* Rule 3: Oscillation A→B→A→B in last 4 entries → stuck.
|
|
83
97
|
*/
|
|
84
|
-
export function
|
|
85
|
-
|
|
98
|
+
export function detectStuck(window) {
|
|
99
|
+
if (window.length < 2)
|
|
100
|
+
return null;
|
|
101
|
+
const last = window[window.length - 1];
|
|
102
|
+
const prev = window[window.length - 2];
|
|
103
|
+
// Rule 1: Same error repeated consecutively
|
|
104
|
+
if (last.error && prev.error && last.error === prev.error) {
|
|
105
|
+
return {
|
|
106
|
+
stuck: true,
|
|
107
|
+
reason: `Same error repeated: ${last.error.slice(0, 200)}`,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
// Rule 2: Same unit 3+ consecutive times
|
|
111
|
+
if (window.length >= 3) {
|
|
112
|
+
const lastThree = window.slice(-3);
|
|
113
|
+
if (lastThree.every((u) => u.key === last.key)) {
|
|
114
|
+
return {
|
|
115
|
+
stuck: true,
|
|
116
|
+
reason: `${last.key} derived 3 consecutive times without progress`,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
// Rule 3: Oscillation (A→B→A→B in last 4)
|
|
121
|
+
if (window.length >= 4) {
|
|
122
|
+
const w = window.slice(-4);
|
|
123
|
+
if (w[0].key === w[2].key &&
|
|
124
|
+
w[1].key === w[3].key &&
|
|
125
|
+
w[0].key !== w[1].key) {
|
|
126
|
+
return {
|
|
127
|
+
stuck: true,
|
|
128
|
+
reason: `Oscillation detected: ${w[0].key} ↔ ${w[1].key}`,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
86
133
|
}
|
|
87
134
|
// ─── runUnit ─────────────────────────────────────────────────────────────────
|
|
88
135
|
/**
|
|
@@ -93,41 +140,16 @@ export function _setActiveSession(session) {
|
|
|
93
140
|
* On session creation failure or timeout, returns { status: 'cancelled' }
|
|
94
141
|
* without awaiting the promise.
|
|
95
142
|
*/
|
|
96
|
-
export async function runUnit(ctx, pi, s, unitType, unitId, prompt
|
|
143
|
+
export async function runUnit(ctx, pi, s, unitType, unitId, prompt) {
|
|
97
144
|
debugLog("runUnit", { phase: "start", unitType, unitId });
|
|
98
|
-
// ── Drain queued events from error-recovery retries ──
|
|
99
|
-
// If an agent_end arrived between iterations (e.g. from a model fallback
|
|
100
|
-
// sendMessage retry), consume it immediately instead of creating a new promise.
|
|
101
|
-
// Cap queue to 3 entries to prevent unbounded growth from stale events.
|
|
102
|
-
if (s.pendingAgentEndQueue.length > 3) {
|
|
103
|
-
debugLog("runUnit", {
|
|
104
|
-
phase: "queue-overflow",
|
|
105
|
-
dropped: s.pendingAgentEndQueue.length - 1,
|
|
106
|
-
unitType,
|
|
107
|
-
unitId,
|
|
108
|
-
});
|
|
109
|
-
s.pendingAgentEndQueue = [
|
|
110
|
-
s.pendingAgentEndQueue[s.pendingAgentEndQueue.length - 1],
|
|
111
|
-
];
|
|
112
|
-
}
|
|
113
|
-
if (s.pendingAgentEndQueue.length > 0) {
|
|
114
|
-
const queued = s.pendingAgentEndQueue.shift();
|
|
115
|
-
debugLog("runUnit", {
|
|
116
|
-
phase: "drained-queued-event",
|
|
117
|
-
unitType,
|
|
118
|
-
unitId,
|
|
119
|
-
queueRemaining: s.pendingAgentEndQueue.length,
|
|
120
|
-
});
|
|
121
|
-
return { status: "completed", event: queued };
|
|
122
|
-
}
|
|
123
145
|
// ── Session creation with timeout ──
|
|
124
146
|
debugLog("runUnit", { phase: "session-create", unitType, unitId });
|
|
125
147
|
let sessionResult;
|
|
126
148
|
let sessionTimeoutHandle;
|
|
127
|
-
|
|
149
|
+
_sessionSwitchInFlight = true;
|
|
128
150
|
try {
|
|
129
151
|
const sessionPromise = s.cmdCtx.newSession().finally(() => {
|
|
130
|
-
|
|
152
|
+
_sessionSwitchInFlight = false;
|
|
131
153
|
});
|
|
132
154
|
const timeoutPromise = new Promise((resolve) => {
|
|
133
155
|
sessionTimeoutHandle = setTimeout(() => resolve({ cancelled: true }), NEW_SESSION_TIMEOUT_MS);
|
|
@@ -155,11 +177,12 @@ export async function runUnit(ctx, pi, s, unitType, unitId, prompt, _prefs) {
|
|
|
155
177
|
if (!s.active) {
|
|
156
178
|
return { status: "cancelled" };
|
|
157
179
|
}
|
|
158
|
-
// ── Create the agent_end promise (
|
|
180
|
+
// ── Create the agent_end promise (per-unit one-shot) ──
|
|
159
181
|
// This happens after newSession completes so session-switch agent_end events
|
|
160
182
|
// from the previous session cannot resolve the new unit.
|
|
183
|
+
_sessionSwitchInFlight = false;
|
|
161
184
|
const unitPromise = new Promise((resolve) => {
|
|
162
|
-
|
|
185
|
+
_currentResolve = resolve;
|
|
163
186
|
});
|
|
164
187
|
// Ensure cwd matches basePath before dispatch (#1389).
|
|
165
188
|
// async_bash and background jobs can drift cwd away from the worktree.
|
|
@@ -182,8 +205,76 @@ export async function runUnit(ctx, pi, s, unitType, unitId, prompt, _prefs) {
|
|
|
182
205
|
unitId,
|
|
183
206
|
status: result.status,
|
|
184
207
|
});
|
|
208
|
+
// Discard trailing follow-up messages (e.g. async_job_result notifications)
|
|
209
|
+
// from the completed unit. Without this, queued follow-ups trigger wasteful
|
|
210
|
+
// LLM turns before the next session can start (#1642).
|
|
211
|
+
// clearQueue() lives on AgentSession but isn't part of the typed
|
|
212
|
+
// ExtensionCommandContext interface — call it via runtime check.
|
|
213
|
+
try {
|
|
214
|
+
const cmdCtxAny = s.cmdCtx;
|
|
215
|
+
if (typeof cmdCtxAny?.clearQueue === "function") {
|
|
216
|
+
cmdCtxAny.clearQueue();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
// Non-fatal — clearQueue may not be available in all contexts
|
|
221
|
+
}
|
|
185
222
|
return result;
|
|
186
223
|
}
|
|
224
|
+
// ─── generateMilestoneReport ──────────────────────────────────────────────────
|
|
225
|
+
/**
|
|
226
|
+
* Generate and write an HTML milestone report snapshot.
|
|
227
|
+
* Extracted from the milestone-transition block in autoLoop.
|
|
228
|
+
*/
|
|
229
|
+
async function generateMilestoneReport(s, ctx, milestoneId) {
|
|
230
|
+
const { loadVisualizerData } = await importExtensionModule(import.meta.url, "./visualizer-data.js");
|
|
231
|
+
const { generateHtmlReport } = await importExtensionModule(import.meta.url, "./export-html.js");
|
|
232
|
+
const { writeReportSnapshot } = await importExtensionModule(import.meta.url, "./reports.js");
|
|
233
|
+
const { basename } = await import("node:path");
|
|
234
|
+
const snapData = await loadVisualizerData(s.basePath);
|
|
235
|
+
const completedMs = snapData.milestones.find((m) => m.id === milestoneId);
|
|
236
|
+
const msTitle = completedMs?.title ?? milestoneId;
|
|
237
|
+
const gsdVersion = process.env.GSD_VERSION ?? "0.0.0";
|
|
238
|
+
const projName = basename(s.basePath);
|
|
239
|
+
const doneSlices = snapData.milestones.reduce((acc, m) => acc + m.slices.filter((sl) => sl.done).length, 0);
|
|
240
|
+
const totalSlices = snapData.milestones.reduce((acc, m) => acc + m.slices.length, 0);
|
|
241
|
+
const outPath = writeReportSnapshot({
|
|
242
|
+
basePath: s.basePath,
|
|
243
|
+
html: generateHtmlReport(snapData, {
|
|
244
|
+
projectName: projName,
|
|
245
|
+
projectPath: s.basePath,
|
|
246
|
+
gsdVersion,
|
|
247
|
+
milestoneId,
|
|
248
|
+
indexRelPath: "index.html",
|
|
249
|
+
}),
|
|
250
|
+
milestoneId,
|
|
251
|
+
milestoneTitle: msTitle,
|
|
252
|
+
kind: "milestone",
|
|
253
|
+
projectName: projName,
|
|
254
|
+
projectPath: s.basePath,
|
|
255
|
+
gsdVersion,
|
|
256
|
+
totalCost: snapData.totals?.cost ?? 0,
|
|
257
|
+
totalTokens: snapData.totals?.tokens.total ?? 0,
|
|
258
|
+
totalDuration: snapData.totals?.duration ?? 0,
|
|
259
|
+
doneSlices,
|
|
260
|
+
totalSlices,
|
|
261
|
+
doneMilestones: snapData.milestones.filter((m) => m.status === "complete").length,
|
|
262
|
+
totalMilestones: snapData.milestones.length,
|
|
263
|
+
phase: snapData.phase,
|
|
264
|
+
});
|
|
265
|
+
ctx.ui.notify(`Report saved: .gsd/reports/${basename(outPath)} — open index.html to browse progression.`, "info");
|
|
266
|
+
}
|
|
267
|
+
// ─── closeoutAndStop ──────────────────────────────────────────────────────────
|
|
268
|
+
/**
|
|
269
|
+
* If a unit is in-flight, close it out, then stop auto-mode.
|
|
270
|
+
* Extracted from ~4 identical if-closeout-then-stop sequences in autoLoop.
|
|
271
|
+
*/
|
|
272
|
+
async function closeoutAndStop(ctx, pi, s, deps, reason) {
|
|
273
|
+
if (s.currentUnit) {
|
|
274
|
+
await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
|
|
275
|
+
}
|
|
276
|
+
await deps.stopAuto(ctx, pi, reason);
|
|
277
|
+
}
|
|
187
278
|
// ─── autoLoop ────────────────────────────────────────────────────────────────
|
|
188
279
|
/**
|
|
189
280
|
* Main auto-mode execution loop. Iterates: derive → dispatch → guards →
|
|
@@ -195,10 +286,11 @@ export async function runUnit(ctx, pi, s, unitType, unitId, prompt, _prefs) {
|
|
|
195
286
|
*/
|
|
196
287
|
export async function autoLoop(ctx, pi, s, deps) {
|
|
197
288
|
debugLog("autoLoop", { phase: "enter" });
|
|
198
|
-
_activeSession = s;
|
|
199
289
|
let iteration = 0;
|
|
200
|
-
|
|
201
|
-
|
|
290
|
+
// ── Sliding-window stuck detection ──
|
|
291
|
+
const recentUnits = [];
|
|
292
|
+
const STUCK_WINDOW_SIZE = 6;
|
|
293
|
+
let stuckRecoveryAttempts = 0;
|
|
202
294
|
let consecutiveErrors = 0;
|
|
203
295
|
while (s.active) {
|
|
204
296
|
iteration++;
|
|
@@ -218,6 +310,18 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
218
310
|
}
|
|
219
311
|
try {
|
|
220
312
|
// ── Blanket try/catch: one bad iteration must not kill the session
|
|
313
|
+
const prefs = deps.loadEffectiveGSDPreferences()?.preferences;
|
|
314
|
+
// ── Check sidecar queue before deriveState ──
|
|
315
|
+
let sidecarItem;
|
|
316
|
+
if (s.sidecarQueue.length > 0) {
|
|
317
|
+
sidecarItem = s.sidecarQueue.shift();
|
|
318
|
+
debugLog("autoLoop", {
|
|
319
|
+
phase: "sidecar-dequeue",
|
|
320
|
+
kind: sidecarItem.kind,
|
|
321
|
+
unitType: sidecarItem.unitType,
|
|
322
|
+
unitId: sidecarItem.unitId,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
221
325
|
const sessionLockBase = deps.lockBase();
|
|
222
326
|
if (sessionLockBase) {
|
|
223
327
|
const lockStatus = deps.validateSessionLock(sessionLockBase);
|
|
@@ -237,419 +341,436 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
237
341
|
break;
|
|
238
342
|
}
|
|
239
343
|
}
|
|
240
|
-
//
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
}
|
|
257
|
-
if (!healthGate.proceed) {
|
|
258
|
-
ctx.ui.notify(healthGate.reason ?? "Pre-dispatch health check failed.", "error");
|
|
259
|
-
await deps.pauseAuto(ctx, pi);
|
|
260
|
-
debugLog("autoLoop", { phase: "exit", reason: "health-gate-failed" });
|
|
344
|
+
// Variables shared between the sidecar and normal paths
|
|
345
|
+
let unitType;
|
|
346
|
+
let unitId;
|
|
347
|
+
let prompt;
|
|
348
|
+
let pauseAfterUatDispatch = false;
|
|
349
|
+
let state;
|
|
350
|
+
let mid;
|
|
351
|
+
let midTitle;
|
|
352
|
+
let observabilityIssues = [];
|
|
353
|
+
if (!sidecarItem) {
|
|
354
|
+
// ── Phase 1: Pre-dispatch ───────────────────────────────────────────
|
|
355
|
+
// Resource version guard
|
|
356
|
+
const staleMsg = deps.checkResourcesStale(s.resourceVersionOnStart);
|
|
357
|
+
if (staleMsg) {
|
|
358
|
+
await deps.stopAuto(ctx, pi, staleMsg);
|
|
359
|
+
debugLog("autoLoop", { phase: "exit", reason: "resources-stale" });
|
|
261
360
|
break;
|
|
262
361
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
deps.syncProjectRootToWorktree(s.originalBasePath, s.basePath, s.currentMilestoneId);
|
|
272
|
-
}
|
|
273
|
-
// Derive state
|
|
274
|
-
let state = await deps.deriveState(s.basePath);
|
|
275
|
-
deps.syncCmuxSidebar(deps.loadEffectiveGSDPreferences()?.preferences, state);
|
|
276
|
-
let mid = state.activeMilestone?.id;
|
|
277
|
-
let midTitle = state.activeMilestone?.title;
|
|
278
|
-
debugLog("autoLoop", {
|
|
279
|
-
phase: "state-derived",
|
|
280
|
-
iteration,
|
|
281
|
-
mid,
|
|
282
|
-
statePhase: state.phase,
|
|
283
|
-
});
|
|
284
|
-
// ── Milestone transition ────────────────────────────────────────────
|
|
285
|
-
if (mid && s.currentMilestoneId && mid !== s.currentMilestoneId) {
|
|
286
|
-
ctx.ui.notify(`Milestone ${s.currentMilestoneId} complete. Advancing to ${mid}: ${midTitle}.`, "info");
|
|
287
|
-
deps.sendDesktopNotification("GSD", `Milestone ${s.currentMilestoneId} complete!`, "success", "milestone");
|
|
288
|
-
deps.logCmuxEvent(deps.loadEffectiveGSDPreferences()?.preferences, `Milestone ${s.currentMilestoneId} complete. Advancing to ${mid}.`, "success");
|
|
289
|
-
const vizPrefs = deps.loadEffectiveGSDPreferences()?.preferences;
|
|
290
|
-
if (vizPrefs?.auto_visualize) {
|
|
291
|
-
ctx.ui.notify("Run /gsd visualize to see progress overview.", "info");
|
|
292
|
-
}
|
|
293
|
-
if (vizPrefs?.auto_report !== false) {
|
|
294
|
-
try {
|
|
295
|
-
const { loadVisualizerData } = await import("./visualizer-data.js");
|
|
296
|
-
const { generateHtmlReport } = await import("./export-html.js");
|
|
297
|
-
const { writeReportSnapshot } = await import("./reports.js");
|
|
298
|
-
const { basename } = await import("node:path");
|
|
299
|
-
const snapData = await loadVisualizerData(s.basePath);
|
|
300
|
-
const completedMs = snapData.milestones.find((m) => m.id === s.currentMilestoneId);
|
|
301
|
-
const msTitle = completedMs?.title ?? s.currentMilestoneId;
|
|
302
|
-
const gsdVersion = process.env.GSD_VERSION ?? "0.0.0";
|
|
303
|
-
const projName = basename(s.basePath);
|
|
304
|
-
const doneSlices = snapData.milestones.reduce((acc, m) => acc +
|
|
305
|
-
m.slices.filter((sl) => sl.done).length, 0);
|
|
306
|
-
const totalSlices = snapData.milestones.reduce((acc, m) => acc + m.slices.length, 0);
|
|
307
|
-
const outPath = writeReportSnapshot({
|
|
308
|
-
basePath: s.basePath,
|
|
309
|
-
html: generateHtmlReport(snapData, {
|
|
310
|
-
projectName: projName,
|
|
311
|
-
projectPath: s.basePath,
|
|
312
|
-
gsdVersion,
|
|
313
|
-
milestoneId: s.currentMilestoneId,
|
|
314
|
-
indexRelPath: "index.html",
|
|
315
|
-
}),
|
|
316
|
-
milestoneId: s.currentMilestoneId,
|
|
317
|
-
milestoneTitle: msTitle,
|
|
318
|
-
kind: "milestone",
|
|
319
|
-
projectName: projName,
|
|
320
|
-
projectPath: s.basePath,
|
|
321
|
-
gsdVersion,
|
|
322
|
-
totalCost: snapData.totals?.cost ?? 0,
|
|
323
|
-
totalTokens: snapData.totals?.tokens.total ?? 0,
|
|
324
|
-
totalDuration: snapData.totals?.duration ?? 0,
|
|
325
|
-
doneSlices,
|
|
326
|
-
totalSlices,
|
|
327
|
-
doneMilestones: snapData.milestones.filter((m) => m.status === "complete").length,
|
|
328
|
-
totalMilestones: snapData.milestones.length,
|
|
329
|
-
phase: snapData.phase,
|
|
330
|
-
});
|
|
331
|
-
ctx.ui.notify(`Report saved: .gsd/reports/${(await import("node:path")).basename(outPath)} — open index.html to browse progression.`, "info");
|
|
362
|
+
deps.invalidateAllCaches();
|
|
363
|
+
s.lastPromptCharCount = undefined;
|
|
364
|
+
s.lastBaselineCharCount = undefined;
|
|
365
|
+
// Pre-dispatch health gate
|
|
366
|
+
try {
|
|
367
|
+
const healthGate = await deps.preDispatchHealthGate(s.basePath);
|
|
368
|
+
if (healthGate.fixesApplied.length > 0) {
|
|
369
|
+
ctx.ui.notify(`Pre-dispatch: ${healthGate.fixesApplied.join(", ")}`, "info");
|
|
332
370
|
}
|
|
333
|
-
|
|
334
|
-
ctx.ui.notify(
|
|
371
|
+
if (!healthGate.proceed) {
|
|
372
|
+
ctx.ui.notify(healthGate.reason ?? "Pre-dispatch health check failed.", "error");
|
|
373
|
+
await deps.pauseAuto(ctx, pi);
|
|
374
|
+
debugLog("autoLoop", { phase: "exit", reason: "health-gate-failed" });
|
|
375
|
+
break;
|
|
335
376
|
}
|
|
336
377
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
378
|
+
catch {
|
|
379
|
+
// Non-fatal
|
|
380
|
+
}
|
|
381
|
+
// Sync project root artifacts into worktree
|
|
382
|
+
if (s.originalBasePath &&
|
|
383
|
+
s.basePath !== s.originalBasePath &&
|
|
384
|
+
s.currentMilestoneId) {
|
|
385
|
+
deps.syncProjectRootToWorktree(s.originalBasePath, s.basePath, s.currentMilestoneId);
|
|
386
|
+
}
|
|
387
|
+
// Derive state
|
|
346
388
|
state = await deps.deriveState(s.basePath);
|
|
389
|
+
deps.syncCmuxSidebar(prefs, state);
|
|
347
390
|
mid = state.activeMilestone?.id;
|
|
348
391
|
midTitle = state.activeMilestone?.title;
|
|
392
|
+
debugLog("autoLoop", {
|
|
393
|
+
phase: "state-derived",
|
|
394
|
+
iteration,
|
|
395
|
+
mid,
|
|
396
|
+
statePhase: state.phase,
|
|
397
|
+
});
|
|
398
|
+
// ── Milestone transition ────────────────────────────────────────────
|
|
399
|
+
if (mid && s.currentMilestoneId && mid !== s.currentMilestoneId) {
|
|
400
|
+
ctx.ui.notify(`Milestone ${s.currentMilestoneId} complete. Advancing to ${mid}: ${midTitle}.`, "info");
|
|
401
|
+
deps.sendDesktopNotification("GSD", `Milestone ${s.currentMilestoneId} complete!`, "success", "milestone");
|
|
402
|
+
deps.logCmuxEvent(prefs, `Milestone ${s.currentMilestoneId} complete. Advancing to ${mid}.`, "success");
|
|
403
|
+
const vizPrefs = prefs;
|
|
404
|
+
if (vizPrefs?.auto_visualize) {
|
|
405
|
+
ctx.ui.notify("Run /gsd visualize to see progress overview.", "info");
|
|
406
|
+
}
|
|
407
|
+
if (vizPrefs?.auto_report !== false) {
|
|
408
|
+
try {
|
|
409
|
+
await generateMilestoneReport(s, ctx, s.currentMilestoneId);
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
ctx.ui.notify(`Report generation failed: ${err instanceof Error ? err.message : String(err)}`, "warning");
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
// Reset dispatch counters for new milestone
|
|
416
|
+
s.unitDispatchCount.clear();
|
|
417
|
+
s.unitRecoveryCount.clear();
|
|
418
|
+
s.unitLifetimeDispatches.clear();
|
|
419
|
+
recentUnits.length = 0;
|
|
420
|
+
stuckRecoveryAttempts = 0;
|
|
421
|
+
// Worktree lifecycle on milestone transition — merge current, enter next
|
|
422
|
+
deps.resolver.mergeAndExit(s.currentMilestoneId, ctx.ui);
|
|
423
|
+
// Opt-in: create draft PR on milestone completion
|
|
424
|
+
if (prefs?.git?.auto_pr) {
|
|
425
|
+
try {
|
|
426
|
+
const { createDraftPR } = await import("./git-service.js");
|
|
427
|
+
const prUrl = createDraftPR(s.basePath, s.currentMilestoneId, `[GSD] ${s.currentMilestoneId} complete`, `Milestone ${s.currentMilestoneId} completed by GSD auto-mode.\n\nSee .gsd/${s.currentMilestoneId}/ for details.`);
|
|
428
|
+
if (prUrl) {
|
|
429
|
+
ctx.ui.notify(`Draft PR created: ${prUrl}`, "info");
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
// Non-fatal — PR creation is best-effort
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
deps.invalidateAllCaches();
|
|
437
|
+
state = await deps.deriveState(s.basePath);
|
|
438
|
+
mid = state.activeMilestone?.id;
|
|
439
|
+
midTitle = state.activeMilestone?.title;
|
|
440
|
+
if (mid) {
|
|
441
|
+
if (deps.getIsolationMode() !== "none") {
|
|
442
|
+
deps.captureIntegrationBranch(s.basePath, mid, {
|
|
443
|
+
commitDocs: prefs?.git?.commit_docs,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
deps.resolver.enterMilestone(mid, ctx.ui);
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
// mid is undefined — no milestone to capture integration branch for
|
|
450
|
+
}
|
|
451
|
+
const pendingIds = state.registry
|
|
452
|
+
.filter((m) => m.status !== "complete" && m.status !== "parked")
|
|
453
|
+
.map((m) => m.id);
|
|
454
|
+
deps.pruneQueueOrder(s.basePath, pendingIds);
|
|
455
|
+
}
|
|
349
456
|
if (mid) {
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
457
|
+
s.currentMilestoneId = mid;
|
|
458
|
+
deps.setActiveMilestoneId(s.basePath, mid);
|
|
459
|
+
}
|
|
460
|
+
// ── Terminal conditions ──────────────────────────────────────────────
|
|
461
|
+
if (!mid) {
|
|
462
|
+
if (s.currentUnit) {
|
|
463
|
+
await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
|
|
355
464
|
}
|
|
356
|
-
|
|
465
|
+
const incomplete = state.registry.filter((m) => m.status !== "complete" && m.status !== "parked");
|
|
466
|
+
if (incomplete.length === 0 && state.registry.length > 0) {
|
|
467
|
+
// All milestones complete — merge milestone branch before stopping
|
|
468
|
+
if (s.currentMilestoneId) {
|
|
469
|
+
deps.resolver.mergeAndExit(s.currentMilestoneId, ctx.ui);
|
|
470
|
+
// Opt-in: create draft PR on milestone completion
|
|
471
|
+
if (prefs?.git?.auto_pr) {
|
|
472
|
+
try {
|
|
473
|
+
const { createDraftPR } = await import("./git-service.js");
|
|
474
|
+
const prUrl = createDraftPR(s.basePath, s.currentMilestoneId, `[GSD] ${s.currentMilestoneId} complete`, `Milestone ${s.currentMilestoneId} completed by GSD auto-mode.\n\nSee .gsd/${s.currentMilestoneId}/ for details.`);
|
|
475
|
+
if (prUrl) {
|
|
476
|
+
ctx.ui.notify(`Draft PR created: ${prUrl}`, "info");
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
catch {
|
|
480
|
+
// Non-fatal — PR creation is best-effort
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
deps.sendDesktopNotification("GSD", "All milestones complete!", "success", "milestone");
|
|
485
|
+
deps.logCmuxEvent(prefs, "All milestones complete.", "success");
|
|
486
|
+
await deps.stopAuto(ctx, pi, "All milestones complete");
|
|
487
|
+
}
|
|
488
|
+
else if (incomplete.length === 0 && state.registry.length === 0) {
|
|
489
|
+
// Empty registry — no milestones visible, likely a path resolution bug
|
|
490
|
+
const diag = `basePath=${s.basePath}, phase=${state.phase}`;
|
|
491
|
+
ctx.ui.notify(`No milestones visible in current scope. Possible path resolution issue.\n Diagnostic: ${diag}`, "error");
|
|
492
|
+
await deps.stopAuto(ctx, pi, `No milestones found — check basePath resolution`);
|
|
493
|
+
}
|
|
494
|
+
else if (state.phase === "blocked") {
|
|
495
|
+
const blockerMsg = `Blocked: ${state.blockers.join(", ")}`;
|
|
496
|
+
await deps.stopAuto(ctx, pi, blockerMsg);
|
|
497
|
+
ctx.ui.notify(`${blockerMsg}. Fix and run /gsd auto.`, "warning");
|
|
498
|
+
deps.sendDesktopNotification("GSD", blockerMsg, "error", "attention");
|
|
499
|
+
deps.logCmuxEvent(prefs, blockerMsg, "error");
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
const ids = incomplete.map((m) => m.id).join(", ");
|
|
503
|
+
const diag = `basePath=${s.basePath}, milestones=[${state.registry.map((m) => `${m.id}:${m.status}`).join(", ")}], phase=${state.phase}`;
|
|
504
|
+
ctx.ui.notify(`Unexpected: ${incomplete.length} incomplete milestone(s) (${ids}) but no active milestone.\n Diagnostic: ${diag}`, "error");
|
|
505
|
+
await deps.stopAuto(ctx, pi, `No active milestone — ${incomplete.length} incomplete (${ids}), see diagnostic above`);
|
|
506
|
+
}
|
|
507
|
+
debugLog("autoLoop", { phase: "exit", reason: "no-active-milestone" });
|
|
508
|
+
break;
|
|
357
509
|
}
|
|
358
|
-
|
|
359
|
-
|
|
510
|
+
if (!midTitle) {
|
|
511
|
+
midTitle = mid;
|
|
512
|
+
ctx.ui.notify(`Milestone ${mid} has no title in roadmap — using ID as fallback.`, "warning");
|
|
360
513
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
.
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
514
|
+
// Mid-merge safety check
|
|
515
|
+
if (deps.reconcileMergeState(s.basePath, ctx)) {
|
|
516
|
+
deps.invalidateAllCaches();
|
|
517
|
+
state = await deps.deriveState(s.basePath);
|
|
518
|
+
mid = state.activeMilestone?.id;
|
|
519
|
+
midTitle = state.activeMilestone?.title;
|
|
520
|
+
}
|
|
521
|
+
if (!mid || !midTitle) {
|
|
522
|
+
const noMilestoneReason = !mid
|
|
523
|
+
? "No active milestone after merge reconciliation"
|
|
524
|
+
: `Milestone ${mid} has no title after reconciliation`;
|
|
525
|
+
await closeoutAndStop(ctx, pi, s, deps, noMilestoneReason);
|
|
526
|
+
debugLog("autoLoop", {
|
|
527
|
+
phase: "exit",
|
|
528
|
+
reason: "no-milestone-after-reconciliation",
|
|
529
|
+
});
|
|
530
|
+
break;
|
|
531
|
+
}
|
|
532
|
+
// Terminal: complete
|
|
533
|
+
if (state.phase === "complete") {
|
|
534
|
+
// Milestone merge on complete (before closeout so branch state is clean)
|
|
378
535
|
if (s.currentMilestoneId) {
|
|
379
536
|
deps.resolver.mergeAndExit(s.currentMilestoneId, ctx.ui);
|
|
537
|
+
// Opt-in: create draft PR on milestone completion
|
|
538
|
+
if (prefs?.git?.auto_pr) {
|
|
539
|
+
try {
|
|
540
|
+
const { createDraftPR } = await import("./git-service.js");
|
|
541
|
+
const prUrl = createDraftPR(s.basePath, s.currentMilestoneId, `[GSD] ${s.currentMilestoneId} complete`, `Milestone ${s.currentMilestoneId} completed by GSD auto-mode.\n\nSee .gsd/${s.currentMilestoneId}/ for details.`);
|
|
542
|
+
if (prUrl) {
|
|
543
|
+
ctx.ui.notify(`Draft PR created: ${prUrl}`, "info");
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
catch {
|
|
547
|
+
// Non-fatal — PR creation is best-effort
|
|
548
|
+
}
|
|
549
|
+
}
|
|
380
550
|
}
|
|
381
|
-
deps.sendDesktopNotification("GSD",
|
|
382
|
-
deps.logCmuxEvent(
|
|
383
|
-
await
|
|
551
|
+
deps.sendDesktopNotification("GSD", `Milestone ${mid} complete!`, "success", "milestone");
|
|
552
|
+
deps.logCmuxEvent(prefs, `Milestone ${mid} complete.`, "success");
|
|
553
|
+
await closeoutAndStop(ctx, pi, s, deps, `Milestone ${mid} complete`);
|
|
554
|
+
debugLog("autoLoop", { phase: "exit", reason: "milestone-complete" });
|
|
555
|
+
break;
|
|
384
556
|
}
|
|
385
|
-
|
|
557
|
+
// Terminal: blocked
|
|
558
|
+
if (state.phase === "blocked") {
|
|
386
559
|
const blockerMsg = `Blocked: ${state.blockers.join(", ")}`;
|
|
387
|
-
await
|
|
560
|
+
await closeoutAndStop(ctx, pi, s, deps, blockerMsg);
|
|
388
561
|
ctx.ui.notify(`${blockerMsg}. Fix and run /gsd auto.`, "warning");
|
|
389
562
|
deps.sendDesktopNotification("GSD", blockerMsg, "error", "attention");
|
|
390
|
-
deps.logCmuxEvent(
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
const ids = incomplete.map((m) => m.id).join(", ");
|
|
394
|
-
const diag = `basePath=${s.basePath}, milestones=[${state.registry.map((m) => `${m.id}:${m.status}`).join(", ")}], phase=${state.phase}`;
|
|
395
|
-
ctx.ui.notify(`Unexpected: ${incomplete.length} incomplete milestone(s) (${ids}) but no active milestone.\n Diagnostic: ${diag}`, "error");
|
|
396
|
-
await deps.stopAuto(ctx, pi, `No active milestone — ${incomplete.length} incomplete (${ids}), see diagnostic above`);
|
|
563
|
+
deps.logCmuxEvent(prefs, blockerMsg, "error");
|
|
564
|
+
debugLog("autoLoop", { phase: "exit", reason: "blocked" });
|
|
565
|
+
break;
|
|
397
566
|
}
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
567
|
+
// ── Phase 2: Guards ─────────────────────────────────────────────────
|
|
568
|
+
// Budget ceiling guard
|
|
569
|
+
const budgetCeiling = prefs?.budget_ceiling;
|
|
570
|
+
if (budgetCeiling !== undefined && budgetCeiling > 0) {
|
|
571
|
+
const currentLedger = deps.getLedger();
|
|
572
|
+
const totalCost = currentLedger
|
|
573
|
+
? deps.getProjectTotals(currentLedger.units).cost
|
|
574
|
+
: 0;
|
|
575
|
+
const budgetPct = totalCost / budgetCeiling;
|
|
576
|
+
const budgetAlertLevel = deps.getBudgetAlertLevel(budgetPct);
|
|
577
|
+
const newBudgetAlertLevel = deps.getNewBudgetAlertLevel(s.lastBudgetAlertLevel, budgetPct);
|
|
578
|
+
const enforcement = prefs?.budget_enforcement ?? "pause";
|
|
579
|
+
const budgetEnforcementAction = deps.getBudgetEnforcementAction(enforcement, budgetPct);
|
|
580
|
+
// Data-driven threshold check — loop descending, fire first match
|
|
581
|
+
const threshold = BUDGET_THRESHOLDS.find((t) => newBudgetAlertLevel >= t.pct);
|
|
582
|
+
if (threshold) {
|
|
583
|
+
s.lastBudgetAlertLevel =
|
|
584
|
+
newBudgetAlertLevel;
|
|
585
|
+
if (threshold.pct === 100 && budgetEnforcementAction !== "none") {
|
|
586
|
+
// 100% — special enforcement logic (halt/pause/warn)
|
|
587
|
+
const msg = `Budget ceiling ${deps.formatCost(budgetCeiling)} reached (spent ${deps.formatCost(totalCost)}).`;
|
|
588
|
+
if (budgetEnforcementAction === "halt") {
|
|
589
|
+
deps.sendDesktopNotification("GSD", msg, "error", "budget");
|
|
590
|
+
await deps.stopAuto(ctx, pi, "Budget ceiling reached");
|
|
591
|
+
debugLog("autoLoop", { phase: "exit", reason: "budget-halt" });
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
if (budgetEnforcementAction === "pause") {
|
|
595
|
+
ctx.ui.notify(`${msg} Pausing auto-mode — /gsd auto to override and continue.`, "warning");
|
|
596
|
+
deps.sendDesktopNotification("GSD", msg, "warning", "budget");
|
|
597
|
+
deps.logCmuxEvent(prefs, msg, "warning");
|
|
598
|
+
await deps.pauseAuto(ctx, pi);
|
|
599
|
+
debugLog("autoLoop", { phase: "exit", reason: "budget-pause" });
|
|
600
|
+
break;
|
|
601
|
+
}
|
|
602
|
+
ctx.ui.notify(`${msg} Continuing (enforcement: warn).`, "warning");
|
|
603
|
+
deps.sendDesktopNotification("GSD", msg, "warning", "budget");
|
|
604
|
+
deps.logCmuxEvent(prefs, msg, "warning");
|
|
605
|
+
}
|
|
606
|
+
else if (threshold.pct < 100) {
|
|
607
|
+
// Sub-100% — simple notification
|
|
608
|
+
const msg = `${threshold.label}: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`;
|
|
609
|
+
ctx.ui.notify(msg, threshold.notifyLevel);
|
|
610
|
+
deps.sendDesktopNotification("GSD", msg, threshold.notifyLevel, "budget");
|
|
611
|
+
deps.logCmuxEvent(prefs, msg, threshold.cmuxLevel);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
else if (budgetAlertLevel === 0) {
|
|
615
|
+
s.lastBudgetAlertLevel = 0;
|
|
616
|
+
}
|
|
430
617
|
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
deps.resolver.mergeAndExit(s.currentMilestoneId, ctx.ui);
|
|
618
|
+
else {
|
|
619
|
+
s.lastBudgetAlertLevel = 0;
|
|
434
620
|
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
}
|
|
446
|
-
const blockerMsg = `Blocked: ${state.blockers.join(", ")}`;
|
|
447
|
-
await deps.stopAuto(ctx, pi, blockerMsg);
|
|
448
|
-
ctx.ui.notify(`${blockerMsg}. Fix and run /gsd auto.`, "warning");
|
|
449
|
-
deps.sendDesktopNotification("GSD", blockerMsg, "error", "attention");
|
|
450
|
-
deps.logCmuxEvent(deps.loadEffectiveGSDPreferences()?.preferences, blockerMsg, "error");
|
|
451
|
-
debugLog("autoLoop", { phase: "exit", reason: "blocked" });
|
|
452
|
-
break;
|
|
453
|
-
}
|
|
454
|
-
// ── Phase 2: Guards ─────────────────────────────────────────────────
|
|
455
|
-
const prefs = deps.loadEffectiveGSDPreferences()?.preferences;
|
|
456
|
-
// Budget ceiling guard
|
|
457
|
-
const budgetCeiling = prefs?.budget_ceiling;
|
|
458
|
-
if (budgetCeiling !== undefined && budgetCeiling > 0) {
|
|
459
|
-
const currentLedger = deps.getLedger();
|
|
460
|
-
const totalCost = currentLedger
|
|
461
|
-
? deps.getProjectTotals(currentLedger.units).cost
|
|
462
|
-
: 0;
|
|
463
|
-
const budgetPct = totalCost / budgetCeiling;
|
|
464
|
-
const budgetAlertLevel = deps.getBudgetAlertLevel(budgetPct);
|
|
465
|
-
const newBudgetAlertLevel = deps.getNewBudgetAlertLevel(s.lastBudgetAlertLevel, budgetPct);
|
|
466
|
-
const enforcement = prefs?.budget_enforcement ?? "pause";
|
|
467
|
-
const budgetEnforcementAction = deps.getBudgetEnforcementAction(enforcement, budgetPct);
|
|
468
|
-
if (newBudgetAlertLevel === 100 && budgetEnforcementAction !== "none") {
|
|
469
|
-
const msg = `Budget ceiling ${deps.formatCost(budgetCeiling)} reached (spent ${deps.formatCost(totalCost)}).`;
|
|
470
|
-
s.lastBudgetAlertLevel =
|
|
471
|
-
newBudgetAlertLevel;
|
|
472
|
-
if (budgetEnforcementAction === "halt") {
|
|
473
|
-
deps.sendDesktopNotification("GSD", msg, "error", "budget");
|
|
474
|
-
await deps.stopAuto(ctx, pi, "Budget ceiling reached");
|
|
475
|
-
debugLog("autoLoop", { phase: "exit", reason: "budget-halt" });
|
|
476
|
-
break;
|
|
477
|
-
}
|
|
478
|
-
if (budgetEnforcementAction === "pause") {
|
|
479
|
-
ctx.ui.notify(`${msg} Pausing auto-mode — /gsd auto to override and continue.`, "warning");
|
|
480
|
-
deps.sendDesktopNotification("GSD", msg, "warning", "budget");
|
|
481
|
-
deps.logCmuxEvent(prefs, msg, "warning");
|
|
621
|
+
// Context window guard
|
|
622
|
+
const contextThreshold = prefs?.context_pause_threshold ?? 0;
|
|
623
|
+
if (contextThreshold > 0 && s.cmdCtx) {
|
|
624
|
+
const contextUsage = s.cmdCtx.getContextUsage();
|
|
625
|
+
if (contextUsage &&
|
|
626
|
+
contextUsage.percent !== null &&
|
|
627
|
+
contextUsage.percent >= contextThreshold) {
|
|
628
|
+
const msg = `Context window at ${contextUsage.percent}% (threshold: ${contextThreshold}%). Pausing to prevent truncated output.`;
|
|
629
|
+
ctx.ui.notify(`${msg} Run /gsd auto to continue (will start fresh session).`, "warning");
|
|
630
|
+
deps.sendDesktopNotification("GSD", `Context ${contextUsage.percent}% — paused`, "warning", "attention");
|
|
482
631
|
await deps.pauseAuto(ctx, pi);
|
|
483
|
-
debugLog("autoLoop", { phase: "exit", reason: "
|
|
632
|
+
debugLog("autoLoop", { phase: "exit", reason: "context-window" });
|
|
484
633
|
break;
|
|
485
634
|
}
|
|
486
|
-
ctx.ui.notify(`${msg} Continuing (enforcement: warn).`, "warning");
|
|
487
|
-
deps.sendDesktopNotification("GSD", msg, "warning", "budget");
|
|
488
|
-
deps.logCmuxEvent(prefs, msg, "warning");
|
|
489
|
-
}
|
|
490
|
-
else if (newBudgetAlertLevel === 90) {
|
|
491
|
-
s.lastBudgetAlertLevel =
|
|
492
|
-
newBudgetAlertLevel;
|
|
493
|
-
ctx.ui.notify(`Budget 90%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "warning");
|
|
494
|
-
deps.sendDesktopNotification("GSD", `Budget 90%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "warning", "budget");
|
|
495
|
-
deps.logCmuxEvent(prefs, `Budget 90%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "warning");
|
|
496
|
-
}
|
|
497
|
-
else if (newBudgetAlertLevel === 80) {
|
|
498
|
-
s.lastBudgetAlertLevel =
|
|
499
|
-
newBudgetAlertLevel;
|
|
500
|
-
ctx.ui.notify(`Approaching budget ceiling — 80%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "warning");
|
|
501
|
-
deps.sendDesktopNotification("GSD", `Approaching budget ceiling — 80%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "warning", "budget");
|
|
502
|
-
deps.logCmuxEvent(prefs, `Budget 80%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "warning");
|
|
503
|
-
}
|
|
504
|
-
else if (newBudgetAlertLevel === 75) {
|
|
505
|
-
s.lastBudgetAlertLevel =
|
|
506
|
-
newBudgetAlertLevel;
|
|
507
|
-
ctx.ui.notify(`Budget 75%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "info");
|
|
508
|
-
deps.sendDesktopNotification("GSD", `Budget 75%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "info", "budget");
|
|
509
|
-
deps.logCmuxEvent(prefs, `Budget 75%: ${deps.formatCost(totalCost)} / ${deps.formatCost(budgetCeiling)}`, "progress");
|
|
510
|
-
}
|
|
511
|
-
else if (budgetAlertLevel === 0) {
|
|
512
|
-
s.lastBudgetAlertLevel = 0;
|
|
513
635
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
await deps.pauseAuto(ctx, pi);
|
|
529
|
-
debugLog("autoLoop", { phase: "exit", reason: "context-window" });
|
|
530
|
-
break;
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
// Secrets re-check gate
|
|
534
|
-
try {
|
|
535
|
-
const manifestStatus = await deps.getManifestStatus(s.basePath, mid, s.originalBasePath);
|
|
536
|
-
if (manifestStatus && manifestStatus.pending.length > 0) {
|
|
537
|
-
const result = await deps.collectSecretsFromManifest(s.basePath, mid, ctx);
|
|
538
|
-
if (result &&
|
|
539
|
-
result.applied &&
|
|
540
|
-
result.skipped &&
|
|
541
|
-
result.existingSkipped) {
|
|
542
|
-
ctx.ui.notify(`Secrets collected: ${result.applied.length} applied, ${result.skipped.length} skipped, ${result.existingSkipped.length} already set.`, "info");
|
|
543
|
-
}
|
|
544
|
-
else {
|
|
545
|
-
ctx.ui.notify("Secrets collection skipped.", "info");
|
|
636
|
+
// Secrets re-check gate
|
|
637
|
+
try {
|
|
638
|
+
const manifestStatus = await deps.getManifestStatus(s.basePath, mid, s.originalBasePath);
|
|
639
|
+
if (manifestStatus && manifestStatus.pending.length > 0) {
|
|
640
|
+
const result = await deps.collectSecretsFromManifest(s.basePath, mid, ctx);
|
|
641
|
+
if (result &&
|
|
642
|
+
result.applied &&
|
|
643
|
+
result.skipped &&
|
|
644
|
+
result.existingSkipped) {
|
|
645
|
+
ctx.ui.notify(`Secrets collected: ${result.applied.length} applied, ${result.skipped.length} skipped, ${result.existingSkipped.length} already set.`, "info");
|
|
646
|
+
}
|
|
647
|
+
else {
|
|
648
|
+
ctx.ui.notify("Secrets collection skipped.", "info");
|
|
649
|
+
}
|
|
546
650
|
}
|
|
547
651
|
}
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
ctx.ui.notify(`Secrets collection error: ${err instanceof Error ? err.message : String(err)}. Continuing with next task.`, "warning");
|
|
551
|
-
}
|
|
552
|
-
// ── Phase 3: Dispatch resolution ────────────────────────────────────
|
|
553
|
-
debugLog("autoLoop", { phase: "dispatch-resolve", iteration });
|
|
554
|
-
const dispatchResult = await deps.resolveDispatch({
|
|
555
|
-
basePath: s.basePath,
|
|
556
|
-
mid,
|
|
557
|
-
midTitle: midTitle,
|
|
558
|
-
state,
|
|
559
|
-
prefs,
|
|
560
|
-
});
|
|
561
|
-
if (dispatchResult.action === "stop") {
|
|
562
|
-
if (s.currentUnit) {
|
|
563
|
-
await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
|
|
652
|
+
catch (err) {
|
|
653
|
+
ctx.ui.notify(`Secrets collection error: ${err instanceof Error ? err.message : String(err)}. Continuing with next task.`, "warning");
|
|
564
654
|
}
|
|
565
|
-
|
|
566
|
-
debugLog("autoLoop", { phase: "
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
let unitType = dispatchResult.unitType;
|
|
575
|
-
let unitId = dispatchResult.unitId;
|
|
576
|
-
let prompt = dispatchResult.prompt;
|
|
577
|
-
const pauseAfterUatDispatch = dispatchResult.pauseAfterDispatch ?? false;
|
|
578
|
-
// ── Same-unit stuck counter with graduated recovery ──
|
|
579
|
-
const derivedKey = `${unitType}/${unitId}`;
|
|
580
|
-
if (derivedKey === lastDerivedUnit && !s.pendingVerificationRetry) {
|
|
581
|
-
sameUnitCount++;
|
|
582
|
-
debugLog("autoLoop", {
|
|
583
|
-
phase: "stuck-check",
|
|
584
|
-
unitType,
|
|
585
|
-
unitId,
|
|
586
|
-
sameUnitCount,
|
|
655
|
+
// ── Phase 3: Dispatch resolution ────────────────────────────────────
|
|
656
|
+
debugLog("autoLoop", { phase: "dispatch-resolve", iteration });
|
|
657
|
+
const dispatchResult = await deps.resolveDispatch({
|
|
658
|
+
basePath: s.basePath,
|
|
659
|
+
mid,
|
|
660
|
+
midTitle: midTitle,
|
|
661
|
+
state,
|
|
662
|
+
prefs,
|
|
663
|
+
session: s,
|
|
587
664
|
});
|
|
588
|
-
if (
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
665
|
+
if (dispatchResult.action === "stop") {
|
|
666
|
+
await closeoutAndStop(ctx, pi, s, deps, dispatchResult.reason);
|
|
667
|
+
debugLog("autoLoop", { phase: "exit", reason: "dispatch-stop" });
|
|
668
|
+
break;
|
|
669
|
+
}
|
|
670
|
+
if (dispatchResult.action !== "dispatch") {
|
|
671
|
+
// Non-dispatch action (e.g. "skip") — re-derive state
|
|
672
|
+
await new Promise((r) => setImmediate(r));
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
unitType = dispatchResult.unitType;
|
|
676
|
+
unitId = dispatchResult.unitId;
|
|
677
|
+
prompt = dispatchResult.prompt;
|
|
678
|
+
pauseAfterUatDispatch = dispatchResult.pauseAfterDispatch ?? false;
|
|
679
|
+
// ── Sliding-window stuck detection with graduated recovery ──
|
|
680
|
+
const derivedKey = `${unitType}/${unitId}`;
|
|
681
|
+
if (!s.pendingVerificationRetry) {
|
|
682
|
+
recentUnits.push({ key: derivedKey });
|
|
683
|
+
if (recentUnits.length > STUCK_WINDOW_SIZE)
|
|
684
|
+
recentUnits.shift();
|
|
685
|
+
const stuckSignal = detectStuck(recentUnits);
|
|
686
|
+
if (stuckSignal) {
|
|
592
687
|
debugLog("autoLoop", {
|
|
593
|
-
phase: "stuck-
|
|
594
|
-
|
|
595
|
-
|
|
688
|
+
phase: "stuck-check",
|
|
689
|
+
unitType,
|
|
690
|
+
unitId,
|
|
691
|
+
reason: stuckSignal.reason,
|
|
692
|
+
recoveryAttempts: stuckRecoveryAttempts,
|
|
596
693
|
});
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
694
|
+
if (stuckRecoveryAttempts === 0) {
|
|
695
|
+
// Level 1: try verifying the artifact, then cache invalidation + retry
|
|
696
|
+
stuckRecoveryAttempts++;
|
|
697
|
+
const artifactExists = deps.verifyExpectedArtifact(unitType, unitId, s.basePath);
|
|
698
|
+
if (artifactExists) {
|
|
699
|
+
debugLog("autoLoop", {
|
|
700
|
+
phase: "stuck-recovery",
|
|
701
|
+
level: 1,
|
|
702
|
+
action: "artifact-found",
|
|
703
|
+
});
|
|
704
|
+
ctx.ui.notify(`Stuck recovery: artifact for ${unitType} ${unitId} found on disk. Invalidating caches.`, "info");
|
|
705
|
+
deps.invalidateAllCaches();
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
ctx.ui.notify(`Stuck on ${unitType} ${unitId} (${stuckSignal.reason}). Invalidating caches and retrying.`, "warning");
|
|
709
|
+
deps.invalidateAllCaches();
|
|
710
|
+
}
|
|
711
|
+
else {
|
|
712
|
+
// Level 2: hard stop — genuinely stuck
|
|
713
|
+
debugLog("autoLoop", {
|
|
714
|
+
phase: "stuck-detected",
|
|
715
|
+
unitType,
|
|
716
|
+
unitId,
|
|
717
|
+
reason: stuckSignal.reason,
|
|
718
|
+
});
|
|
719
|
+
await deps.stopAuto(ctx, pi, `Stuck: ${stuckSignal.reason}`);
|
|
720
|
+
ctx.ui.notify(`Stuck on ${unitType} ${unitId} — ${stuckSignal.reason}. The expected artifact was not written.`, "error");
|
|
721
|
+
break;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
else {
|
|
725
|
+
// Progress detected — reset recovery counter
|
|
726
|
+
if (stuckRecoveryAttempts > 0) {
|
|
727
|
+
debugLog("autoLoop", {
|
|
728
|
+
phase: "stuck-counter-reset",
|
|
729
|
+
from: recentUnits[recentUnits.length - 2]?.key ?? "",
|
|
730
|
+
to: derivedKey,
|
|
731
|
+
});
|
|
732
|
+
stuckRecoveryAttempts = 0;
|
|
733
|
+
}
|
|
600
734
|
}
|
|
601
|
-
ctx.ui.notify(`Stuck on ${unitType} ${unitId} (attempt ${sameUnitCount}). Invalidating caches and retrying.`, "warning");
|
|
602
|
-
deps.invalidateAllCaches();
|
|
603
735
|
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
736
|
+
// Pre-dispatch hooks
|
|
737
|
+
const preDispatchResult = deps.runPreDispatchHooks(unitType, unitId, prompt, s.basePath);
|
|
738
|
+
if (preDispatchResult.firedHooks.length > 0) {
|
|
739
|
+
ctx.ui.notify(`Pre-dispatch hook${preDispatchResult.firedHooks.length > 1 ? "s" : ""}: ${preDispatchResult.firedHooks.join(", ")}`, "info");
|
|
740
|
+
}
|
|
741
|
+
if (preDispatchResult.action === "skip") {
|
|
742
|
+
ctx.ui.notify(`Skipping ${unitType} ${unitId} (pre-dispatch hook).`, "info");
|
|
743
|
+
await new Promise((r) => setImmediate(r));
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (preDispatchResult.action === "replace") {
|
|
747
|
+
prompt = preDispatchResult.prompt ?? prompt;
|
|
748
|
+
if (preDispatchResult.unitType)
|
|
749
|
+
unitType = preDispatchResult.unitType;
|
|
750
|
+
}
|
|
751
|
+
else if (preDispatchResult.prompt) {
|
|
752
|
+
prompt = preDispatchResult.prompt;
|
|
753
|
+
}
|
|
754
|
+
const priorSliceBlocker = deps.getPriorSliceCompletionBlocker(s.basePath, deps.getMainBranch(s.basePath), unitType, unitId);
|
|
755
|
+
if (priorSliceBlocker) {
|
|
756
|
+
await deps.stopAuto(ctx, pi, priorSliceBlocker);
|
|
757
|
+
debugLog("autoLoop", { phase: "exit", reason: "prior-slice-blocker" });
|
|
614
758
|
break;
|
|
615
759
|
}
|
|
760
|
+
observabilityIssues = await deps.collectObservabilityWarnings(ctx, s.basePath, unitType, unitId);
|
|
761
|
+
// Derive state for shared use in execution phase
|
|
762
|
+
// (state, mid, midTitle already set above)
|
|
616
763
|
}
|
|
617
764
|
else {
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
sameUnitCount = 0;
|
|
627
|
-
}
|
|
628
|
-
// Pre-dispatch hooks
|
|
629
|
-
const preDispatchResult = deps.runPreDispatchHooks(unitType, unitId, prompt, s.basePath);
|
|
630
|
-
if (preDispatchResult.firedHooks.length > 0) {
|
|
631
|
-
ctx.ui.notify(`Pre-dispatch hook${preDispatchResult.firedHooks.length > 1 ? "s" : ""}: ${preDispatchResult.firedHooks.join(", ")}`, "info");
|
|
632
|
-
}
|
|
633
|
-
if (preDispatchResult.action === "skip") {
|
|
634
|
-
ctx.ui.notify(`Skipping ${unitType} ${unitId} (pre-dispatch hook).`, "info");
|
|
635
|
-
await new Promise((r) => setImmediate(r));
|
|
636
|
-
continue;
|
|
637
|
-
}
|
|
638
|
-
if (preDispatchResult.action === "replace") {
|
|
639
|
-
prompt = preDispatchResult.prompt ?? prompt;
|
|
640
|
-
if (preDispatchResult.unitType)
|
|
641
|
-
unitType = preDispatchResult.unitType;
|
|
642
|
-
}
|
|
643
|
-
else if (preDispatchResult.prompt) {
|
|
644
|
-
prompt = preDispatchResult.prompt;
|
|
645
|
-
}
|
|
646
|
-
const priorSliceBlocker = deps.getPriorSliceCompletionBlocker(s.basePath, deps.getMainBranch(s.basePath), unitType, unitId);
|
|
647
|
-
if (priorSliceBlocker) {
|
|
648
|
-
await deps.stopAuto(ctx, pi, priorSliceBlocker);
|
|
649
|
-
debugLog("autoLoop", { phase: "exit", reason: "prior-slice-blocker" });
|
|
650
|
-
break;
|
|
765
|
+
// ── Sidecar path: use values from the sidecar item directly ──
|
|
766
|
+
unitType = sidecarItem.unitType;
|
|
767
|
+
unitId = sidecarItem.unitId;
|
|
768
|
+
prompt = sidecarItem.prompt;
|
|
769
|
+
// Derive minimal state for progress widget / execution context
|
|
770
|
+
state = await deps.deriveState(s.basePath);
|
|
771
|
+
mid = state.activeMilestone?.id;
|
|
772
|
+
midTitle = state.activeMilestone?.title;
|
|
651
773
|
}
|
|
652
|
-
const observabilityIssues = await deps.collectObservabilityWarnings(ctx, s.basePath, unitType, unitId);
|
|
653
774
|
// ── Phase 4: Unit execution ─────────────────────────────────────────
|
|
654
775
|
debugLog("autoLoop", {
|
|
655
776
|
phase: "unit-execution",
|
|
@@ -662,33 +783,6 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
662
783
|
s.currentUnit.type === unitType &&
|
|
663
784
|
s.currentUnit.id === unitId);
|
|
664
785
|
const previousTier = s.currentUnitRouting?.tier;
|
|
665
|
-
// Closeout previous unit
|
|
666
|
-
if (s.currentUnit) {
|
|
667
|
-
await deps.closeoutUnit(ctx, s.basePath, s.currentUnit.type, s.currentUnit.id, s.currentUnit.startedAt, deps.buildSnapshotOpts(s.currentUnit.type, s.currentUnit.id));
|
|
668
|
-
if (s.currentUnitRouting) {
|
|
669
|
-
const isRetry = s.currentUnit.type === unitType && s.currentUnit.id === unitId;
|
|
670
|
-
deps.recordOutcome(s.currentUnit.type, s.currentUnitRouting.tier, !isRetry);
|
|
671
|
-
}
|
|
672
|
-
const closeoutKey = `${s.currentUnit.type}/${s.currentUnit.id}`;
|
|
673
|
-
const incomingKey = `${unitType}/${unitId}`;
|
|
674
|
-
const isHookUnit = s.currentUnit.type.startsWith("hook/");
|
|
675
|
-
const artifactVerified = isHookUnit ||
|
|
676
|
-
deps.verifyExpectedArtifact(s.currentUnit.type, s.currentUnit.id, s.basePath);
|
|
677
|
-
if (closeoutKey !== incomingKey && artifactVerified) {
|
|
678
|
-
s.completedUnits.push({
|
|
679
|
-
type: s.currentUnit.type,
|
|
680
|
-
id: s.currentUnit.id,
|
|
681
|
-
startedAt: s.currentUnit.startedAt,
|
|
682
|
-
finishedAt: Date.now(),
|
|
683
|
-
});
|
|
684
|
-
if (s.completedUnits.length > 200) {
|
|
685
|
-
s.completedUnits = s.completedUnits.slice(-200);
|
|
686
|
-
}
|
|
687
|
-
deps.clearUnitRuntimeRecord(s.basePath, s.currentUnit.type, s.currentUnit.id);
|
|
688
|
-
s.unitDispatchCount.delete(`${s.currentUnit.type}/${s.currentUnit.id}`);
|
|
689
|
-
s.unitRecoveryCount.delete(`${s.currentUnit.type}/${s.currentUnit.id}`);
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
786
|
s.currentUnit = { type: unitType, id: unitId, startedAt: Date.now() };
|
|
693
787
|
deps.captureAvailableSkills();
|
|
694
788
|
deps.writeUnitRuntimeRecord(s.basePath, unitType, unitId, s.currentUnit.startedAt, {
|
|
@@ -706,7 +800,6 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
706
800
|
deps.updateProgressWidget(ctx, unitType, unitId, state);
|
|
707
801
|
deps.ensurePreconditions(unitType, unitId, s.basePath, state);
|
|
708
802
|
// Prompt injection
|
|
709
|
-
const MAX_RECOVERY_CHARS = 50_000;
|
|
710
803
|
let finalPrompt = prompt;
|
|
711
804
|
if (s.pendingVerificationRetry) {
|
|
712
805
|
const retryCtx = s.pendingVerificationRetry;
|
|
@@ -744,7 +837,7 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
744
837
|
s.lastBaselineCharCount = undefined;
|
|
745
838
|
if (deps.isDbAvailable()) {
|
|
746
839
|
try {
|
|
747
|
-
const { inlineGsdRootFile } = await import
|
|
840
|
+
const { inlineGsdRootFile } = await importExtensionModule(import.meta.url, "./auto-prompts.js");
|
|
748
841
|
const [decisionsContent, requirementsContent, projectContent] = await Promise.all([
|
|
749
842
|
inlineGsdRootFile(s.basePath, "decisions.md", "Decisions"),
|
|
750
843
|
inlineGsdRootFile(s.basePath, "requirements.md", "Requirements"),
|
|
@@ -767,8 +860,8 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
767
860
|
const msg = reorderErr instanceof Error ? reorderErr.message : String(reorderErr);
|
|
768
861
|
process.stderr.write(`[gsd] prompt reorder failed (non-fatal): ${msg}\n`);
|
|
769
862
|
}
|
|
770
|
-
// Select and apply model (with tier escalation on retry)
|
|
771
|
-
const modelResult = await deps.selectAndApplyModel(ctx, pi, unitType, unitId, s.basePath, prefs, s.verbose, s.autoModeStartModel, { isRetry, previousTier });
|
|
863
|
+
// Select and apply model (with tier escalation on retry — normal units only)
|
|
864
|
+
const modelResult = await deps.selectAndApplyModel(ctx, pi, unitType, unitId, s.basePath, prefs, s.verbose, s.autoModeStartModel, sidecarItem ? undefined : { isRetry, previousTier });
|
|
772
865
|
s.currentUnitRouting =
|
|
773
866
|
modelResult.routing;
|
|
774
867
|
// Start unit supervision
|
|
@@ -794,7 +887,7 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
794
887
|
unitType,
|
|
795
888
|
unitId,
|
|
796
889
|
});
|
|
797
|
-
const unitResult = await runUnit(ctx, pi, s, unitType, unitId, finalPrompt
|
|
890
|
+
const unitResult = await runUnit(ctx, pi, s, unitType, unitId, finalPrompt);
|
|
798
891
|
debugLog("autoLoop", {
|
|
799
892
|
phase: "runUnit-end",
|
|
800
893
|
iteration,
|
|
@@ -802,12 +895,60 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
802
895
|
unitId,
|
|
803
896
|
status: unitResult.status,
|
|
804
897
|
});
|
|
898
|
+
// Tag the most recent window entry with error info for stuck detection
|
|
899
|
+
if (unitResult.status === "error" || unitResult.status === "cancelled") {
|
|
900
|
+
const lastEntry = recentUnits[recentUnits.length - 1];
|
|
901
|
+
if (lastEntry) {
|
|
902
|
+
lastEntry.error = `${unitResult.status}:${unitType}/${unitId}`;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
else if (unitResult.event?.messages?.length) {
|
|
906
|
+
const lastMsg = unitResult.event.messages[unitResult.event.messages.length - 1];
|
|
907
|
+
const msgStr = typeof lastMsg === "string" ? lastMsg : JSON.stringify(lastMsg);
|
|
908
|
+
if (/error|fail|exception/i.test(msgStr)) {
|
|
909
|
+
const lastEntry = recentUnits[recentUnits.length - 1];
|
|
910
|
+
if (lastEntry) {
|
|
911
|
+
lastEntry.error = msgStr.slice(0, 200);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
}
|
|
805
915
|
if (unitResult.status === "cancelled") {
|
|
806
916
|
ctx.ui.notify(`Session creation timed out or was cancelled for ${unitType} ${unitId}. Will retry.`, "warning");
|
|
807
917
|
await deps.stopAuto(ctx, pi, "Session creation failed");
|
|
808
918
|
debugLog("autoLoop", { phase: "exit", reason: "session-failed" });
|
|
809
919
|
break;
|
|
810
920
|
}
|
|
921
|
+
// ── Immediate unit closeout (metrics, activity log, memory) ────────
|
|
922
|
+
// Run right after runUnit() returns so telemetry is never lost to a
|
|
923
|
+
// crash between iterations.
|
|
924
|
+
await deps.closeoutUnit(ctx, s.basePath, unitType, unitId, s.currentUnit.startedAt, deps.buildSnapshotOpts(unitType, unitId));
|
|
925
|
+
if (s.currentUnitRouting) {
|
|
926
|
+
deps.recordOutcome(unitType, s.currentUnitRouting.tier, true);
|
|
927
|
+
}
|
|
928
|
+
const isHookUnit = unitType.startsWith("hook/");
|
|
929
|
+
const artifactVerified = isHookUnit ||
|
|
930
|
+
deps.verifyExpectedArtifact(unitType, unitId, s.basePath);
|
|
931
|
+
if (artifactVerified) {
|
|
932
|
+
s.completedUnits.push({
|
|
933
|
+
type: unitType,
|
|
934
|
+
id: unitId,
|
|
935
|
+
startedAt: s.currentUnit.startedAt,
|
|
936
|
+
finishedAt: Date.now(),
|
|
937
|
+
});
|
|
938
|
+
if (s.completedUnits.length > 200) {
|
|
939
|
+
s.completedUnits = s.completedUnits.slice(-200);
|
|
940
|
+
}
|
|
941
|
+
// Flush completed-units to disk so the record survives crashes
|
|
942
|
+
try {
|
|
943
|
+
const completedKeysPath = join(gsdRoot(s.basePath), "completed-units.json");
|
|
944
|
+
const keys = s.completedUnits.map((u) => `${u.type}/${u.id}`);
|
|
945
|
+
atomicWriteSync(completedKeysPath, JSON.stringify(keys, null, 2));
|
|
946
|
+
}
|
|
947
|
+
catch { /* non-fatal: disk flush failure */ }
|
|
948
|
+
deps.clearUnitRuntimeRecord(s.basePath, unitType, unitId);
|
|
949
|
+
s.unitDispatchCount.delete(`${unitType}/${unitId}`);
|
|
950
|
+
s.unitRecoveryCount.delete(`${unitType}/${unitId}`);
|
|
951
|
+
}
|
|
811
952
|
// ── Phase 5: Finalize ───────────────────────────────────────────────
|
|
812
953
|
debugLog("autoLoop", { phase: "finalize", iteration });
|
|
813
954
|
// Clear unit timeout (unit completed)
|
|
@@ -824,7 +965,13 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
824
965
|
updateProgressWidget: deps.updateProgressWidget,
|
|
825
966
|
};
|
|
826
967
|
// Pre-verification processing (commit, doctor, state rebuild, etc.)
|
|
827
|
-
|
|
968
|
+
// Sidecar items use lightweight pre-verification opts
|
|
969
|
+
const preVerificationOpts = sidecarItem
|
|
970
|
+
? sidecarItem.kind === "hook"
|
|
971
|
+
? { skipSettleDelay: true, skipDoctor: true, skipStateRebuild: true, skipWorktreeSync: true }
|
|
972
|
+
: { skipSettleDelay: true, skipStateRebuild: true }
|
|
973
|
+
: undefined;
|
|
974
|
+
const preResult = await deps.postUnitPreVerification(postUnitCtx, preVerificationOpts);
|
|
828
975
|
if (preResult === "dispatched") {
|
|
829
976
|
debugLog("autoLoop", {
|
|
830
977
|
phase: "exit",
|
|
@@ -838,17 +985,28 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
838
985
|
debugLog("autoLoop", { phase: "exit", reason: "uat-pause" });
|
|
839
986
|
break;
|
|
840
987
|
}
|
|
841
|
-
// Verification gate
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
988
|
+
// Verification gate
|
|
989
|
+
// Hook sidecar items skip verification entirely.
|
|
990
|
+
// Non-hook sidecar items run verification but skip retries (just continue).
|
|
991
|
+
const skipVerification = sidecarItem?.kind === "hook";
|
|
992
|
+
if (!skipVerification) {
|
|
993
|
+
const verificationResult = await deps.runPostUnitVerification({ s, ctx, pi }, deps.pauseAuto);
|
|
994
|
+
if (verificationResult === "pause") {
|
|
995
|
+
debugLog("autoLoop", { phase: "exit", reason: "verification-pause" });
|
|
996
|
+
break;
|
|
997
|
+
}
|
|
998
|
+
if (verificationResult === "retry") {
|
|
999
|
+
if (sidecarItem) {
|
|
1000
|
+
// Sidecar verification retries are skipped — just continue
|
|
1001
|
+
debugLog("autoLoop", { phase: "sidecar-verification-retry-skipped", iteration });
|
|
1002
|
+
}
|
|
1003
|
+
else {
|
|
1004
|
+
// s.pendingVerificationRetry was set by runPostUnitVerification.
|
|
1005
|
+
// Continue the loop — next iteration will inject the retry context into the prompt.
|
|
1006
|
+
debugLog("autoLoop", { phase: "verification-retry", iteration });
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
852
1010
|
}
|
|
853
1011
|
// Post-verification processing (DB dual-write, hooks, triage, quick-tasks)
|
|
854
1012
|
const postResult = await deps.postUnitPostVerification(postUnitCtx);
|
|
@@ -864,102 +1022,6 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
864
1022
|
debugLog("autoLoop", { phase: "exit", reason: "step-wizard" });
|
|
865
1023
|
break;
|
|
866
1024
|
}
|
|
867
|
-
// ── Sidecar drain: dispatch enqueued hooks/triage/quick-tasks ──
|
|
868
|
-
let sidecarBroke = false;
|
|
869
|
-
while (s.sidecarQueue.length > 0 && s.active) {
|
|
870
|
-
const item = s.sidecarQueue.shift();
|
|
871
|
-
debugLog("autoLoop", {
|
|
872
|
-
phase: "sidecar-dequeue",
|
|
873
|
-
kind: item.kind,
|
|
874
|
-
unitType: item.unitType,
|
|
875
|
-
unitId: item.unitId,
|
|
876
|
-
});
|
|
877
|
-
// Set up as current unit
|
|
878
|
-
const sidecarStartedAt = Date.now();
|
|
879
|
-
s.currentUnit = {
|
|
880
|
-
type: item.unitType,
|
|
881
|
-
id: item.unitId,
|
|
882
|
-
startedAt: sidecarStartedAt,
|
|
883
|
-
};
|
|
884
|
-
deps.writeUnitRuntimeRecord(s.basePath, item.unitType, item.unitId, sidecarStartedAt, {
|
|
885
|
-
phase: "dispatched",
|
|
886
|
-
wrapupWarningSent: false,
|
|
887
|
-
timeoutAt: null,
|
|
888
|
-
lastProgressAt: sidecarStartedAt,
|
|
889
|
-
progressCount: 0,
|
|
890
|
-
lastProgressKind: "dispatch",
|
|
891
|
-
});
|
|
892
|
-
// Model selection (handles hook model override)
|
|
893
|
-
await deps.selectAndApplyModel(ctx, pi, item.unitType, item.unitId, s.basePath, prefs, s.verbose, s.autoModeStartModel);
|
|
894
|
-
// Supervision
|
|
895
|
-
deps.clearUnitTimeout();
|
|
896
|
-
deps.startUnitSupervision({
|
|
897
|
-
s,
|
|
898
|
-
ctx,
|
|
899
|
-
pi,
|
|
900
|
-
unitType: item.unitType,
|
|
901
|
-
unitId: item.unitId,
|
|
902
|
-
prefs,
|
|
903
|
-
buildSnapshotOpts: () => deps.buildSnapshotOpts(item.unitType, item.unitId),
|
|
904
|
-
buildRecoveryContext: () => ({}),
|
|
905
|
-
pauseAuto: deps.pauseAuto,
|
|
906
|
-
});
|
|
907
|
-
// Write lock
|
|
908
|
-
const sidecarSessionFile = deps.getSessionFile(ctx);
|
|
909
|
-
deps.writeLock(deps.lockBase(), item.unitType, item.unitId, s.completedUnits.length, sidecarSessionFile);
|
|
910
|
-
// Execute via standard runUnit
|
|
911
|
-
const sidecarResult = await runUnit(ctx, pi, s, item.unitType, item.unitId, item.prompt, prefs);
|
|
912
|
-
deps.clearUnitTimeout();
|
|
913
|
-
if (sidecarResult.status === "cancelled") {
|
|
914
|
-
ctx.ui.notify(`Sidecar unit ${item.unitType} ${item.unitId} session cancelled. Stopping.`, "warning");
|
|
915
|
-
await deps.stopAuto(ctx, pi, "Sidecar session creation failed");
|
|
916
|
-
sidecarBroke = true;
|
|
917
|
-
break;
|
|
918
|
-
}
|
|
919
|
-
// Run pre-verification for the sidecar unit
|
|
920
|
-
const sidecarPreResult = await deps.postUnitPreVerification(postUnitCtx);
|
|
921
|
-
if (sidecarPreResult === "dispatched") {
|
|
922
|
-
// Pre-verification caused stop/pause
|
|
923
|
-
debugLog("autoLoop", {
|
|
924
|
-
phase: "exit",
|
|
925
|
-
reason: "sidecar-pre-verification-stop",
|
|
926
|
-
});
|
|
927
|
-
sidecarBroke = true;
|
|
928
|
-
break;
|
|
929
|
-
}
|
|
930
|
-
// Verification gate for non-hook sidecar units (triage, quick-tasks)
|
|
931
|
-
// Hook units are lightweight and don't need verification.
|
|
932
|
-
if (item.kind !== "hook") {
|
|
933
|
-
const sidecarVerification = await deps.runPostUnitVerification({ s, ctx, pi }, deps.pauseAuto);
|
|
934
|
-
if (sidecarVerification === "pause") {
|
|
935
|
-
debugLog("autoLoop", {
|
|
936
|
-
phase: "exit",
|
|
937
|
-
reason: "sidecar-verification-pause",
|
|
938
|
-
});
|
|
939
|
-
sidecarBroke = true;
|
|
940
|
-
break;
|
|
941
|
-
}
|
|
942
|
-
// "retry" for sidecars — skip retry, just continue (sidecar retries are not worth the complexity)
|
|
943
|
-
}
|
|
944
|
-
// Post-verification (may enqueue more sidecar items)
|
|
945
|
-
const sidecarPostResult = await deps.postUnitPostVerification(postUnitCtx);
|
|
946
|
-
if (sidecarPostResult === "stopped") {
|
|
947
|
-
debugLog("autoLoop", { phase: "exit", reason: "sidecar-stopped" });
|
|
948
|
-
sidecarBroke = true;
|
|
949
|
-
break;
|
|
950
|
-
}
|
|
951
|
-
if (sidecarPostResult === "step-wizard") {
|
|
952
|
-
debugLog("autoLoop", {
|
|
953
|
-
phase: "exit",
|
|
954
|
-
reason: "sidecar-step-wizard",
|
|
955
|
-
});
|
|
956
|
-
sidecarBroke = true;
|
|
957
|
-
break;
|
|
958
|
-
}
|
|
959
|
-
// "continue" — loop checks sidecarQueue again
|
|
960
|
-
}
|
|
961
|
-
if (sidecarBroke)
|
|
962
|
-
break;
|
|
963
1025
|
consecutiveErrors = 0; // Iteration completed successfully
|
|
964
1026
|
debugLog("autoLoop", { phase: "iteration-complete", iteration });
|
|
965
1027
|
}
|
|
@@ -990,6 +1052,6 @@ export async function autoLoop(ctx, pi, s, deps) {
|
|
|
990
1052
|
}
|
|
991
1053
|
}
|
|
992
1054
|
}
|
|
993
|
-
|
|
1055
|
+
_currentResolve = null;
|
|
994
1056
|
debugLog("autoLoop", { phase: "exit", totalIterations: iteration });
|
|
995
1057
|
}
|