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>
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
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
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
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>
* 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>
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>
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
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
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
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
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
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
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
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
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
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
On Windows, scanProjectFiles returns backslash paths (e.g.
"apps\mobile\app\build.gradle") but PROJECT_FILES markers use forward
slashes ("app/build.gradle"). Normalize scanned paths to forward
slashes before matching.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The doctor-task-done-missing-summary-slice-loop test was written for
the old filesystem-based task_done_missing_summary check, which was
refactored to db_done_task_no_summary (SQLite-based). The test creates
filesystem structures but the current check queries the database,
making it fundamentally incompatible.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
`_deriveStateImpl` (used when no gsd.db exists) lacked the SUMMARY-based
reconciliation added to `deriveStateFromDb` in 0e7a01f4. Heading-style
tasks (`### T01:`) are always parsed as `done=false` by `parsePlan`
because the heading syntax has no checkbox. When the agent writes a
SUMMARY file but the plan heading has no checkbox, the task appears
incomplete forever, causing infinite re-dispatch.
Now checks each non-done task for a SUMMARY file on disk after
`parsePlan()`, mirroring the DB reconciliation logic.
Root cause: `parsePlan()` recognizes two task formats:
1. `- [x] **T01: Title**` → done from checkbox state
2. `### T01: Title` → always done=false (no checkbox to read)
The DB path (deriveStateFromDb) was already fixed in 0e7a01f4 to
reconcile via SUMMARY files. This commit applies the same fix to
the filesystem path used by projects without gsd.db.
Consolidate two separate imports from files.js into one to resolve
TS2300 duplicate identifier error.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
MilestoneRow and SliceRow interfaces don't have index signatures,
so they can't be assigned to Record<string, unknown>. Using
Record<string, any> allows the helper to accept any typed row object.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Extract syncDirFiles() helper to eliminate duplicated iterate/filter/copy/catch
logic across three directory levels (milestone root, slices, tasks). Reduces
maximum nesting depth from 4 to 2.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add ErrorContext interface to UnitResult so error information (provider
errors, timeouts, idle watchdog kills) is no longer discarded at the
resolve boundary. The four call sites that previously threw away context
now attach typed error metadata with category, message, and transience.
Downstream consumers (stuck detection in phases.ts, journal unit-end
events) use the structured errorContext field directly instead of
fragile regex heuristics on message content.
The test referenced task_done_missing_summary which was renamed to
db_done_task_no_summary in the DoctorIssueCode type.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The same ~20-line cleanup sequence (merge abort / squash msg unlink /
hard reset) appeared twice in reconcileMergeState(). Extract into a
private abortAndResetMerge() helper to eliminate the duplication.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Deduplicate near-identical "has any non-empty field" checks for milestone
and slice planning state into a shared hasNonEmptyFields() helper with
field-name arrays, reducing 8 repeated String(row.field||"").trim() calls
to 2 declarative one-liners.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Each health check function (git, runtime, global, engine) moves to its
own file with only the imports it needs. doctor-checks.ts becomes a
re-export barrel for backward compatibility.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Embed 6 new quality questions (Q3-Q8) into the GSD lifecycle so
consumer projects get adversarial, failure, load, and operational
coverage by default. All sections are opt-out ("OMIT ENTIRELY") for
simple slices.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>