singularity-forge/src/resources/extensions/gsd/auto-start.ts

570 lines
18 KiB
TypeScript
Raw Normal View History

/**
* Auto-mode bootstrap fresh-start initialization path.
*
* Git/state bootstrap, crash lock detection, debug init, worktree recovery,
* guided flow gate, session init, worktree lifecycle, DB lifecycle,
* preflight validation.
*
* Extracted from startAuto() in auto.ts. The resume path (s.paused)
* remains in auto.ts this module handles only the fresh-start path.
*/
import type {
ExtensionAPI,
ExtensionCommandContext,
} from "@gsd/pi-coding-agent";
import { deriveState } from "./state.js";
import { loadFile, getManifestStatus } from "./files.js";
import {
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
loadEffectiveGSDPreferences,
resolveSkillDiscoveryMode,
getIsolationMode,
} from "./preferences.js";
import { collectSecretsFromManifest } from "../get-secrets-from-user.js";
import { gsdRoot, resolveMilestoneFile, milestonesDir } from "./paths.js";
import { invalidateAllCaches } from "./cache.js";
import { synthesizeCrashRecovery } from "./session-forensics.js";
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
import {
writeLock,
clearLock,
readCrashLock,
formatCrashInfo,
isLockProcessAlive,
} from "./crash-recovery.js";
import {
acquireSessionLock,
releaseSessionLock,
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
updateSessionLock,
} from "./session-lock.js";
import { ensureGitignore, untrackRuntimeFiles } from "./gitignore.js";
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
import {
nativeIsRepo,
nativeInit,
nativeAddAll,
nativeCommit,
} from "./native-git-bridge.js";
import { GitServiceImpl } from "./git-service.js";
import {
captureIntegrationBranch,
detectWorktreeName,
setActiveMilestoneId,
} from "./worktree.js";
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
import { getAutoWorktreePath, isInAutoWorktree } from "./auto-worktree.js";
import { readResourceVersion } from "./auto-worktree-sync.js";
import { initMetrics } from "./metrics.js";
import { initRoutingHistory } from "./routing-history.js";
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
import { restoreHookState, resetHookState } from "./post-unit-hooks.js";
import { resetProactiveHealing } from "./doctor-proactive.js";
import { snapshotSkills } from "./skill-discovery.js";
import { isDbAvailable } from "./gsd-db.js";
import { hideFooter } from "./auto-dashboard.js";
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
import {
debugLog,
enableDebug,
isDebugEnabled,
getDebugLogPath,
} from "./debug-logger.js";
import type { AutoSession } from "./auto/session.js";
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
import {
existsSync,
mkdirSync,
readdirSync,
statSync,
unlinkSync,
} from "node:fs";
import { join } from "node:path";
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
import { sep as pathSep } from "node:path";
import type { WorktreeResolver } from "./worktree-resolver.js";
export interface BootstrapDeps {
shouldUseWorktreeIsolation: () => boolean;
registerSigtermHandler: (basePath: string) => void;
lockBase: () => string;
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
buildResolver: () => WorktreeResolver;
}
/**
* Bootstrap a fresh auto-mode session. Handles everything from git init
* through secrets collection, returning when ready for the first
* dispatchNextUnit call.
*
* Returns false if the bootstrap aborted (e.g., guided flow returned,
* concurrent session detected). Returns true when ready to dispatch.
*/
export async function bootstrapAutoSession(
s: AutoSession,
ctx: ExtensionCommandContext,
pi: ExtensionAPI,
base: string,
verboseMode: boolean,
requestedStepMode: boolean,
deps: BootstrapDeps,
): Promise<boolean> {
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
const {
shouldUseWorktreeIsolation,
registerSigtermHandler,
lockBase,
buildResolver,
} = deps;
const lockResult = acquireSessionLock(base);
if (!lockResult.acquired) {
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
ctx.ui.notify(lockResult.reason, "error");
return false;
}
function releaseLockAndReturn(): false {
releaseSessionLock(base);
clearLock(base);
return false;
}
try {
// Ensure git repo exists
if (!nativeIsRepo(base)) {
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
const mainBranch =
loadEffectiveGSDPreferences()?.preferences?.git?.main_branch || "main";
nativeInit(base, mainBranch);
}
// Ensure .gitignore has baseline patterns
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
const gitPrefs = loadEffectiveGSDPreferences()?.preferences?.git;
const commitDocs = gitPrefs?.commit_docs;
const manageGitignore = gitPrefs?.manage_gitignore;
ensureGitignore(base, { commitDocs, manageGitignore });
if (manageGitignore !== false) untrackRuntimeFiles(base);
// Bootstrap .gsd/ if it doesn't exist
const gsdDir = join(base, ".gsd");
if (!existsSync(gsdDir)) {
mkdirSync(join(gsdDir, "milestones"), { recursive: true });
if (commitDocs !== false) {
try {
nativeAddAll(base);
nativeCommit(base, "chore: init gsd");
} catch {
/* nothing to commit */
}
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Initialize GitServiceImpl
s.gitService = new GitServiceImpl(
s.basePath,
loadEffectiveGSDPreferences()?.preferences?.git ?? {},
);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Check for crash from previous session. Skip our own fresh bootstrap lock.
const crashLock = readCrashLock(base);
if (crashLock && crashLock.pid !== process.pid) {
if (isLockProcessAlive(crashLock)) {
ctx.ui.notify(
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
`Another auto-mode session (PID ${crashLock.pid}) appears to be running.\nStop it with \`kill ${crashLock.pid}\` before starting a new session.`,
"error",
);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
return releaseLockAndReturn();
}
const recoveredMid = crashLock.unitId.split("/")[0];
const milestoneAlreadyComplete = recoveredMid
? !!resolveMilestoneFile(base, recoveredMid, "SUMMARY")
: false;
if (milestoneAlreadyComplete) {
ctx.ui.notify(
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
`Crash recovery: discarding stale context for ${crashLock.unitId} — milestone ${recoveredMid} is already complete.`,
"info",
);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
} else {
const activityDir = join(gsdRoot(base), "activity");
const recovery = synthesizeCrashRecovery(
base,
crashLock.unitType,
crashLock.unitId,
crashLock.sessionFile,
activityDir,
);
if (recovery && recovery.trace.toolCallCount > 0) {
s.pendingCrashRecovery = recovery.prompt;
ctx.ui.notify(
`${formatCrashInfo(crashLock)}\nRecovered ${recovery.trace.toolCallCount} tool calls from crashed session. Resuming with full context.`,
"warning",
);
} else {
ctx.ui.notify(
`${formatCrashInfo(crashLock)}\nNo session data recovered. Resuming from disk state.`,
"warning",
);
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
clearLock(base);
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// ── Debug mode ──
if (!isDebugEnabled() && process.env.GSD_DEBUG === "1") {
enableDebug(base);
}
if (isDebugEnabled()) {
const { isNativeParserAvailable } =
await import("./native-parser-bridge.js");
debugLog("debug-start", {
platform: process.platform,
arch: process.arch,
node: process.version,
model: ctx.model?.id ?? "unknown",
provider: ctx.model?.provider ?? "unknown",
nativeParser: isNativeParserAvailable(),
cwd: base,
});
ctx.ui.notify(`Debug logging enabled → ${getDebugLogPath()}`, "info");
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Invalidate caches before initial state derivation
invalidateAllCaches();
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Clean stale runtime unit files for completed milestones (#887)
try {
const runtimeUnitsDir = join(gsdRoot(base), "runtime", "units");
if (existsSync(runtimeUnitsDir)) {
for (const file of readdirSync(runtimeUnitsDir)) {
if (!file.endsWith(".json")) continue;
const midMatch = file.match(/(M\d+(?:-[a-z0-9]{6})?)/);
if (!midMatch) continue;
const mid = midMatch[1];
if (resolveMilestoneFile(base, mid, "SUMMARY")) {
try {
unlinkSync(join(runtimeUnitsDir, file));
} catch (e) {
debugLog("stale-unit-cleanup-failed", {
file,
error: e instanceof Error ? e.message : String(e),
});
}
}
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
} catch (e) {
debugLog("stale-unit-dir-cleanup-failed", {
error: e instanceof Error ? e.message : String(e),
});
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
let state = await deriveState(base);
// Stale worktree state recovery (#654)
if (
state.activeMilestone &&
shouldUseWorktreeIsolation() &&
!detectWorktreeName(base)
) {
const wtPath = getAutoWorktreePath(base, state.activeMilestone.id);
if (wtPath) {
state = await deriveState(wtPath);
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Milestone branch recovery (#601)
let hasSurvivorBranch = false;
if (
state.activeMilestone &&
(state.phase === "pre-planning" || state.phase === "needs-discussion") &&
shouldUseWorktreeIsolation() &&
!detectWorktreeName(base) &&
!base.includes(`${pathSep}.gsd${pathSep}worktrees${pathSep}`)
) {
const milestoneBranch = `milestone/${state.activeMilestone.id}`;
const { nativeBranchExists } = await import("./native-git-bridge.js");
hasSurvivorBranch = nativeBranchExists(base, milestoneBranch);
if (hasSurvivorBranch) {
ctx.ui.notify(
`Found prior session branch ${milestoneBranch}. Resuming.`,
"info",
);
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
if (!hasSurvivorBranch) {
// No active work — start a new milestone via discuss flow
if (!state.activeMilestone || state.phase === "complete") {
const { showSmartEntry } = await import("./guided-flow.js");
await showSmartEntry(ctx, pi, base, { step: requestedStepMode });
invalidateAllCaches();
const postState = await deriveState(base);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
if (
postState.activeMilestone &&
postState.phase !== "complete" &&
postState.phase !== "pre-planning"
) {
state = postState;
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
} else if (
postState.activeMilestone &&
postState.phase === "pre-planning"
) {
const contextFile = resolveMilestoneFile(
base,
postState.activeMilestone.id,
"CONTEXT",
);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
const hasContext = !!(contextFile && (await loadFile(contextFile)));
if (hasContext) {
state = postState;
} else {
ctx.ui.notify(
"Discussion completed but no milestone context was written. Run /gsd to try the discussion again, or /gsd auto after creating the milestone manually.",
"warning",
);
return releaseLockAndReturn();
}
} else {
return releaseLockAndReturn();
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Active milestone exists but has no roadmap
if (state.phase === "pre-planning") {
const mid = state.activeMilestone!.id;
const contextFile = resolveMilestoneFile(base, mid, "CONTEXT");
const hasContext = !!(contextFile && (await loadFile(contextFile)));
if (!hasContext) {
const { showSmartEntry } = await import("./guided-flow.js");
await showSmartEntry(ctx, pi, base, { step: requestedStepMode });
invalidateAllCaches();
const postState = await deriveState(base);
if (postState.activeMilestone && postState.phase !== "pre-planning") {
state = postState;
} else {
ctx.ui.notify(
"Discussion completed but milestone context is still missing. Run /gsd to try again.",
"warning",
);
return releaseLockAndReturn();
}
}
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Unreachable safety check
if (!state.activeMilestone) {
const { showSmartEntry } = await import("./guided-flow.js");
await showSmartEntry(ctx, pi, base, { step: requestedStepMode });
return releaseLockAndReturn();
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// ── Initialize session state ──
s.active = true;
s.stepMode = requestedStepMode;
s.verbose = verboseMode;
s.cmdCtx = ctx;
s.basePath = base;
s.unitDispatchCount.clear();
s.unitRecoveryCount.clear();
s.lastBudgetAlertLevel = 0;
s.unitLifetimeDispatches.clear();
resetHookState();
restoreHookState(base);
resetProactiveHealing();
s.autoStartTime = Date.now();
s.resourceVersionOnStart = readResourceVersion();
s.completedUnits = [];
s.pendingQuickTasks = [];
s.currentUnit = null;
s.currentMilestoneId = state.activeMilestone?.id ?? null;
s.originalModelId = ctx.model?.id ?? null;
s.originalModelProvider = ctx.model?.provider ?? null;
// Register SIGTERM handler
registerSigtermHandler(base);
// Capture integration branch
if (s.currentMilestoneId) {
if (getIsolationMode() !== "none") {
captureIntegrationBranch(base, s.currentMilestoneId, { commitDocs });
}
setActiveMilestoneId(base, s.currentMilestoneId);
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// ── Auto-worktree setup ──
s.originalBasePath = base;
const isUnderGsdWorktrees = (p: string): boolean => {
const marker = `${pathSep}.gsd${pathSep}worktrees${pathSep}`;
if (p.includes(marker)) return true;
const worktreesSuffix = `${pathSep}.gsd${pathSep}worktrees`;
return p.endsWith(worktreesSuffix);
};
if (
s.currentMilestoneId &&
shouldUseWorktreeIsolation() &&
!detectWorktreeName(base) &&
!isUnderGsdWorktrees(base)
) {
buildResolver().enterMilestone(s.currentMilestoneId, {
notify: ctx.ui.notify.bind(ctx.ui),
});
if (s.basePath !== base) {
// Successfully entered worktree — re-register SIGTERM handler at original base
registerSigtermHandler(s.originalBasePath);
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// ── DB lifecycle ──
const gsdDbPath = join(s.basePath, ".gsd", "gsd.db");
const gsdDirPath = join(s.basePath, ".gsd");
if (existsSync(gsdDirPath) && !existsSync(gsdDbPath)) {
const hasDecisions = existsSync(join(gsdDirPath, "DECISIONS.md"));
const hasRequirements = existsSync(join(gsdDirPath, "REQUIREMENTS.md"));
const hasMilestones = existsSync(join(gsdDirPath, "milestones"));
if (hasDecisions || hasRequirements || hasMilestones) {
try {
const { openDatabase: openDb } = await import("./gsd-db.js");
const { migrateFromMarkdown } = await import("./md-importer.js");
openDb(gsdDbPath);
migrateFromMarkdown(s.basePath);
} catch (err) {
process.stderr.write(
`gsd-migrate: auto-migration failed: ${(err as Error).message}\n`,
);
}
}
}
if (existsSync(gsdDbPath) && !isDbAvailable()) {
try {
const { openDatabase: openDb } = await import("./gsd-db.js");
openDb(gsdDbPath);
} catch (err) {
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
process.stderr.write(
`gsd-db: failed to open existing database: ${(err as Error).message}\n`,
);
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Initialize metrics
initMetrics(s.basePath);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Initialize routing history
initRoutingHistory(s.basePath);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Capture session's model at auto-mode start (#650)
const currentModel = ctx.model;
if (currentModel) {
s.autoModeStartModel = {
provider: currentModel.provider,
id: currentModel.id,
};
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Snapshot installed skills
if (resolveSkillDiscoveryMode() !== "off") {
snapshotSkills();
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
ctx.ui.setStatus("gsd-auto", s.stepMode ? "next" : "auto");
ctx.ui.setFooter(hideFooter);
const modeLabel = s.stepMode ? "Step-mode" : "Auto-mode";
const pendingCount = (state.registry ?? []).filter(
(m) => m.status !== "complete" && m.status !== "parked",
).length;
const scopeMsg =
pendingCount > 1
? `Will loop through ${pendingCount} milestones.`
: "Will loop until milestone complete.";
ctx.ui.notify(`${modeLabel} started. ${scopeMsg}`, "info");
updateSessionLock(
lockBase(),
"starting",
s.currentMilestoneId ?? "unknown",
0,
);
writeLock(lockBase(), "starting", s.currentMilestoneId ?? "unknown", 0);
// Secrets collection gate
const mid = state.activeMilestone!.id;
try {
const manifestStatus = await getManifestStatus(base, mid, s.originalBasePath || base);
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
if (manifestStatus && manifestStatus.pending.length > 0) {
const result = await collectSecretsFromManifest(base, mid, ctx);
if (
result &&
result.applied &&
result.skipped &&
result.existingSkipped
) {
ctx.ui.notify(
`Secrets collected: ${result.applied.length} applied, ${result.skipped.length} skipped, ${result.existingSkipped.length} already set.`,
"info",
);
} else {
ctx.ui.notify("Secrets collection skipped.", "info");
}
}
} catch (err) {
ctx.ui.notify(
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
`Secrets collection error: ${err instanceof Error ? err.message : String(err)}. Continuing with next task.`,
"warning",
);
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Self-heal: remove stale .git/index.lock
try {
const gitLockFile = join(base, ".git", "index.lock");
if (existsSync(gitLockFile)) {
const lockAge = Date.now() - statSync(gitLockFile).mtimeMs;
if (lockAge > 60_000) {
unlinkSync(gitLockFile);
ctx.ui.notify(
"Removed stale .git/index.lock from prior crash.",
"info",
);
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
} catch (e) {
debugLog("git-lock-cleanup-failed", {
error: e instanceof Error ? e.message : String(e),
});
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
// Pre-flight: validate milestone queue
try {
const msDir = join(base, ".gsd", "milestones");
if (existsSync(msDir)) {
const milestoneIds = readdirSync(msDir, { withFileTypes: true })
.filter((d) => d.isDirectory() && /^M\d{3}/.test(d.name))
.map((d) => d.name.match(/^(M\d{3})/)?.[1] ?? d.name);
if (milestoneIds.length > 1) {
const issues: string[] = [];
for (const id of milestoneIds) {
const draft = resolveMilestoneFile(base, id, "CONTEXT-DRAFT");
if (draft)
issues.push(
`${id}: has CONTEXT-DRAFT.md (will pause for discussion)`,
);
}
if (issues.length > 0) {
ctx.ui.notify(
`Pre-flight: ${milestoneIds.length} milestones queued.\n${issues.map((i) => `${i}`).join("\n")}`,
"warning",
);
} else {
ctx.ui.notify(
`Pre-flight: ${milestoneIds.length} milestones queued. All have full context.`,
"info",
);
}
}
}
M001: The Minimal Machine — linear auto-loop, sole-authority state, sidecar queue, WorktreeResolver (#1419) * refactor: replace recursive auto-dispatch with linear autoLoop, delete ~3k lines of dead code Replace the complex recursive dispatch system (dispatchNextUnit, reentrancy guards, stall detection, idempotency tracking, skip-depth machinery) with a simple linear while(s.active) loop in auto-loop.ts. Key changes: - New auto-loop.ts with autoLoop(), runUnit(), resolveAgentEnd() - Deleted auto-idempotency.ts, auto-stuck-detection.ts, session-lock.ts, mechanical-completion.ts, progress-score.ts, auto-constants.ts, unit-id.ts - Extracted WorktreeResolver class for worktree path resolution - Added auto-worktree-sync.ts for worktree synchronization - Simplified auto.ts from ~1400 lines to ~400 lines - Fixed 9 TypeScript errors (NotifyCtx type widening, capture typing) - Comprehensive test coverage: 32 auto-loop tests + worktree resolver/DB tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address 6 audit findings in auto-loop refactor 1. CRITICAL: Move pendingResolve to AutoSession + queue orphaned agent_end events instead of silently dropping them. Prevents permanent stalls when error-recovery sendMessage retries fire between loop iterations. 2. HIGH: Scope pendingResolve per-session via _activeSession ref, preventing concurrent /gsd auto sessions from corrupting each other's promises. 3. HIGH: Replace console.log in dispatchHookUnit with debugLog to prevent hook prompt content (potentially containing secrets) from leaking to stdout. 4. HIGH: Restore parked milestone handling in state.ts — Phase 1 skips parked milestones so they don't satisfy depends_on, Phase 2 registers them as 'parked' status. Add 'parked' to MilestoneRegistryEntry type. 5. MEDIUM: Restore queuePhaseActive parameter in shouldBlockContextWrite and re-export setQueuePhaseActive for guided-flow-queue.ts consumers. 6. MEDIUM: Add MAX_LOOP_ITERATIONS (500) lifetime cap to autoLoop to prevent runaway loops when units alternate between IDs. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve build breakers, add correctness fixes, and graduated recovery Build breakers (CRITICAL): - Restore unit-id.ts (deleted but still imported by complexity-classifier.ts, metrics.ts) - Restore progress-score.ts (deleted but still imported by commands.ts, dashboard-overlay.ts, doctor.ts) - Rewrite worktree-sync-milestones.test.ts to use new syncProjectRootToWorktree API Correctness fixes (MEDIUM): - Cap pendingAgentEndQueue to 3 entries to prevent unbounded growth from stale events - Add milestoneId path traversal validation in WorktreeResolver - Clear depthVerificationDone on session_start to prevent cross-session leaks in RPC mode - Add verification gate for non-hook sidecar units (triage, quick-tasks) - Remove dead handleAgentEnd import from index.ts Graduated recovery (Jeremy's feedback): - Blanket try/catch around loop body — one bad iteration no longer kills the session - Graduated stuck recovery: at count 3 try artifact verification + cache invalidation, at count 5 hard stop (was: binary stop at 5 with no recovery attempt) - Graduated error recovery: 1st error retries, 2nd invalidates caches, 3rd stops Test results: 32/32 auto-loop, 28/28 worktree-resolver, 11/11 sidecar-queue, tsc clean. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore copyWorktreeDb/reconcileWorktreeDb exports and fix loadToolApiKeys import Two missing exports caused ~90% of the 120 pre-existing test failures: 1. copyWorktreeDb + reconcileWorktreeDb — imported by auto-worktree.ts but never added to gsd-db.ts. Restored with the original implementations. 2. loadToolApiKeys — moved to commands-config.ts but index.ts still imported from commands.ts. Fixed the import path. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move loadToolApiKeys import to commands-config.js loadToolApiKeys was moved to commands-config.ts but index.ts still imported it from commands.ts, causing runtime failures in all tests that transitively load the extension entry point. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: fix provider error assertion on windows --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:56:00 -06:00
} catch {
/* non-fatal */
}
return true;
} catch (err) {
releaseSessionLock(base);
clearLock(base);
throw err;
}
}