- Extract emitMessagePair() to consolidate 6 message_start/message_end push pairs in agent-loop.ts
- Extract emitErrorSequence() to deduplicate identical catch blocks in agentLoop and agentLoopContinue
- Export ZERO_USAGE constant and reuse it in agent.ts instead of inline object literals
- Merge identical message_start/message_update switch cases in Agent._runLoop
- Extract Agent._updatePendingToolCalls() to consolidate tool_execution_start/end Set mutation
Replace 30+ repetitive setter method bodies with four generic private
helpers: setGlobalSetting, setScopedSetting, setNestedGlobalSetting,
and setProjectSetting. Each setter method retains its original public
signature and behavior — only the internal implementation is consolidated.
Methods with custom logic (setEditorPaddingX, setAutocompleteMaxVisible,
setSearchExcludeDirs, setFallbackChain, removeFallbackChain,
setDefaultModelAndProvider) are left unchanged or minimally adapted.
Net reduction: 79 lines (164 deleted, 85 added).
Add a new /gsd changelog command that fetches releases from the GitHub API,
filters by version, and sends the raw changelog into the conversation for the
LLM to summarize the most important changes.
- New changelog.ts module: GitHub API fetch, semver filtering, body parsing
- Routing block in commands.ts with lazy import (same pattern as forensics)
- Tab completion in commands-bootstrap.ts TOP_LEVEL_SUBCOMMANDS
- Help text under VISIBILITY section in showHelp()
- No new npm dependencies — uses built-in fetch()
- Delete theme-schema.json (335 lines): redundant with the TypeBox
schema already defined in theme.ts, only referenced via $schema URLs
in the JSON files for editor autocomplete.
- Delete dark.json (85 lines) and light.json (84 lines): move built-in
theme definitions into themes.ts as TypeScript objects, eliminating
runtime filesystem reads and the getThemesDir() dependency.
- Export ThemeJson type from theme.ts so themes.ts can reference it.
- Net reduction: ~319 lines removed.
Move overlay positioning (resolveOverlayLayout, resolveAnchorRow/Col),
line compositing (compositeLineAt, compositeOverlays, applyLineResets),
cursor extraction, and size parsing into overlay-layout.ts. These are
pure functions with no TUI state dependencies, reducing tui.ts from
1,200 to 899 lines.
Move slash command dispatch logic and 12 individual command handlers
(/export, /share, /copy, /name, /session, /changelog, /hotkeys,
/compact, /thinking, /edit-mode, /arminsayshi, plus showThinkingSelector)
into a new slash-command-handlers.ts module.
InteractiveMode now delegates to dispatchSlashCommand() via a
SlashCommandContext interface, keeping the integration surface minimal.
Handlers that are also invoked from keybindings/events remain on
InteractiveMode and are accessed through the context.
Reduces interactive-mode.ts from 4,783 to 4,272 lines (-511).
* 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>
Extract two self-contained subsystems from agent-session.ts (3,367 -> 2,737 lines):
- RetryHandler: auto-retry with exponential backoff, credential rotation,
and cross-provider fallback logic
- CompactionOrchestrator: manual/auto compaction, overflow recovery, and
extension integration for custom compaction providers
Also add shared getErrorMessage() utility to replace repeated
`err instanceof Error ? err.message : String(err)` patterns.
The extracted modules receive AgentSession state via dependency injection
interfaces, avoiding state duplication. AgentSession remains the coordinator
that delegates to these modules.
markdown.ts: Extract renderCodeBlock() helper to eliminate duplicated
code block rendering between renderToken and renderListItem.
keys.ts: Consolidate LEGACY_KEY_SEQUENCES, LEGACY_SHIFT_SEQUENCES, and
LEGACY_CTRL_SEQUENCES into a single LEGACY_SEQUENCES structure with
plain/shift/ctrl variants per key. Auto-generate LEGACY_SEQUENCE_KEY_IDS
from this structure instead of hand-maintaining a 50+ entry reverse
lookup. Extract hasKittyEventType() to deduplicate isKeyRelease and
isKeyRepeat. Net reduction of ~80 lines.
Extract the duplicated commandContextActions implementations from
rpc-mode.ts and print-mode.ts into a shared
createDefaultCommandContextActions() factory in
modes/shared/command-context-actions.ts.
Both headless modes (RPC and print) had identical implementations of
waitForIdle, newSession, fork, navigateTree, switchSession, and reload
that simply delegate to AgentSession. The shared factory provides these
defaults; interactive mode continues to layer TUI-specific behavior on
top via its own overrides.
Also fixes a subtle redundancy in print mode where newSession manually
called options.setup after session.newSession(), even though
session.newSession() already handles the setup callback internally.
Extract duplicated implementations of startCallbackServer, parseRedirectUrl,
getUserEmail, and token refresh logic from google-antigravity.ts and
google-gemini-cli.ts into a shared google-oauth-utils.ts module.
Extract the duplicated file lock mechanism from auth-storage.ts and
session-manager.ts into a shared lock-utils.ts module.
- acquireLockSyncWithRetry(): throwing variant (used by auth-storage)
- tryAcquireLockSync(): non-throwing variant (used by session-manager)
- acquireLockAsync(): async lock with retries and staleness detection
Removes ~55 lines of duplicated retry-loop logic. The shared module
also provides a foundation for deduplicating identical patterns in
settings-manager.ts and models-json-writer.ts.
- Replace dedupePrompts() and dedupeThemes() with generic dedupeResources<T>()
that accepts getName/getPath/resourceType callbacks
- Replace discoverSystemPromptFile() and discoverAppendSystemPromptFile() with
generic discoverFileInSearchPaths(filename)
- Import ResourceCollision type for use in dedupeResources signature
- Net reduction of 24 lines (868 → 844) with elimination of duplicated logic
Release session locks on bootstrap abort paths and reset same-process lock state before re-acquiring so stale proper-lockfile callbacks cannot poison a fresh auto-mode session. Adds regression coverage for bootstrap cleanup and re-entrant lock acquisition.
Move duplicated patterns from compaction.ts and branch-summarization.ts
into shared utilities in utils.ts:
- getMessageFromEntry(): unified entry-to-message conversion with
optional toolResult skipping for branch summarization
- collectMessages(): replaces three identical for-loops that collect
AgentMessages from entry ranges
- extractTextContent(): replaces five instances of the
.filter(text).map(text).join() pattern
- createSummarizationMessage(): replaces three identical user-message
construction blocks for LLM summarization calls
Net reduction of ~90 lines of duplication.
- toPosixPath: remove private copies in skills.ts and package-manager.ts,
import from canonical utils/path-display.ts
- ZERO_USAGE: export from agent-loop.ts, replace inline zero-usage
objects in agent.ts and proxy.ts
- shortenPath: extract to shared modes/interactive/utils/shorten-path.ts,
import in tool-execution.ts and session-selector.ts
Extract the duplicated loop pattern (create context, iterate extensions,
iterate handlers, try/catch, emitError) into a private invokeHandlers()
helper. Each emit method is now a thin wrapper that delegates the
iteration to invokeHandlers and provides only its result-processing
callback. Net reduction of ~124 lines with identical runtime behavior.
Replace 7 individual ToolResultEvent type guards (isBashToolResult,
isReadToolResult, etc.) with a unified isToolResultEventType() function,
mirroring the existing isToolCallEventType() pattern.
Inline 14 handler type aliases (SendMessageHandler, SetModelHandler, etc.)
directly into the ExtensionActions interface since they were only used there
and added no semantic value.
Update documentation examples to use the new unified guard.
On older Linux distributions (e.g., RHEL 8 with older glibc), the native
Rust addon fails to load. The proxy throws on every function call, but
wrapTextWithAnsi and visibleWidth in pi-tui had no JS fallback — causing
an uncaught crash during TUI rendering.
Fix: Both functions now catch native throws and fall back to JS
implementations (simple word-wrap and ANSI-strip length).
Fixes#1418