* feat(vscode): status bar, auto-retry, session name, copy response, keyboard shortcuts, full stats * feat(vscode): file decorations, bash terminal, session tree view * feat(vscode): conversation history webview, slash completion, code lens - conversation-history.ts: GsdConversationHistoryPanel webview panel using getMessages() RPC; renders user/assistant turns with a Refresh button - slash-completion.ts: GsdSlashCompletionProvider triggers on '/' at line start in md/plaintext/ts/js; fetches getCommands() RPC and caches results - code-lens.ts: GsdCodeLensProvider adds 'Ask GSD' lens above named functions/classes in ts/js/py/go/rust; respects gsd.codeLens setting - extension.ts: registers all three providers and new commands (gsd.showHistory, gsd.askAboutSymbol) - package.json: declares new commands and gsd.codeLens config toggle * feat(vscode): activity feed, workflow controls, session forking, enhanced code lens - Activity feed TreeView showing real-time tool executions with status icons, duration, and click-to-open file support - Workflow quick actions in sidebar: Auto, Next, Quick, Capture, Status, and Fork buttons that send /gsd slash commands - Progress notifications with cancel button while agent is working - Context window usage bar with color-coded threshold warnings - Session forking via QuickPick (get_fork_messages + fork RPC) - Queue mode controls for steering and follow-up (all vs 1-at-a-time) - Enhanced conversation history with tool call rendering, thinking blocks (collapsible), search filter, and fork-from-here buttons - Enhanced code lens: Refactor, Find Bugs, and Generate Tests actions alongside existing Ask GSD - 4 new configuration settings: showProgressNotifications, activityFeedMaxItems, showContextWarning, contextWarningThreshold - 8 new commands bringing total to 33 * chore(vscode): bump version to 0.2.0, update changelog * refactor: extract runSafely helper for try-catch-debug-continue pattern (#2611) * refactor: extract runSafely helper for try-catch-debug-continue pattern Reduces boilerplate in auto-post-unit.ts by extracting the repeated try { op() } catch (e) { debugLog(ctx, { phase, error }) } pattern into a reusable runSafely() helper in auto-utils.ts. Replaces 6 sequential blocks (github-sync, prune-bg-shell, browser-teardown, worktree-sync, rewrite-docs-resolve, reactive-state-cleanup). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * ci: trigger rebuild after null-safety fix * chore: trigger CI rebuild --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: update DB task status in writeBlockerPlaceholder for execute-task (#2657) writeBlockerPlaceholder writes a placeholder SUMMARY file when idle recovery exhausts all retries, but never updated the DB task status. verifyExpectedArtifact checks the DB as the authoritative source for execute-task units — with status still "pending", verification failed, deriveState re-derived the same task, and the dispatch loop repeated indefinitely (observed as 8-9 "Advancing pipeline" messages). After writing the file, call updateTaskStatus to mark the task as "complete" in the DB. This lets verifyExpectedArtifact pass and breaks the infinite re-dispatch loop. Closes #2531 * fix(vscode): support Remote SSH by adding extensionKind and error handler (#2650) * fix(vscode): add extensionKind and error handler for Remote SSH support * fix(vscode): reject failed RPC startup * fix: respect queue-order.json in DB-backed state derivation (#2649) getActiveMilestoneId and deriveStateFromDb sorted milestones by ID (localeCompare / milestoneIdSort) while the dispatch guard in dispatch-guard.ts sorted by queue-order.json via findMilestoneIds. When a user reordered milestones via /gsd queue to prioritize a later-numbered milestone, the state machine ignored the reordering and dispatched to the earlier-numbered one. The dispatch guard then blocked completion because the queue-ordered-first milestone was incomplete — producing a deadlock. Replace the lexicographic sort with sortByQueueOrder(loadQueueOrder()) in both the getActiveMilestoneId DB path and the deriveStateFromDb milestone sort. This aligns all three subsystems (state derivation, dispatch, and dispatch guard) on the same ordering. Closes #2556 * fix: prevent double mergeAndExit on milestone completion (#2648) When a milestone completes, phases.ts calls mergeAndExit to merge the worktree branch back to main. It then calls closeoutAndStop → stopAuto, which unconditionally calls mergeAndExit again. The second call fails because the branch was already deleted by the first merge, producing a misleading 'not something we can merge' warning even though the merge succeeded. Add a milestoneMergedInPhases session flag that phases.ts sets after a successful merge. stopAuto checks this flag and skips its own merge when it is already set. The flag is cleared in AutoSession.reset() so it does not leak across sessions. Closes #2645 * fix: signal malformed tool arguments in toolcall_end event (#2647) When the API stream is truncated mid-tool-call, PartialMessageBuilder emits a toolcall_end event with { _raw: "<broken json>" } in the arguments — but the event looks identical to a healthy tool completion. Downstream consumers (error classifiers, tool handlers, activity log) have no way to distinguish a truncated call from a completed one. Add a malformedArguments: boolean flag to the toolcall_end event variant in AssistantMessageEvent. The flag is set to true only in the JSON parse catch path, so existing consumers (which do not check for it) are unaffected. New consumers like classifyProviderError can use it to handle truncated tool calls appropriately. Closes #2574 * refine: extract enqueueSidecar helper in auto-post-unit Consolidate three near-identical sidecar enqueue blocks (hook, triage, quick-task) into a shared enqueueSidecar() helper that handles the push + debugLog + optional UI notification + return "continue" pattern. Update static-analysis tests to accept the helper call pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use pauseAuto instead of stopAuto for warning-level dispatch stops (#2666) When the uat-verdict-gate returns a non-PASS verdict, it returns action: "stop" with level: "warning". This was routed to closeoutAndStop() → stopAuto(), which destroys the session — the user must cold-restart `/gsd auto` from scratch. A non-PASS UAT verdict is a recoverable human checkpoint, not an infrastructure failure. The fix routes warning-level stops to pauseAuto() instead, making the session resumable with `/gsd auto`. Error and info-level stops continue to use closeoutAndStop() for infrastructure failures and terminal conditions respectively. Closes #2474 * chore: consolidate docs, remove stale artifacts, and repo hygiene (#2665) * fix(vscode): add extensionKind and error handler for Remote SSH support * fix(vscode): reject failed RPC startup * docs: consolidate docs, remove stale artifacts, and repo hygiene - Remove docs-internal/ (duplicate of docs/); update pr-risk-check.mjs path - Sync 9 diverged files to latest content (commands, config, troubleshooting, etc.) - Fix pi --web → gsd --web naming in docs/README.md - Copy FRONTIER-TECHNIQUES.md and ADR-004 to docs/ before removal - Delete orphaned PR screenshot folders (pr-876/, pr-1530/) — unreferenced - Remove committed pnpm-lock.yaml files (project uses npm) - Move PLAN.md → .plans/doctor-cleanup-consolidation.md - Move web/left-native-tui-main-session-plan.md → .plans/ - Delete .DS_Store and vscode-extension/dist/ from disk Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * fix: check ASSESSMENT file for UAT verdict in checkNeedsRunUat (#2646) The run-uat prompt instructs the agent to write the UAT verdict to the ASSESSMENT file (via gsd_summary_save artifact_type:"ASSESSMENT"), but checkNeedsRunUat only checked the UAT spec file for a verdict. Since the spec file never receives a verdict, hasVerdict() always returned false and the run-uat unit was re-dispatched indefinitely — triggering the stuck-loop detector after 3 identical dispatches. Add ASSESSMENT file checks on both the DB-primary and file-based fallback paths in checkNeedsRunUat. If either the UAT spec or the ASSESSMENT file contains a verdict, UAT has been run and dispatch is skipped. Closes #2644 * fix: isLockProcessAlive should return true for own PID (#2642) The self-PID guard in isLockProcessAlive returned false for process.pid, treating the current process as dead. This caused the doctor to delete auto.lock and .gsd.lock/ during live auto-mode sessions (via postUnitPreVerification), breaking the session lock and silently stopping auto-mode. The guard was originally added for startAuto() where a matching PID could mean a recycled PID from a prior crash. But startAuto already has its own `crashLock.pid !== process.pid` check before calling isLockProcessAlive, so the function-level guard was redundant there and harmful everywhere else. Change `pid === process.pid` to return true (alive) instead of false. Closes #2470 * fix(prompts): use --body-file for forensics issue creation (#2641) The forensics prompt instructed the agent to create GitHub issues using an inline heredoc with --body "$(cat <<'EOF' ... EOF)". This caused two bugs: 1. Escaping: backticks and double-quotes in the body were passed with leading backslashes, breaking fenced code blocks and inline code in the rendered issue. 2. Truncation: the heredoc delimiter EOF could match a bare "EOF" line in the body content, silently dropping everything after it. Switch to writing the body to a temp file and passing it via --body-file, which bypasses shell quoting entirely. Also change the heredoc delimiter from EOF to GSD_ISSUE_BODY to avoid accidental termination. Closes #2465 * fix: call ensureDbOpen() before slice queries in /gsd discuss (#2640) showDiscuss() is a command handler, not a tool handler, so it lacks the automatic ensureDbOpen() call that tool handlers get. On cold-start sessions where no GSD tool has been called yet, isDbAvailable() returns false, normSlices falls to [], and the function exits with a misleading "All slices are complete — nothing to discuss." notification. Add ensureDbOpen() before both isDbAvailable() call sites in guided-flow.ts: 1. showDiscuss() — the primary bug (false "all complete" exit) 2. buildDiscussSlicePrompt() — secondary (incomplete context when inlining completed-slice summaries) Closes #2560 * refine: replace manual unitId.split() with parseUnitId() across 12 files Consolidate 21 manual unitId.split("/") calls to use the typed parseUnitId() function from unit-id.ts, gaining ParsedUnitId type safety and consistent milestone/slice/task naming. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: classify stream-truncation JSON parse errors as transient (#2636) When the API stream is truncated mid-chunk, pi reassembles the partial tool-call JSON and gets a SyntaxError (e.g. "Expected double-quoted property name", "Unexpected end of JSON input"). classifyProviderError() did not match these patterns and fell through to the "unknown = permanent" default, pausing auto-mode indefinitely instead of retrying. These JSON parse errors are the downstream symptom of a connection drop — same root cause as ECONNRESET, one layer up. Add an isMalformedStream guard that matches common JSON SyntaxError patterns and classifies them as transient with the same 15s backoff as connection errors. Closes #2572 * fix(notifications): prefer terminal-notifier over osascript on macOS (#2633) osascript display notification is silently swallowed by macOS when the calling terminal app (Ghostty, iTerm2, etc.) lacks notification permissions in System Settings. The command exits 0 with no error, making the failure invisible. terminal-notifier registers as its own Notification Center app, so macOS prompts the user for permission on first use — the expected UX. Changes: - Add findExecutable() helper to locate terminal-notifier on PATH - buildDesktopNotificationCommand() prefers terminal-notifier when available, falls back to osascript (preserving existing behavior) - Update tests to handle both terminal-notifier and osascript paths - Add macOS delivery note to docs/configuration.md notifications section - Add troubleshooting entry for notifications not appearing on macOS Fixes #2632 Co-authored-by: Yang Yang(NYC) <Yang.Yang2@bcg.com> * test: add cross-platform filesystem safety static analysis guard (#2541) * test: add cross-platform filesystem safety static analysis guard Scan all production .ts files for patterns that break on Windows, Linux, or macOS: 1. Hardcoded /tmp paths (FAIL) — use os.tmpdir() 2. String concatenation path separators (WARN) — use path.join() 3. rmSync without force: true (FAIL) — Windows read-only files 4. Shell command path interpolation (FAIL) — injection/spaces risk 5. existsSync + delete TOCTOU races (WARN) — informational 6. Recursive rmSync without containment check (WARN) — safety audit Includes allowlists for known-safe patterns (e.g. cmux Unix socket, npm package name constants). Reports violations with file path and line number context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: normalize path separators in allowlist matching for Windows CI The isAllowlisted function compared relative paths using forward slashes, but path.relative() produces backslashes on Windows, causing allowlist entries to never match on the Windows CI runner. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refine: extract findMissingSummaries helper in auto-dispatch (#2672) Deduplicate the missing-slice-summary validation logic used by both the validating-milestone and completing-milestone dispatch rules into a single findMissingSummaries() helper function. Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: update triage-dispatch static analysis tests for enqueueSidecar helper The static analysis tests check source code for `return "continue"` patterns. After extracting enqueueSidecar(), the return is now via the helper call. Accept both patterns in the assertion. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add non-null assertions for parseUnitId optional fields in tests parseUnitId returns { milestone, slice?, task? } where slice and task are optional. Test code that knows these fields are present needs ! assertions to satisfy strict TypeScript checking. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: persist rewrite-docs attempt counter to disk for session restart survival (#2671) The rewrite-docs circuit breaker counter (MAX_REWRITE_ATTEMPTS=3) was stored on the in-memory session object, resetting to 0 on every session restart (crash recovery, pause/resume, step-mode). This allowed the rewrite-docs dispatch rule to fire indefinitely without ever tripping the circuit breaker. The fix persists the counter to .gsd/runtime/rewrite-count.json using the established runtime directory pattern. The dispatch rule reads from disk instead of the session object, and the post-unit completion handler resets both disk and in-memory counters. Closes #2203 * fix: exclude lastReasoning from retry diagnostic to prevent hallucination loops (#2663) formatTraceSummary() is used by getDeepDiagnostic() which feeds into retry prompts in phases.ts. Including the prior assistant's free-text reasoning caused hallucination loops when the previous turn was truncated or malformed — the model would recycle its own interrupted reasoning as if it were diagnostic truth. The fix removes the lastReasoning field from formatTraceSummary() output. The crash recovery path (formatCrashRecoveryBriefing) has its own safe handling of lastReasoning with explicit framing and is not affected. Closes #2195 * fix: honor explicit model config when model is not in known tier map (#2643) When a user configures a phase-specific model that is not in MODEL_CAPABILITY_TIER (e.g. gpt-5.4, custom-provider/my-model), getModelTier() defaults to "heavy". This causes resolveModelForComplexity to downgrade every standard/light unit to tier_models, silently ignoring the user's explicit configuration. Add an isKnownModel() check before the downgrade logic. If the configured primary model is not in the known tier map, skip downgrading entirely and honor the user's choice. Known models continue to be routed normally. Closes #2192 * feat(validate): inject verification classes into milestone validation prompt (#2621) Verification class fields (contract, integration, operational, UAT) are captured during milestone planning and stored in the DB, but the validate-milestone prompt never reads them back. This means milestones can pass validation even when planned operational verification items (migrations, deployments, runtime checks) were never addressed. This change: - Queries getMilestone() in buildValidateMilestonePrompt() to retrieve verification_* fields and injects them as structured context - Adds a verification class compliance step to validate-milestone.md that requires the validator to check evidence for each non-empty class - Adds a Verification Class Compliance table to the validation template Backwards compatible: empty verification_* fields (existing milestones) produce no additional prompt content. Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: managed RTK integration with opt-in preference and web UI toggle (#2620) * feat: integrate managed RTK across shell workflows * fix(rtk): unify managed fallback and live savings wiring * fix(rtk): improve TUI status visibility * fix(tests): make portability tests independent of pi-coding-agent dist build The CI portability test runs don't guarantee that packages/pi-coding-agent has been compiled. Any test that imported files pulling in @gsd/pi-coding-agent (resource-loader, preferences-skills, async-bash-tool, etc.) crashed with ERR_MODULE_NOT_FOUND pointing at dist/index.js. Two changes to dist-redirect.mjs (the Node ESM loader hook used by all unit tests): - Redirect the bare @gsd/pi-coding-agent specifier to the workspace source entrypoint (src/index.ts) so no dist/ artifact is needed. - Extend the load() hook to transpile *.ts files under packages/pi-coding-agent/src/ through TypeScript's transpileModule. Node's --experimental-strip-types can't handle parameter properties and similar syntax present in that package's source; full transpilation avoids the ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX crash. Also fix the dashboard.tsx responsive grid: - xl:grid-cols-5 → xl:grid-cols-4 2xl:grid-cols-5 (5 metric cards no longer fit at xl without overflow; test contract expected xl:grid-cols-4) - Keep loading-skeletons.tsx in sync with the same breakpoints. Add src/tests/resolve-ts-loader.test.ts to guard the loader behaviour: - bare @gsd/pi-coding-agent redirect points to workspace source - direct source-entry rewrite (.js → .ts) - transpilation removes TS parameter property syntax that strip-only mode cannot parse * fix(tests): redirect all workspace package imports to source in portability tests The previous fix only redirected @gsd/pi-coding-agent to its source entrypoint. In CI, pi-coding-agent/src itself imports @gsd/pi-ai (and other workspace packages) which were still pointing at dist/. Since no workspace dist is built during the portability test run, any transitive resolution hit the same ERR_MODULE_NOT_FOUND. Changes to dist-redirect.mjs: - Redirect @gsd/pi-ai, @gsd/pi-ai/oauth, @gsd/pi-agent-core, and @gsd/pi-tui bare imports to their workspace src/ entrypoints. - Broaden the load() transpilation condition from '/packages/pi-coding-agent/src/' to '/packages/*/src/' so that all workspace source files are run through TypeScript's transpileModule, handling parameter properties and other syntax that Node's strip-only mode rejects. Verified by hiding all four workspace dist/ directories locally and running the failing test set — 96/96 pass. * fix(tests): redirect @gsd/native sub-paths; fix Windows .cmd spawnSync Two more portability failures after the previous fix: 1. @gsd/native sub-path imports (@gsd/native/fd, @gsd/native/text, etc.) were not redirected — the loader only handled the bare specifier. Added a prefix-match redirect for @gsd/native/* → packages/native/src/<sub>/index.ts. 2. Windows RTK tests failed because createFakeRtk produces a .cmd wrapper on Windows, and spawnSync(binaryPath, [...]) without shell:true silently returns non-zero when the binary is a .cmd file. Added shell: /\.(cmd|bat)$/i.test(binaryPath) to the spawnSync calls in: - src/resources/extensions/shared/rtk.ts (rewriteCommandWithRtk) - src/resources/extensions/shared/rtk-session-stats.ts (readCurrentRtkGainSummary) - packages/pi-coding-agent/src/utils/rtk.ts (rewriteCommandForGsd) Production use of rtk.exe is unaffected; the shell flag is only true for .cmd/.bat paths. Verified: all 93 portability tests pass with all workspace dist/ directories removed (simulating CI portability environment). * fix(tests): Windows portability fixes — HOME env, managed RTK path, perf threshold Four Windows-specific failures fixed: 1. app-smoke.test.ts: process.env.HOME is undefined on Windows (uses USERPROFILE instead). Changed to homedir() from node:os which works cross-platform. 2. Managed RTK path tests on Windows: tests placed a fake RTK as rtk.exe (by copying a .cmd script into a .exe filename), which Windows cannot execute. Two-part fix: - resolveRtkBinaryPath() in both rtk.ts files now falls back to rtk.cmd in the managed dir on Windows when rtk.exe is absent. - withManagedFakeRtk and equivalent patterns in rtk.test.ts, rtk-session-stats.test.ts, rtk-execution-seams.test.ts changed to place the fake at rtk.cmd instead of rtk.exe on Windows. 3. bg_shell RTK test on Windows: requires bash (for shell sessions), which is not available on the blacksmith-4vcpu-windows-2025 runner without Git Bash installed. Test now skips on win32. 4. derive-state-db perf assertion: 10ms threshold was too tight for Windows CI runners (measured 12ms under load). Raised to 25ms — still catches real regressions (baseline is 3ms locally and ~12ms on stressed runners). * fix(tests): fix managed RTK path fallback on Windows in src/rtk.ts + fix copyable fake Two remaining Windows failures: 1. src/rtk.ts was never patched with the rtk.cmd managed-dir fallback (only the shared/rtk.ts and pi-coding-agent/src/utils/rtk.ts were updated). Added the same rtk.cmd fallback and shell:.cmd detection to src/rtk.ts, which is what rtk.test.ts imports from. 2. createFakeRtk on Windows wrote '%~dp0\fake-rtk.js' in the .cmd content — this resolves relative to the .cmd file's own directory. When the test copies rtk.cmd to a different managed dir, %~dp0 resolves to the copy destination where fake-rtk.js does not exist. Fixed by embedding the absolute path to fake-rtk.js directly in the .cmd content so the fake works correctly regardless of where the .cmd is copied. * feat(experimental): add RTK opt-in preference with web UI toggle - Add `experimental` category to GSDPreferences with `rtk: boolean` (default: false) - RTK is now opt-in: disabled by default for all projects unless explicitly enabled - Validate experimental.* keys; unknown experimental keys produce warnings Web UI: - Add ExperimentalPanel component with animated toggle switch per flag - Add /api/experimental route (GET/PATCH) to read/write flags in preferences.md - Add 'Experimental' tab to settings dialog sidebar nav (FlaskConical icon) - Include ExperimentalPanel at bottom of gsd-prefs mega-scroll - Fix toggle disabled state: trigger loadSettingsData for 'experimental' section and self-fetch on mount when data is absent Dashboard: - Gate RTK Saved metric card on rtkEnabled from live auto state (web) - Gate TUI dashboard RTK savings row on rtkEnabled - Gate TUI footer RTK status updates on experimental.rtk preference - Propagate rtkEnabled through AutoDashboardData → bridge-service → store Build: - Add scripts/build-if-stale.cjs: incremental build driver that skips each step (packages, root tsc, copy-resources, web) when output is newer than source; replaces full rebuild chain in gsd:web - Add scripts/web-stop.cjs: robust stop with registry + legacy PID + orphan sweep via pgrep; handles crash/restart orphaned next-server processes - gsd:web now uses build-if-stale.cjs (fast cold starts, instant when unchanged) - gsd:web:stop / gsd:web:stop:all use web-stop.cjs directly Fix: correct import path in rtk-status.ts (./preferences.js not ../preferences.js) * fix: restore em-dash encoding in package.json to match upstream * refactor(rtk): move command rewrite out of pi-coding-agent into GSD extension Per review feedback from igouss: pi-coding-agent should not be modified to add GSD-specific logic. Instead, add a proper extension point and wire RTK through it. Changes to packages/pi-coding-agent (extension API only — no RTK logic): - Add BashTransformEvent + BashTransformEventResult types to extension API - Add on('bash_transform') overload to ExtensionAPI interface - Add emitBashTransform() to ExtensionRunner (chains all handlers in order) - Call emitBashTransform() in wrapToolWithExtensions before bash tool execution - Export new types from extensions/index.ts and package index.ts - Revert all RTK-specific changes from bash-executor.ts, tools/bash.ts - Remove packages/pi-coding-agent/src/utils/rtk.ts entirely Changes to GSD extension: - Register bash_transform handler in register-hooks.ts that calls rewriteCommandWithRtk() from the existing shared/rtk.ts module - Handler is a no-op when RTK is disabled or not installed * fix: correct import path for shared/rtk.js in register-hooks * fix(tests): remove deleted pi-coding-agent/utils/rtk imports from execution seams test The RTK rewrite logic was moved out of pi-coding-agent into the GSD extension (bash_transform hook). Tests that directly imported the deleted utils/rtk.ts are removed; remaining tests verify the shared RTK module and GSD-layer surfaces that still call rewriteCommandWithRtk. * feat(validate): extract followUps and knownLimitations in parseSummary (#2622) Slice summaries capture Follow-ups and Known Limitations sections during completion, but parseSummary() never extracts them. This makes the data write-only — no downstream code can access it programmatically. Add followUps and knownLimitations fields to the Summary interface, extract them via extractSection() in parseSummary(), and aggregate outstanding items from all slices into the validate-milestone prompt context so the validator can assess unresolved work. Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(auto): check verification class compliance before milestone completion (#2623) The completing-milestone dispatch gate checks structural prerequisites (slice summaries exist, implementation artifacts present) but does not check whether planned verification classes were addressed in validation. Add a check: if verification_operational is non-empty and not "none", verify the validation output documents operational compliance. If not addressed, stop progression with a warning directing the user to re-run validation with verification class awareness. Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: TÂCHES <afromanguy@me.com> * fix: improve light theme warning contrast (#2674) * feat: add /terminal slash command for direct shell execution (#2349) Runs commands in the user's login shell ($SHELL -l -c) so PATH additions and env vars from shell profiles (.zprofile/.profile) are available. Shell aliases are intentionally not loaded (requires -i which causes startup noise and job control side effects). Implementation spawns $SHELL directly via a loginShell flag threaded through the bash executor — no double-shell wrapping. - Registered as builtin slash command with autocomplete - Reuses existing bash execution pipeline (streaming, session recording) - Output included in LLM context for agent reference - Added loginShell option to executeBash and handleBashCommand - Browser mode rejects /terminal (terminal-only command) - Updated web-command-parity-contract tests AI-assisted: This change was authored with Claude (AI pair programming). * release: v2.51.0 * fix: include preferences.md in worktree sync and initial seed preferences.md was missing from both ROOT_STATE_FILES (used by syncGsdStateToWorktree and syncWorktreeStateBack) and the copyPlanningArtifacts file list (initial worktree seed). Because .gsd/ is gitignored, worktrees start with an empty .gsd/ directory — the bootstrap is the only opportunity to carry config over. Without preferences.md, post_unit_hooks, skill rules, custom instructions, and all other preference-driven config silently stop working once auto-mode enters a worktree. Closes #2684 * feat: Added RPC protocol v2 types, init handshake with version detectio… - "packages/pi-coding-agent/src/modes/rpc/rpc-types.ts" - "packages/pi-coding-agent/src/modes/rpc/rpc-mode.ts" - "packages/pi-coding-agent/src/modes/rpc/rpc-client.ts" - "packages/pi-coding-agent/src/modes/index.ts" - "packages/pi-coding-agent/src/index.ts" GSD-Task: S01/T01 * feat: Added runId generation on prompt/steer/follow_up commands, event… - "packages/pi-coding-agent/src/modes/rpc/rpc-mode.ts" - "packages/pi-coding-agent/src/modes/rpc/rpc-client.ts" - "packages/pi-coding-agent/src/modes/rpc/rpc-types.ts" GSD-Task: S01/T02 * test: Added 61 tests across 9 suites covering JSONL utilities, v2 type… - "packages/pi-coding-agent/src/modes/rpc/rpc-protocol-v2.test.ts" GSD-Task: S01/T03 * refactor(gsd): unify three overlapping error classifiers into single classify→decide→act pipeline Three independent error classifiers (isTransientNetworkError, classifyProviderError, and inline network-retry logic) had diverging counters and duplicate regex coverage. Every new edge case required patching a different classifier. Replaces all three with a single classifyError() returning a discriminated union ErrorClass, one RetryState object with explicit lifecycle, and a clean classify→decide→act flow in handleAgentEnd. Behavioral change: rate-limit errors no longer trigger model fallback — throttling is a provider issue, switching models on the same provider is pointless. Closes #2577 * test: Added --output-format text|json|stream-json flag, standardized ex… - "src/headless-types.ts" - "src/headless-events.ts" - "src/headless.ts" - "src/help-text.ts" - "src/tests/headless-cli-surface.test.ts" GSD-Task: S02/T01 * feat: Wire --bare mode across headless → pi-coding-agent → resource-loa… - "src/headless.ts" - "packages/pi-coding-agent/src/cli/args.ts" - "packages/pi-coding-agent/src/main.ts" - "src/tests/headless-cli-surface.test.ts" GSD-Task: S02/T02 * fix(gsd): remove redundant assertions that fail TS2367 typecheck After assert.equal narrows result.kind to a literal type, comparing it against a different literal is flagged as always-true by tsc. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: Remove premature pendingTools.delete in webSearchResult handler (#2743) The webSearchResult branch deleted entries from pendingTools after rendering, which removed the duplicate-prevention guard. Subsequent streaming tokens re-iterated content blocks, re-created the serverToolUse component, and re-rendered the search result — producing 18+ duplicate blocks. The message_end handler already calls pendingTools.clear(), so the explicit deletes were unnecessary and harmful. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(gsd): wire setLogBasePath into engine init to resurrect audit log (#2745) * fix: wire setLogBasePath into engine init to resurrect audit log _auditBasePath was always null — setLogBasePath() existed but was never called from any production code path. Every logWarning/logError call hit the if (_auditBasePath) guard as false, so nothing was ever written to .gsd/audit-log.jsonl. Two independent fixes: 1. Remove _auditBasePath = null from _resetLogs() — the base path must survive unit resets, it's stable for process lifetime 2. Call setLogBasePath(base) after s.basePath = base in both the fresh- start path (bootstrapAutoSession) and the resume path (startAuto) Adds two tests verifying disk persistence and that _resetLogs doesn't kill the audit path. Fixes #2722 * refactor: clean up audit log tests and avoid redundant mkdirSync - Use makeTempDir/cleanup from test-utils.ts instead of inline mkdtempSync/rmSync - Add afterEach in audit describe block to reset _auditBasePath via setLogBasePath("") — prevents state bleed into subsequent tests since _resetLogs() no longer clears it - Drop four raw imports (mkdtempSync, rmSync, tmpdir — join was already used) - Guard mkdirSync in _push() with _auditDirEnsured flag — was calling mkdirSync on every log entry; now called once per base path * revert: remove _auditDirEnsured flag mkdirSync({ recursive: true }) on an existing dir is a cheap stat, not meaningful overhead on a low-frequency warn/error path. The flag added mutable state for no real gain. * fix(gsd): delete orphaned verification_evidence rows on complete-task rollback (#2746) When complete-task's disk render fails, the rollback path resets the task status to 'pending' but did not clean up verification_evidence rows inserted in the same transaction. Since insertVerificationEvidence uses plain INSERT (no ON CONFLICT dedup), each retry accumulated additional evidence rows pointing to a pending task. Fix: add DELETE FROM verification_evidence before the status rollback UPDATE. The DELETE must come first due to the FK constraint (evidence references tasks). This matches the cleanup order already used in undoTask() and resetSlice() at gsd-db.ts:1699-1712. Closes #2724 * fix(windows): prevent EINVAL by disabling detached process groups on Win32 (#2744) On Windows, `spawn()` with `detached: true` sets the CREATE_NEW_PROCESS_GROUP flag in CreateProcess. In certain terminal contexts — notably VSCode's integrated terminal (ConPTY), Windows Terminal, and some MSYS2/Git Bash configurations — this flag conflicts with the parent process group hierarchy and causes a synchronous EINVAL from libuv, making *every* bash/async_bash/bg_shell command fail immediately with `spawn EINVAL`. The bg-shell extension already guards against this with `detached: process.platform !== "win32"` (process-manager.ts:109), but three other spawn sites were missed: - `packages/pi-coding-agent/src/core/tools/bash.ts` (bash tool) - `packages/pi-coding-agent/src/core/bash-executor.ts` (RPC executor) - `src/resources/extensions/async-jobs/async-bash-tool.ts` (async_bash) This commit aligns all spawn sites with the bg-shell pattern. Additionally fixes two related issues: 1. `killProcessTree()` in shell.ts used `detached: true` on its own `taskkill` spawn call — unnecessary and potentially problematic in the same terminal contexts. Removed. 2. `killTree()` in async-bash-tool.ts used Unix-only `process.kill(-pid)` with no Windows fallback. On Windows, negative PIDs (process group kill) are not supported, so orphaned child processes could survive timeout kills. Now uses `taskkill /F /T` on Windows, matching the bg-shell and shell.ts implementations. Includes a regression test that statically verifies no spawn site uses unconditional `detached: true`, plus a smoke test confirming the platform-guarded pattern works on all platforms. Reproduction: Run GSD v2.42-v2.51 inside VSCode on Windows 11 with Git Bash as the shell. Any bash tool call fails with `spawn EINVAL`. The error is 100% reproducible and affects all shell operations (bash, async_bash, bg_shell start). Co-authored-by: Matt Haynes <matt@auroraventures.io> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * fix(gsd): extract and honor milestone argument in /gsd auto and /gsd next (#2729) `/gsd auto M016` silently discarded the milestone ID and started whichever milestone deriveState() picked as first incomplete. The command handler parsed --verbose, --debug, and --yolo flags but never extracted a milestone target. Root cause: handleAutoCommand() had no milestone-ID extraction step. The `rest` string from parseYoloFlag was only checked for flags, and startAuto() was always called without milestone scoping. Fix: add parseMilestoneTarget() to extract M-prefixed IDs (M001, M001-a3b4c5) from the command string. When a milestone is specified: 1. Validate it exists via findMilestoneIds() — notify on missing 2. Set GSD_MILESTONE_LOCK env var (already honored by state.ts at three derivation points and by auto-post-unit.ts) via a withMilestoneLock() wrapper that cleans up the env var when auto-mode exits, preventing leakage into subsequent commands. Both `/gsd auto <milestone>` and `/gsd next <milestone>` are supported. Flags (--verbose, --debug) continue to work in any order. Closes #2521 * fix(gsd): write DB before disk in validate-milestone to match engine pattern (#2742) * fix(gsd): write DB before disk in validate-milestone to match engine pattern validate-milestone.ts wrote the VALIDATION.md file to disk before inserting the assessment row into the DB. Every other handler in the engine (complete-task, complete-slice) does DB-first, disk-second with rollback compensation. The inverted order meant a crash between disk write and DB insert would leave an orphaned file with no DB record — a state that is harder to detect and recover from than the inverse (DB row exists, file missing → projection rendering can regenerate). Fix: reorder to DB-first, disk-second. On disk write failure, delete the DB row via DELETE FROM assessments so state stays consistent. Add two handler-level tests verifying: 1. Both DB row and disk file exist after success 2. DB row is rolled back (deleted) when disk write fails Closes #2725 * fix(test): use file-as-directory to trigger disk failure cross-platform chmod 0o444 does not prevent writes on Windows. Replace with replacing the milestone directory with a regular file, so saveFile's mkdirSync/write fails on all platforms. Fixes windows-portability CI failure. * chore: rename preferences.md to PREFERENCES.md for consistency (#2700) (#2738) All other .gsd/ state files use uppercase naming (DECISIONS.md, REQUIREMENTS.md, PROJECT.md, etc). This renames the canonical preferences file to PREFERENCES.md while keeping a migration fallback — the loader checks PREFERENCES.md first, then falls back to lowercase preferences.md for existing installations. Closes #2700 Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * fix(docker): overhaul fragile setup, adopt proven container patterns (#2716) Split fake multi-stage Dockerfile into independent CI builder and runtime images. Add proper entrypoint with UID/GID remapping via PUID/PGID, sentinel-based first-boot bootstrap, pre-creation of critical file targets, and signal-forwarding privilege drop via gosu. Standardize on Node 24, split compose into minimal + full reference. Closes #9 * fix: surface exhausted Claude SDK streams as errors (#2719) Treat Claude SDK generator exhaustion without a terminal result as a stream interruption instead of a successful completion. This prevents phantom-success auto-mode advances, keeps the failure classifiable as transient provider recovery, and adds regression tests for the fallback message plus provider classification. Closes #2575 * fix: idle watchdog stalled-tool detection overridden by filesystem activity (#2697) Bug 1: When a tool stalls longer than idle_timeout, the watchdog notifies but falls through to detectWorkingTreeActivity(), which resets lastProgressAt when files were modified earlier in the task. Recovery is never called — the session burns tokens indefinitely. Fix: Add stalledToolDetected flag + clearInFlightTools() call. The filesystem-activity check is guarded by !stalledToolDetected so it cannot override the stall verdict. Bug 2: After async recoverTimedOutUnit(), pauseAuto/stopAuto may set s.currentUnit = null during the await, but the next line accesses s.currentUnit.startedAt without a null guard — crash. Fix: Add null guard for s.currentUnit after the recovery call. Closes #2527 * test: Add audit persistence regression tests (#2722) (#2749) * feat: Created gsd-orchestrator/ skill directory with ClawHub frontmatte… - "gsd-orchestrator/SKILL.md" - "gsd-orchestrator/references/commands.md" - "gsd-orchestrator/references/answer-injection.md" - "gsd-orchestrator/references/json-result.md" GSD-Task: S03/T01 * test: Add audit persistence tests for workflow-logger (#2722) The production fix for #2722 (wiring setLogBasePath + preserving _auditBasePath across _resetLogs) was already merged but had no test coverage. Add tests verifying both behaviors. Closes #2722 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(remote-questions): empty-key entry in auth.json shadows valid Discord bot token (#2737) * fix(remote-questions): empty-key entry in auth.json shadows valid Discord bot token removeProviderToken() called auth.set(provider, { key: '' }) instead of auth.remove(provider). Since AuthStorage.set() appends for api_key type (deduplicating by exact key match), this inserted an empty-key entry at index 0. Every credential lookup (.get(), .find()) matched the empty entry first, shadowing valid tokens at later indices. Fixes: - remote-command.ts: use auth.remove() instead of auth.set() with empty key - config.ts: hydrateRemoteTokensFromAuth .find() now requires non-empty key - wizard.ts: loadStoredEnvKeys uses getCredentialsForProvider + .find() instead of .get() which returns creds[0] - onboarding.ts: check existing tokens via .some() over full credentials array instead of .get() which only returns first entry - key-manager.ts: filter empty-key entries in getAllKeyStatuses, add/remove/ rotate provider pickers, and doctor env-conflict check Tests: 3186 pass, 0 fail across full GSD test suite * fix(config): ignore empty shadowing tool keys * feat(web): Dark mode contrast — raise token floor and flatten opacity tier system (#2734) * feat: Raised four dark-mode tokens, converted five hardcoded oklch valu… - "web/app/globals.css" - "web/components/gsd/code-editor.tsx" GSD-Task: S01/T01 * feat: Applied border-border 2-tier sweep across 21 component files: /20… - "web/components/gsd/command-surface.tsx" - "web/components/gsd/remaining-command-panels.tsx" - "web/components/gsd/chat-mode.tsx" - "web/components/gsd/settings-panels.tsx" - "web/components/gsd/diagnostics-panels.tsx" - "web/components/gsd/onboarding/step-authenticate.tsx" - "web/components/gsd/knowledge-captures-panel.tsx" - "web/components/gsd/projects-view.tsx" GSD-Task: S02/T01 * feat: Swept text-foreground/muted-foreground/sidebar-foreground opacity… - "web/components/gsd/command-surface.tsx" - "web/components/gsd/remaining-command-panels.tsx" - "web/components/gsd/chat-mode.tsx" - "web/components/gsd/settings-panels.tsx" - "web/components/gsd/diagnostics-panels.tsx" - "web/components/gsd/knowledge-captures-panel.tsx" - "web/components/gsd/projects-view.tsx" - "web/components/gsd/visualizer-view.tsx" GSD-Task: S02/T02 * feat: Applied background opacity mapping tables across all component fi… - "web/components/gsd/remaining-command-panels.tsx" - "web/components/gsd/command-surface.tsx" - "web/components/gsd/visualizer-view.tsx" - "web/components/gsd/chat-mode.tsx" - "web/components/gsd/settings-panels.tsx" - "web/components/gsd/diagnostics-panels.tsx" - "web/components/gsd/onboarding/step-authenticate.tsx" - "web/components/gsd/knowledge-captures-panel.tsx" GSD-Task: S02/T03 * fix(web): auth token gate — synthetic 401 on missing token, unauthenticated boot state, and recovery screen (#2740) When `gsd --web` is opened without the #token= hash fragment (manual URL entry, bookmark, new tab), `authenticatedFetch` previously fell through to a naked `fetch()` that always returned 401, flooding the console with cascading errors and leaving the UI in a broken state with no recovery path. Three changes: 1. `web/lib/auth.ts` — `authFetch()` now returns a synthetic 401 Response when `getAuthToken()` returns null instead of delegating to bare fetch. This makes missing-token failures consistent and immediately catchable by all callers without a network round-trip. 2. `web/lib/gsd-workspace-store.tsx` — Added `"unauthenticated"` to `WorkspaceStatus`. `refreshBoot()` now detects a 401 response from /api/boot and patches `bootStatus` to `"unauthenticated"` instead of throwing a generic error. This is a distinct state — not an error worth retrying, but a configuration problem the user must resolve. 3. `web/components/gsd/app-shell.tsx` — Added an early-return guard that renders a minimal "Authentication Required" screen when `bootStatus === "unauthenticated"`. The screen explains the problem and tells users to copy the full terminal URL (including `#token=…`) or restart with `gsd --web`. Fixes #2731 * fix(gsd): sync milestone DB status in parkMilestone and unparkMilestone (#2696) * fix: sync milestone DB status in parkMilestone and unparkMilestone parkMilestone only wrote the PARKED.md filesystem marker but never updated the DB milestones.status field. Similarly, unparkMilestone deleted the marker but left the DB at 'parked'. Because deriveStateFromDb checks BOTH the filesystem marker AND m.status, an unparked milestone was still skipped — the user saw 'All milestones complete' despite the milestone being unparked on disk. The fix adds updateMilestoneStatus() to gsd-db.ts and calls it from both parkMilestone (→ 'parked') and unparkMilestone (→ 'active'), guarded by isDbAvailable() with non-fatal try/catch. Closes #2694 * review: log DB sync failures instead of silently swallowing Replace empty catch blocks with process.stderr.write so park/unpark DB sync failures are visible. Matches the pattern used in gsd-db.ts for non-fatal DB errors. Addresses review feedback from igouss on PR #2696. * fix: block complete-milestone dispatch when VALIDATION is needs-remediation (#2682) When VALIDATION.md has verdict needs-remediation and all slices appear done in the DB, the state machine enters completing-milestone. The complete-milestone dispatch rule had no verdict check, so it dispatched the unit — the agent correctly refused (validation failed), no SUMMARY was written, and the unit was re-dispatched up to MAX_LIFETIME_DISPATCHES times before stuck detection fired. The fix adds a verdict check in the completing-milestone dispatch rule that returns action: stop with level: warning when the verdict is needs-remediation. Using warning level ensures the session pauses (resumable) rather than hard-stopping, matching the pattern from #2474. Closes #2675 * feat(vscode): status bar, file decorations, bash terminal, session tree, conversation history, code lens [1/2] (#2651) * feat(vscode): status bar, auto-retry, session name, copy response, keyboard shortcuts, full stats * feat(vscode): file decorations, bash terminal, session tree view * feat(vscode): conversation history webview, slash completion, code lens - conversation-history.ts: GsdConversationHistoryPanel webview panel using getMessages() RPC; renders user/assistant turns with a Refresh button - slash-completion.ts: GsdSlashCompletionProvider triggers on '/' at line start in md/plaintext/ts/js; fetches getCommands() RPC and caches results - code-lens.ts: GsdCodeLensProvider adds 'Ask GSD' lens above named functions/classes in ts/js/py/go/rust; respects gsd.codeLens setting - extension.ts: registers all three providers and new commands (gsd.showHistory, gsd.askAboutSymbol) - package.json: declares new commands and gsd.codeLens config toggle * fix: guard allSlicesDone against vacuous truth on empty slice array (#2679) deriveStateFromDb line 565 used activeMilestoneSlices.every() without a length > 0 guard. In JavaScript, [].every() === true (vacuous truth), which would cause a premature phase transition to validating-milestone if the array were empty at that point. While the current code has an early-return at line 536 that catches length === 0, the guard is still necessary for consistency with the identical checks at lines 368 and 413 (which both have the guard), and to protect against future control-flow changes that might bypass the early return. Closes #2667 * fix: exempt interactive tools from idle watchdog stall detection (#2676) The idle watchdog treated ask_user_questions and secure_env_collect as stalled tools, killing sessions before users could respond. Root cause: tool tracking stored only toolCallId → timestamp with no tool name, so the watchdog couldn't distinguish user-interactive tools from hung tools. Changes: - auto-tool-tracking: store toolName alongside timestamp, add INTERACTIVE_TOOLS set and hasInteractiveToolInFlight() - auto.ts: forward optional toolName through markToolStart wrapper - register-hooks: pass event.toolName to markToolStart - auto-timers: skip stall detection when interactive tool is in-flight, record lastProgressKind: 'interactive-tool-waiting' - New test: 13 cases covering interactive exemption, completion cleanup, backwards compat, and existing behavior preservation * fix(claude-import): discover marketplace plugins nested inside container directories (#2718) Claude Code stores marketplace sources under ~/.claude/plugins/marketplaces/, where each subdirectory (e.g. marketplaces/my-marketplace/) is a marketplace repo containing .claude-plugin/marketplace.json. The parent directory itself does not have a marketplace.json. categorizePluginRoots was checking only the root path for marketplace.json, so ~/.claude/plugins/marketplaces/ was always categorized as flat (no marketplace.json at that level). The flat fallback then looked for package.json, which Claude plugins don't have — they use .claude-plugin/plugin.json. Two fixes: 1. categorizePluginRoots now scans one level deeper: when a root isn't itself a marketplace, it enumerates immediate subdirectories to find child marketplace repos. Deduplicates via a seen set when the same marketplace is reachable through multiple roots. 2. discoverClaudePlugins now recognizes .claude-plugin/plugin.json in addition to package.json, so cached Claude marketplace plugins are discoverable in the flat-path fallback. Closes #2717 Co-authored-by: Eric Muller <ericmuller@confluent.io> * fix(gsd): seed preferences.md into auto-mode worktrees (#2693) preferences.md was missing from both copyPlanningArtifacts() (initial worktree seed) and the ongoing forward-sync in syncGsdStateToWorktree(). This meant post_unit_hooks, skill rules, and custom instructions from preferences.md were silently unavailable in auto-mode worktrees. Fix: - Add preferences.md to copyPlanningArtifacts() file list - Add dedicated preferences.md forward-sync in syncGsdStateToWorktree() with additive-only semantics (only copies when missing in worktree) - NOT added to ROOT_STATE_FILES to prevent syncWorktreeStateBack() from overwriting the project root's authoritative preferences.md Regression test verifies: 1. Forward-sync copies preferences.md when missing from worktree 2. Forward-sync does NOT overwrite existing worktree preferences.md 3. Back-sync does NOT overwrite project root preferences.md Closes #2684 * fix: reconcile disk milestones into empty DB before deriveStateFromDb guard (#2686) When the milestones DB table has 0 rows (e.g. failed initial migration per #2529), deriveState fell through to the filesystem path because deriveStateFromDb was only called when dbMilestones.length > 0. The reconciliation code inside deriveStateFromDb was unreachable — the very condition it was supposed to fix gated its execution. The fix moves disk→DB sync into deriveState itself: when the DB is available but empty, scan disk milestone directories and insert them before the length check. This ensures the DB path activates correctly even after a failed migration. Closes #2631 * perf(gsd-db): comprehensive SQLite audit fixes — indexes, caching, safety, reconciliation 13 improvements from a full audit of the SQLite DB system powering /gsd auto: Performance: - Add 5 missing indexes for hot-path dispatch queries (schema v13) - Add PRAGMA synchronous=NORMAL, cache_size, mmap_size, temp_store tuning - Implement prepared statement caching in DbAdapter (eliminates re-parse) - Replace getActiveSliceFromDb N+1 query with single json_each() query - Add lightweight query variants (getActiveMilestoneIdFromDb, getSliceTaskCounts, etc.) - Batch enforceMemoryCap into single UPDATE (was N individual updates) Safety: - Wrap deleteSlice/deleteTask in transactions (prevents orphaned rows on crash) - Harden reconcileWorktreeDb path sanitization (reject quotes, semicolons, nulls) - Fix memory ID race condition (insert-then-derive from AUTOINCREMENT seq) Completeness: - Extend worktree reconciliation to merge all 7 tables (was only 3) - Add slice_dependencies junction table for indexed dep queries (schema v14) - Add DB vacuuming (incremental on close, full VACUUM export for milestones) - Update dead-code sequence column comments to "ordering hint" All 22 DB-related tests pass (gsd-db, memory-store, worktree-db). https://claude.ai/code/session_019h5VhLuSYNnQEd6kz9otwk * refactor(pi-ai): replace model-ID pattern matching with capability metadata (#2548) * refactor(pi-ai): replace model-ID pattern matching with capability metadata Add ModelCapabilities to Model<TApi> and a CAPABILITY_PATCHES mechanism so call sites read model.capabilities fields instead of parsing model IDs or hardcoding provider names. - types.ts: add ModelCapabilities interface (supportsXhigh, requiresToolCallId, supportsServiceTier, charsPerToken) and capabilities?: ModelCapabilities to Model<TApi> - models.ts: add CAPABILITY_PATCHES table applied at registry init; patches declare GPT-5.x and Opus 4.6 capabilities once instead of repeating ID checks at every call site; supportsXhigh() now reads capabilities only - service-tier.ts: extract SERVICE_TIER_MODEL_PREFIXES constant so the gating list has a single named home; add path comment pointing to issue #2546 for the full capability-driven follow-up No behaviour change. New models and providers can declare capabilities in their model definitions without touching function logic. Closes #2546 * fix(pi-ai): apply capability patches to custom/discovered/extension models Models constructed outside the static pi-ai registry (custom models from models.json, extension-registered models, discovered models) bypassed CAPABILITY_PATCHES — causing supportsXhigh() to silently return false for GPT-5.x or Opus 4.6 variants registered through those paths. Export applyCapabilityPatches() from pi-ai and call it in ModelRegistry after model assembly in all three construction paths: loadModels(), applyProviderConfig(), and discoverModels(). Add regression tests covering patching, precedence, idempotency, and synthetic models that mimic the custom/extension path. Closes #2546 * fix(gsd): move state machine guards inside transaction in 5 tool handlers (#2752) plan-task, plan-slice, plan-milestone, reassess-roadmap, and replan-slice all ran state machine guards (getSlice, getMilestone, getTask) outside the transaction() callback, then performed writes in a separate transaction. This created a TOCTOU race: two agents could both pass the guard simultaneously and both write successfully. Fix: move all guard checks into the transaction() callback using the guardError pattern already used by complete-task, complete-slice, reopen-task, and reopen-slice. The SQLite write lock now covers both the guard reads and the subsequent writes atomically. Closes #2723 * Fix WARN log readability by improving yellow contrast in light theme (#2689) * Merge branch 'main' into fix/unified-error-classifier Resolve conflicts in provider-error-pause.ts and provider-errors.test.ts. Add stream_exhausted(_without_result) pattern to unified CONNECTION_RE (ported from main's classifyProviderError addition). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * ci: enforce test requirements and coverage thresholds on PRs Add two CI gates to enforce CONTRIBUTING.md test requirements: 1. File-matching check (lint job): fails PRs that change source files without including test file changes. Exempts docs/chore/ci branches. 2. Coverage gate (build job): wires existing `npm run test:coverage` into CI with c8 thresholds (40% statements/lines, 20% branches/functions). Previously defined in package.json but never ran in CI. Lowers coverage thresholds from 50% to 40% for statements/lines to match current codebase reality (~44%) — prevents the gate from blocking every PR on day one while still catching coverage regressions. * fix: wire tool handlers through DB port layer, remove _getAdapter from all tools Fixes #2726. Tool handlers were bypassing the DB port layer by calling _getAdapter() directly for raw SQL. Replace all such callsites with proper exported DB functions. - Add setTaskSummaryMd(), setSliceSummaryMd() to gsd-db.ts - Extend updateMilestoneStatus() to accept optional completedAt param - Add deleteVerificationEvidence(), deleteAssessmentByScope() to gsd-db.ts - complete-task.ts: use updateTaskStatus, setTaskSummaryMd, deleteVerificationEvidence - complete-slice.ts: use updateSliceStatus, setSliceSummaryMd - complete-milestone.ts: use updateMilestoneStatus for both complete and rollback - validate-milestone.ts: use insertAssessment, deleteAssessmentByScope - plan-slice.ts, plan-milestone.ts: remove dead _getAdapter import * fix: remove preferences.md from ROOT_STATE_FILES to prevent back-sync overwrite preferences.md was in ROOT_STATE_FILES which caused syncWorktreeStateBack() to overwrite the project root's authoritative copy with the worktree's stale copy. The forward-sync (main → worktree) is already handled separately in syncGsdStateToWorktree() as additive-only. Fixes the failing CI test: worktree-preferences-sync.test.ts:107 '#2684: syncWorktreeStateBack does NOT overwrite project root preferences.md' Also updates preferences-worktree-sync.test.ts to assert preferences.md is NOT in ROOT_STATE_FILES (it must be handled separately). * fix: make transaction() re-entrant and add slice_dependencies to initSchema Two bugs fixed: 1. transaction() now tracks nesting depth. When deleteTask/deleteSlice (which wrap in transaction()) are called from within an outer transaction() in reassess-roadmap.ts or replan-slice.ts, the inner call skips BEGIN/COMMIT since SQLite doesn't support nested transactions. This fixes: - reassess-handler.test.ts: 3 failing tests - replan-handler.test.ts: 4 failing tests All errors were: 'cannot start a transaction within a transaction' 2. slice_dependencies table and v13/v14 indexes were only created in migrateSchema (for upgrades from older versions) but missing from initSchema (for fresh databases). New databases started at schema version 14 but never created the table, causing 'no such table: slice_dependencies' when deleteSlice was called. --------- Co-authored-by: TÂCHES <afromanguy@me.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: mastertyko <11311479+mastertyko@users.noreply.github.com> Co-authored-by: Lex Christopherson <lex@glittercowboy.com> Co-authored-by: Yang Yang <Jokerkeny@gmail.com> Co-authored-by: Yang Yang(NYC) <Yang.Yang2@bcg.com> Co-authored-by: Tom Boucher <trekkie@nomorestars.com> Co-authored-by: deseltrus <101901449+deseltrus@users.noreply.github.com> Co-authored-by: Andrew <43323844+snowdamiz@users.noreply.github.com> Co-authored-by: DavidMei <94948521@163.com> Co-authored-by: madjack <148759141+m4djack@users.noreply.github.com> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Iouri Goussev <i.gouss@gmail.com> Co-authored-by: Matt Haynes <lucidbloks@gmail.com> Co-authored-by: Matt Haynes <matt@auroraventures.io> Co-authored-by: Vojtěch Šplíchal <splichal@gmail.com> Co-authored-by: Eric Muller <emuller@confluent.io> Co-authored-by: Eric Muller <ericmuller@confluent.io> Co-authored-by: drkthng <drkthng@gmail.com> Co-authored-by: deekshanayak-1108 <deekshakeshavanayak11@gmail.com> |
||
|---|---|---|
| .github | ||
| .plans | ||
| docker | ||
| docs | ||
| gsd-orchestrator | ||
| mintlify-docs | ||
| native | ||
| packages | ||
| pkg | ||
| scripts | ||
| src | ||
| studio | ||
| tests | ||
| vscode-extension | ||
| web | ||
| .dockerignore | ||
| .gitignore | ||
| .npmignore | ||
| .npmrc | ||
| .secretscanignore | ||
| CHANGELOG.md | ||
| CONTRIBUTING.md | ||
| Dockerfile | ||
| LICENSE | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
| tsconfig.extensions.json | ||
| tsconfig.json | ||
| tsconfig.resources.json | ||
| tsconfig.test.json | ||
| VISION.md | ||
GSD 2
The evolution of Get Shit Done — now a real coding agent.
The original GSD went viral as a prompt framework for Claude Code. It worked, but it was fighting the tool — injecting prompts through slash commands, hoping the LLM would follow instructions, with no actual control over context windows, sessions, or execution.
This version is different. GSD is now a standalone CLI built on the Pi SDK, which gives it direct TypeScript access to the agent harness itself. That means GSD can actually do what v1 could only ask the LLM to do: clear context between tasks, inject exactly the right files at dispatch time, manage git branches, track cost and tokens, detect stuck loops, recover from crashes, and auto-advance through an entire milestone without human intervention.
One command. Walk away. Come back to a built project with clean git history.
npm install -g gsd-pi@latest
GSD now provisions a managed RTK binary on supported macOS, Linux, and Windows installs to compress shell-command output in
bash,async_bash,bg_shell, and verification flows. GSD forcesRTK_TELEMETRY_DISABLED=1for all managed invocations. SetGSD_RTK_DISABLED=1to disable the integration.
📋 NOTICE: New to Node on Mac? If you installed Node.js via Homebrew, you may be running a development release instead of LTS. Read this guide to pin Node 24 LTS and avoid compatibility issues.
What's New in v2.46.0
Single-Writer State Engine
The biggest architectural change since DB-backed planning tools. The single-writer engine enforces disciplined state transitions through three iterations:
- v2 — discipline layer — adds a write-side discipline layer on top of the DB architecture, ensuring all state mutations flow through controlled tool calls.
- v3 — state machine guards, actor identity, reversibility — introduces formal state machine guards, tracks which actor (human vs agent) initiated each transition, and makes transitions reversible.
- Hardened — closes TOCTOU race conditions, intercepts bypass attempts, and resolves status inconsistencies.
All prompts are now aligned with the single-writer tool API, and a new workflow-logger is wired into the engine, tool, manifest, and reconcile paths for full observability. (#2494)
v2.45.0 — New Commands and Capabilities
/gsd rethink— conversational project reorganization. Rethink your milestone structure, slice decomposition, or overall approach through guided discussion. (#2459)/gsd mcp— MCP server status and connectivity. Check which MCP servers are configured, connected, and healthy. (#2362)- Complete offline mode — GSD now works fully offline with local models. (#2429)
- Global KNOWLEDGE.md injection —
~/.gsd/agent/KNOWLEDGE.mdis injected into the system prompt, so cross-project knowledge persists globally. (#2331) - Mobile-responsive web UI — the browser interface now works on phones and tablets. (#2354)
- DB tool previews —
renderCall/renderResultpreviews on DB tools show what each tool call does before and after execution. (#2273) - Message timestamps — user and assistant messages now include timestamps. (#2368)
Key Changes
- Default isolation mode changed to
none—git.isolationnow defaults tononeinstead ofworktree. Projects that rely on worktree isolation should setgit.isolation: worktreeexplicitly in preferences. (#2481) - Startup checks — GSD now validates Node.js version and git availability at startup, with clear error messages. (#2463)
- Worktree lifecycle journaling — worktree create, switch, merge, and remove events are recorded in the event journal. (#2486)
- Milestone verification gate — milestone completion is blocked when verification fails, preventing premature closure. (#2500)
Key Fixes
- Auto-mode stability — recovery attempts reset on unit re-dispatch (#2424), survivor branch recovery handles
phase=complete(#2427), and auto mode stops on real merge conflicts (#2428). - Supervision timeouts — now respect task
est:annotations, so complex tasks get proportionally longer timeouts. (#2434) auto_pr: truefixed — three interacting bugs prevented auto-PR creation; all three are resolved. (#2433)- Rich task plan preservation — plans survive DB roundtrip without losing structured content. (#2453)
- Artifact truncation prevention —
saveArtifactToDbno longer overwrites larger files with truncated content. (#2447) - Worktree teardown — submodule state is detected and preserved during teardown (#2425), and worktree merge back to main works after
stopAutoon milestone completion (#2430). - Windows portability —
retentionDays=0handling and CRLF fixes on Windows. (#2460) - Voice on Linux — misleading portaudio error on PEP 668 systems replaced with actionable guidance. (#2407)
Previous highlights (v2.42–v2.44)
- Non-API-key provider extensions — support for Claude Code CLI and similar providers. (#2382)
- Docker sandbox template — official Docker template for isolated auto mode. (#2360)
- DB-backed planning tools — write-side state transitions use atomic SQLite tool calls. (#2141)
- Declarative workflow engine — YAML workflows through auto-loop. (#2024)
/gsd fast— toggle service tier for prioritized API routing. (#1862)- Forensics dedup — duplicate detection before issue creation. (#2105)
- Startup optimizations — pre-compiled extensions, compile cache, batch discovery. (#2125)
What's New in v2.41.0
New Features
- Browser-based web interface — run GSD from the browser with
gsd --web. Full project management, real-time progress, and multi-project support via server-sent events. (#1717) - Doctor: worktree lifecycle checks —
/gsd doctornow validates worktree health, detects orphaned worktrees, consolidates cleanup, and enhances/worktree listwith lifecycle status. (#1814) - CI: docs-only PR detection — PRs that only change documentation skip build and test steps, with a new prompt injection scan for security. (#1699)
- Custom Models guide — new documentation for adding custom providers (Ollama, vLLM, LM Studio, proxies) via
models.json. (#1670)
Data Loss Prevention (Critical Fixes)
This release includes 7 fixes preventing silent data loss in auto-mode:
- Hallucination guard — execute-task agents that complete with zero tool calls are now rejected as hallucinated. Previously, agents could produce detailed but fabricated summaries without writing any code, wasting ~$25/milestone. (#1838)
- Merge anchor verification — before deleting a milestone worktree/branch, GSD now verifies the code is actually on the integration branch. Prevents orphaning commits when squash-merge produces an empty diff. (#1829)
- Dirty working tree detection —
nativeMergeSquashnow distinguishes dirty-tree rejections from content conflicts, preventing silent commit loss when synced.gsd/files block the merge. (#1752) - Doctor cleanup safety — the
orphaned_completed_unitscheck no longer auto-fixes during post-task health checks. Previously, timing races could cause the doctor to remove valid completion keys, reverting users to earlier tasks. (#1825) - Root file reverse-sync — worktree teardown now syncs root-level
.gsd/files (PROJECT.md, REQUIREMENTS.md, completed-units.json) back to the project root. Previously these were lost on milestone closeout. (#1831) - Empty merge guard — milestone branches with unanchored code changes are preserved instead of deleted when squash-merge produces nothing to commit. (#1755)
- Crash-safe task closeout — orphaned checkboxes in PLAN.md are unchecked on retry, preventing phantom task completion. (#1759)
Auto-Mode Stability
- Terminal hang fix —
stopAuto()now resolves pending promises, preventing the terminal from freezing permanently after stopping auto-mode. (#1818) - Signal handler coverage — SIGHUP and SIGINT now clean up lock files, not just SIGTERM. Prevents stranded locks on VS-Code crash. (#1821)
- Needs-discussion routing — milestones in
needs-discussionphase now route to the smart entry UI instead of hard-stopping, breaking the infinite loop. (#1820) - Infrastructure error handling — auto-mode stops immediately on ENOSPC, ENOMEM, and similar unrecoverable errors instead of retrying. (#1780)
- Dependency-aware dispatch — slice dispatch now uses declared
depends_oninstead of positional ordering. (#1770) - Queue mode depth verification — the write gate now processes depth verification in queue mode, fixing a deadlock where CONTEXT.md writes were permanently blocked. (#1823)
Roadmap Parser Improvements
- Table format support — roadmaps using markdown tables (
| S01 | Title | Risk | Status |) are now parsed correctly. (#1741) - Prose header fallback — when
## Slicescontains H3 headers instead of checkboxes, the prose parser is invoked as a fallback. (#1744) - Completion marker detection — prose headers with
✓or(Complete)markers are correctly identified as done. (#1816) - Zero-slice stub handling — stub roadmaps from
/gsd queuereturnpre-planninginstead ofblocked. (#1826) - Immediate roadmap fix — roadmap checkbox and UAT stub are fixed immediately after last task instead of deferring to
complete-slice. (#1819)
State & Git Improvements
- CONTEXT-DRAFT.md fallback —
depends_onis read from CONTEXT-DRAFT.md when CONTEXT.md doesn't exist, preventing draft milestones from being promoted past dependency constraints. (#1743) - Unborn branch support —
nativeBranchExistshandles repos with zero commits, preventing dispatch deadlock on new repos. (#1815) - Ghost milestone detection — empty
.gsd/milestones/directories are skipped instead of crashingderiveState(). (#1817) - Default branch detection — milestone merge detects
mastervsmaininstead of hardcoding. (#1669) - Milestone title extraction — titles are pulled from CONTEXT.md headings when no ROADMAP exists. (#1729)
Windows & Platform
- Windows path handling — 8.3 short paths,
pathToFileURLfor ESM imports, andrealpathSync.nativefixes across the test suite and verification gate. (#1804) - DEP0190 fix —
spawnSyncdeprecation warning eliminated by passing commands to shell explicitly. (#1827) - Web build skip on Windows — Next.js webpack EPERM errors on system directories are handled gracefully.
Developer Experience
- @ file finder fix — typing
@no longer freezes the TUI. The fix adds debounce, dedup, and empty-query short-circuit. (#1832) - Tool-call loop guard — detects and breaks infinite tool-call loops within a single unit, preventing stack overflow. (#1801)
- Completion deferral fix — roadmap checkbox and UAT stub are fixed at task level, closing the fragile handoff window between last task and
complete-slice. (#1819)
See the full Changelog for all 70+ fixes in this release.
Previous highlights (v2.39–v2.41)
- Browser-based web interface — run GSD from the browser with
gsd --web - GitHub sync extension — auto-sync milestones to GitHub Issues, PRs, and Milestones
- Skill tool resolution — skills auto-activate in dispatched prompts
- Health check phase 2 — real-time doctor issues in dashboard and visualizer
- Forensics upgrade — full-access GSD debugger with anomaly detection
- 7 data-loss prevention fixes — hallucination guard, merge anchor verification, dirty tree detection, and more
- Pipeline decomposition — auto-loop rewritten as linear phase pipeline
- Sliding-window stuck detection — pattern-aware, fewer false positives
- Data-loss recovery — automatic detection and recovery from v2.30–v2.38 migration issues
Documentation
Full documentation is available at gsd.build (powered by Mintlify) and in the docs/ directory:
- Getting Started — install, first run, basic usage
- Auto Mode — autonomous execution deep-dive
- Configuration — all preferences, models, git, and hooks
- Custom Models — add custom providers (Ollama, vLLM, LM Studio, proxies)
- Token Optimization — profiles, context compression, complexity routing
- Cost Management — budgets, tracking, projections
- Git Strategy — worktree isolation, branching, merge behavior
- Parallel Orchestration — run multiple milestones simultaneously
- Working in Teams — unique IDs, shared artifacts
- Skills — bundled skills, discovery, custom authoring
- Commands Reference — all commands and keyboard shortcuts
- Architecture — system design and dispatch pipeline
- Troubleshooting — common issues, doctor, forensics, recovery
- CI/CD Pipeline — three-stage promotion pipeline (Dev → Test → Prod)
- VS Code Extension — chat participant, sidebar dashboard, RPC integration
- Visualizer — workflow visualizer with stats and discussion status
- Remote Questions — route decisions to Slack or Discord when human input is needed
- Dynamic Model Routing — complexity-based model selection and budget pressure
- Web Interface — browser-based project management and real-time progress
- Pipeline Simplification (ADR-003) — merged research into planning, mechanical completion
- Docker Sandbox — run GSD auto mode in an isolated Docker container
- Migration from v1 —
.planning→.gsdmigration
What Changed From v1
The original GSD was a collection of markdown prompts installed into ~/.claude/commands/. It relied entirely on the LLM reading those prompts and doing the right thing. That worked surprisingly well — but it had hard limits:
- No context control. The LLM accumulated garbage over a long session. Quality degraded.
- No real automation. "Auto mode" was the LLM calling itself in a loop, burning context on orchestration overhead.
- No crash recovery. If the session died mid-task, you started over.
- No observability. No cost tracking, no progress dashboard, no stuck detection.
GSD v2 solves all of these because it's not a prompt framework anymore — it's a TypeScript application that controls the agent session.
| v1 (Prompt Framework) | v2 (Agent Application) | |
|---|---|---|
| Runtime | Claude Code slash commands | Standalone CLI via Pi SDK |
| Context management | Hope the LLM doesn't fill up | Fresh session per task, programmatic |
| Auto mode | LLM self-loop | State machine reading .gsd/ files |
| Crash recovery | None | Lock files + session forensics |
| Git strategy | LLM writes git commands | Worktree isolation, sequential commits, squash merge |
| Cost tracking | None | Per-unit token/cost ledger with dashboard |
| Stuck detection | None | Retry once, then stop with diagnostics |
| Timeout supervision | None | Soft/idle/hard timeouts with recovery steering |
| Context injection | "Read this file" | Pre-inlined into dispatch prompt |
| Roadmap reassessment | Manual | Automatic after each slice completes |
| Skill discovery | None | Auto-detect and install relevant skills during research |
| Verification | Manual | Automated verification commands with auto-fix retries |
| Reporting | None | Self-contained HTML reports with metrics and dep graphs |
| Parallel execution | None | Multi-worker parallel milestone orchestration |
Migrating from v1
Note: Migration works best with a
ROADMAP.mdfile for milestone structure. Without one, milestones are inferred from thephases/directory.
If you have projects with .planning directories from the original Get Shit Done, you can migrate them to GSD-2's .gsd format:
# From within the project directory
/gsd migrate
# Or specify a path
/gsd migrate ~/projects/my-old-project
The migration tool:
- Parses your old
PROJECT.md,ROADMAP.md,REQUIREMENTS.md, phase directories, plans, summaries, and research - Maps phases → slices, plans → tasks, milestones → milestones
- Preserves completion state (
[x]phases stay done, summaries carry over) - Consolidates research files into the new structure
- Shows a preview before writing anything
- Optionally runs an agent-driven review of the output for quality assurance
Supports format variations including milestone-sectioned roadmaps with <details> blocks, bold phase entries, bullet-format requirements, decimal phase numbering, and duplicate phase numbers across milestones.
How It Works
GSD structures work into a hierarchy:
Milestone → a shippable version (4-10 slices)
Slice → one demoable vertical capability (1-7 tasks)
Task → one context-window-sized unit of work
The iron rule: a task must fit in one context window. If it can't, it's two tasks.
The Loop
Each slice flows through phases automatically:
Plan (with integrated research) → Execute (per task) → Complete → Reassess Roadmap → Next Slice
↓ (all slices done)
Validate Milestone → Complete Milestone
Plan scouts the codebase, researches relevant docs, and decomposes the slice into tasks with must-haves (mechanically verifiable outcomes). Execute runs each task in a fresh context window with only the relevant files pre-loaded — then runs configured verification commands (lint, test, etc.) with auto-fix retries. Complete writes the summary, UAT script, marks the roadmap, and commits with meaningful messages derived from task summaries. Reassess checks if the roadmap still makes sense given what was learned. Validate Milestone runs a reconciliation gate after all slices complete — comparing roadmap success criteria against actual results before sealing the milestone.
/gsd auto — The Main Event
This is what makes GSD different. Run it, walk away, come back to built software.
/gsd auto
Auto mode is a state machine driven by files on disk. It reads .gsd/STATE.md, determines the next unit of work, creates a fresh agent session, injects a focused prompt with all relevant context pre-inlined, and lets the LLM execute. When the LLM finishes, auto mode reads disk state again and dispatches the next unit.
What happens under the hood:
-
Fresh session per unit — Every task, every research phase, every planning step gets a clean 200k-token context window. No accumulated garbage. No "I'll be more concise now."
-
Context pre-loading — The dispatch prompt includes inlined task plans, slice plans, prior task summaries, dependency summaries, roadmap excerpts, and decisions register. The LLM starts with everything it needs instead of spending tool calls reading files.
-
Git isolation — When
git.isolationis set toworktreeorbranch, each milestone runs on its ownmilestone/<MID>branch (in a worktree or in-place). All slice work commits sequentially — no branch switching, no merge conflicts. When the milestone completes, it's squash-merged to main as one clean commit. The default isnone(work on the current branch), configurable via preferences. -
Crash recovery — A lock file tracks the current unit. If the session dies, the next
/gsd autoreads the surviving session file, synthesizes a recovery briefing from every tool call that made it to disk, and resumes with full context. Parallel orchestrator state is persisted to disk with PID liveness detection, so multi-worker sessions survive crashes too. In headless mode, crashes trigger automatic restart with exponential backoff (default 3 attempts). -
Provider error recovery — Transient provider errors (rate limits, 500/503 server errors, overloaded) auto-resume after a delay. Permanent errors (auth, billing) pause for manual review. The model fallback chain retries transient network errors before switching models.
-
Stuck detection — A sliding-window detector identifies repeated dispatch patterns (including multi-unit cycles). On detection, it retries once with a deep diagnostic. If it fails again, auto mode stops with the exact file it expected.
-
Timeout supervision — Soft timeout warns the LLM to wrap up. Idle watchdog detects stalls. Hard timeout pauses auto mode. Recovery steering nudges the LLM to finish durable output before giving up.
-
Cost tracking — Every unit's token usage and cost is captured, broken down by phase, slice, and model. The dashboard shows running totals and projections. Budget ceilings can pause auto mode before overspending.
-
Adaptive replanning — After each slice completes, the roadmap is reassessed. If the work revealed new information that changes the plan, slices are reordered, added, or removed before continuing.
-
Verification enforcement — Configure shell commands (
npm run lint,npm run test, etc.) that run automatically after task execution. Failures trigger auto-fix retries before advancing. Auto-discovered checks frompackage.jsonrun in advisory mode — they log warnings but don't block on pre-existing errors. Configurable viaverification_commands,verification_auto_fix, andverification_max_retriespreferences. -
Milestone validation — After all slices complete, a
validate-milestonegate compares roadmap success criteria against actual results before sealing the milestone. -
Escape hatch — Press Escape to pause. The conversation is preserved. Interact with the agent, inspect what happened, or just
/gsd autoto resume from disk state.
/gsd and /gsd next — Step Mode
By default, /gsd runs in step mode: the same state machine as auto mode, but it pauses between units with a wizard showing what completed and what's next. You advance one step at a time, review the output, and continue when ready.
- No
.gsd/directory → Start a new project. Discussion flow captures your vision, constraints, and preferences. - Milestone exists, no roadmap → Discuss or research the milestone.
- Roadmap exists, slices pending → Plan the next slice, execute one task, or switch to auto.
- Mid-task → Resume from where you left off.
/gsd next is an explicit alias for step mode. You can switch from step → auto mid-session via the wizard.
Step mode is the on-ramp. Auto mode is the highway.
Getting Started
Install
npm install -g gsd-pi
Log in to a provider
First, choose your LLM provider:
gsd
/login
Select from 20+ providers — Anthropic, OpenAI, Google, OpenRouter, GitHub Copilot, and more. If you have a Claude Max or Copilot subscription, the OAuth flow handles everything. Otherwise, paste your API key when prompted.
GSD auto-selects a default model after login. To switch models later:
/model
Use it
Open a terminal in your project and run:
gsd
GSD opens an interactive agent session. From there, you have two ways to work:
/gsd — step mode. Type /gsd and GSD executes one unit of work at a time, pausing between each with a wizard showing what completed and what's next. Same state machine as auto mode, but you stay in the loop. No project yet? It starts the discussion flow. Roadmap exists? It plans or executes the next step.
/gsd auto — autonomous mode. Type /gsd auto and walk away. GSD researches, plans, executes, verifies, commits, and advances through every slice until the milestone is complete. Fresh context window per task. No babysitting.
Two terminals, one project
The real workflow: run auto mode in one terminal, steer from another.
Terminal 1 — let it build
gsd
/gsd auto
Terminal 2 — steer while it works
gsd
/gsd discuss # talk through architecture decisions
/gsd status # check progress
/gsd queue # queue the next milestone
Both terminals read and write the same .gsd/ files on disk. Your decisions in terminal 2 are picked up automatically at the next phase boundary — no need to stop auto mode.
Headless mode — CI and scripts
gsd headless runs any /gsd command without a TUI. Designed for CI pipelines, cron jobs, and scripted automation.
# Run auto mode in CI
gsd headless --timeout 600000
# Create and execute a milestone end-to-end
gsd headless new-milestone --context spec.md --auto
# One unit at a time (cron-friendly)
gsd headless next
# Instant JSON snapshot (no LLM, ~50ms)
gsd headless query
# Force a specific pipeline phase
gsd headless dispatch plan
Headless auto-responds to interactive prompts, detects completion, and exits with structured codes: 0 complete, 1 error/timeout, 2 blocked. Auto-restarts on crash with exponential backoff. Use gsd headless query for instant, machine-readable state inspection — returns phase, next dispatch preview, and parallel worker costs as a single JSON object without spawning an LLM session. Pair with remote questions to route decisions to Slack or Discord when human input is needed.
Multi-session orchestration — headless mode supports file-based IPC in .gsd/parallel/ for coordinating multiple GSD workers across milestones. Build orchestrators that spawn, monitor, and budget-cap a fleet of GSD workers.
First launch
On first run, GSD launches a branded setup wizard that walks you through LLM provider selection (OAuth or API key), then optional tool API keys (Brave Search, Context7, Jina, Slack, Discord). Every step is skippable — press Enter to skip any. If you have an existing Pi installation, your provider credentials (LLM and tool keys) are imported automatically. Run gsd config anytime to re-run the wizard.
Commands
| Command | What it does |
|---|---|
/gsd |
Step mode — executes one unit at a time, pauses between each |
/gsd next |
Explicit step mode (same as bare /gsd) |
/gsd auto |
Autonomous mode — researches, plans, executes, commits, repeats |
/gsd quick |
Execute a quick task with GSD guarantees, skip planning overhead |
/gsd stop |
Stop auto mode gracefully |
/gsd steer |
Hard-steer plan documents during execution |
/gsd discuss |
Discuss architecture and decisions (works alongside auto mode) |
/gsd rethink |
Conversational project reorganization |
/gsd mcp |
MCP server status and connectivity |
/gsd status |
Progress dashboard |
/gsd queue |
Queue future milestones (safe during auto mode) |
/gsd prefs |
Model selection, timeouts, budget ceiling |
/gsd migrate |
Migrate a v1 .planning directory to .gsd format |
/gsd help |
Categorized command reference for all GSD subcommands |
/gsd mode |
Switch workflow mode (solo/team) with coordinated defaults |
/gsd forensics |
Full-access GSD debugger for auto-mode failure investigation |
/gsd cleanup |
Archive phase directories from completed milestones |
/gsd doctor |
Runtime health checks — issues surface across widget, visualizer, and reports |
/gsd keys |
API key manager — list, add, remove, test, rotate, doctor |
/gsd logs |
Browse activity, debug, and metrics logs |
/gsd export --html |
Generate HTML report for current or completed milestone |
/worktree (/wt) |
Git worktree lifecycle — create, switch, merge, remove |
/voice |
Toggle real-time speech-to-text (macOS, Linux) |
/exit |
Graceful shutdown — saves session state before exiting |
/kill |
Kill GSD process immediately |
/clear |
Start a new session (alias for /new) |
Ctrl+Alt+G |
Toggle dashboard overlay |
Ctrl+Alt+V |
Toggle voice transcription |
Ctrl+Alt+B |
Show background shell processes |
Alt+V |
Paste clipboard image (macOS) |
gsd config |
Re-run the setup wizard (LLM provider + tool keys) |
gsd update |
Update GSD to the latest version |
gsd headless [cmd] |
Run /gsd commands without TUI (CI, cron, scripts) |
gsd headless query |
Instant JSON snapshot — state, next dispatch, costs (no LLM) |
gsd --continue (-c) |
Resume the most recent session for the current directory |
gsd --worktree (-w) |
Launch an isolated worktree session for the active milestone |
gsd sessions |
Interactive session picker — browse and resume any saved session |
What GSD Manages For You
Context Engineering
Every dispatch is carefully constructed. The LLM never wastes tool calls on orientation.
| Artifact | Purpose |
|---|---|
PROJECT.md |
Living doc — what the project is right now |
DECISIONS.md |
Append-only register of architectural decisions |
KNOWLEDGE.md |
Cross-session rules, patterns, and lessons learned |
RUNTIME.md |
Runtime context — API endpoints, env vars, services (v2.39) |
STATE.md |
Quick-glance dashboard — always read first |
M001-ROADMAP.md |
Milestone plan with slice checkboxes, risk levels, dependencies |
M001-CONTEXT.md |
User decisions from the discuss phase |
M001-RESEARCH.md |
Codebase and ecosystem research |
S01-PLAN.md |
Slice task decomposition with must-haves |
T01-PLAN.md |
Individual task plan with verification criteria |
T01-SUMMARY.md |
What happened — YAML frontmatter + narrative |
S01-UAT.md |
Human test script derived from slice outcomes |
Git Strategy
Branch-per-slice with squash merge. Fully automated.
main:
docs(M001/S04): workflow documentation and examples
fix(M001/S03): bug fixes and doc corrections
feat(M001/S02): API endpoints and middleware
feat(M001/S01): data model and type system
gsd/M001/S01 (deleted after merge):
feat(S01/T03): file writer with round-trip fidelity
feat(S01/T02): markdown parser for plan files
feat(S01/T01): core types and interfaces
One squash commit per milestone on main (or whichever branch you started from). The worktree is torn down after merge. Git bisect works. Individual milestones are revertable. Commit messages are generated from task summaries — no more generic "complete task" messages.
Verification
Every task has must-haves — mechanically checkable outcomes:
- Truths — Observable behaviors ("User can sign up with email")
- Artifacts — Files that must exist with real implementation, not stubs
- Key Links — Imports and wiring between artifacts
The verification ladder: static checks → command execution → behavioral testing → human review (only when the agent genuinely can't verify itself).
Dashboard
Ctrl+Alt+G or /gsd status opens a real-time overlay showing:
- Current milestone, slice, and task progress
- Auto mode elapsed time and phase
- Per-unit cost and token breakdown by phase, slice, and model
- Cost projections based on completed work
- Completed and in-progress units
HTML Reports
After a milestone completes, GSD auto-generates a self-contained HTML report in .gsd/reports/. Each report includes project summary, progress tree, slice dependency graph (SVG DAG), cost/token metrics with bar charts, execution timeline, changelog, and knowledge base sections. No external dependencies — all CSS and JS are inlined, printable to PDF from any browser.
An auto-generated index.html shows all reports with progression metrics across milestones.
- Automatic — generated after milestone completion (configurable via
auto_reportpreference) - Manual — run
/gsd export --htmlanytime
Configuration
Preferences
GSD preferences live in ~/.gsd/PREFERENCES.md (global) or .gsd/PREFERENCES.md (project). Manage with /gsd prefs.
---
version: 1
models:
research: claude-sonnet-4-6
planning:
model: claude-opus-4-6
fallbacks:
- openrouter/z-ai/glm-5
- openrouter/minimax/minimax-m2.5
execution: claude-sonnet-4-6
completion: claude-sonnet-4-6
skill_discovery: suggest
auto_supervisor:
soft_timeout_minutes: 20
idle_timeout_minutes: 10
hard_timeout_minutes: 30
budget_ceiling: 50.00
unique_milestone_ids: true
verification_commands:
- npm run lint
- npm run test
auto_report: true
---
Key settings:
| Setting | What it controls |
|---|---|
models.* |
Per-phase model selection — string for a single model, or {model, fallbacks} for automatic failover |
skill_discovery |
auto / suggest / off — how GSD finds and applies skills |
auto_supervisor.* |
Timeout thresholds for auto mode supervision |
budget_ceiling |
USD ceiling — auto mode pauses when reached |
uat_dispatch |
Enable automatic UAT runs after slice completion |
always_use_skills |
Skills to always load when relevant |
skill_rules |
Situational rules for skill routing |
skill_staleness_days |
Skills unused for N days get deprioritized (default: 60, 0 = disabled) |
unique_milestone_ids |
Uses unique milestone names to avoid clashes when working in teams of people |
git.isolation |
none (default), worktree, or branch — enable worktree or branch isolation for milestone work |
git.manage_gitignore |
Set false to prevent GSD from modifying .gitignore |
verification_commands |
Array of shell commands to run after task execution (e.g., ["npm run lint", "npm run test"]) |
verification_auto_fix |
Auto-retry on verification failures (default: true) |
verification_max_retries |
Max retries for verification failures (default: 2) |
require_slice_discussion |
Pause auto-mode before each slice for human discussion review |
auto_report |
Auto-generate HTML reports after milestone completion (default: true) |
searchExcludeDirs |
Directories to exclude from @ file autocomplete (e.g., ["node_modules", ".git", "dist"]) |
Agent Instructions
Place an AGENTS.md file in any directory to provide persistent behavioral guidance for that scope. Pi core loads AGENTS.md automatically (with CLAUDE.md as a fallback) at both user and project levels. Use these files for coding standards, architectural decisions, domain terminology, or workflow preferences.
Note: The legacy
agent-instructions.mdformat (~/.gsd/agent-instructions.mdand.gsd/agent-instructions.md) is deprecated and no longer loaded. Migrate any existing instructions toAGENTS.mdorCLAUDE.md.
Debug Mode
Start GSD with gsd --debug to enable structured JSONL diagnostic logging. Debug logs capture dispatch decisions, state transitions, and timing data for troubleshooting auto-mode issues.
Token Optimization
GSD includes a coordinated token optimization system that reduces usage by 40-60% on cost-sensitive workloads. Set a single preference to coordinate model selection, phase skipping, and context compression:
token_profile: budget # or balanced (default), quality
| Profile | Savings | What It Does |
|---|---|---|
budget |
40-60% | Cheap models, skip research/reassess, minimal context inlining |
balanced |
10-20% | Default models, skip slice research, standard context |
quality |
0% | All phases, all context, full model power |
Complexity-based routing automatically classifies tasks as simple/standard/complex and routes to appropriate models. Simple docs tasks get Haiku; complex architectural work gets Opus. The classification is heuristic (sub-millisecond, no LLM calls) and learns from outcomes via a persistent routing history.
Budget pressure graduates model downgrading as you approach your budget ceiling — 50%, 75%, and 90% thresholds progressively shift work to cheaper tiers.
See the full Token Optimization Guide for details.
Bundled Tools
GSD ships with 19 extensions, all loaded automatically:
| Extension | What it provides |
|---|---|
| GSD | Core workflow engine, auto mode, commands, dashboard |
| Browser Tools | Playwright-based browser with form intelligence, intent-ranked element finding, semantic actions, PDF export, session state persistence, network mocking, device emulation, structured extraction, visual diffing, region zoom, test code generation, and prompt injection detection |
| Search the Web | Brave Search, Tavily, or Jina page extraction |
| Google Search | Gemini-powered web search with AI-synthesized answers |
| Context7 | Up-to-date library/framework documentation |
| Background Shell | Long-running process management with readiness detection |
| Async Jobs | Background bash commands with job tracking and cancellation |
| Subagent | Delegated tasks with isolated context windows |
| GitHub | Full-suite GitHub issues and PR management via /gh command |
| Mac Tools | macOS native app automation via Accessibility APIs |
| MCP Client | Native MCP server integration via @modelcontextprotocol/sdk |
| Voice | Real-time speech-to-text transcription (macOS, Linux — Ubuntu 22.04+) |
| Slash Commands | Custom command creation |
| Ask User Questions | Structured user input with single/multi-select |
| Secure Env Collect | Masked secret collection without manual .env editing |
| Remote Questions | Route decisions to Slack/Discord when human input is needed in headless/CI mode |
| Universal Config | Discover and import MCP servers and rules from other AI coding tools |
| AWS Auth | Automatic Bedrock credential refresh for AWS-hosted models |
| TTSR | Tool-use type-safe runtime validation |
Bundled Agents
Three specialized subagents for delegated work:
| Agent | Role |
|---|---|
| Scout | Fast codebase recon — returns compressed context for handoff |
| Researcher | Web research — finds and synthesizes current information |
| Worker | General-purpose execution in an isolated context window |
Working in teams
The best practice for working in teams is to ensure unique milestone names across all branches (by using unique_milestone_ids) and checking in the right .gsd/ artifacts to share valuable context between teammates.
Suggested .gitignore setup
# ── GSD: Runtime / Ephemeral (per-developer, per-session) ──────────────────
# Crash detection sentinel — PID lock, written per auto-mode session
.gsd/auto.lock
# Auto-mode dispatch tracker — prevents re-running completed units
.gsd/completed-units.json
# Derived state cache — regenerated from plan/roadmap files on disk
.gsd/STATE.md
# Per-developer token/cost accumulator
.gsd/metrics.json
# Raw JSONL session dumps — crash recovery forensics, auto-pruned
.gsd/activity/
# Unit execution records — dispatch phase, timeouts, recovery tracking
.gsd/runtime/
# Git worktree working copies
.gsd/worktrees/
# Parallel orchestration IPC and worker status
.gsd/parallel/
# Generated HTML reports (regenerable via /gsd export --html)
.gsd/reports/
# Session-specific interrupted-work markers
.gsd/milestones/**/continue.md
.gsd/milestones/**/*-CONTINUE.md
Unique Milestone Names
Create or amend your .gsd/PREFERENCES.md file within the repo to include unique_milestone_ids: true e.g.
---
version: 1
unique_milestone_ids: true
---
With the above .gitignore set up, the .gsd/PREFERENCES.md file is checked into the repo ensuring all teammates use unique milestone names to avoid collisions.
Milestone names will now be generated with a 6 char random string appended e.g. instead of M001 you'll get something like M001-ush8s3
Migrating an existing git ignored .gsd/ folder
- Ensure you are not in the middle of any milestones (clean state)
- Update the
.gsd/related entries in your.gitignoreto follow theSuggested .gitignore setupsection underWorking in teams(ensure you are no longer blanket ignoring the whole.gsd/directory) - Update your
.gsd/PREFERENCES.mdfile within the repo as per sectionUnique Milestone Names - If you want to update all your existing milestones use this prompt in GSD:
I have turned on unique milestone ids, please update all old milestone ids to use this new format e.g. M001-abc123 where abc123 is a random 6 char lowercase alpha numeric string. Update all references in all .gsd file contents, file names and directory names. Validate your work once done to ensure referential integrity. - Commit to git
Architecture
GSD is a TypeScript application that embeds the Pi coding agent SDK.
gsd (CLI binary)
└─ loader.ts Sets PI_PACKAGE_DIR, GSD env vars, dynamic-imports cli.ts
└─ cli.ts Wires SDK managers, loads extensions, starts InteractiveMode
├─ headless.ts Headless orchestrator (spawns RPC child, auto-responds, detects completion)
├─ onboarding.ts First-run setup wizard (LLM provider + tool keys)
├─ wizard.ts Env hydration from stored auth.json credentials
├─ app-paths.ts ~/.gsd/agent/, ~/.gsd/sessions/, auth.json
├─ resource-loader.ts Syncs bundled extensions + agents to ~/.gsd/agent/
└─ src/resources/
├─ extensions/gsd/ Core GSD extension (auto, state, commands, ...)
├─ extensions/... 18 supporting extensions
├─ agents/ scout, researcher, worker
├─ AGENTS.md Agent routing instructions
└─ GSD-WORKFLOW.md Manual bootstrap protocol
Key design decisions:
pkg/shim directory —PI_PACKAGE_DIRpoints here (not project root) to avoid Pi's theme resolution collision with oursrc/directory. Contains onlypiConfigand theme assets.- Two-file loader pattern —
loader.tssets all env vars with zero SDK imports, then dynamic-importscli.tswhich does static SDK imports. This ensuresPI_PACKAGE_DIRis set before any SDK code evaluates. - Always-overwrite sync —
npm update -gtakes effect immediately. Bundled extensions and agents are synced to~/.gsd/agent/on every launch, not just first run. - State lives on disk —
.gsd/is the source of truth. Auto mode reads it, writes it, and advances based on what it finds. No in-memory state survives across sessions.
Requirements
- Node.js ≥ 22.0.0 (24 LTS recommended)
- An LLM provider — any of the 20+ supported providers (see Use Any Model)
- Git — initialized automatically if missing
Optional:
- Brave Search API key (web research)
- Tavily API key (web research — alternative to Brave)
- Google Gemini API key (web research via Gemini Search grounding)
- Context7 API key (library docs)
- Jina API key (page extraction)
Use Any Model
GSD isn't locked to one provider. It runs on the Pi SDK, which supports 20+ model providers out of the box. Use different models for different phases — Opus for planning, Sonnet for execution, a fast model for research.
Built-in Providers
Anthropic, Anthropic (Vertex AI), OpenAI, Google (Gemini), OpenRouter, GitHub Copilot, Amazon Bedrock, Azure OpenAI, Google Vertex, Groq, Cerebras, Mistral, xAI, HuggingFace, Vercel AI Gateway, and more.
OAuth / Max Plans
If you have a Claude Max, Codex, or GitHub Copilot subscription, you can use those directly — Pi handles the OAuth flow. No API key needed.
⚠️ Important: Using OAuth tokens from subscription plans outside their native applications may violate the provider's Terms of Service. In particular:
- Google Gemini — Using Gemini CLI or Antigravity OAuth tokens in third-party tools has resulted in Google account suspensions. This affects your entire Google account, not just the Gemini service. Use a Gemini API key instead.
- Claude Max — Anthropic's ToS may not explicitly permit OAuth use outside Claude's own applications.
- GitHub Copilot — Usage outside GitHub's own tools may be restricted by your subscription terms.
GSD supports API key authentication for all providers as the safe alternative. We strongly recommend using API keys over OAuth for Google Gemini.
OpenRouter
OpenRouter gives you access to hundreds of models through a single API key. Use it to run GSD with Llama, DeepSeek, Qwen, or anything else OpenRouter supports.
Per-Phase Model Selection
In your preferences (/gsd prefs), assign different models to different phases:
models:
research: openrouter/deepseek/deepseek-r1
planning:
model: claude-opus-4-6
fallbacks:
- openrouter/z-ai/glm-5
execution: claude-sonnet-4-6
completion: claude-sonnet-4-6
Use expensive models where quality matters (planning, complex execution) and cheaper/faster models where speed matters (research, simple completions). Each phase accepts a simple model string or an object with model and fallbacks — if the primary model fails (provider outage, rate limit, credit exhaustion), GSD automatically tries the next fallback. GSD tracks cost per-model so you can see exactly where your budget goes.
Star History
License
The original GSD showed what was possible. This version delivers it.
npm install -g gsd-pi && gsd