refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
/ * *
* 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" ;
2026-03-20 22:34:30 -04:00
import type { InterruptedSessionAssessment } from "./interrupted-session.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ;
2026-03-21 14:58:25 -06:00
import { ensureGsdSymlink , isInheritedRepo , validateProjectId } from "./repo-identity.js" ;
fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364) (#1367)
* rfc: GitOps branching & versioning strategy proposal
Proposes a Git-Flow Lite model with automated integration branches:
main ← production-ready, tagged releases only
next ← integration branch for next minor (PRs target here)
release/X.Y ← stabilization branch, only bugfixes allowed
hotfix/X.Y.Z ← emergency fixes cherry-picked to release
Includes:
- RFC document with lifecycle diagrams, migration path, open questions
- Workflow scaffolds (in docs/proposals/workflows/, NOT .github/):
- create-release.yml: manual dispatch to cut release branch from next
- sync-next.yml: auto-sync next branch after version tags
- backmerge.yml: auto back-merge release fixes to next
This is an experimental proposal requesting community feedback before
any implementation. The workflow files are inert scaffolds — they do
not run in CI.
* fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364)
CRITICAL DATA-LOSS FIX: ensureGitignore() unconditionally added '.gsd' to
.gitignore even when .gsd/ was a real git-tracked directory, causing git to
report ~889 tracked files as deleted.
Root cause: BASELINE_PATTERNS included '.gsd' unconditionally, and the
gitignore modification ran BEFORE migration checks in auto-start.ts.
Changes:
- Add hasGitTrackedGsdFiles() helper using nativeLsFiles to detect tracked
.gsd/ content
- ensureGitignore() now skips the '.gsd' pattern when .gsd/ has tracked files
- untrackRuntimeFiles() now skips entirely when .gsd/ has tracked files
- migrateToExternalState() aborts when .gsd/ has tracked files
- Reorder auto-start.ts: migration runs BEFORE gitignore modification
- Add 8 regression tests covering all scenarios
Fixes #1364
* fix: break recursive dialog loop when all milestones complete (#1348)
Two interacting bugs:
1. Recursive dialog loop: When all milestones are complete, bootstrapAutoSession
calls showSmartEntry → sets pendingAutoStart → checkAutoStartAfterDiscuss
calls startAuto → bootstrapAutoSession → showSmartEntry → infinite loop.
The discuss workflow completes without producing a milestone directory, so
phase stays 'complete' and the cycle never breaks.
Fix: Add a re-entry counter (_consecutiveCompleteBootstraps) that tracks
how many times bootstrapAutoSession enters the 'complete' branch without
advancing. After 2 consecutive attempts, break the loop with a warning
message and return false.
2. Missing _releaseFunction = null in retry lock onCompromised handler:
The retry lock path in session-lock.ts set _lockCompromised but didn't
null out _releaseFunction, which could leave a stale reference that
masks the compromise detection in validateSessionLock().
Fixes #1348
* fix: self-heal stale roadmap checkbox for interrupted complete-slice (#1350)
When complete-slice is interrupted after writing SUMMARY.md and UAT.md but
before flipping the roadmap checkbox, auto-mode enters an infinite loop —
re-launching the same complete-slice unit because the dispatch loop uses
the roadmap checkbox as the sole 'slice done' signal.
Fix: Add a self-heal case in selfHealRuntimeRecords that detects when
SUMMARY + UAT exist but the roadmap checkbox is unchecked, and auto-fixes
the checkbox. This allows the verification to pass and the dispatch loop
to advance.
Fixes #1350
* fix: add EISDIR guard to complete/validate milestone prompts (#1343)
The LLM was passing tasks/ directory paths to the read tool during
milestone completion, causing EISDIR crashes. Added file system safety
instructions to both complete-milestone and validate-milestone prompts
telling the LLM to use ls/find for directory listing, not the read tool.
Fixes #1343
* feat: improve extension conflict messages with removal guidance (#1347)
When a user extension registers tools/commands that now ship as built-ins,
the conflict message now includes '(built-in tool supersedes — consider
removing <path>)' and the log level is downgraded from 'Extension load error'
to 'Extension conflict'.
Changes:
- resource-loader.ts: detect built-in vs user extension conflicts, add hint
- cli.ts: downgrade severity for superseded-tool conflicts
Fixes #1347
* test: fix always-skipped preferences test, add test:marketplace script
- preferences.test.ts: Replace always-skipped getIsolationMode test with
a filesystem-independent version that validates the default through
validatePreferences() instead of reading ~/.gsd/preferences.md.
Reduces skipped count from 3 → 2.
- package.json: Add test:marketplace script for running marketplace
contract tests (claude-import-tui, plugin-importer-live,
marketplace-discovery) with GSD_TEST_CLONE_MARKETPLACES=1.
These tests need external repos and self-skip in unit test runs.
Remaining 2 skips:
- Marketplace contract test suites (need external repos, run via test:marketplace)
- Windows-only tests in validate-directory.test.ts are platform-conditional
and correctly skip on macOS
* fix: use execFileSync in regression tests for Windows portability
The regression tests used execSync with shell-dependent constructs:
- '&&' command chaining (works in bash/cmd but fragile)
- Single-quoted commit messages (bash-only, cmd.exe splits on spaces)
Replaced with execFileSync via a git() helper that bypasses the shell
entirely. Each git operation is a separate call with proper argument
arrays, eliminating all shell interpretation issues.
Fixes windows-portability CI failure.
* fix: guard milestone completion against missing slice summaries (#1368)
Auto-mode could report a milestone as complete after executing only the
last slice, skipping earlier unexecuted slices. The milestone completion
signal fired based on roadmap checkbox state, which could be stale or
inconsistent after worktree transitions.
Changes:
- auto-dispatch.ts: Added slice SUMMARY file existence check to both
validating-milestone and completing-milestone dispatch rules. If any
slice lacks a SUMMARY file, dispatch stops with a diagnostic error
instead of proceeding to validation/completion.
- validate-milestone.test.ts: Updated tests to create slice summary
files (required by the new guard).
- file-watcher.test.ts: Fixed flaky 'auth.json change emits auth-changed
event' test by adding watcher initialization delay and increasing event
propagation timeout (race condition when run in full suite).
Fixes #1368
* fix: warn on common misspelled preference keys + verify field guidance (#1373, #1341)
#1373: Users setting 'taskIsolation.mode: none' instead of 'git.isolation: none'
got a generic 'unknown key' warning. Added KEY_MIGRATION_HINTS that map common
misspellings (taskIsolation, task_isolation, isolation, manage_gitignore, auto_push,
main_branch) to their correct git.* equivalents with actionable messages.
#1341: Planning agent writes aspirational prose in Verify fields ('Sections 3.1
and 3.2 exist with exact formulas. Zero TBD.') instead of executable commands.
Added explicit verify field rules to the plan template: must be mechanically
executable, with examples of good vs bad patterns for content tasks.
Fixes #1373, partially addresses #1341
* refactor: extract roadmap-mutations.ts + shared test-utils.ts
Consolidation:
- roadmap-mutations.ts: Extracted markSliceDoneInRoadmap() and markTaskDoneInPlan()
from duplicated implementations in doctor.ts, mechanical-completion.ts, and
auto-recovery.ts. All three callers used identical regex patterns.
mechanical-completion.ts and auto-recovery.ts now import the shared utility.
(doctor.ts deferred — touched by PR #1349)
- test-utils.ts: Shared cross-platform test utilities for GSD extension tests.
Provides git() helper (execFileSync, no shell), makeTempRepo() with
core.autocrlf=false, cleanup(), createFile(), safeReadFile(), and
writeMilestoneFixture(). 12 test files currently define their own versions
of these helpers — new tests should import from test-utils.ts instead.
Security audit: No injection vectors (sid/tid are alphanumeric from roadmap
parser), no path traversal, no secrets, no new dependencies.
* fix: port conflict false positive on non-Node projects + paused worktree resume (#1381, #1383)
projects without package.json. macOS AirPlay Receiver listens on port 5000,
causing a spurious warning on non-Node projects.
Fix: Skip port checks entirely when no package.json exists. When using
default ports, filter out 5000 on macOS.
in-memory only. Re-entering /gsd started a fresh bootstrap from the project
root instead of the active worktree.
Fix: pauseAuto() now writes paused-session.json to .gsd/runtime/ with
milestoneId, worktreePath, originalBasePath, and stepMode. startAuto()
checks for this file before bootstrap and restores the paused session
context, including worktree re-entry. stopAuto() cleans up the file.
Fixes #1381, #1383
* fix: catch spawn ENOENT in uncaught exception guard + snapshot session lock path (#1384, #1363)
uncaught exception and crashes auto-mode. The EPIPE guard now also catches
ENOENT from spawn syscalls — logs the error and continues instead of
terminating the process.
the lock path differently via gsdRoot() because basePath could be either the
project root or a worktree path. gsdRoot() produces different results for
each, so the lock was written to one path and validated against another.
Fix: Snapshot the resolved lock path (_snapshotLockPath) at acquisition time
and reuse it for all subsequent lock operations within the session.
Fixes #1384, #1363
* fix: suppress false-positive lock compromise + skip migration with active worktrees (#1362, #1337)
because the event loop stall delays the heartbeat mtime update. The handler
now checks elapsed time since acquisition — if within the 30-minute stale
window, it logs a warning and continues instead of setting _lockCompromised.
Real takeovers (past the stale window) still trigger the compromise flag.
even when .gsd/worktrees/ contained active git worktrees with locked
directory handles. This caused EBUSY errors and destructive data loss.
Migration now checks for active worktree directories and skips entirely
if any are found.
Fixes #1362, #1337
2026-03-19 19:06:01 -04:00
import { migrateToExternalState , recoverFailedMigration } from "./migrate-external.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 { collectSecretsFromManifest } from "../get-secrets-from-user.js" ;
2026-03-20 22:34:30 -04:00
import { gsdRoot , resolveMilestoneFile } from "./paths.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
import { invalidateAllCaches } from "./cache.js" ;
2026-03-20 22:34:30 -04:00
import { writeLock , clearLock } from "./crash-recovery.js" ;
2026-03-18 10:10:56 -05:00
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 ,
2026-03-18 10:10:56 -05:00
} from "./session-lock.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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 ,
2026-04-06 18:55:33 -07:00
nativeGetCurrentBranch ,
nativeDetectMainBranch ,
nativeCheckoutBranch ,
2026-04-07 16:33:03 -05:00
nativeBranchList ,
nativeBranchListMerged ,
nativeBranchDelete ,
nativeWorktreeRemove ,
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
} from "./native-git-bridge.js" ;
import { GitServiceImpl } from "./git-service.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ;
2026-03-25 22:47:18 -06:00
import { readResourceVersion , cleanStaleRuntimeUnits } from "./auto-worktree.js" ;
2026-04-07 16:33:03 -05:00
import { worktreePath as getWorktreeDir , isInsideWorktreesDir } from "./worktree-manager.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 { initMetrics } from "./metrics.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ;
feat: health check phase 2 — real-time doctor issue visibility across widget, visualizer, and HTML reports (#1644)
* feat: surface real doctor issue details in progress score widget
Previously the progress score traffic light (green/yellow/red) only
showed generic labels like "2 consecutive error units" or "Health
trend declining". The actual doctor issue descriptions were computed
in auto-post-unit but discarded before reaching the widget — only
aggregate counts were stored in HealthSnapshot.
Now the full data flows through:
- HealthSnapshot stores issue details (code, message, severity,
unitId) and fix descriptions alongside the counts
- recordHealthSnapshot() accepts optional issue/fix arrays
(backwards compatible — existing callers unchanged)
- getLatestHealthIssues() and getLatestHealthFixes() retrieve the
most recent details for display
- computeProgressScore() surfaces up to 5 real issue messages
(errors first) and up to 3 recent fixes as ProgressSignals
when the level is yellow or red
- Dashboard overlay renders signal details with ✓/✗/· icons
below the traffic light when degraded
This gives real-time visibility into what the auto-doctor is
detecting and fixing, without requiring manual /gsd doctor runs
or opening the full dashboard to investigate.
* feat: integrate doctor health data into visualizer and HTML reports
Phase 2b: close visibility gaps across visualizer and export surfaces.
Persistence (doctor.ts):
- Enrich DoctorHistoryEntry with issue details (severity, code,
message, unitId) and fix descriptions
- appendDoctorHistory now persists up to 10 issues per entry and
all fix descriptions to doctor-history.jsonl
- Export DoctorHistoryEntry type for consumers
Data layer (visualizer-data.ts):
- Add VisualizerDoctorEntry and VisualizerProgressScore types
- Extend HealthInfo with doctorHistory (last 20 persisted entries)
and progressScore (current in-memory traffic light)
- loadHealth reads doctor-history.jsonl synchronously and snapshots
current progress score when health data exists
TUI visualizer (visualizer-views.ts):
- Health tab now shows "Progress Score" section with traffic light
icon, summary, and all signal details (✓/✗/· prefixed)
- Health tab now shows "Doctor History" section with timestamped
entries, issue messages, and applied fixes
HTML export (export-html.ts):
- Health section includes progress score with colored indicator
and signal breakdown
- Health section includes "Doctor Run History" table with
timestamps, error/warning/fix counts, issue codes, expandable
issue messages, and fix descriptions
* feat: fill remaining health gaps — scope tagging, level notifications, human-readable logs
Gap fills:
Per-milestone/slice scope tagging:
- HealthSnapshot now stores scope (e.g. "M001/S02") from the
doctor run's unit context
- DoctorHistoryEntry persists scope to doctor-history.jsonl
- Visualizer and HTML reports display scope tags per entry
State transition notifications:
- setLevelChangeCallback() registers a handler for progress level
changes (green→yellow, yellow→red, red→green, etc.)
- auto-start.ts wires the callback to ctx.ui.notify on start
- auto.ts clears it on stop
- Notifications include the triggering issue message
Human-readable formatting throughout:
- formatHealthSummary() uses full words: "2 errors, 3 warnings ·
trend degrading · 1 fix applied · 1 of 5 consecutive errors
before escalation · latest: Missing PLAN.md for S03"
- DoctorHistoryEntry stores a human-readable summary field
built from error counts, fix counts, and top issue message
- Visualizer doctor history shows summary instead of "2E 1W 0F"
- HTML export doctor table uses summary column with scope tags
- Post-unit notification says what was fixed ("Doctor: rebuilt
STATE.md; cleared stale lock") instead of "applied 2 fix(es)"
Test updates:
- formatHealthSummary assertions updated for new readable format
* fix: default UAT type to artifact-driven to prevent unnecessary auto-mode pauses (#1651)
When a UAT file has no `## UAT Type` section, `extractUatType()` returns
`undefined`. The fallback was `"human-experience"`, causing `pauseAfterDispatch:
true` in the auto-dispatch rule. Since doctor-generated UAT placeholders never
include a UAT Type section and LLM-executed UATs are always artifact-driven,
the correct default is `"artifact-driven"`.
Closes #1649
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove duplicate doctorScope declaration (CI build fix)
* fix: resolve PR1644 regressions in health views and post-unit hook
---------
Co-authored-by: TÂCHES <afromanguy@me.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 16:33:40 -05:00
import { resetProactiveHealing , setLevelChangeCallback } from "./doctor-proactive.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
import { snapshotSkills } from "./skill-discovery.js" ;
2026-04-05 00:49:29 -04:00
import { isDbAvailable , getMilestone , openDatabase } from "./gsd-db.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ;
refactor(gsd): migrate all catch blocks to centralized workflow-logger
Replace raw process.stderr.write(), console.error(), and empty catch
blocks across 50 GSD files with structured logWarning/logError calls
from the centralized workflow-logger system.
Add 13 new LogComponent types to cover all subsystems: recovery,
session, prompt, dashboard, timer, worktree, command, parallel, fs,
bootstrap, guided, registry, renderer.
Every migrated catch block now automatically:
- Shows in terminal (stderr) with component tag
- Gets buffered for auto-loop stuck-detection summary
- Persists to .gsd/audit-log.jsonl for post-mortem analysis
Update regression test to verify catch blocks use workflow-logger
instead of raw stderr/console, covering auto-mode files and all
explicitly migrated infrastructure files.
Closes #3506
Supersedes the approach in #3496
2026-04-04 13:42:55 -05:00
import { logWarning , logError } from "./workflow-logger.js" ;
2026-03-25 23:07:55 -06:00
import { parseUnitId } from "./unit-id.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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 ,
2026-04-07 16:33:03 -05:00
rmSync ,
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
statSync ,
unlinkSync ,
} from "node:fs" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ;
fix: isolate guided-flow session state and key discussion milestone queries (#2985) (#3094)
* fix: resolve 4 correctness bugs in GSD extension core (#2985)
Bug 1 — preferences.ts process.cwd() side-channel:
loadEffectiveGSDPreferences() and loadProjectGSDPreferences() now accept
an optional projectRoot parameter. When provided, preferences are loaded
from the specified project directory instead of relying on process.cwd().
All 37+ callers continue to work unchanged (parameter defaults to cwd).
Bug 2 — state.ts DB writes inside read functions (CQS violation):
Extracted disk-to-DB milestone reconciliation into a new exported function
reconcileDiskMilestonesToDb(). deriveState() and deriveStateFromDb() no
longer write to the DB as a side effect of reading state. Callers that
need reconciliation (auto-start.ts, guided-flow.ts, register-hooks.ts)
now call it explicitly before reading state.
Bug 3 — guided-flow.ts module-level session state:
Converted pendingAutoStart from a module-level singleton to a Map keyed
by basePath. Concurrent discuss sessions for different projects are now
independent — the second session no longer silently overwrites the first.
Bug 4 — getDiscussionMilestoneId() unkeyed query:
getDiscussionMilestoneId() now accepts an optional basePath parameter for
keyed lookup. When multiple sessions exist and no basePath is provided,
it returns null instead of an arbitrary entry. Single-session backward
compatibility is preserved.
Closes #2985
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: narrow scope to complement igouss PRs #2986 and #2987
Revert changes to preferences.ts (Bug 1), state.ts, auto-start.ts,
register-hooks.ts (Bug 2), and their test files. Those fixes are
covered by @igouss in PRs #2986 and #2987.
This PR now only contains:
- Bug 3: guided-flow.ts pendingAutoStart singleton → Map (session isolation)
- Bug 4: getDiscussionMilestoneId() keyed by basePath
- Supporting unitType additions in preferences-models.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: align source code with test expectations after scope narrowing
The refactor commit (6972c97c) reverted source changes to state.ts,
preferences.ts, and auto-start.ts but left their corresponding test
assertions in place, causing 8 CI failures:
- isValidationTerminal: treat any extracted verdict as terminal (#2769)
- parseHeadingListFormat: handle raw YAML blocks under headings (#2794)
- bootstrapAutoSession: snapshot ctx.model before guided-flow (#2829)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: open project DB before initial deriveState on cold bootstrap (#2841)
When auto-mode starts cold (no prior DB handle), deriveState silently
falls back to markdown-only data for DB-backed helpers (queue-order,
task status), producing stale or incomplete state. Add
openProjectDbIfPresent() helper that resolves the project-root DB path
and opens it before the first deriveState call, ensuring full data
visibility from the start.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 16:33:30 -04:00
import { resolveProjectRootDbPath } from "./bootstrap/dynamic-tools.js" ;
2026-04-04 17:15:43 -05:00
import { resolveDefaultSessionModel } from "./preferences-models.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 type { WorktreeResolver } from "./worktree-resolver.js" ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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 ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
/ * *
* 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 .
* /
fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364) (#1367)
* rfc: GitOps branching & versioning strategy proposal
Proposes a Git-Flow Lite model with automated integration branches:
main ← production-ready, tagged releases only
next ← integration branch for next minor (PRs target here)
release/X.Y ← stabilization branch, only bugfixes allowed
hotfix/X.Y.Z ← emergency fixes cherry-picked to release
Includes:
- RFC document with lifecycle diagrams, migration path, open questions
- Workflow scaffolds (in docs/proposals/workflows/, NOT .github/):
- create-release.yml: manual dispatch to cut release branch from next
- sync-next.yml: auto-sync next branch after version tags
- backmerge.yml: auto back-merge release fixes to next
This is an experimental proposal requesting community feedback before
any implementation. The workflow files are inert scaffolds — they do
not run in CI.
* fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364)
CRITICAL DATA-LOSS FIX: ensureGitignore() unconditionally added '.gsd' to
.gitignore even when .gsd/ was a real git-tracked directory, causing git to
report ~889 tracked files as deleted.
Root cause: BASELINE_PATTERNS included '.gsd' unconditionally, and the
gitignore modification ran BEFORE migration checks in auto-start.ts.
Changes:
- Add hasGitTrackedGsdFiles() helper using nativeLsFiles to detect tracked
.gsd/ content
- ensureGitignore() now skips the '.gsd' pattern when .gsd/ has tracked files
- untrackRuntimeFiles() now skips entirely when .gsd/ has tracked files
- migrateToExternalState() aborts when .gsd/ has tracked files
- Reorder auto-start.ts: migration runs BEFORE gitignore modification
- Add 8 regression tests covering all scenarios
Fixes #1364
* fix: break recursive dialog loop when all milestones complete (#1348)
Two interacting bugs:
1. Recursive dialog loop: When all milestones are complete, bootstrapAutoSession
calls showSmartEntry → sets pendingAutoStart → checkAutoStartAfterDiscuss
calls startAuto → bootstrapAutoSession → showSmartEntry → infinite loop.
The discuss workflow completes without producing a milestone directory, so
phase stays 'complete' and the cycle never breaks.
Fix: Add a re-entry counter (_consecutiveCompleteBootstraps) that tracks
how many times bootstrapAutoSession enters the 'complete' branch without
advancing. After 2 consecutive attempts, break the loop with a warning
message and return false.
2. Missing _releaseFunction = null in retry lock onCompromised handler:
The retry lock path in session-lock.ts set _lockCompromised but didn't
null out _releaseFunction, which could leave a stale reference that
masks the compromise detection in validateSessionLock().
Fixes #1348
* fix: self-heal stale roadmap checkbox for interrupted complete-slice (#1350)
When complete-slice is interrupted after writing SUMMARY.md and UAT.md but
before flipping the roadmap checkbox, auto-mode enters an infinite loop —
re-launching the same complete-slice unit because the dispatch loop uses
the roadmap checkbox as the sole 'slice done' signal.
Fix: Add a self-heal case in selfHealRuntimeRecords that detects when
SUMMARY + UAT exist but the roadmap checkbox is unchecked, and auto-fixes
the checkbox. This allows the verification to pass and the dispatch loop
to advance.
Fixes #1350
* fix: add EISDIR guard to complete/validate milestone prompts (#1343)
The LLM was passing tasks/ directory paths to the read tool during
milestone completion, causing EISDIR crashes. Added file system safety
instructions to both complete-milestone and validate-milestone prompts
telling the LLM to use ls/find for directory listing, not the read tool.
Fixes #1343
* feat: improve extension conflict messages with removal guidance (#1347)
When a user extension registers tools/commands that now ship as built-ins,
the conflict message now includes '(built-in tool supersedes — consider
removing <path>)' and the log level is downgraded from 'Extension load error'
to 'Extension conflict'.
Changes:
- resource-loader.ts: detect built-in vs user extension conflicts, add hint
- cli.ts: downgrade severity for superseded-tool conflicts
Fixes #1347
* test: fix always-skipped preferences test, add test:marketplace script
- preferences.test.ts: Replace always-skipped getIsolationMode test with
a filesystem-independent version that validates the default through
validatePreferences() instead of reading ~/.gsd/preferences.md.
Reduces skipped count from 3 → 2.
- package.json: Add test:marketplace script for running marketplace
contract tests (claude-import-tui, plugin-importer-live,
marketplace-discovery) with GSD_TEST_CLONE_MARKETPLACES=1.
These tests need external repos and self-skip in unit test runs.
Remaining 2 skips:
- Marketplace contract test suites (need external repos, run via test:marketplace)
- Windows-only tests in validate-directory.test.ts are platform-conditional
and correctly skip on macOS
* fix: use execFileSync in regression tests for Windows portability
The regression tests used execSync with shell-dependent constructs:
- '&&' command chaining (works in bash/cmd but fragile)
- Single-quoted commit messages (bash-only, cmd.exe splits on spaces)
Replaced with execFileSync via a git() helper that bypasses the shell
entirely. Each git operation is a separate call with proper argument
arrays, eliminating all shell interpretation issues.
Fixes windows-portability CI failure.
* fix: guard milestone completion against missing slice summaries (#1368)
Auto-mode could report a milestone as complete after executing only the
last slice, skipping earlier unexecuted slices. The milestone completion
signal fired based on roadmap checkbox state, which could be stale or
inconsistent after worktree transitions.
Changes:
- auto-dispatch.ts: Added slice SUMMARY file existence check to both
validating-milestone and completing-milestone dispatch rules. If any
slice lacks a SUMMARY file, dispatch stops with a diagnostic error
instead of proceeding to validation/completion.
- validate-milestone.test.ts: Updated tests to create slice summary
files (required by the new guard).
- file-watcher.test.ts: Fixed flaky 'auth.json change emits auth-changed
event' test by adding watcher initialization delay and increasing event
propagation timeout (race condition when run in full suite).
Fixes #1368
* fix: warn on common misspelled preference keys + verify field guidance (#1373, #1341)
#1373: Users setting 'taskIsolation.mode: none' instead of 'git.isolation: none'
got a generic 'unknown key' warning. Added KEY_MIGRATION_HINTS that map common
misspellings (taskIsolation, task_isolation, isolation, manage_gitignore, auto_push,
main_branch) to their correct git.* equivalents with actionable messages.
#1341: Planning agent writes aspirational prose in Verify fields ('Sections 3.1
and 3.2 exist with exact formulas. Zero TBD.') instead of executable commands.
Added explicit verify field rules to the plan template: must be mechanically
executable, with examples of good vs bad patterns for content tasks.
Fixes #1373, partially addresses #1341
* refactor: extract roadmap-mutations.ts + shared test-utils.ts
Consolidation:
- roadmap-mutations.ts: Extracted markSliceDoneInRoadmap() and markTaskDoneInPlan()
from duplicated implementations in doctor.ts, mechanical-completion.ts, and
auto-recovery.ts. All three callers used identical regex patterns.
mechanical-completion.ts and auto-recovery.ts now import the shared utility.
(doctor.ts deferred — touched by PR #1349)
- test-utils.ts: Shared cross-platform test utilities for GSD extension tests.
Provides git() helper (execFileSync, no shell), makeTempRepo() with
core.autocrlf=false, cleanup(), createFile(), safeReadFile(), and
writeMilestoneFixture(). 12 test files currently define their own versions
of these helpers — new tests should import from test-utils.ts instead.
Security audit: No injection vectors (sid/tid are alphanumeric from roadmap
parser), no path traversal, no secrets, no new dependencies.
* fix: port conflict false positive on non-Node projects + paused worktree resume (#1381, #1383)
projects without package.json. macOS AirPlay Receiver listens on port 5000,
causing a spurious warning on non-Node projects.
Fix: Skip port checks entirely when no package.json exists. When using
default ports, filter out 5000 on macOS.
in-memory only. Re-entering /gsd started a fresh bootstrap from the project
root instead of the active worktree.
Fix: pauseAuto() now writes paused-session.json to .gsd/runtime/ with
milestoneId, worktreePath, originalBasePath, and stepMode. startAuto()
checks for this file before bootstrap and restores the paused session
context, including worktree re-entry. stopAuto() cleans up the file.
Fixes #1381, #1383
* fix: catch spawn ENOENT in uncaught exception guard + snapshot session lock path (#1384, #1363)
uncaught exception and crashes auto-mode. The EPIPE guard now also catches
ENOENT from spawn syscalls — logs the error and continues instead of
terminating the process.
the lock path differently via gsdRoot() because basePath could be either the
project root or a worktree path. gsdRoot() produces different results for
each, so the lock was written to one path and validated against another.
Fix: Snapshot the resolved lock path (_snapshotLockPath) at acquisition time
and reuse it for all subsequent lock operations within the session.
Fixes #1384, #1363
* fix: suppress false-positive lock compromise + skip migration with active worktrees (#1362, #1337)
because the event loop stall delays the heartbeat mtime update. The handler
now checks elapsed time since acquisition — if within the 30-minute stale
window, it logs a warning and continues instead of setting _lockCompromised.
Real takeovers (past the stale window) still trigger the compromise flag.
even when .gsd/worktrees/ contained active git worktrees with locked
directory handles. This caused EBUSY errors and destructive data loss.
Migration now checks for active worktree directories and skips entirely
if any are found.
Fixes #1362, #1337
2026-03-19 19:06:01 -04:00
2026-04-07 12:35:43 -05:00
// Guard constant for consecutive bootstrap attempts that found phase === "complete".
// Counter moved to AutoSession.consecutiveCompleteBootstraps so s.reset() clears it.
2026-04-05 00:49:29 -04:00
const MAX_CONSECUTIVE_COMPLETE_BOOTSTRAPS = 2 ;
export async function openProjectDbIfPresent ( basePath : string ) : Promise < void > {
2026-03-27 18:19:24 +01:00
const gsdDbPath = resolveProjectRootDbPath ( basePath ) ;
2026-04-05 00:49:29 -04:00
if ( ! existsSync ( gsdDbPath ) || isDbAvailable ( ) ) return ;
2026-03-27 18:19:24 +01:00
try {
openDatabase ( gsdDbPath ) ;
fix(gsd): add diagnostic logging to empty catch blocks in auto-mode
Auto-mode has empty catch blocks across 11 files that silently
swallow errors. When these operations fail (DB writes, git commands,
file sync, worktree operations), the error is lost and downstream
systems see stale or inconsistent state — leading to stuck loops,
phantom milestones, and silent data loss.
Replace every empty catch with a process.stderr.write() call that
logs the operation context and error message. Format:
gsd [filename]: <operation> failed: <error.message>
For catches already annotated with /* non-fatal */ or /* best-effort */
comments, the logging is added alongside the annotation to preserve
the original intent while making failures observable.
Adds a regression test that scans all auto-mode source files and
asserts no empty catch blocks remain.
Files modified (11):
auto-worktree.ts, auto.ts, auto-recovery.ts, auto-prompts.ts,
auto-dashboard.ts, auto-start.ts, auto-timers.ts, auto-post-unit.ts,
auto-dispatch.ts, auto-unit-closeout.ts, auto/phases.ts
No behavioral changes — only diagnostic output added.
Addresses #3348, addresses #3345
2026-04-04 04:03:14 -07:00
} catch ( err ) {
2026-04-05 00:49:29 -04:00
logWarning ( "engine" , ` gsd-db: failed to open existing database: ${ err instanceof Error ? err.message : String ( err ) } ` ) ;
2026-03-27 18:19:24 +01:00
}
}
2026-04-07 16:33:03 -05:00
/ * *
* Audit for orphaned milestone branches at bootstrap .
*
* After a milestone completes , the teardown step ( merge branch → main ,
* delete branch , remove worktree ) runs as a post - completion engine step .
* If the session ends between completion and teardown , the branch and
* worktree are orphaned — the DB says "complete" so auto - mode won ' t
* re - enter the milestone , and the teardown is never retried .
*
* This audit runs on every fresh bootstrap to catch that gap :
* 1 . Lists all local ` milestone/* ` branches .
* 2 . For each , checks if the milestone ' s DB status is "complete" .
* 3 . If the branch is already merged into main → deletes the branch
* and cleans up any orphaned worktree directory ( safe , no data loss ) .
* 4 . If the branch is NOT merged → preserves it and warns the user
* so they can merge manually ( data safety first ) .
*
* Returns a summary of actions taken for the caller to surface via notify .
* /
export function auditOrphanedMilestoneBranches (
basePath : string ,
isolationMode : "worktree" | "branch" | "none" ,
) : { recovered : string [ ] ; warnings : string [ ] } {
const recovered : string [ ] = [ ] ;
const warnings : string [ ] = [ ] ;
// Skip in none mode — no milestone branches are created
if ( isolationMode === "none" ) return { recovered , warnings } ;
// Skip if DB not available — can't determine completion status
if ( ! isDbAvailable ( ) ) return { recovered , warnings } ;
let milestoneBranches : string [ ] ;
try {
milestoneBranches = nativeBranchList ( basePath , "milestone/*" ) ;
} catch {
// git branch list failed — skip audit
return { recovered , warnings } ;
}
if ( milestoneBranches . length === 0 ) return { recovered , warnings } ;
// Detect main branch for merge-check
let mainBranch : string ;
try {
mainBranch = nativeDetectMainBranch ( basePath ) ;
} catch {
mainBranch = "main" ;
}
// Get branches already merged into main
let mergedBranches : Set < string > ;
try {
mergedBranches = new Set ( nativeBranchListMerged ( basePath , mainBranch , "milestone/*" ) ) ;
} catch {
mergedBranches = new Set ( ) ;
}
for ( const branch of milestoneBranches ) {
const milestoneId = branch . replace ( /^milestone\// , "" ) ;
const milestone = getMilestone ( milestoneId ) ;
// Only audit completed milestones
if ( ! milestone || milestone . status !== "complete" ) continue ;
const isMerged = mergedBranches . has ( branch ) ;
if ( isMerged ) {
// Branch is merged — safe to delete branch and clean up worktree dir
try {
nativeBranchDelete ( basePath , branch , true ) ;
recovered . push ( ` Deleted merged branch ${ branch } for completed milestone ${ milestoneId } . ` ) ;
} catch ( err ) {
warnings . push ( ` Failed to delete merged branch ${ branch } : ${ err instanceof Error ? err.message : String ( err ) } ` ) ;
}
// Clean up orphaned worktree directory if it exists
const wtDir = getWorktreeDir ( basePath , milestoneId ) ;
if ( existsSync ( wtDir ) ) {
// Try git worktree remove first (handles registered worktrees)
try {
nativeWorktreeRemove ( basePath , wtDir , true ) ;
2026-04-07 21:41:08 -05:00
} catch ( e ) {
2026-04-07 16:33:03 -05:00
// Not a registered worktree — expected for orphaned dirs
2026-04-07 21:41:08 -05:00
logWarning ( "engine" , ` worktree remove failed (expected for orphaned dirs): ${ e instanceof Error ? e.message : String ( e ) } ` ) ;
2026-04-07 16:33:03 -05:00
}
// If the directory still exists after git worktree remove (either it
// wasn't registered or the remove was a noop), fall back to direct
// filesystem removal — but only inside .gsd/worktrees/ for safety (#2365).
if ( existsSync ( wtDir ) ) {
if ( isInsideWorktreesDir ( basePath , wtDir ) ) {
try {
rmSync ( wtDir , { recursive : true , force : true } ) ;
recovered . push ( ` Removed orphaned worktree directory for ${ milestoneId } . ` ) ;
} catch ( err2 ) {
warnings . push ( ` Failed to remove worktree directory for ${ milestoneId } : ${ err2 instanceof Error ? err2.message : String ( err2 ) } ` ) ;
}
} else {
warnings . push ( ` Orphaned worktree directory for ${ milestoneId } is outside .gsd/worktrees/ — skipping removal for safety. ` ) ;
}
} else {
recovered . push ( ` Removed orphaned worktree directory for ${ milestoneId } . ` ) ;
}
}
} else {
// Branch is NOT merged — preserve for safety, warn the user
warnings . push (
` Branch ${ branch } exists for completed milestone ${ milestoneId } but is NOT merged into ${ mainBranch } . ` +
` This may contain unmerged work. Merge manually or run \` /gsd health --fix \` to resolve. ` ,
) ;
}
}
return { recovered , warnings } ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
export async function bootstrapAutoSession (
s : AutoSession ,
ctx : ExtensionCommandContext ,
pi : ExtensionAPI ,
base : string ,
verboseMode : boolean ,
requestedStepMode : boolean ,
deps : BootstrapDeps ,
2026-03-20 22:34:30 -04:00
interrupted : InterruptedSessionAssessment ,
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
) : 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 ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
2026-03-18 10:10:56 -05:00
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" ) ;
2026-03-18 10:10:56 -05:00
return false ;
}
2026-03-19 14:12:06 -04:00
function releaseLockAndReturn ( ) : false {
releaseSessionLock ( base ) ;
clearLock ( base ) ;
return false ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
2026-03-27 21:47:14 +01:00
// Capture the user's session model before guided-flow dispatch can apply a
// phase-specific planning model for a discuss turn (#2829).
2026-04-04 17:15:43 -05:00
//
// GSD PREFERENCES.md takes priority over the session model from settings.json
// (#3517). The session model (ctx.model) comes from findInitialModel() which
// reads defaultProvider/defaultModel from ~/.gsd/agent/settings.json. When
// the user has explicit model preferences in PREFERENCES.md, those should win.
2026-04-04 18:10:50 -05:00
const preferredModel = resolveDefaultSessionModel ( ctx . model ? . provider ) ;
2026-04-04 17:15:43 -05:00
const startModelSnapshot = preferredModel
? ? ( ctx . model
? { provider : ctx.model.provider , id : ctx.model.id }
: null ) ;
2026-03-27 21:47:14 +01:00
2026-03-19 14:12:06 -04:00
try {
2026-03-21 01:56:19 +10:00
// Validate GSD_PROJECT_ID early so the user gets immediate feedback
const customProjectId = process . env . GSD_PROJECT_ID ;
if ( customProjectId && ! validateProjectId ( customProjectId ) ) {
ctx . ui . notify (
` GSD_PROJECT_ID must contain only alphanumeric characters, hyphens, and underscores. Got: " ${ customProjectId } " ` ,
"error" ,
) ;
return releaseLockAndReturn ( ) ;
}
2026-03-25 18:42:27 +00:00
// Ensure git repo exists *locally* at base.
// nativeIsRepo() uses `git rev-parse` which traverses up to parent dirs,
// so a parent repo can make it return true even when base has no .git of
// its own. Check for a local .git instead (defense-in-depth for the case
// where isInheritedRepo() returns a false negative, e.g. stale .gsd at
// the parent git root). See #2393 and related issue.
const hasLocalGit = existsSync ( join ( base , ".git" ) ) ;
if ( ! hasLocalGit || isInheritedRepo ( 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" ;
2026-03-19 14:12:06 -04:00
nativeInit ( base , mainBranch ) ;
}
fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364) (#1367)
* rfc: GitOps branching & versioning strategy proposal
Proposes a Git-Flow Lite model with automated integration branches:
main ← production-ready, tagged releases only
next ← integration branch for next minor (PRs target here)
release/X.Y ← stabilization branch, only bugfixes allowed
hotfix/X.Y.Z ← emergency fixes cherry-picked to release
Includes:
- RFC document with lifecycle diagrams, migration path, open questions
- Workflow scaffolds (in docs/proposals/workflows/, NOT .github/):
- create-release.yml: manual dispatch to cut release branch from next
- sync-next.yml: auto-sync next branch after version tags
- backmerge.yml: auto back-merge release fixes to next
This is an experimental proposal requesting community feedback before
any implementation. The workflow files are inert scaffolds — they do
not run in CI.
* fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364)
CRITICAL DATA-LOSS FIX: ensureGitignore() unconditionally added '.gsd' to
.gitignore even when .gsd/ was a real git-tracked directory, causing git to
report ~889 tracked files as deleted.
Root cause: BASELINE_PATTERNS included '.gsd' unconditionally, and the
gitignore modification ran BEFORE migration checks in auto-start.ts.
Changes:
- Add hasGitTrackedGsdFiles() helper using nativeLsFiles to detect tracked
.gsd/ content
- ensureGitignore() now skips the '.gsd' pattern when .gsd/ has tracked files
- untrackRuntimeFiles() now skips entirely when .gsd/ has tracked files
- migrateToExternalState() aborts when .gsd/ has tracked files
- Reorder auto-start.ts: migration runs BEFORE gitignore modification
- Add 8 regression tests covering all scenarios
Fixes #1364
* fix: break recursive dialog loop when all milestones complete (#1348)
Two interacting bugs:
1. Recursive dialog loop: When all milestones are complete, bootstrapAutoSession
calls showSmartEntry → sets pendingAutoStart → checkAutoStartAfterDiscuss
calls startAuto → bootstrapAutoSession → showSmartEntry → infinite loop.
The discuss workflow completes without producing a milestone directory, so
phase stays 'complete' and the cycle never breaks.
Fix: Add a re-entry counter (_consecutiveCompleteBootstraps) that tracks
how many times bootstrapAutoSession enters the 'complete' branch without
advancing. After 2 consecutive attempts, break the loop with a warning
message and return false.
2. Missing _releaseFunction = null in retry lock onCompromised handler:
The retry lock path in session-lock.ts set _lockCompromised but didn't
null out _releaseFunction, which could leave a stale reference that
masks the compromise detection in validateSessionLock().
Fixes #1348
* fix: self-heal stale roadmap checkbox for interrupted complete-slice (#1350)
When complete-slice is interrupted after writing SUMMARY.md and UAT.md but
before flipping the roadmap checkbox, auto-mode enters an infinite loop —
re-launching the same complete-slice unit because the dispatch loop uses
the roadmap checkbox as the sole 'slice done' signal.
Fix: Add a self-heal case in selfHealRuntimeRecords that detects when
SUMMARY + UAT exist but the roadmap checkbox is unchecked, and auto-fixes
the checkbox. This allows the verification to pass and the dispatch loop
to advance.
Fixes #1350
* fix: add EISDIR guard to complete/validate milestone prompts (#1343)
The LLM was passing tasks/ directory paths to the read tool during
milestone completion, causing EISDIR crashes. Added file system safety
instructions to both complete-milestone and validate-milestone prompts
telling the LLM to use ls/find for directory listing, not the read tool.
Fixes #1343
* feat: improve extension conflict messages with removal guidance (#1347)
When a user extension registers tools/commands that now ship as built-ins,
the conflict message now includes '(built-in tool supersedes — consider
removing <path>)' and the log level is downgraded from 'Extension load error'
to 'Extension conflict'.
Changes:
- resource-loader.ts: detect built-in vs user extension conflicts, add hint
- cli.ts: downgrade severity for superseded-tool conflicts
Fixes #1347
* test: fix always-skipped preferences test, add test:marketplace script
- preferences.test.ts: Replace always-skipped getIsolationMode test with
a filesystem-independent version that validates the default through
validatePreferences() instead of reading ~/.gsd/preferences.md.
Reduces skipped count from 3 → 2.
- package.json: Add test:marketplace script for running marketplace
contract tests (claude-import-tui, plugin-importer-live,
marketplace-discovery) with GSD_TEST_CLONE_MARKETPLACES=1.
These tests need external repos and self-skip in unit test runs.
Remaining 2 skips:
- Marketplace contract test suites (need external repos, run via test:marketplace)
- Windows-only tests in validate-directory.test.ts are platform-conditional
and correctly skip on macOS
* fix: use execFileSync in regression tests for Windows portability
The regression tests used execSync with shell-dependent constructs:
- '&&' command chaining (works in bash/cmd but fragile)
- Single-quoted commit messages (bash-only, cmd.exe splits on spaces)
Replaced with execFileSync via a git() helper that bypasses the shell
entirely. Each git operation is a separate call with proper argument
arrays, eliminating all shell interpretation issues.
Fixes windows-portability CI failure.
* fix: guard milestone completion against missing slice summaries (#1368)
Auto-mode could report a milestone as complete after executing only the
last slice, skipping earlier unexecuted slices. The milestone completion
signal fired based on roadmap checkbox state, which could be stale or
inconsistent after worktree transitions.
Changes:
- auto-dispatch.ts: Added slice SUMMARY file existence check to both
validating-milestone and completing-milestone dispatch rules. If any
slice lacks a SUMMARY file, dispatch stops with a diagnostic error
instead of proceeding to validation/completion.
- validate-milestone.test.ts: Updated tests to create slice summary
files (required by the new guard).
- file-watcher.test.ts: Fixed flaky 'auth.json change emits auth-changed
event' test by adding watcher initialization delay and increasing event
propagation timeout (race condition when run in full suite).
Fixes #1368
* fix: warn on common misspelled preference keys + verify field guidance (#1373, #1341)
#1373: Users setting 'taskIsolation.mode: none' instead of 'git.isolation: none'
got a generic 'unknown key' warning. Added KEY_MIGRATION_HINTS that map common
misspellings (taskIsolation, task_isolation, isolation, manage_gitignore, auto_push,
main_branch) to their correct git.* equivalents with actionable messages.
#1341: Planning agent writes aspirational prose in Verify fields ('Sections 3.1
and 3.2 exist with exact formulas. Zero TBD.') instead of executable commands.
Added explicit verify field rules to the plan template: must be mechanically
executable, with examples of good vs bad patterns for content tasks.
Fixes #1373, partially addresses #1341
* refactor: extract roadmap-mutations.ts + shared test-utils.ts
Consolidation:
- roadmap-mutations.ts: Extracted markSliceDoneInRoadmap() and markTaskDoneInPlan()
from duplicated implementations in doctor.ts, mechanical-completion.ts, and
auto-recovery.ts. All three callers used identical regex patterns.
mechanical-completion.ts and auto-recovery.ts now import the shared utility.
(doctor.ts deferred — touched by PR #1349)
- test-utils.ts: Shared cross-platform test utilities for GSD extension tests.
Provides git() helper (execFileSync, no shell), makeTempRepo() with
core.autocrlf=false, cleanup(), createFile(), safeReadFile(), and
writeMilestoneFixture(). 12 test files currently define their own versions
of these helpers — new tests should import from test-utils.ts instead.
Security audit: No injection vectors (sid/tid are alphanumeric from roadmap
parser), no path traversal, no secrets, no new dependencies.
* fix: port conflict false positive on non-Node projects + paused worktree resume (#1381, #1383)
projects without package.json. macOS AirPlay Receiver listens on port 5000,
causing a spurious warning on non-Node projects.
Fix: Skip port checks entirely when no package.json exists. When using
default ports, filter out 5000 on macOS.
in-memory only. Re-entering /gsd started a fresh bootstrap from the project
root instead of the active worktree.
Fix: pauseAuto() now writes paused-session.json to .gsd/runtime/ with
milestoneId, worktreePath, originalBasePath, and stepMode. startAuto()
checks for this file before bootstrap and restores the paused session
context, including worktree re-entry. stopAuto() cleans up the file.
Fixes #1381, #1383
* fix: catch spawn ENOENT in uncaught exception guard + snapshot session lock path (#1384, #1363)
uncaught exception and crashes auto-mode. The EPIPE guard now also catches
ENOENT from spawn syscalls — logs the error and continues instead of
terminating the process.
the lock path differently via gsdRoot() because basePath could be either the
project root or a worktree path. gsdRoot() produces different results for
each, so the lock was written to one path and validated against another.
Fix: Snapshot the resolved lock path (_snapshotLockPath) at acquisition time
and reuse it for all subsequent lock operations within the session.
Fixes #1384, #1363
* fix: suppress false-positive lock compromise + skip migration with active worktrees (#1362, #1337)
because the event loop stall delays the heartbeat mtime update. The handler
now checks elapsed time since acquisition — if within the 30-minute stale
window, it logs a warning and continues instead of setting _lockCompromised.
Real takeovers (past the stale window) still trigger the compromise flag.
even when .gsd/worktrees/ contained active git worktrees with locked
directory handles. This caused EBUSY errors and destructive data loss.
Migration now checks for active worktree directories and skips entirely
if any are found.
Fixes #1362, #1337
2026-03-19 19:06:01 -04:00
// Migrate legacy in-project .gsd/ to external state directory.
// Migration MUST run before ensureGitignore to avoid adding ".gsd" to
// .gitignore when .gsd/ is git-tracked (data-loss bug #1364).
recoverFailedMigration ( base ) ;
const migration = migrateToExternalState ( base ) ;
if ( migration . error ) {
ctx . ui . notify ( ` External state migration warning: ${ migration . error } ` , "warning" ) ;
}
// Ensure symlink exists (handles fresh projects and post-migration)
ensureGsdSymlink ( base ) ;
// Ensure .gitignore has baseline patterns.
// ensureGitignore checks for git-tracked .gsd/ files and skips the
// ".gsd" pattern if the project intentionally tracks .gsd/ in 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
const gitPrefs = loadEffectiveGSDPreferences ( ) ? . preferences ? . git ;
const manageGitignore = gitPrefs ? . manage_gitignore ;
2026-03-23 11:00:02 -06:00
ensureGitignore ( base , { manageGitignore } ) ;
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 ( manageGitignore !== false ) untrackRuntimeFiles ( base ) ;
2026-03-30 16:31:10 -04:00
// Bootstrap milestones/ if it doesn't exist.
// Check milestones/ directly — ensureGsdSymlink above already created .gsd/,
// so checking .gsd/ existence would be dead code (#2942).
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 gsdDir = join ( base , ".gsd" ) ;
2026-03-30 16:31:10 -04:00
const milestonesPath = join ( gsdDir , "milestones" ) ;
if ( ! existsSync ( milestonesPath ) ) {
mkdirSync ( milestonesPath , { recursive : true } ) ;
2026-03-23 11:00:02 -06:00
try {
nativeAddAll ( base ) ;
nativeCommit ( base , "chore: init gsd" ) ;
fix(gsd): add diagnostic logging to empty catch blocks in auto-mode
Auto-mode has empty catch blocks across 11 files that silently
swallow errors. When these operations fail (DB writes, git commands,
file sync, worktree operations), the error is lost and downstream
systems see stale or inconsistent state — leading to stuck loops,
phantom milestones, and silent data loss.
Replace every empty catch with a process.stderr.write() call that
logs the operation context and error message. Format:
gsd [filename]: <operation> failed: <error.message>
For catches already annotated with /* non-fatal */ or /* best-effort */
comments, the logging is added alongside the annotation to preserve
the original intent while making failures observable.
Adds a regression test that scans all auto-mode source files and
asserts no empty catch blocks remain.
Files modified (11):
auto-worktree.ts, auto.ts, auto-recovery.ts, auto-prompts.ts,
auto-dashboard.ts, auto-start.ts, auto-timers.ts, auto-post-unit.ts,
auto-dispatch.ts, auto-unit-closeout.ts, auto/phases.ts
No behavioral changes — only diagnostic output added.
Addresses #3348, addresses #3345
2026-04-04 04:03:14 -07:00
} catch ( err ) {
2026-03-23 11:00:02 -06:00
/* nothing to commit */
refactor(gsd): migrate all catch blocks to centralized workflow-logger
Replace raw process.stderr.write(), console.error(), and empty catch
blocks across 50 GSD files with structured logWarning/logError calls
from the centralized workflow-logger system.
Add 13 new LogComponent types to cover all subsystems: recovery,
session, prompt, dashboard, timer, worktree, command, parallel, fs,
bootstrap, guided, registry, renderer.
Every migrated catch block now automatically:
- Shows in terminal (stderr) with component tag
- Gets buffered for auto-loop stuck-detection summary
- Persists to .gsd/audit-log.jsonl for post-mortem analysis
Update regression test to verify catch blocks use workflow-logger
instead of raw stderr/console, covering auto-mode files and all
explicitly migrated infrastructure files.
Closes #3506
Supersedes the approach in #3496
2026-04-04 13:42:55 -05:00
logWarning ( "engine" , ` mkdir failed: ${ err instanceof Error ? err.message : String ( 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
}
}
2026-03-18 14:05:10 -06:00
2026-04-10 06:03:14 -05:00
if ( ctx . model ? . provider === "claude-code" ) {
try {
const { ensureProjectWorkflowMcpConfig } = await import ( "./mcp-project-config.js" ) ;
const result = ensureProjectWorkflowMcpConfig ( base ) ;
if ( result . status !== "unchanged" ) {
ctx . ui . notify ( ` Claude Code MCP prepared at ${ result . configPath } ` , "info" ) ;
}
} catch ( err ) {
ctx . ui . notify (
` Claude Code MCP prep failed: ${ err instanceof Error ? err.message : String ( err ) } ` ,
"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
// Initialize GitServiceImpl
s . gitService = new GitServiceImpl (
s . basePath ,
loadEffectiveGSDPreferences ( ) ? . preferences ? . git ? ? { } ,
) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ) ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
2026-03-20 22:34:30 -04:00
if ( interrupted . classification !== "recoverable" ) {
s . pendingCrashRecovery = null ;
}
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 ( ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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)
2026-03-25 22:47:18 -06:00
cleanStaleRuntimeUnits (
gsdRoot ( base ) ,
( mid ) = > ! ! resolveMilestoneFile ( base , mid , "SUMMARY" ) ,
) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
fix: isolate guided-flow session state and key discussion milestone queries (#2985) (#3094)
* fix: resolve 4 correctness bugs in GSD extension core (#2985)
Bug 1 — preferences.ts process.cwd() side-channel:
loadEffectiveGSDPreferences() and loadProjectGSDPreferences() now accept
an optional projectRoot parameter. When provided, preferences are loaded
from the specified project directory instead of relying on process.cwd().
All 37+ callers continue to work unchanged (parameter defaults to cwd).
Bug 2 — state.ts DB writes inside read functions (CQS violation):
Extracted disk-to-DB milestone reconciliation into a new exported function
reconcileDiskMilestonesToDb(). deriveState() and deriveStateFromDb() no
longer write to the DB as a side effect of reading state. Callers that
need reconciliation (auto-start.ts, guided-flow.ts, register-hooks.ts)
now call it explicitly before reading state.
Bug 3 — guided-flow.ts module-level session state:
Converted pendingAutoStart from a module-level singleton to a Map keyed
by basePath. Concurrent discuss sessions for different projects are now
independent — the second session no longer silently overwrites the first.
Bug 4 — getDiscussionMilestoneId() unkeyed query:
getDiscussionMilestoneId() now accepts an optional basePath parameter for
keyed lookup. When multiple sessions exist and no basePath is provided,
it returns null instead of an arbitrary entry. Single-session backward
compatibility is preserved.
Closes #2985
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: narrow scope to complement igouss PRs #2986 and #2987
Revert changes to preferences.ts (Bug 1), state.ts, auto-start.ts,
register-hooks.ts (Bug 2), and their test files. Those fixes are
covered by @igouss in PRs #2986 and #2987.
This PR now only contains:
- Bug 3: guided-flow.ts pendingAutoStart singleton → Map (session isolation)
- Bug 4: getDiscussionMilestoneId() keyed by basePath
- Supporting unitType additions in preferences-models.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: align source code with test expectations after scope narrowing
The refactor commit (6972c97c) reverted source changes to state.ts,
preferences.ts, and auto-start.ts but left their corresponding test
assertions in place, causing 8 CI failures:
- isValidationTerminal: treat any extracted verdict as terminal (#2769)
- parseHeadingListFormat: handle raw YAML blocks under headings (#2794)
- bootstrapAutoSession: snapshot ctx.model before guided-flow (#2829)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: open project DB before initial deriveState on cold bootstrap (#2841)
When auto-mode starts cold (no prior DB handle), deriveState silently
falls back to markdown-only data for DB-backed helpers (queue-order,
task status), producing stale or incomplete state. Add
openProjectDbIfPresent() helper that resolves the project-root DB path
and opens it before the first deriveState call, ensuring full data
visibility from the start.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 16:33:30 -04:00
// Open the project-root DB before deriveState so DB-backed state
// derivation (queue-order, task status) works on a cold start (#2841).
await openProjectDbIfPresent ( base ) ;
2026-04-07 16:33:03 -05:00
// ── Orphaned milestone branch audit ──
// Catches completed milestones whose teardown (merge + branch delete)
// was lost due to session ending between completion and teardown.
// Must run after DB open and before worktree entry.
try {
const auditResult = auditOrphanedMilestoneBranches ( base , getIsolationMode ( ) ) ;
for ( const msg of auditResult . recovered ) {
ctx . ui . notify ( ` Orphan audit: ${ msg } ` , "info" ) ;
}
for ( const msg of auditResult . warnings ) {
ctx . ui . notify ( ` Orphan audit: ${ msg } ` , "warning" ) ;
}
if ( auditResult . recovered . length > 0 ) {
debugLog ( "orphan-audit" , { recovered : auditResult.recovered , warnings : auditResult.warnings } ) ;
}
} catch ( err ) {
// Non-fatal — the audit is defensive, never block bootstrap
logWarning ( "bootstrap" , ` orphaned milestone branch audit failed: ${ err instanceof Error ? err.message : String ( 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
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 ) ;
}
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
2026-03-25 02:05:39 -04:00
// Milestone branch recovery (#601, #2358)
// Detect survivor milestone branches in both pre-planning and complete phases.
// In phase=complete, the milestone artifacts exist but finalization (merge,
// worktree cleanup) was never run — the survivor branch must be merged.
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 hasSurvivorBranch = false ;
if (
state . activeMilestone &&
2026-03-25 02:05:39 -04:00
( state . phase === "pre-planning" || state . phase === "complete" ) &&
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
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" ,
) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
}
2026-03-21 09:46:17 -06:00
// Survivor branch exists but milestone still needs discussion (#1726):
// The worktree/branch was created but the milestone only has CONTEXT-DRAFT.md.
// Route to the interactive discussion handler instead of falling through to
// auto-mode, which would immediately stop with "needs discussion".
if ( hasSurvivorBranch && state . phase === "needs-discussion" ) {
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 !== "needs-discussion"
) {
state = postState ;
// Discussion succeeded — clear survivor flag so normal flow continues
hasSurvivorBranch = false ;
} else {
ctx . ui . notify (
"Discussion completed but milestone draft was not promoted. Run /gsd to try again." ,
"warning" ,
) ;
return releaseLockAndReturn ( ) ;
}
}
2026-03-25 02:05:39 -04:00
// Survivor branch exists and milestone is complete (#2358):
// The milestone artifacts were written but finalization (merge, worktree
// cleanup) never ran. Run mergeAndExit to finalize, then re-derive state
// so the normal "all milestones complete" or "next milestone" path runs.
if ( hasSurvivorBranch && state . phase === "complete" ) {
const mid = state . activeMilestone ! . id ;
ctx . ui . notify (
` Milestone ${ mid } is complete but branch/worktree was not finalized. Running merge now. ` ,
"info" ,
) ;
const resolver = buildResolver ( ) ;
resolver . mergeAndExit ( mid , {
notify : ctx.ui.notify.bind ( ctx . ui ) ,
} ) ;
invalidateAllCaches ( ) ;
state = await deriveState ( base ) ;
// Clear survivor flag — finalization is done
hasSurvivorBranch = false ;
}
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" ) {
fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364) (#1367)
* rfc: GitOps branching & versioning strategy proposal
Proposes a Git-Flow Lite model with automated integration branches:
main ← production-ready, tagged releases only
next ← integration branch for next minor (PRs target here)
release/X.Y ← stabilization branch, only bugfixes allowed
hotfix/X.Y.Z ← emergency fixes cherry-picked to release
Includes:
- RFC document with lifecycle diagrams, migration path, open questions
- Workflow scaffolds (in docs/proposals/workflows/, NOT .github/):
- create-release.yml: manual dispatch to cut release branch from next
- sync-next.yml: auto-sync next branch after version tags
- backmerge.yml: auto back-merge release fixes to next
This is an experimental proposal requesting community feedback before
any implementation. The workflow files are inert scaffolds — they do
not run in CI.
* fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364)
CRITICAL DATA-LOSS FIX: ensureGitignore() unconditionally added '.gsd' to
.gitignore even when .gsd/ was a real git-tracked directory, causing git to
report ~889 tracked files as deleted.
Root cause: BASELINE_PATTERNS included '.gsd' unconditionally, and the
gitignore modification ran BEFORE migration checks in auto-start.ts.
Changes:
- Add hasGitTrackedGsdFiles() helper using nativeLsFiles to detect tracked
.gsd/ content
- ensureGitignore() now skips the '.gsd' pattern when .gsd/ has tracked files
- untrackRuntimeFiles() now skips entirely when .gsd/ has tracked files
- migrateToExternalState() aborts when .gsd/ has tracked files
- Reorder auto-start.ts: migration runs BEFORE gitignore modification
- Add 8 regression tests covering all scenarios
Fixes #1364
* fix: break recursive dialog loop when all milestones complete (#1348)
Two interacting bugs:
1. Recursive dialog loop: When all milestones are complete, bootstrapAutoSession
calls showSmartEntry → sets pendingAutoStart → checkAutoStartAfterDiscuss
calls startAuto → bootstrapAutoSession → showSmartEntry → infinite loop.
The discuss workflow completes without producing a milestone directory, so
phase stays 'complete' and the cycle never breaks.
Fix: Add a re-entry counter (_consecutiveCompleteBootstraps) that tracks
how many times bootstrapAutoSession enters the 'complete' branch without
advancing. After 2 consecutive attempts, break the loop with a warning
message and return false.
2. Missing _releaseFunction = null in retry lock onCompromised handler:
The retry lock path in session-lock.ts set _lockCompromised but didn't
null out _releaseFunction, which could leave a stale reference that
masks the compromise detection in validateSessionLock().
Fixes #1348
* fix: self-heal stale roadmap checkbox for interrupted complete-slice (#1350)
When complete-slice is interrupted after writing SUMMARY.md and UAT.md but
before flipping the roadmap checkbox, auto-mode enters an infinite loop —
re-launching the same complete-slice unit because the dispatch loop uses
the roadmap checkbox as the sole 'slice done' signal.
Fix: Add a self-heal case in selfHealRuntimeRecords that detects when
SUMMARY + UAT exist but the roadmap checkbox is unchecked, and auto-fixes
the checkbox. This allows the verification to pass and the dispatch loop
to advance.
Fixes #1350
* fix: add EISDIR guard to complete/validate milestone prompts (#1343)
The LLM was passing tasks/ directory paths to the read tool during
milestone completion, causing EISDIR crashes. Added file system safety
instructions to both complete-milestone and validate-milestone prompts
telling the LLM to use ls/find for directory listing, not the read tool.
Fixes #1343
* feat: improve extension conflict messages with removal guidance (#1347)
When a user extension registers tools/commands that now ship as built-ins,
the conflict message now includes '(built-in tool supersedes — consider
removing <path>)' and the log level is downgraded from 'Extension load error'
to 'Extension conflict'.
Changes:
- resource-loader.ts: detect built-in vs user extension conflicts, add hint
- cli.ts: downgrade severity for superseded-tool conflicts
Fixes #1347
* test: fix always-skipped preferences test, add test:marketplace script
- preferences.test.ts: Replace always-skipped getIsolationMode test with
a filesystem-independent version that validates the default through
validatePreferences() instead of reading ~/.gsd/preferences.md.
Reduces skipped count from 3 → 2.
- package.json: Add test:marketplace script for running marketplace
contract tests (claude-import-tui, plugin-importer-live,
marketplace-discovery) with GSD_TEST_CLONE_MARKETPLACES=1.
These tests need external repos and self-skip in unit test runs.
Remaining 2 skips:
- Marketplace contract test suites (need external repos, run via test:marketplace)
- Windows-only tests in validate-directory.test.ts are platform-conditional
and correctly skip on macOS
* fix: use execFileSync in regression tests for Windows portability
The regression tests used execSync with shell-dependent constructs:
- '&&' command chaining (works in bash/cmd but fragile)
- Single-quoted commit messages (bash-only, cmd.exe splits on spaces)
Replaced with execFileSync via a git() helper that bypasses the shell
entirely. Each git operation is a separate call with proper argument
arrays, eliminating all shell interpretation issues.
Fixes windows-portability CI failure.
* fix: guard milestone completion against missing slice summaries (#1368)
Auto-mode could report a milestone as complete after executing only the
last slice, skipping earlier unexecuted slices. The milestone completion
signal fired based on roadmap checkbox state, which could be stale or
inconsistent after worktree transitions.
Changes:
- auto-dispatch.ts: Added slice SUMMARY file existence check to both
validating-milestone and completing-milestone dispatch rules. If any
slice lacks a SUMMARY file, dispatch stops with a diagnostic error
instead of proceeding to validation/completion.
- validate-milestone.test.ts: Updated tests to create slice summary
files (required by the new guard).
- file-watcher.test.ts: Fixed flaky 'auth.json change emits auth-changed
event' test by adding watcher initialization delay and increasing event
propagation timeout (race condition when run in full suite).
Fixes #1368
* fix: warn on common misspelled preference keys + verify field guidance (#1373, #1341)
#1373: Users setting 'taskIsolation.mode: none' instead of 'git.isolation: none'
got a generic 'unknown key' warning. Added KEY_MIGRATION_HINTS that map common
misspellings (taskIsolation, task_isolation, isolation, manage_gitignore, auto_push,
main_branch) to their correct git.* equivalents with actionable messages.
#1341: Planning agent writes aspirational prose in Verify fields ('Sections 3.1
and 3.2 exist with exact formulas. Zero TBD.') instead of executable commands.
Added explicit verify field rules to the plan template: must be mechanically
executable, with examples of good vs bad patterns for content tasks.
Fixes #1373, partially addresses #1341
* refactor: extract roadmap-mutations.ts + shared test-utils.ts
Consolidation:
- roadmap-mutations.ts: Extracted markSliceDoneInRoadmap() and markTaskDoneInPlan()
from duplicated implementations in doctor.ts, mechanical-completion.ts, and
auto-recovery.ts. All three callers used identical regex patterns.
mechanical-completion.ts and auto-recovery.ts now import the shared utility.
(doctor.ts deferred — touched by PR #1349)
- test-utils.ts: Shared cross-platform test utilities for GSD extension tests.
Provides git() helper (execFileSync, no shell), makeTempRepo() with
core.autocrlf=false, cleanup(), createFile(), safeReadFile(), and
writeMilestoneFixture(). 12 test files currently define their own versions
of these helpers — new tests should import from test-utils.ts instead.
Security audit: No injection vectors (sid/tid are alphanumeric from roadmap
parser), no path traversal, no secrets, no new dependencies.
* fix: port conflict false positive on non-Node projects + paused worktree resume (#1381, #1383)
projects without package.json. macOS AirPlay Receiver listens on port 5000,
causing a spurious warning on non-Node projects.
Fix: Skip port checks entirely when no package.json exists. When using
default ports, filter out 5000 on macOS.
in-memory only. Re-entering /gsd started a fresh bootstrap from the project
root instead of the active worktree.
Fix: pauseAuto() now writes paused-session.json to .gsd/runtime/ with
milestoneId, worktreePath, originalBasePath, and stepMode. startAuto()
checks for this file before bootstrap and restores the paused session
context, including worktree re-entry. stopAuto() cleans up the file.
Fixes #1381, #1383
* fix: catch spawn ENOENT in uncaught exception guard + snapshot session lock path (#1384, #1363)
uncaught exception and crashes auto-mode. The EPIPE guard now also catches
ENOENT from spawn syscalls — logs the error and continues instead of
terminating the process.
the lock path differently via gsdRoot() because basePath could be either the
project root or a worktree path. gsdRoot() produces different results for
each, so the lock was written to one path and validated against another.
Fix: Snapshot the resolved lock path (_snapshotLockPath) at acquisition time
and reuse it for all subsequent lock operations within the session.
Fixes #1384, #1363
* fix: suppress false-positive lock compromise + skip migration with active worktrees (#1362, #1337)
because the event loop stall delays the heartbeat mtime update. The handler
now checks elapsed time since acquisition — if within the 30-minute stale
window, it logs a warning and continues instead of setting _lockCompromised.
Real takeovers (past the stale window) still trigger the compromise flag.
even when .gsd/worktrees/ contained active git worktrees with locked
directory handles. This caused EBUSY errors and destructive data loss.
Migration now checks for active worktree directories and skips entirely
if any are found.
Fixes #1362, #1337
2026-03-19 19:06:01 -04:00
// Guard against recursive dialog loop (#1348):
// If we've entered this branch multiple times in quick succession,
// the discuss workflow isn't producing a milestone. Break the cycle.
2026-04-07 12:35:43 -05:00
s . consecutiveCompleteBootstraps ++ ;
if ( s . consecutiveCompleteBootstraps > MAX_CONSECUTIVE_COMPLETE_BOOTSTRAPS ) {
s . consecutiveCompleteBootstraps = 0 ;
fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364) (#1367)
* rfc: GitOps branching & versioning strategy proposal
Proposes a Git-Flow Lite model with automated integration branches:
main ← production-ready, tagged releases only
next ← integration branch for next minor (PRs target here)
release/X.Y ← stabilization branch, only bugfixes allowed
hotfix/X.Y.Z ← emergency fixes cherry-picked to release
Includes:
- RFC document with lifecycle diagrams, migration path, open questions
- Workflow scaffolds (in docs/proposals/workflows/, NOT .github/):
- create-release.yml: manual dispatch to cut release branch from next
- sync-next.yml: auto-sync next branch after version tags
- backmerge.yml: auto back-merge release fixes to next
This is an experimental proposal requesting community feedback before
any implementation. The workflow files are inert scaffolds — they do
not run in CI.
* fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364)
CRITICAL DATA-LOSS FIX: ensureGitignore() unconditionally added '.gsd' to
.gitignore even when .gsd/ was a real git-tracked directory, causing git to
report ~889 tracked files as deleted.
Root cause: BASELINE_PATTERNS included '.gsd' unconditionally, and the
gitignore modification ran BEFORE migration checks in auto-start.ts.
Changes:
- Add hasGitTrackedGsdFiles() helper using nativeLsFiles to detect tracked
.gsd/ content
- ensureGitignore() now skips the '.gsd' pattern when .gsd/ has tracked files
- untrackRuntimeFiles() now skips entirely when .gsd/ has tracked files
- migrateToExternalState() aborts when .gsd/ has tracked files
- Reorder auto-start.ts: migration runs BEFORE gitignore modification
- Add 8 regression tests covering all scenarios
Fixes #1364
* fix: break recursive dialog loop when all milestones complete (#1348)
Two interacting bugs:
1. Recursive dialog loop: When all milestones are complete, bootstrapAutoSession
calls showSmartEntry → sets pendingAutoStart → checkAutoStartAfterDiscuss
calls startAuto → bootstrapAutoSession → showSmartEntry → infinite loop.
The discuss workflow completes without producing a milestone directory, so
phase stays 'complete' and the cycle never breaks.
Fix: Add a re-entry counter (_consecutiveCompleteBootstraps) that tracks
how many times bootstrapAutoSession enters the 'complete' branch without
advancing. After 2 consecutive attempts, break the loop with a warning
message and return false.
2. Missing _releaseFunction = null in retry lock onCompromised handler:
The retry lock path in session-lock.ts set _lockCompromised but didn't
null out _releaseFunction, which could leave a stale reference that
masks the compromise detection in validateSessionLock().
Fixes #1348
* fix: self-heal stale roadmap checkbox for interrupted complete-slice (#1350)
When complete-slice is interrupted after writing SUMMARY.md and UAT.md but
before flipping the roadmap checkbox, auto-mode enters an infinite loop —
re-launching the same complete-slice unit because the dispatch loop uses
the roadmap checkbox as the sole 'slice done' signal.
Fix: Add a self-heal case in selfHealRuntimeRecords that detects when
SUMMARY + UAT exist but the roadmap checkbox is unchecked, and auto-fixes
the checkbox. This allows the verification to pass and the dispatch loop
to advance.
Fixes #1350
* fix: add EISDIR guard to complete/validate milestone prompts (#1343)
The LLM was passing tasks/ directory paths to the read tool during
milestone completion, causing EISDIR crashes. Added file system safety
instructions to both complete-milestone and validate-milestone prompts
telling the LLM to use ls/find for directory listing, not the read tool.
Fixes #1343
* feat: improve extension conflict messages with removal guidance (#1347)
When a user extension registers tools/commands that now ship as built-ins,
the conflict message now includes '(built-in tool supersedes — consider
removing <path>)' and the log level is downgraded from 'Extension load error'
to 'Extension conflict'.
Changes:
- resource-loader.ts: detect built-in vs user extension conflicts, add hint
- cli.ts: downgrade severity for superseded-tool conflicts
Fixes #1347
* test: fix always-skipped preferences test, add test:marketplace script
- preferences.test.ts: Replace always-skipped getIsolationMode test with
a filesystem-independent version that validates the default through
validatePreferences() instead of reading ~/.gsd/preferences.md.
Reduces skipped count from 3 → 2.
- package.json: Add test:marketplace script for running marketplace
contract tests (claude-import-tui, plugin-importer-live,
marketplace-discovery) with GSD_TEST_CLONE_MARKETPLACES=1.
These tests need external repos and self-skip in unit test runs.
Remaining 2 skips:
- Marketplace contract test suites (need external repos, run via test:marketplace)
- Windows-only tests in validate-directory.test.ts are platform-conditional
and correctly skip on macOS
* fix: use execFileSync in regression tests for Windows portability
The regression tests used execSync with shell-dependent constructs:
- '&&' command chaining (works in bash/cmd but fragile)
- Single-quoted commit messages (bash-only, cmd.exe splits on spaces)
Replaced with execFileSync via a git() helper that bypasses the shell
entirely. Each git operation is a separate call with proper argument
arrays, eliminating all shell interpretation issues.
Fixes windows-portability CI failure.
* fix: guard milestone completion against missing slice summaries (#1368)
Auto-mode could report a milestone as complete after executing only the
last slice, skipping earlier unexecuted slices. The milestone completion
signal fired based on roadmap checkbox state, which could be stale or
inconsistent after worktree transitions.
Changes:
- auto-dispatch.ts: Added slice SUMMARY file existence check to both
validating-milestone and completing-milestone dispatch rules. If any
slice lacks a SUMMARY file, dispatch stops with a diagnostic error
instead of proceeding to validation/completion.
- validate-milestone.test.ts: Updated tests to create slice summary
files (required by the new guard).
- file-watcher.test.ts: Fixed flaky 'auth.json change emits auth-changed
event' test by adding watcher initialization delay and increasing event
propagation timeout (race condition when run in full suite).
Fixes #1368
* fix: warn on common misspelled preference keys + verify field guidance (#1373, #1341)
#1373: Users setting 'taskIsolation.mode: none' instead of 'git.isolation: none'
got a generic 'unknown key' warning. Added KEY_MIGRATION_HINTS that map common
misspellings (taskIsolation, task_isolation, isolation, manage_gitignore, auto_push,
main_branch) to their correct git.* equivalents with actionable messages.
#1341: Planning agent writes aspirational prose in Verify fields ('Sections 3.1
and 3.2 exist with exact formulas. Zero TBD.') instead of executable commands.
Added explicit verify field rules to the plan template: must be mechanically
executable, with examples of good vs bad patterns for content tasks.
Fixes #1373, partially addresses #1341
* refactor: extract roadmap-mutations.ts + shared test-utils.ts
Consolidation:
- roadmap-mutations.ts: Extracted markSliceDoneInRoadmap() and markTaskDoneInPlan()
from duplicated implementations in doctor.ts, mechanical-completion.ts, and
auto-recovery.ts. All three callers used identical regex patterns.
mechanical-completion.ts and auto-recovery.ts now import the shared utility.
(doctor.ts deferred — touched by PR #1349)
- test-utils.ts: Shared cross-platform test utilities for GSD extension tests.
Provides git() helper (execFileSync, no shell), makeTempRepo() with
core.autocrlf=false, cleanup(), createFile(), safeReadFile(), and
writeMilestoneFixture(). 12 test files currently define their own versions
of these helpers — new tests should import from test-utils.ts instead.
Security audit: No injection vectors (sid/tid are alphanumeric from roadmap
parser), no path traversal, no secrets, no new dependencies.
* fix: port conflict false positive on non-Node projects + paused worktree resume (#1381, #1383)
projects without package.json. macOS AirPlay Receiver listens on port 5000,
causing a spurious warning on non-Node projects.
Fix: Skip port checks entirely when no package.json exists. When using
default ports, filter out 5000 on macOS.
in-memory only. Re-entering /gsd started a fresh bootstrap from the project
root instead of the active worktree.
Fix: pauseAuto() now writes paused-session.json to .gsd/runtime/ with
milestoneId, worktreePath, originalBasePath, and stepMode. startAuto()
checks for this file before bootstrap and restores the paused session
context, including worktree re-entry. stopAuto() cleans up the file.
Fixes #1381, #1383
* fix: catch spawn ENOENT in uncaught exception guard + snapshot session lock path (#1384, #1363)
uncaught exception and crashes auto-mode. The EPIPE guard now also catches
ENOENT from spawn syscalls — logs the error and continues instead of
terminating the process.
the lock path differently via gsdRoot() because basePath could be either the
project root or a worktree path. gsdRoot() produces different results for
each, so the lock was written to one path and validated against another.
Fix: Snapshot the resolved lock path (_snapshotLockPath) at acquisition time
and reuse it for all subsequent lock operations within the session.
Fixes #1384, #1363
* fix: suppress false-positive lock compromise + skip migration with active worktrees (#1362, #1337)
because the event loop stall delays the heartbeat mtime update. The handler
now checks elapsed time since acquisition — if within the 30-minute stale
window, it logs a warning and continues instead of setting _lockCompromised.
Real takeovers (past the stale window) still trigger the compromise flag.
even when .gsd/worktrees/ contained active git worktrees with locked
directory handles. This caused EBUSY errors and destructive data loss.
Migration now checks for active worktree directories and skips entirely
if any are found.
Fixes #1362, #1337
2026-03-19 19:06:01 -04:00
ctx . ui . notify (
"All milestones are complete and the discussion didn't produce a new one. " +
"Run /gsd to start a new milestone manually." ,
"warning" ,
) ;
return releaseLockAndReturn ( ) ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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"
) {
2026-04-07 12:35:43 -05:00
s . consecutiveCompleteBootstraps = 0 ; // Successfully advanced past "complete"
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ,
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
) ;
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 {
2026-03-19 14:12:06 -04:00
return releaseLockAndReturn ( ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
}
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 ( ) ;
}
}
}
2026-03-21 10:53:48 -04:00
// Active milestone has CONTEXT-DRAFT but no full context — needs discussion
if ( state . phase === "needs-discussion" ) {
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 !== "needs-discussion"
) {
state = postState ;
} else {
ctx . ui . notify (
"Discussion completed but milestone draft was not promoted. 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
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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 ( ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364) (#1367)
* rfc: GitOps branching & versioning strategy proposal
Proposes a Git-Flow Lite model with automated integration branches:
main ← production-ready, tagged releases only
next ← integration branch for next minor (PRs target here)
release/X.Y ← stabilization branch, only bugfixes allowed
hotfix/X.Y.Z ← emergency fixes cherry-picked to release
Includes:
- RFC document with lifecycle diagrams, migration path, open questions
- Workflow scaffolds (in docs/proposals/workflows/, NOT .github/):
- create-release.yml: manual dispatch to cut release branch from next
- sync-next.yml: auto-sync next branch after version tags
- backmerge.yml: auto back-merge release fixes to next
This is an experimental proposal requesting community feedback before
any implementation. The workflow files are inert scaffolds — they do
not run in CI.
* fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364)
CRITICAL DATA-LOSS FIX: ensureGitignore() unconditionally added '.gsd' to
.gitignore even when .gsd/ was a real git-tracked directory, causing git to
report ~889 tracked files as deleted.
Root cause: BASELINE_PATTERNS included '.gsd' unconditionally, and the
gitignore modification ran BEFORE migration checks in auto-start.ts.
Changes:
- Add hasGitTrackedGsdFiles() helper using nativeLsFiles to detect tracked
.gsd/ content
- ensureGitignore() now skips the '.gsd' pattern when .gsd/ has tracked files
- untrackRuntimeFiles() now skips entirely when .gsd/ has tracked files
- migrateToExternalState() aborts when .gsd/ has tracked files
- Reorder auto-start.ts: migration runs BEFORE gitignore modification
- Add 8 regression tests covering all scenarios
Fixes #1364
* fix: break recursive dialog loop when all milestones complete (#1348)
Two interacting bugs:
1. Recursive dialog loop: When all milestones are complete, bootstrapAutoSession
calls showSmartEntry → sets pendingAutoStart → checkAutoStartAfterDiscuss
calls startAuto → bootstrapAutoSession → showSmartEntry → infinite loop.
The discuss workflow completes without producing a milestone directory, so
phase stays 'complete' and the cycle never breaks.
Fix: Add a re-entry counter (_consecutiveCompleteBootstraps) that tracks
how many times bootstrapAutoSession enters the 'complete' branch without
advancing. After 2 consecutive attempts, break the loop with a warning
message and return false.
2. Missing _releaseFunction = null in retry lock onCompromised handler:
The retry lock path in session-lock.ts set _lockCompromised but didn't
null out _releaseFunction, which could leave a stale reference that
masks the compromise detection in validateSessionLock().
Fixes #1348
* fix: self-heal stale roadmap checkbox for interrupted complete-slice (#1350)
When complete-slice is interrupted after writing SUMMARY.md and UAT.md but
before flipping the roadmap checkbox, auto-mode enters an infinite loop —
re-launching the same complete-slice unit because the dispatch loop uses
the roadmap checkbox as the sole 'slice done' signal.
Fix: Add a self-heal case in selfHealRuntimeRecords that detects when
SUMMARY + UAT exist but the roadmap checkbox is unchecked, and auto-fixes
the checkbox. This allows the verification to pass and the dispatch loop
to advance.
Fixes #1350
* fix: add EISDIR guard to complete/validate milestone prompts (#1343)
The LLM was passing tasks/ directory paths to the read tool during
milestone completion, causing EISDIR crashes. Added file system safety
instructions to both complete-milestone and validate-milestone prompts
telling the LLM to use ls/find for directory listing, not the read tool.
Fixes #1343
* feat: improve extension conflict messages with removal guidance (#1347)
When a user extension registers tools/commands that now ship as built-ins,
the conflict message now includes '(built-in tool supersedes — consider
removing <path>)' and the log level is downgraded from 'Extension load error'
to 'Extension conflict'.
Changes:
- resource-loader.ts: detect built-in vs user extension conflicts, add hint
- cli.ts: downgrade severity for superseded-tool conflicts
Fixes #1347
* test: fix always-skipped preferences test, add test:marketplace script
- preferences.test.ts: Replace always-skipped getIsolationMode test with
a filesystem-independent version that validates the default through
validatePreferences() instead of reading ~/.gsd/preferences.md.
Reduces skipped count from 3 → 2.
- package.json: Add test:marketplace script for running marketplace
contract tests (claude-import-tui, plugin-importer-live,
marketplace-discovery) with GSD_TEST_CLONE_MARKETPLACES=1.
These tests need external repos and self-skip in unit test runs.
Remaining 2 skips:
- Marketplace contract test suites (need external repos, run via test:marketplace)
- Windows-only tests in validate-directory.test.ts are platform-conditional
and correctly skip on macOS
* fix: use execFileSync in regression tests for Windows portability
The regression tests used execSync with shell-dependent constructs:
- '&&' command chaining (works in bash/cmd but fragile)
- Single-quoted commit messages (bash-only, cmd.exe splits on spaces)
Replaced with execFileSync via a git() helper that bypasses the shell
entirely. Each git operation is a separate call with proper argument
arrays, eliminating all shell interpretation issues.
Fixes windows-portability CI failure.
* fix: guard milestone completion against missing slice summaries (#1368)
Auto-mode could report a milestone as complete after executing only the
last slice, skipping earlier unexecuted slices. The milestone completion
signal fired based on roadmap checkbox state, which could be stale or
inconsistent after worktree transitions.
Changes:
- auto-dispatch.ts: Added slice SUMMARY file existence check to both
validating-milestone and completing-milestone dispatch rules. If any
slice lacks a SUMMARY file, dispatch stops with a diagnostic error
instead of proceeding to validation/completion.
- validate-milestone.test.ts: Updated tests to create slice summary
files (required by the new guard).
- file-watcher.test.ts: Fixed flaky 'auth.json change emits auth-changed
event' test by adding watcher initialization delay and increasing event
propagation timeout (race condition when run in full suite).
Fixes #1368
* fix: warn on common misspelled preference keys + verify field guidance (#1373, #1341)
#1373: Users setting 'taskIsolation.mode: none' instead of 'git.isolation: none'
got a generic 'unknown key' warning. Added KEY_MIGRATION_HINTS that map common
misspellings (taskIsolation, task_isolation, isolation, manage_gitignore, auto_push,
main_branch) to their correct git.* equivalents with actionable messages.
#1341: Planning agent writes aspirational prose in Verify fields ('Sections 3.1
and 3.2 exist with exact formulas. Zero TBD.') instead of executable commands.
Added explicit verify field rules to the plan template: must be mechanically
executable, with examples of good vs bad patterns for content tasks.
Fixes #1373, partially addresses #1341
* refactor: extract roadmap-mutations.ts + shared test-utils.ts
Consolidation:
- roadmap-mutations.ts: Extracted markSliceDoneInRoadmap() and markTaskDoneInPlan()
from duplicated implementations in doctor.ts, mechanical-completion.ts, and
auto-recovery.ts. All three callers used identical regex patterns.
mechanical-completion.ts and auto-recovery.ts now import the shared utility.
(doctor.ts deferred — touched by PR #1349)
- test-utils.ts: Shared cross-platform test utilities for GSD extension tests.
Provides git() helper (execFileSync, no shell), makeTempRepo() with
core.autocrlf=false, cleanup(), createFile(), safeReadFile(), and
writeMilestoneFixture(). 12 test files currently define their own versions
of these helpers — new tests should import from test-utils.ts instead.
Security audit: No injection vectors (sid/tid are alphanumeric from roadmap
parser), no path traversal, no secrets, no new dependencies.
* fix: port conflict false positive on non-Node projects + paused worktree resume (#1381, #1383)
projects without package.json. macOS AirPlay Receiver listens on port 5000,
causing a spurious warning on non-Node projects.
Fix: Skip port checks entirely when no package.json exists. When using
default ports, filter out 5000 on macOS.
in-memory only. Re-entering /gsd started a fresh bootstrap from the project
root instead of the active worktree.
Fix: pauseAuto() now writes paused-session.json to .gsd/runtime/ with
milestoneId, worktreePath, originalBasePath, and stepMode. startAuto()
checks for this file before bootstrap and restores the paused session
context, including worktree re-entry. stopAuto() cleans up the file.
Fixes #1381, #1383
* fix: catch spawn ENOENT in uncaught exception guard + snapshot session lock path (#1384, #1363)
uncaught exception and crashes auto-mode. The EPIPE guard now also catches
ENOENT from spawn syscalls — logs the error and continues instead of
terminating the process.
the lock path differently via gsdRoot() because basePath could be either the
project root or a worktree path. gsdRoot() produces different results for
each, so the lock was written to one path and validated against another.
Fix: Snapshot the resolved lock path (_snapshotLockPath) at acquisition time
and reuse it for all subsequent lock operations within the session.
Fixes #1384, #1363
* fix: suppress false-positive lock compromise + skip migration with active worktrees (#1362, #1337)
because the event loop stall delays the heartbeat mtime update. The handler
now checks elapsed time since acquisition — if within the 30-minute stale
window, it logs a warning and continues instead of setting _lockCompromised.
Real takeovers (past the stale window) still trigger the compromise flag.
even when .gsd/worktrees/ contained active git worktrees with locked
directory handles. This caused EBUSY errors and destructive data loss.
Migration now checks for active worktree directories and skips entirely
if any are found.
Fixes #1362, #1337
2026-03-19 19:06:01 -04:00
// Successfully resolved an active milestone — reset the re-entry guard
2026-04-07 12:35:43 -05:00
s . consecutiveCompleteBootstraps = 0 ;
fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364) (#1367)
* rfc: GitOps branching & versioning strategy proposal
Proposes a Git-Flow Lite model with automated integration branches:
main ← production-ready, tagged releases only
next ← integration branch for next minor (PRs target here)
release/X.Y ← stabilization branch, only bugfixes allowed
hotfix/X.Y.Z ← emergency fixes cherry-picked to release
Includes:
- RFC document with lifecycle diagrams, migration path, open questions
- Workflow scaffolds (in docs/proposals/workflows/, NOT .github/):
- create-release.yml: manual dispatch to cut release branch from next
- sync-next.yml: auto-sync next branch after version tags
- backmerge.yml: auto back-merge release fixes to next
This is an experimental proposal requesting community feedback before
any implementation. The workflow files are inert scaffolds — they do
not run in CI.
* fix: prevent ensureGitignore from adding .gsd when tracked in git (#1364)
CRITICAL DATA-LOSS FIX: ensureGitignore() unconditionally added '.gsd' to
.gitignore even when .gsd/ was a real git-tracked directory, causing git to
report ~889 tracked files as deleted.
Root cause: BASELINE_PATTERNS included '.gsd' unconditionally, and the
gitignore modification ran BEFORE migration checks in auto-start.ts.
Changes:
- Add hasGitTrackedGsdFiles() helper using nativeLsFiles to detect tracked
.gsd/ content
- ensureGitignore() now skips the '.gsd' pattern when .gsd/ has tracked files
- untrackRuntimeFiles() now skips entirely when .gsd/ has tracked files
- migrateToExternalState() aborts when .gsd/ has tracked files
- Reorder auto-start.ts: migration runs BEFORE gitignore modification
- Add 8 regression tests covering all scenarios
Fixes #1364
* fix: break recursive dialog loop when all milestones complete (#1348)
Two interacting bugs:
1. Recursive dialog loop: When all milestones are complete, bootstrapAutoSession
calls showSmartEntry → sets pendingAutoStart → checkAutoStartAfterDiscuss
calls startAuto → bootstrapAutoSession → showSmartEntry → infinite loop.
The discuss workflow completes without producing a milestone directory, so
phase stays 'complete' and the cycle never breaks.
Fix: Add a re-entry counter (_consecutiveCompleteBootstraps) that tracks
how many times bootstrapAutoSession enters the 'complete' branch without
advancing. After 2 consecutive attempts, break the loop with a warning
message and return false.
2. Missing _releaseFunction = null in retry lock onCompromised handler:
The retry lock path in session-lock.ts set _lockCompromised but didn't
null out _releaseFunction, which could leave a stale reference that
masks the compromise detection in validateSessionLock().
Fixes #1348
* fix: self-heal stale roadmap checkbox for interrupted complete-slice (#1350)
When complete-slice is interrupted after writing SUMMARY.md and UAT.md but
before flipping the roadmap checkbox, auto-mode enters an infinite loop —
re-launching the same complete-slice unit because the dispatch loop uses
the roadmap checkbox as the sole 'slice done' signal.
Fix: Add a self-heal case in selfHealRuntimeRecords that detects when
SUMMARY + UAT exist but the roadmap checkbox is unchecked, and auto-fixes
the checkbox. This allows the verification to pass and the dispatch loop
to advance.
Fixes #1350
* fix: add EISDIR guard to complete/validate milestone prompts (#1343)
The LLM was passing tasks/ directory paths to the read tool during
milestone completion, causing EISDIR crashes. Added file system safety
instructions to both complete-milestone and validate-milestone prompts
telling the LLM to use ls/find for directory listing, not the read tool.
Fixes #1343
* feat: improve extension conflict messages with removal guidance (#1347)
When a user extension registers tools/commands that now ship as built-ins,
the conflict message now includes '(built-in tool supersedes — consider
removing <path>)' and the log level is downgraded from 'Extension load error'
to 'Extension conflict'.
Changes:
- resource-loader.ts: detect built-in vs user extension conflicts, add hint
- cli.ts: downgrade severity for superseded-tool conflicts
Fixes #1347
* test: fix always-skipped preferences test, add test:marketplace script
- preferences.test.ts: Replace always-skipped getIsolationMode test with
a filesystem-independent version that validates the default through
validatePreferences() instead of reading ~/.gsd/preferences.md.
Reduces skipped count from 3 → 2.
- package.json: Add test:marketplace script for running marketplace
contract tests (claude-import-tui, plugin-importer-live,
marketplace-discovery) with GSD_TEST_CLONE_MARKETPLACES=1.
These tests need external repos and self-skip in unit test runs.
Remaining 2 skips:
- Marketplace contract test suites (need external repos, run via test:marketplace)
- Windows-only tests in validate-directory.test.ts are platform-conditional
and correctly skip on macOS
* fix: use execFileSync in regression tests for Windows portability
The regression tests used execSync with shell-dependent constructs:
- '&&' command chaining (works in bash/cmd but fragile)
- Single-quoted commit messages (bash-only, cmd.exe splits on spaces)
Replaced with execFileSync via a git() helper that bypasses the shell
entirely. Each git operation is a separate call with proper argument
arrays, eliminating all shell interpretation issues.
Fixes windows-portability CI failure.
* fix: guard milestone completion against missing slice summaries (#1368)
Auto-mode could report a milestone as complete after executing only the
last slice, skipping earlier unexecuted slices. The milestone completion
signal fired based on roadmap checkbox state, which could be stale or
inconsistent after worktree transitions.
Changes:
- auto-dispatch.ts: Added slice SUMMARY file existence check to both
validating-milestone and completing-milestone dispatch rules. If any
slice lacks a SUMMARY file, dispatch stops with a diagnostic error
instead of proceeding to validation/completion.
- validate-milestone.test.ts: Updated tests to create slice summary
files (required by the new guard).
- file-watcher.test.ts: Fixed flaky 'auth.json change emits auth-changed
event' test by adding watcher initialization delay and increasing event
propagation timeout (race condition when run in full suite).
Fixes #1368
* fix: warn on common misspelled preference keys + verify field guidance (#1373, #1341)
#1373: Users setting 'taskIsolation.mode: none' instead of 'git.isolation: none'
got a generic 'unknown key' warning. Added KEY_MIGRATION_HINTS that map common
misspellings (taskIsolation, task_isolation, isolation, manage_gitignore, auto_push,
main_branch) to their correct git.* equivalents with actionable messages.
#1341: Planning agent writes aspirational prose in Verify fields ('Sections 3.1
and 3.2 exist with exact formulas. Zero TBD.') instead of executable commands.
Added explicit verify field rules to the plan template: must be mechanically
executable, with examples of good vs bad patterns for content tasks.
Fixes #1373, partially addresses #1341
* refactor: extract roadmap-mutations.ts + shared test-utils.ts
Consolidation:
- roadmap-mutations.ts: Extracted markSliceDoneInRoadmap() and markTaskDoneInPlan()
from duplicated implementations in doctor.ts, mechanical-completion.ts, and
auto-recovery.ts. All three callers used identical regex patterns.
mechanical-completion.ts and auto-recovery.ts now import the shared utility.
(doctor.ts deferred — touched by PR #1349)
- test-utils.ts: Shared cross-platform test utilities for GSD extension tests.
Provides git() helper (execFileSync, no shell), makeTempRepo() with
core.autocrlf=false, cleanup(), createFile(), safeReadFile(), and
writeMilestoneFixture(). 12 test files currently define their own versions
of these helpers — new tests should import from test-utils.ts instead.
Security audit: No injection vectors (sid/tid are alphanumeric from roadmap
parser), no path traversal, no secrets, no new dependencies.
* fix: port conflict false positive on non-Node projects + paused worktree resume (#1381, #1383)
projects without package.json. macOS AirPlay Receiver listens on port 5000,
causing a spurious warning on non-Node projects.
Fix: Skip port checks entirely when no package.json exists. When using
default ports, filter out 5000 on macOS.
in-memory only. Re-entering /gsd started a fresh bootstrap from the project
root instead of the active worktree.
Fix: pauseAuto() now writes paused-session.json to .gsd/runtime/ with
milestoneId, worktreePath, originalBasePath, and stepMode. startAuto()
checks for this file before bootstrap and restores the paused session
context, including worktree re-entry. stopAuto() cleans up the file.
Fixes #1381, #1383
* fix: catch spawn ENOENT in uncaught exception guard + snapshot session lock path (#1384, #1363)
uncaught exception and crashes auto-mode. The EPIPE guard now also catches
ENOENT from spawn syscalls — logs the error and continues instead of
terminating the process.
the lock path differently via gsdRoot() because basePath could be either the
project root or a worktree path. gsdRoot() produces different results for
each, so the lock was written to one path and validated against another.
Fix: Snapshot the resolved lock path (_snapshotLockPath) at acquisition time
and reuse it for all subsequent lock operations within the session.
Fixes #1384, #1363
* fix: suppress false-positive lock compromise + skip migration with active worktrees (#1362, #1337)
because the event loop stall delays the heartbeat mtime update. The handler
now checks elapsed time since acquisition — if within the 30-minute stale
window, it logs a warning and continues instead of setting _lockCompromised.
Real takeovers (past the stale window) still trigger the compromise flag.
even when .gsd/worktrees/ contained active git worktrees with locked
directory handles. This caused EBUSY errors and destructive data loss.
Migration now checks for active worktree directories and skips entirely
if any are found.
Fixes #1362, #1337
2026-03-19 19:06:01 -04:00
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 ( ) ;
feat: health check phase 2 — real-time doctor issue visibility across widget, visualizer, and HTML reports (#1644)
* feat: surface real doctor issue details in progress score widget
Previously the progress score traffic light (green/yellow/red) only
showed generic labels like "2 consecutive error units" or "Health
trend declining". The actual doctor issue descriptions were computed
in auto-post-unit but discarded before reaching the widget — only
aggregate counts were stored in HealthSnapshot.
Now the full data flows through:
- HealthSnapshot stores issue details (code, message, severity,
unitId) and fix descriptions alongside the counts
- recordHealthSnapshot() accepts optional issue/fix arrays
(backwards compatible — existing callers unchanged)
- getLatestHealthIssues() and getLatestHealthFixes() retrieve the
most recent details for display
- computeProgressScore() surfaces up to 5 real issue messages
(errors first) and up to 3 recent fixes as ProgressSignals
when the level is yellow or red
- Dashboard overlay renders signal details with ✓/✗/· icons
below the traffic light when degraded
This gives real-time visibility into what the auto-doctor is
detecting and fixing, without requiring manual /gsd doctor runs
or opening the full dashboard to investigate.
* feat: integrate doctor health data into visualizer and HTML reports
Phase 2b: close visibility gaps across visualizer and export surfaces.
Persistence (doctor.ts):
- Enrich DoctorHistoryEntry with issue details (severity, code,
message, unitId) and fix descriptions
- appendDoctorHistory now persists up to 10 issues per entry and
all fix descriptions to doctor-history.jsonl
- Export DoctorHistoryEntry type for consumers
Data layer (visualizer-data.ts):
- Add VisualizerDoctorEntry and VisualizerProgressScore types
- Extend HealthInfo with doctorHistory (last 20 persisted entries)
and progressScore (current in-memory traffic light)
- loadHealth reads doctor-history.jsonl synchronously and snapshots
current progress score when health data exists
TUI visualizer (visualizer-views.ts):
- Health tab now shows "Progress Score" section with traffic light
icon, summary, and all signal details (✓/✗/· prefixed)
- Health tab now shows "Doctor History" section with timestamped
entries, issue messages, and applied fixes
HTML export (export-html.ts):
- Health section includes progress score with colored indicator
and signal breakdown
- Health section includes "Doctor Run History" table with
timestamps, error/warning/fix counts, issue codes, expandable
issue messages, and fix descriptions
* feat: fill remaining health gaps — scope tagging, level notifications, human-readable logs
Gap fills:
Per-milestone/slice scope tagging:
- HealthSnapshot now stores scope (e.g. "M001/S02") from the
doctor run's unit context
- DoctorHistoryEntry persists scope to doctor-history.jsonl
- Visualizer and HTML reports display scope tags per entry
State transition notifications:
- setLevelChangeCallback() registers a handler for progress level
changes (green→yellow, yellow→red, red→green, etc.)
- auto-start.ts wires the callback to ctx.ui.notify on start
- auto.ts clears it on stop
- Notifications include the triggering issue message
Human-readable formatting throughout:
- formatHealthSummary() uses full words: "2 errors, 3 warnings ·
trend degrading · 1 fix applied · 1 of 5 consecutive errors
before escalation · latest: Missing PLAN.md for S03"
- DoctorHistoryEntry stores a human-readable summary field
built from error counts, fix counts, and top issue message
- Visualizer doctor history shows summary instead of "2E 1W 0F"
- HTML export doctor table uses summary column with scope tags
- Post-unit notification says what was fixed ("Doctor: rebuilt
STATE.md; cleared stale lock") instead of "applied 2 fix(es)"
Test updates:
- formatHealthSummary assertions updated for new readable format
* fix: default UAT type to artifact-driven to prevent unnecessary auto-mode pauses (#1651)
When a UAT file has no `## UAT Type` section, `extractUatType()` returns
`undefined`. The fallback was `"human-experience"`, causing `pauseAfterDispatch:
true` in the auto-dispatch rule. Since doctor-generated UAT placeholders never
include a UAT Type section and LLM-executed UATs are always artifact-driven,
the correct default is `"artifact-driven"`.
Closes #1649
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove duplicate doctorScope declaration (CI build fix)
* fix: resolve PR1644 regressions in health views and post-unit hook
---------
Co-authored-by: TÂCHES <afromanguy@me.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 16:33:40 -05:00
// Notify user on health level transitions (green→yellow→red and back)
setLevelChangeCallback ( ( _from , to , summary ) = > {
const level = to === "red" ? "error" : to === "yellow" ? "warning" : "info" ;
ctx . ui . notify ( summary , level as "info" | "warning" | "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
s . autoStartTime = Date . now ( ) ;
s . resourceVersionOnStart = readResourceVersion ( ) ;
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" ) {
2026-03-23 11:00:02 -06:00
captureIntegrationBranch ( 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
}
setActiveMilestoneId ( base , s . currentMilestoneId ) ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
2026-04-06 18:55:33 -07:00
// Guard against stale milestone branch when isolation:none (#3613).
// A prior session with isolation:branch/worktree may have left HEAD on
// milestone/<MID>. Auto-checkout back to the integration branch.
if ( getIsolationMode ( ) === "none" && nativeIsRepo ( base ) ) {
try {
const currentBranch = nativeGetCurrentBranch ( base ) ;
if ( currentBranch . startsWith ( "milestone/" ) ) {
const integrationBranch = nativeDetectMainBranch ( base ) ;
nativeCheckoutBranch ( base , integrationBranch ) ;
2026-04-06 22:45:03 -07:00
logWarning ( "bootstrap" , ` Returned to " ${ integrationBranch } " — HEAD was on stale milestone branch " ${ currentBranch } " (isolation: none does not use milestone branches). ` ) ;
2026-04-06 18:55:33 -07:00
}
2026-04-06 23:00:06 -07:00
} catch ( err ) {
logWarning ( "bootstrap" , ` Could not auto-checkout from stale milestone branch: ${ err instanceof Error ? err.message : String ( err ) } ` ) ;
2026-04-06 18:55:33 -07:00
}
}
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 = > {
2026-03-20 11:10:45 -03:00
// Direct layout: /.gsd/worktrees/
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 marker = ` ${ pathSep } .gsd ${ pathSep } worktrees ${ pathSep } ` ;
if ( p . includes ( marker ) ) return true ;
const worktreesSuffix = ` ${ pathSep } .gsd ${ pathSep } worktrees ` ;
2026-03-20 11:10:45 -03:00
if ( p . endsWith ( worktreesSuffix ) ) return true ;
// Symlink-resolved layout: /.gsd/projects/<hash>/worktrees/
const symlinkRe = new RegExp (
` \\ ${ pathSep } \\ .gsd \\ ${ pathSep } projects \\ ${ pathSep } [a-f0-9]+ \\ ${ pathSep } worktrees(?: \\ ${ pathSep } | $ ) ` ,
) ;
return symlinkRe . test ( p ) ;
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 (
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 ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
}
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 ──
fix: isolate guided-flow session state and key discussion milestone queries (#2985) (#3094)
* fix: resolve 4 correctness bugs in GSD extension core (#2985)
Bug 1 — preferences.ts process.cwd() side-channel:
loadEffectiveGSDPreferences() and loadProjectGSDPreferences() now accept
an optional projectRoot parameter. When provided, preferences are loaded
from the specified project directory instead of relying on process.cwd().
All 37+ callers continue to work unchanged (parameter defaults to cwd).
Bug 2 — state.ts DB writes inside read functions (CQS violation):
Extracted disk-to-DB milestone reconciliation into a new exported function
reconcileDiskMilestonesToDb(). deriveState() and deriveStateFromDb() no
longer write to the DB as a side effect of reading state. Callers that
need reconciliation (auto-start.ts, guided-flow.ts, register-hooks.ts)
now call it explicitly before reading state.
Bug 3 — guided-flow.ts module-level session state:
Converted pendingAutoStart from a module-level singleton to a Map keyed
by basePath. Concurrent discuss sessions for different projects are now
independent — the second session no longer silently overwrites the first.
Bug 4 — getDiscussionMilestoneId() unkeyed query:
getDiscussionMilestoneId() now accepts an optional basePath parameter for
keyed lookup. When multiple sessions exist and no basePath is provided,
it returns null instead of an arbitrary entry. Single-session backward
compatibility is preserved.
Closes #2985
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: narrow scope to complement igouss PRs #2986 and #2987
Revert changes to preferences.ts (Bug 1), state.ts, auto-start.ts,
register-hooks.ts (Bug 2), and their test files. Those fixes are
covered by @igouss in PRs #2986 and #2987.
This PR now only contains:
- Bug 3: guided-flow.ts pendingAutoStart singleton → Map (session isolation)
- Bug 4: getDiscussionMilestoneId() keyed by basePath
- Supporting unitType additions in preferences-models.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: align source code with test expectations after scope narrowing
The refactor commit (6972c97c) reverted source changes to state.ts,
preferences.ts, and auto-start.ts but left their corresponding test
assertions in place, causing 8 CI failures:
- isValidationTerminal: treat any extracted verdict as terminal (#2769)
- parseHeadingListFormat: handle raw YAML blocks under headings (#2794)
- bootstrapAutoSession: snapshot ctx.model before guided-flow (#2829)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: open project DB before initial deriveState on cold bootstrap (#2841)
When auto-mode starts cold (no prior DB handle), deriveState silently
falls back to markdown-only data for DB-backed helpers (queue-order,
task status), producing stale or incomplete state. Add
openProjectDbIfPresent() helper that resolves the project-root DB path
and opens it before the first deriveState call, ensuring full data
visibility from the start.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 16:33:30 -04:00
const gsdDbPath = join ( s . basePath , ".gsd" , "gsd.db" ) ;
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 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" ) ) ;
2026-03-25 10:29:53 -06:00
try {
fix: isolate guided-flow session state and key discussion milestone queries (#2985) (#3094)
* fix: resolve 4 correctness bugs in GSD extension core (#2985)
Bug 1 — preferences.ts process.cwd() side-channel:
loadEffectiveGSDPreferences() and loadProjectGSDPreferences() now accept
an optional projectRoot parameter. When provided, preferences are loaded
from the specified project directory instead of relying on process.cwd().
All 37+ callers continue to work unchanged (parameter defaults to cwd).
Bug 2 — state.ts DB writes inside read functions (CQS violation):
Extracted disk-to-DB milestone reconciliation into a new exported function
reconcileDiskMilestonesToDb(). deriveState() and deriveStateFromDb() no
longer write to the DB as a side effect of reading state. Callers that
need reconciliation (auto-start.ts, guided-flow.ts, register-hooks.ts)
now call it explicitly before reading state.
Bug 3 — guided-flow.ts module-level session state:
Converted pendingAutoStart from a module-level singleton to a Map keyed
by basePath. Concurrent discuss sessions for different projects are now
independent — the second session no longer silently overwrites the first.
Bug 4 — getDiscussionMilestoneId() unkeyed query:
getDiscussionMilestoneId() now accepts an optional basePath parameter for
keyed lookup. When multiple sessions exist and no basePath is provided,
it returns null instead of an arbitrary entry. Single-session backward
compatibility is preserved.
Closes #2985
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: narrow scope to complement igouss PRs #2986 and #2987
Revert changes to preferences.ts (Bug 1), state.ts, auto-start.ts,
register-hooks.ts (Bug 2), and their test files. Those fixes are
covered by @igouss in PRs #2986 and #2987.
This PR now only contains:
- Bug 3: guided-flow.ts pendingAutoStart singleton → Map (session isolation)
- Bug 4: getDiscussionMilestoneId() keyed by basePath
- Supporting unitType additions in preferences-models.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: align source code with test expectations after scope narrowing
The refactor commit (6972c97c) reverted source changes to state.ts,
preferences.ts, and auto-start.ts but left their corresponding test
assertions in place, causing 8 CI failures:
- isValidationTerminal: treat any extracted verdict as terminal (#2769)
- parseHeadingListFormat: handle raw YAML blocks under headings (#2794)
- bootstrapAutoSession: snapshot ctx.model before guided-flow (#2829)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: open project DB before initial deriveState on cold bootstrap (#2841)
When auto-mode starts cold (no prior DB handle), deriveState silently
falls back to markdown-only data for DB-backed helpers (queue-order,
task status), producing stale or incomplete state. Add
openProjectDbIfPresent() helper that resolves the project-root DB path
and opens it before the first deriveState call, ensuring full data
visibility from the start.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 16:33:30 -04:00
const { openDatabase : openDb } = await import ( "./gsd-db.js" ) ;
openDb ( gsdDbPath ) ;
2026-03-25 10:29:53 -06:00
if ( hasDecisions || hasRequirements || hasMilestones ) {
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 { migrateFromMarkdown } = await import ( "./md-importer.js" ) ;
migrateFromMarkdown ( s . basePath ) ;
}
2026-03-25 10:29:53 -06:00
} catch ( err ) {
refactor(gsd): migrate all catch blocks to centralized workflow-logger
Replace raw process.stderr.write(), console.error(), and empty catch
blocks across 50 GSD files with structured logWarning/logError calls
from the centralized workflow-logger system.
Add 13 new LogComponent types to cover all subsystems: recovery,
session, prompt, dashboard, timer, worktree, command, parallel, fs,
bootstrap, guided, registry, renderer.
Every migrated catch block now automatically:
- Shows in terminal (stderr) with component tag
- Gets buffered for auto-loop stuck-detection summary
- Persists to .gsd/audit-log.jsonl for post-mortem analysis
Update regression test to verify catch blocks use workflow-logger
instead of raw stderr/console, covering auto-mode files and all
explicitly migrated infrastructure files.
Closes #3506
Supersedes the approach in #3496
2026-04-04 13:42:55 -05:00
logError ( "engine" , ` auto-migration failed: ${ ( err as Error ) . message } ` ) ;
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 ( existsSync ( gsdDbPath ) && ! isDbAvailable ( ) ) {
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
try {
fix: isolate guided-flow session state and key discussion milestone queries (#2985) (#3094)
* fix: resolve 4 correctness bugs in GSD extension core (#2985)
Bug 1 — preferences.ts process.cwd() side-channel:
loadEffectiveGSDPreferences() and loadProjectGSDPreferences() now accept
an optional projectRoot parameter. When provided, preferences are loaded
from the specified project directory instead of relying on process.cwd().
All 37+ callers continue to work unchanged (parameter defaults to cwd).
Bug 2 — state.ts DB writes inside read functions (CQS violation):
Extracted disk-to-DB milestone reconciliation into a new exported function
reconcileDiskMilestonesToDb(). deriveState() and deriveStateFromDb() no
longer write to the DB as a side effect of reading state. Callers that
need reconciliation (auto-start.ts, guided-flow.ts, register-hooks.ts)
now call it explicitly before reading state.
Bug 3 — guided-flow.ts module-level session state:
Converted pendingAutoStart from a module-level singleton to a Map keyed
by basePath. Concurrent discuss sessions for different projects are now
independent — the second session no longer silently overwrites the first.
Bug 4 — getDiscussionMilestoneId() unkeyed query:
getDiscussionMilestoneId() now accepts an optional basePath parameter for
keyed lookup. When multiple sessions exist and no basePath is provided,
it returns null instead of an arbitrary entry. Single-session backward
compatibility is preserved.
Closes #2985
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: narrow scope to complement igouss PRs #2986 and #2987
Revert changes to preferences.ts (Bug 1), state.ts, auto-start.ts,
register-hooks.ts (Bug 2), and their test files. Those fixes are
covered by @igouss in PRs #2986 and #2987.
This PR now only contains:
- Bug 3: guided-flow.ts pendingAutoStart singleton → Map (session isolation)
- Bug 4: getDiscussionMilestoneId() keyed by basePath
- Supporting unitType additions in preferences-models.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: align source code with test expectations after scope narrowing
The refactor commit (6972c97c) reverted source changes to state.ts,
preferences.ts, and auto-start.ts but left their corresponding test
assertions in place, causing 8 CI failures:
- isValidationTerminal: treat any extracted verdict as terminal (#2769)
- parseHeadingListFormat: handle raw YAML blocks under headings (#2794)
- bootstrapAutoSession: snapshot ctx.model before guided-flow (#2829)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: open project DB before initial deriveState on cold bootstrap (#2841)
When auto-mode starts cold (no prior DB handle), deriveState silently
falls back to markdown-only data for DB-backed helpers (queue-order,
task status), producing stale or incomplete state. Add
openProjectDbIfPresent() helper that resolves the project-root DB path
and opens it before the first deriveState call, ensuring full data
visibility from the start.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 16:33:30 -04:00
const { openDatabase : openDb } = await import ( "./gsd-db.js" ) ;
openDb ( gsdDbPath ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
} catch ( err ) {
refactor(gsd): migrate all catch blocks to centralized workflow-logger
Replace raw process.stderr.write(), console.error(), and empty catch
blocks across 50 GSD files with structured logWarning/logError calls
from the centralized workflow-logger system.
Add 13 new LogComponent types to cover all subsystems: recovery,
session, prompt, dashboard, timer, worktree, command, parallel, fs,
bootstrap, guided, registry, renderer.
Every migrated catch block now automatically:
- Shows in terminal (stderr) with component tag
- Gets buffered for auto-loop stuck-detection summary
- Persists to .gsd/audit-log.jsonl for post-mortem analysis
Update regression test to verify catch blocks use workflow-logger
instead of raw stderr/console, covering auto-mode files and all
explicitly migrated infrastructure files.
Closes #3506
Supersedes the approach in #3496
2026-04-04 13:42:55 -05:00
logError ( "engine" , ` failed to open existing database: ${ ( err as Error ) . message } ` ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
}
2026-03-24 23:37:19 -04:00
// Gate: abort bootstrap if the DB file exists but the provider is
// still unavailable after both open attempts above. Without this,
// auto-mode starts but every gsd_task_complete / gsd_slice_complete
// call returns "db_unavailable", triggering artifact-retry which
// re-dispatches the same task — producing an infinite loop (#2419).
if ( existsSync ( gsdDbPath ) && ! isDbAvailable ( ) ) {
ctx . ui . notify (
"SQLite database exists but failed to open. Auto-mode cannot proceed without a working database provider. " +
"Check for corrupt gsd.db or missing native SQLite bindings." ,
"error" ,
) ;
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 metrics
initMetrics ( s . basePath ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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 ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
2026-03-27 21:47:14 +01:00
// Restore the model that was active when auto bootstrap began (#650, #2829).
if ( startModelSnapshot ) {
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
s . autoModeStartModel = {
2026-03-27 21:47:14 +01:00
provider : startModelSnapshot.provider ,
id : startModelSnapshot.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
} ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
2026-03-29 05:37:48 -05:00
// Apply worker model override from parallel orchestrator (#worker-model).
// GSD_WORKER_MODEL is injected by the coordinator when parallel.worker_model
// is configured, so parallel milestone workers use a cheaper model than the
// coordinator session (e.g. Haiku for execution, Sonnet for planning).
const workerModelOverride = process . env . GSD_WORKER_MODEL ;
if ( workerModelOverride && process . env . GSD_PARALLEL_WORKER === "1" ) {
const availableModels = ctx . modelRegistry . getAvailable ( ) ;
const { resolveModelId } = await import ( "./auto-model-selection.js" ) ;
const overrideModel = resolveModelId ( workerModelOverride , availableModels , ctx . model ? . provider ) ;
if ( overrideModel ) {
const ok = await pi . setModel ( overrideModel , { persist : false } ) ;
if ( ok ) {
// Update start model so all subsequent units use this as the baseline
s . autoModeStartModel = { provider : overrideModel.provider , id : overrideModel.id } ;
ctx . ui . notify ( ` Worker model override: ${ overrideModel . provider } / ${ overrideModel . id } ` , "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
// Snapshot installed skills
if ( resolveSkillDiscoveryMode ( ) !== "off" ) {
snapshotSkills ( ) ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
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" ,
) ;
fix(gsd): remove stale completedUnits refs, fix writeLock callers, add missing imports
- Remove completedUnits from dashboard, context, parallel, guided-flow, merge
- Fix writeLock callers to match new (basePath, unitType, unitId, sessionFile?) signature
- Add gsdRoot, atomicWriteSync, verifyExpectedArtifact, writeUnitRuntimeRecord imports to phases.ts
- Add full_plan_md to workflow-manifest snapshot mapping
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 08:37:32 -06:00
writeLock ( lockBase ( ) , "starting" , s . currentMilestoneId ? ? "unknown" ) ;
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 gate
const mid = state . activeMilestone ! . id ;
try {
2026-03-19 18:57:59 -04:00
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 ) {
2026-03-18 09:32:46 -05:00
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. ` ,
2026-03-18 09:32:46 -05:00
"warning" ,
) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
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" ,
) ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
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 ) ,
} ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
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 ) {
2026-03-25 21:19:00 +01:00
// Skip completed/parked milestones — a leftover CONTEXT-DRAFT.md
// on a finished milestone is harmless residue, not an actionable warning.
if ( isDbAvailable ( ) ) {
const ms = getMilestone ( id ) ;
if ( ms ? . status === "complete" || ms ? . status === "parked" ) continue ;
}
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 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" ,
) ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
}
fix(gsd): add diagnostic logging to empty catch blocks in auto-mode
Auto-mode has empty catch blocks across 11 files that silently
swallow errors. When these operations fail (DB writes, git commands,
file sync, worktree operations), the error is lost and downstream
systems see stale or inconsistent state — leading to stuck loops,
phantom milestones, and silent data loss.
Replace every empty catch with a process.stderr.write() call that
logs the operation context and error message. Format:
gsd [filename]: <operation> failed: <error.message>
For catches already annotated with /* non-fatal */ or /* best-effort */
comments, the logging is added alongside the annotation to preserve
the original intent while making failures observable.
Adds a regression test that scans all auto-mode source files and
asserts no empty catch blocks remain.
Files modified (11):
auto-worktree.ts, auto.ts, auto-recovery.ts, auto-prompts.ts,
auto-dashboard.ts, auto-start.ts, auto-timers.ts, auto-post-unit.ts,
auto-dispatch.ts, auto-unit-closeout.ts, auto/phases.ts
No behavioral changes — only diagnostic output added.
Addresses #3348, addresses #3345
2026-04-04 04:03:14 -07:00
} 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
/* non-fatal */
refactor(gsd): migrate all catch blocks to centralized workflow-logger
Replace raw process.stderr.write(), console.error(), and empty catch
blocks across 50 GSD files with structured logWarning/logError calls
from the centralized workflow-logger system.
Add 13 new LogComponent types to cover all subsystems: recovery,
session, prompt, dashboard, timer, worktree, command, parallel, fs,
bootstrap, guided, registry, renderer.
Every migrated catch block now automatically:
- Shows in terminal (stderr) with component tag
- Gets buffered for auto-loop stuck-detection summary
- Persists to .gsd/audit-log.jsonl for post-mortem analysis
Update regression test to verify catch blocks use workflow-logger
instead of raw stderr/console, covering auto-mode files and all
explicitly migrated infrastructure files.
Closes #3506
Supersedes the approach in #3496
2026-04-04 13:42:55 -05:00
logWarning ( "engine" , ` preflight validation failed: ${ err instanceof Error ? err.message : String ( err ) } ` ) ;
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}
2026-03-19 14:12:06 -04:00
return true ;
} catch ( err ) {
releaseSessionLock ( base ) ;
clearLock ( base ) ;
throw err ;
}
refactor: decompose auto.ts into 6 focused modules (#1088)
Extract 6 cohesive modules from the 3,476-line auto.ts god file,
reducing it to 1,732 lines while preserving all external import paths.
New modules:
- auto-timers.ts (223 lines): Unit supervision timers — soft timeout,
idle watchdog, hard timeout, context-pressure monitor
- auto-idempotency.ts (150 lines): Completed-key checks, skip loop
detection, phantom loop handling, fallback persistence
- auto-stuck-detection.ts (220 lines): Dispatch count tracking,
lifetime cap, MAX_UNIT_DISPATCHES loop detection, stub recovery.
Uses return values instead of calling stopAuto/dispatchNextUnit.
- auto-verification.ts (195 lines): Post-unit typecheck/lint/test gate,
runtime error capture, dependency audit, auto-fix retry logic
- auto-post-unit.ts (585 lines): Split into postUnitPreVerification
and postUnitPostVerification — commit, doctor, state rebuild,
worktree sync, DB dual-write, hooks, triage, quick-tasks
- auto-start.ts (472 lines): Fresh session bootstrap — git/state init,
crash lock detection, debug init, worktree setup, DB lifecycle
All extracted functions receive AutoSession + context as parameters.
No circular dependencies — new modules import from leaf dependencies
only, never from ./auto.js. All public exports from auto.ts are
preserved so external import paths continue to work unchanged.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 22:26:05 -06:00
}