gsd-pi 2.73.1-dev.6f61020 → 2.73.1-dev.9a4cd44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/cli-web-branch.d.ts +4 -3
  2. package/dist/cli-web-branch.js +10 -7
  3. package/dist/cli.js +99 -206
  4. package/dist/logo.d.ts +1 -1
  5. package/dist/logo.js +1 -1
  6. package/dist/onboarding.js +59 -53
  7. package/dist/resource-loader.js +2 -2
  8. package/dist/resources/extensions/gsd/auto/phases.js +15 -9
  9. package/dist/resources/extensions/gsd/auto-dispatch.js +11 -3
  10. package/dist/resources/extensions/gsd/auto-post-unit.js +41 -1
  11. package/dist/resources/extensions/gsd/auto-timeout-recovery.js +13 -0
  12. package/dist/resources/extensions/gsd/auto-verification.js +88 -3
  13. package/dist/resources/extensions/gsd/auto.js +21 -8
  14. package/dist/resources/extensions/gsd/docs/preferences-reference.md +1 -1
  15. package/dist/resources/extensions/gsd/notification-widget.js +2 -2
  16. package/dist/resources/extensions/gsd/state.js +61 -14
  17. package/dist/web/standalone/.next/BUILD_ID +1 -1
  18. package/dist/web/standalone/.next/app-path-routes-manifest.json +15 -15
  19. package/dist/web/standalone/.next/build-manifest.json +2 -2
  20. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  21. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  22. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  23. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  24. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  25. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  26. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  27. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  28. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  29. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  30. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  31. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  32. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  33. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  34. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  35. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  36. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  37. package/dist/web/standalone/.next/server/app/index.html +1 -1
  38. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  39. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  40. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  41. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  42. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  43. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  44. package/dist/web/standalone/.next/server/app-paths-manifest.json +15 -15
  45. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  46. package/dist/web/standalone/.next/server/middleware-manifest.json +5 -5
  47. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  48. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  49. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  50. package/package.json +1 -2
  51. package/packages/pi-coding-agent/dist/core/chat-controller-ordering.test.js +138 -0
  52. package/packages/pi-coding-agent/dist/core/chat-controller-ordering.test.js.map +1 -1
  53. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.d.ts +2 -1
  54. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  55. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.js +9 -3
  56. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  57. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.test.d.ts +2 -0
  58. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.test.d.ts.map +1 -0
  59. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.test.js +52 -0
  60. package/packages/pi-coding-agent/dist/modes/interactive/components/dynamic-border.test.js.map +1 -0
  61. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.d.ts.map +1 -1
  62. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.js +21 -4
  63. package/packages/pi-coding-agent/dist/modes/interactive/controllers/chat-controller.js.map +1 -1
  64. package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  65. package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.js +5 -1
  66. package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.js.map +1 -1
  67. package/packages/pi-coding-agent/src/core/chat-controller-ordering.test.ts +157 -0
  68. package/packages/pi-coding-agent/src/modes/interactive/components/dynamic-border.test.ts +73 -0
  69. package/packages/pi-coding-agent/src/modes/interactive/components/dynamic-border.ts +9 -3
  70. package/packages/pi-coding-agent/src/modes/interactive/controllers/chat-controller.ts +21 -4
  71. package/packages/pi-coding-agent/src/modes/interactive/interactive-mode.ts +5 -1
  72. package/packages/pi-tui/dist/__tests__/tui.test.js +30 -0
  73. package/packages/pi-tui/dist/__tests__/tui.test.js.map +1 -1
  74. package/packages/pi-tui/dist/tui.d.ts +1 -0
  75. package/packages/pi-tui/dist/tui.d.ts.map +1 -1
  76. package/packages/pi-tui/dist/tui.js +22 -3
  77. package/packages/pi-tui/dist/tui.js.map +1 -1
  78. package/packages/pi-tui/src/__tests__/tui.test.ts +38 -0
  79. package/packages/pi-tui/src/tui.ts +20 -3
  80. package/src/resources/extensions/gsd/auto/phases.ts +22 -9
  81. package/src/resources/extensions/gsd/auto-dispatch.ts +10 -4
  82. package/src/resources/extensions/gsd/auto-post-unit.ts +47 -1
  83. package/src/resources/extensions/gsd/auto-timeout-recovery.ts +17 -0
  84. package/src/resources/extensions/gsd/auto-verification.ts +98 -3
  85. package/src/resources/extensions/gsd/auto.ts +26 -14
  86. package/src/resources/extensions/gsd/docs/preferences-reference.md +1 -1
  87. package/src/resources/extensions/gsd/notification-widget.ts +2 -2
  88. package/src/resources/extensions/gsd/state.ts +71 -15
  89. package/src/resources/extensions/gsd/tests/auto-loop.test.ts +2 -2
  90. package/src/resources/extensions/gsd/tests/auto-post-unit-step-message.test.ts +53 -0
  91. package/src/resources/extensions/gsd/tests/complete-milestone-false-merge.test.ts +142 -0
  92. package/src/resources/extensions/gsd/tests/completed-at-reconcile.test.ts +42 -0
  93. package/src/resources/extensions/gsd/tests/derive-state-crossval.test.ts +3 -2
  94. package/src/resources/extensions/gsd/tests/derive-state-db.test.ts +3 -2
  95. package/src/resources/extensions/gsd/tests/derive-state-helpers.test.ts +68 -8
  96. package/src/resources/extensions/gsd/tests/derive-state.test.ts +3 -3
  97. package/src/resources/extensions/gsd/tests/integration/state-machine-edge-cases.test.ts +4 -2
  98. package/src/resources/extensions/gsd/tests/state-machine-full-walkthrough.test.ts +5 -7
  99. package/src/resources/extensions/gsd/tests/token-profile.test.ts +1 -1
  100. package/src/resources/extensions/gsd/tests/validate-milestone-stuck-guard.test.ts +179 -0
  101. /package/dist/web/standalone/.next/static/{xEc_9MXTYTFRfqJP-SGqp → ASJ2RGD7E1iiUYzA0xT2i}/_buildManifest.js +0 -0
  102. /package/dist/web/standalone/.next/static/{xEc_9MXTYTFRfqJP-SGqp → ASJ2RGD7E1iiUYzA0xT2i}/_ssgManifest.js +0 -0
@@ -12,10 +12,15 @@
12
12
 
13
13
  import type { ExtensionContext, ExtensionAPI } from "@gsd/pi-coding-agent";
14
14
  import { mkdirSync, writeFileSync } from "node:fs";
15
- import { resolveSliceFile, resolveSlicePath } from "./paths.js";
15
+ import { resolveSliceFile, resolveSlicePath, resolveMilestoneFile } from "./paths.js";
16
16
  import { parseUnitId } from "./unit-id.js";
17
- import { isDbAvailable, getTask, getSliceTasks, type TaskRow } from "./gsd-db.js";
17
+ import { isDbAvailable, getTask, getSliceTasks, getMilestoneSlices, type TaskRow } from "./gsd-db.js";
18
18
  import { loadEffectiveGSDPreferences } from "./preferences.js";
19
+ import { extractVerdict } from "./verdict-parser.js";
20
+ import { isClosedStatus } from "./status-guards.js";
21
+ import { loadFile } from "./files.js";
22
+ import { parseRoadmap } from "./parsers-legacy.js";
23
+ import { isMilestoneComplete } from "./state.js";
19
24
  import {
20
25
  runVerificationGate,
21
26
  formatFailureContext,
@@ -43,6 +48,88 @@ function isInfraVerificationFailure(stderr: string): boolean {
43
48
  );
44
49
  }
45
50
 
51
+ /**
52
+ * Post-unit guard for `validate-milestone` units (#4094).
53
+ *
54
+ * When validate-milestone writes verdict=needs-remediation, the agent is
55
+ * expected to also call gsd_reassess_roadmap in the same turn to add
56
+ * remediation slices. If they don't, the state machine re-derives
57
+ * `phase: validating-milestone` indefinitely (all slices still complete +
58
+ * verdict still needs-remediation), wasting ~3 dispatches before the stuck
59
+ * detector fires.
60
+ *
61
+ * This guard fires immediately on the first occurrence: if VALIDATION.md
62
+ * verdict is needs-remediation and no incomplete slices exist for the
63
+ * milestone, pause the auto-loop with a clear blocker.
64
+ */
65
+ async function runValidateMilestonePostCheck(
66
+ vctx: VerificationContext,
67
+ pauseAuto: (ctx?: ExtensionContext, pi?: ExtensionAPI) => Promise<void>,
68
+ ): Promise<VerificationResult> {
69
+ const { s, ctx, pi } = vctx;
70
+ if (!s.currentUnit) return "continue";
71
+
72
+ const { milestone: mid } = parseUnitId(s.currentUnit.id);
73
+ if (!mid) return "continue";
74
+
75
+ const validationFile = resolveMilestoneFile(s.basePath, mid, "VALIDATION");
76
+ if (!validationFile) return "continue";
77
+
78
+ const validationContent = await loadFile(validationFile);
79
+ if (!validationContent) return "continue";
80
+
81
+ const verdict = extractVerdict(validationContent);
82
+ if (verdict !== "needs-remediation") return "continue";
83
+
84
+ const incompleteSliceCount = await countIncompleteSlices(s.basePath, mid);
85
+
86
+ // If any non-closed slices exist, the agent successfully queued remediation
87
+ // work — proceed normally. The state machine will execute those slices and
88
+ // re-validate per the #3596/#3670 fix.
89
+ if (incompleteSliceCount > 0) return "continue";
90
+
91
+ ctx.ui.notify(
92
+ `Milestone ${mid} validation returned verdict=needs-remediation but no remediation slices were added. Pausing for human review.`,
93
+ "error",
94
+ );
95
+ process.stderr.write(
96
+ `validate-milestone: pausing — verdict=needs-remediation with no incomplete slices for ${mid}. ` +
97
+ `The agent must call gsd_reassess_roadmap to add remediation slices before re-validation.\n`,
98
+ );
99
+ await pauseAuto(ctx, pi);
100
+ return "pause";
101
+ }
102
+
103
+ /**
104
+ * Count slices for a milestone that are not in a closed status.
105
+ * DB-backed projects are authoritative (#4094 peer review); falls back to
106
+ * roadmap parsing only when the DB is unavailable.
107
+ */
108
+ async function countIncompleteSlices(basePath: string, milestoneId: string): Promise<number> {
109
+ if (isDbAvailable()) {
110
+ const slices = getMilestoneSlices(milestoneId);
111
+ if (slices.length === 0) {
112
+ // No DB rows — treat as "unknown", do not pause.
113
+ return 1;
114
+ }
115
+ return slices.filter((slice) => !isClosedStatus(slice.status)).length;
116
+ }
117
+
118
+ // Filesystem fallback: parse the roadmap markdown.
119
+ try {
120
+ const roadmapFile = resolveMilestoneFile(basePath, milestoneId, "ROADMAP");
121
+ if (!roadmapFile) return 1;
122
+ const roadmapContent = await loadFile(roadmapFile);
123
+ if (!roadmapContent) return 1;
124
+ const roadmap = parseRoadmap(roadmapContent);
125
+ if (roadmap.slices.length === 0) return 1;
126
+ return isMilestoneComplete(roadmap) ? 0 : 1;
127
+ } catch {
128
+ // Parsing failures should not cause false-positive pauses.
129
+ return 1;
130
+ }
131
+ }
132
+
46
133
  /**
47
134
  * Run the verification gate for the current execute-task unit.
48
135
  * Returns:
@@ -56,7 +143,15 @@ export async function runPostUnitVerification(
56
143
  ): Promise<VerificationResult> {
57
144
  const { s, ctx, pi } = vctx;
58
145
 
59
- if (!s.currentUnit || s.currentUnit.type !== "execute-task") {
146
+ if (!s.currentUnit) {
147
+ return "continue";
148
+ }
149
+
150
+ if (s.currentUnit.type === "validate-milestone") {
151
+ return await runValidateMilestonePostCheck(vctx, pauseAuto);
152
+ }
153
+
154
+ if (s.currentUnit.type !== "execute-task") {
60
155
  return "continue";
61
156
  }
62
157
 
@@ -187,7 +187,7 @@ import {
187
187
  deregisterSigtermHandler as _deregisterSigtermHandler,
188
188
  detectWorkingTreeActivity,
189
189
  } from "./auto-supervisor.js";
190
- import { isDbAvailable } from "./gsd-db.js";
190
+ import { isDbAvailable, getMilestone } from "./gsd-db.js";
191
191
  import { countPendingCaptures } from "./captures.js";
192
192
  import { clearCmuxSidebar, logCmuxEvent, syncCmuxSidebar } from "../cmux/index.js";
193
193
 
@@ -761,24 +761,36 @@ export async function stopAuto(
761
761
  : { notify: () => {} };
762
762
  const resolver = buildResolver();
763
763
 
764
- // Check if the milestone is complete — SUMMARY file is the authoritative signal.
764
+ // Check if the milestone is complete. DB status is the authoritative
765
+ // signal — only a successful gsd_complete_milestone call flips it to
766
+ // "complete" (tools/complete-milestone.ts). SUMMARY file presence is
767
+ // NOT sufficient: a blocker placeholder stub or a partial write can
768
+ // leave a file behind without the milestone actually being done,
769
+ // which previously caused stopAuto to merge a failed milestone and
770
+ // emit a misleading metadata-only merge warning (#4175).
771
+ // DB-unavailable projects fall back to SUMMARY-file presence.
765
772
  let milestoneComplete = false;
766
773
  try {
767
- const summaryPath = resolveMilestoneFile(
768
- s.originalBasePath || s.basePath,
769
- s.currentMilestoneId,
770
- "SUMMARY",
771
- );
772
- if (!summaryPath) {
773
- // Also check in the worktree path (SUMMARY may not be synced yet)
774
- const wtSummaryPath = resolveMilestoneFile(
775
- s.basePath,
774
+ if (isDbAvailable()) {
775
+ const dbRow = getMilestone(s.currentMilestoneId);
776
+ milestoneComplete = dbRow?.status === "complete";
777
+ } else {
778
+ const summaryPath = resolveMilestoneFile(
779
+ s.originalBasePath || s.basePath,
776
780
  s.currentMilestoneId,
777
781
  "SUMMARY",
778
782
  );
779
- milestoneComplete = wtSummaryPath !== null;
780
- } else {
781
- milestoneComplete = true;
783
+ if (!summaryPath) {
784
+ // Also check in the worktree path (SUMMARY may not be synced yet)
785
+ const wtSummaryPath = resolveMilestoneFile(
786
+ s.basePath,
787
+ s.currentMilestoneId,
788
+ "SUMMARY",
789
+ );
790
+ milestoneComplete = wtSummaryPath !== null;
791
+ } else {
792
+ milestoneComplete = true;
793
+ }
782
794
  }
783
795
  } catch (err) {
784
796
  // Non-fatal — fall through to preserveBranch path
@@ -157,7 +157,7 @@ Setting `prefer_skills: []` does **not** disable skill discovery — it just mea
157
157
 
158
158
  - `phases`: fine-grained control over which phases run. Usually set by `token_profile`, but can be overridden. Keys:
159
159
  - `skip_research`: boolean — skip milestone-level research. Default: `false`.
160
- - `reassess_after_slice`: boolean — run roadmap reassessment after each completed slice. Default: `false`.
160
+ - `reassess_after_slice`: boolean — run roadmap reassessment after each completed slice. Default: `true`.
161
161
  - `skip_reassess`: boolean — force-disable roadmap reassessment even if `reassess_after_slice` is enabled. Default: `false`.
162
162
  - `skip_slice_research`: boolean — skip per-slice research. Default: `false`.
163
163
 
@@ -1,6 +1,6 @@
1
1
  // GSD Extension — Notification Widget
2
2
  // Always-on ambient widget rendered belowEditor showing unread count and
3
- // the most recent notification message. Refreshes every 5 seconds.
3
+ // the most recent notification message. Refreshes every 30 seconds.
4
4
  // Widget key: "gsd-notifications", placement: "belowEditor"
5
5
 
6
6
  import type { ExtensionContext } from "@gsd/pi-coding-agent";
@@ -19,7 +19,7 @@ export function buildNotificationWidgetLines(): string[] {
19
19
 
20
20
  // ─── Widget init ────────────────────────────────────────────────────────
21
21
 
22
- const REFRESH_INTERVAL_MS = 5_000;
22
+ const REFRESH_INTERVAL_MS = 30_000;
23
23
 
24
24
  /**
25
25
  * Initialize the always-on notification widget (belowEditor).
@@ -386,6 +386,10 @@ function buildCompletenessSet(basePath: string, milestones: MilestoneRow[]) {
386
386
  const completeMilestoneIds = new Set<string>();
387
387
  const parkedMilestoneIds = new Set<string>();
388
388
 
389
+ // DB-authoritative: a milestone is only "complete" when its DB row says so.
390
+ // SUMMARY-file presence is NOT a completion signal here — an orphan SUMMARY
391
+ // (crashed complete-milestone turn, partial merge, manual edit) must not
392
+ // flip derived state to complete and cascade into a false auto-merge (#4179).
389
393
  for (const m of milestones) {
390
394
  const parkedFile = resolveMilestoneFile(basePath, m.id, "PARKED");
391
395
  if (parkedFile || m.status === 'parked') {
@@ -396,11 +400,6 @@ function buildCompletenessSet(basePath: string, milestones: MilestoneRow[]) {
396
400
  completeMilestoneIds.add(m.id);
397
401
  continue;
398
402
  }
399
- const summaryFile = resolveMilestoneFile(basePath, m.id, "SUMMARY");
400
- if (summaryFile) {
401
- completeMilestoneIds.add(m.id);
402
- continue;
403
- }
404
403
  }
405
404
  return { completeMilestoneIds, parkedMilestoneIds };
406
405
  }
@@ -429,18 +428,22 @@ async function buildRegistryAndFindActive(
429
428
  if (isGhostMilestone(basePath, m.id)) continue;
430
429
  }
431
430
 
432
- const summaryFile = resolveMilestoneFile(basePath, m.id, "SUMMARY");
433
-
434
- if (completeMilestoneIds.has(m.id) || (summaryFile !== null)) {
431
+ // DB-authoritative completeness (#4179): only trust completeMilestoneIds,
432
+ // which is itself derived from DB status. SUMMARY-file presence alone must
433
+ // not imply completion. The summary file may still be consulted below as a
434
+ // title source for legitimately-complete milestones whose DB row has no title.
435
+ if (completeMilestoneIds.has(m.id)) {
435
436
  let title = stripMilestonePrefix(m.title) || m.id;
436
- if (summaryFile && !m.title) {
437
- const summaryContent = await loadFile(summaryFile);
438
- if (summaryContent) {
439
- title = parseSummary(summaryContent).title || m.id;
437
+ if (!m.title) {
438
+ const summaryFile = resolveMilestoneFile(basePath, m.id, "SUMMARY");
439
+ if (summaryFile) {
440
+ const summaryContent = await loadFile(summaryFile);
441
+ if (summaryContent) {
442
+ title = parseSummary(summaryContent).title || m.id;
443
+ }
440
444
  }
441
445
  }
442
446
  registry.push({ id: m.id, title, status: 'complete' });
443
- completeMilestoneIds.add(m.id);
444
447
  continue;
445
448
  }
446
449
 
@@ -481,7 +484,14 @@ async function buildRegistryAndFindActive(
481
484
  const validationContent = validationFile ? await loadFile(validationFile) : null;
482
485
  const validationTerminal = validationContent ? isValidationTerminal(validationContent) : false;
483
486
 
484
- if (!validationTerminal || (validationTerminal && !summaryFile)) {
487
+ // DB-authoritative (#4179): completeness is already decided by
488
+ // completeMilestoneIds above. If we reached this branch, the DB says
489
+ // the milestone is NOT complete — so any SUMMARY file on disk is an
490
+ // orphan (crashed complete-milestone, partial merge, manual edit) and
491
+ // must not short-circuit this path. When validation is terminal, fall
492
+ // through to the default active-push below so `complete-milestone` can
493
+ // re-run idempotently.
494
+ if (!validationTerminal) {
485
495
  activeMilestone = { id: m.id, title };
486
496
  activeMilestoneSlices = slices;
487
497
  activeMilestoneFound = true;
@@ -630,13 +640,39 @@ function resolveSliceDependencies(activeMilestoneSlices: SliceRow[]): { activeSl
630
640
  }
631
641
  }
632
642
 
643
+ // First pass: find a slice with ALL dependencies satisfied (strict)
644
+ let bestFallback: SliceRow | null = null;
645
+ let bestFallbackSatisfied = -1;
646
+
633
647
  for (const s of activeMilestoneSlices) {
634
648
  if (isStatusDone(s.status)) continue;
635
649
  if (isDeferredStatus(s.status)) continue;
636
650
  if (s.depends.every(dep => doneSliceIds.has(dep))) {
637
651
  return { activeSlice: { id: s.id, title: s.title }, activeSliceRow: s };
638
652
  }
653
+ // Track the slice with the most satisfied dependencies as fallback
654
+ const satisfied = s.depends.filter(dep => doneSliceIds.has(dep)).length;
655
+ if (satisfied > bestFallbackSatisfied || (satisfied === bestFallbackSatisfied && !bestFallback)) {
656
+ bestFallback = s;
657
+ bestFallbackSatisfied = satisfied;
658
+ }
639
659
  }
660
+
661
+ // Fallback: if no slice has all deps met but there ARE incomplete non-deferred
662
+ // slices, pick the one with the most deps satisfied. This prevents hard-blocking
663
+ // when dependency metadata is stale (e.g. after reassessment added/removed slices)
664
+ // or when deps reference slices from previous milestones.
665
+ if (bestFallback) {
666
+ const unmet = bestFallback.depends.filter(dep => !doneSliceIds.has(dep));
667
+ logWarning("state",
668
+ `No slice has all deps satisfied — falling back to ${bestFallback.id} ` +
669
+ `(${bestFallbackSatisfied}/${bestFallback.depends.length} deps met, ` +
670
+ `unmet: ${unmet.join(", ")})`,
671
+ { mid: activeMilestoneSlices[0]?.milestone_id, sid: bestFallback.id },
672
+ );
673
+ return { activeSlice: { id: bestFallback.id, title: bestFallback.title }, activeSliceRow: bestFallback };
674
+ }
675
+
640
676
  return { activeSlice: null, activeSliceRow: null };
641
677
  }
642
678
 
@@ -684,7 +720,7 @@ async function reconcileSliceTasks(
684
720
  const summaryPath = resolveTaskFile(basePath, milestoneId, sliceId, t.id, "SUMMARY");
685
721
  if (summaryPath && existsSync(summaryPath)) {
686
722
  try {
687
- updateTaskStatus(milestoneId, sliceId, t.id, "complete");
723
+ updateTaskStatus(milestoneId, sliceId, t.id, "complete", new Date().toISOString());
688
724
  logWarning("reconcile", `task ${milestoneId}/${sliceId}/${t.id} status reconciled from "${t.status}" to "complete" (#2514)`, { mid: milestoneId, sid: sliceId, tid: t.id });
689
725
  reconciled = true;
690
726
  } catch (e) {
@@ -1431,12 +1467,32 @@ export async function _deriveStateImpl(basePath: string): Promise<GSDState> {
1431
1467
  };
1432
1468
  }
1433
1469
  } else {
1470
+ let bestFallbackLegacy: { id: string; title: string; depends: string[] } | null = null;
1471
+ let bestFallbackLegacySatisfied = -1;
1472
+
1434
1473
  for (const s of activeRoadmap.slices) {
1435
1474
  if (s.done) continue;
1436
1475
  if (s.depends.every(dep => doneSliceIds.has(dep))) {
1437
1476
  activeSlice = { id: s.id, title: s.title };
1438
1477
  break;
1439
1478
  }
1479
+ // Track best fallback
1480
+ const satisfied = s.depends.filter(dep => doneSliceIds.has(dep)).length;
1481
+ if (satisfied > bestFallbackLegacySatisfied) {
1482
+ bestFallbackLegacy = s;
1483
+ bestFallbackLegacySatisfied = satisfied;
1484
+ }
1485
+ }
1486
+
1487
+ // Fallback: if no slice has all deps met, pick the one with the most deps satisfied
1488
+ if (!activeSlice && bestFallbackLegacy) {
1489
+ const unmet = bestFallbackLegacy.depends.filter(dep => !doneSliceIds.has(dep));
1490
+ logWarning("state",
1491
+ `No slice has all deps satisfied — falling back to ${bestFallbackLegacy.id} ` +
1492
+ `(${bestFallbackLegacySatisfied}/${bestFallbackLegacy.depends.length} deps met, ` +
1493
+ `unmet: ${unmet.join(", ")})`,
1494
+ );
1495
+ activeSlice = { id: bestFallbackLegacy.id, title: bestFallbackLegacy.title };
1440
1496
  }
1441
1497
  }
1442
1498
 
@@ -688,8 +688,8 @@ test("autoLoop exits on terminal blocked state", async (t) => {
688
688
 
689
689
  assert.ok(deps.callLog.includes("deriveState"), "should have derived state");
690
690
  assert.ok(
691
- deps.callLog.includes("stopAuto"),
692
- "should have called stopAuto for blocked state",
691
+ deps.callLog.includes("pauseAuto"),
692
+ "should have called pauseAuto for blocked state",
693
693
  );
694
694
  assert.ok(
695
695
  !deps.callLog.includes("resolveDispatch"),
@@ -0,0 +1,53 @@
1
+ // GSD-2 — Tests for step-mode completion messages in auto-post-unit
2
+
3
+ import test from "node:test";
4
+ import assert from "node:assert/strict";
5
+
6
+ import { buildStepCompleteMessage, STEP_COMPLETE_FALLBACK_MESSAGE } from "../auto-post-unit.ts";
7
+ import type { GSDState } from "../types.ts";
8
+
9
+ function makeState(overrides: Partial<GSDState>): GSDState {
10
+ return {
11
+ activeMilestone: null,
12
+ activeSlice: null,
13
+ activeTask: null,
14
+ phase: "executing",
15
+ recentDecisions: [],
16
+ blockers: [],
17
+ nextAction: "",
18
+ registry: [],
19
+ ...overrides,
20
+ };
21
+ }
22
+
23
+ test("buildStepCompleteMessage: milestone complete surfaces review guidance", () => {
24
+ const msg = buildStepCompleteMessage(makeState({ phase: "complete" }));
25
+ assert.match(msg, /milestone finished/);
26
+ assert.match(msg, /\/gsd status/);
27
+ assert.doesNotMatch(msg, /Next:/);
28
+ });
29
+
30
+ test("buildStepCompleteMessage: mid-flight step includes next unit label and /clear hint", () => {
31
+ const state = makeState({
32
+ phase: "executing",
33
+ activeSlice: { id: "S01", title: "Core" },
34
+ activeTask: { id: "T03", title: "Wire notify" },
35
+ });
36
+ const msg = buildStepCompleteMessage(state);
37
+ assert.match(msg, /Next: Execute T03: Wire notify/);
38
+ assert.match(msg, /\/clear/);
39
+ assert.match(msg, /\/gsd to continue/);
40
+ });
41
+
42
+ test("buildStepCompleteMessage: unknown phase falls back to generic continue label", () => {
43
+ // Cast to bypass Phase union so we exercise the default branch of describeNextUnit.
44
+ const state = makeState({ phase: "totally-unknown" as unknown as GSDState["phase"] });
45
+ const msg = buildStepCompleteMessage(state);
46
+ assert.match(msg, /Next: Continue/);
47
+ assert.match(msg, /\/clear/);
48
+ });
49
+
50
+ test("STEP_COMPLETE_FALLBACK_MESSAGE: used when deriveState throws, still points users at /clear + /gsd", () => {
51
+ assert.match(STEP_COMPLETE_FALLBACK_MESSAGE, /\/clear/);
52
+ assert.match(STEP_COMPLETE_FALLBACK_MESSAGE, /\/gsd/);
53
+ });
@@ -0,0 +1,142 @@
1
+ /**
2
+ * complete-milestone-false-merge.test.ts — Regression test for #4175.
3
+ *
4
+ * Before the fix, a failed complete-milestone unit could leave a stub
5
+ * SUMMARY blocker placeholder on disk. stopAuto's SUMMARY-presence check
6
+ * then treated the milestone as complete and merged the worktree branch
7
+ * into main — emitting a misleading metadata-only merge warning for a
8
+ * milestone that was never legitimately finished.
9
+ *
10
+ * The fix has three cooperating parts:
11
+ * 1. stopAuto uses DB status (authoritative) instead of SUMMARY presence
12
+ * when the project DB is available.
13
+ * 2. postUnitPreVerification pauses auto-mode for complete-milestone
14
+ * after retries are exhausted instead of writing a blocker placeholder.
15
+ * 3. recoverTimedOutUnit pauses for complete-milestone instead of
16
+ * writing a blocker placeholder.
17
+ *
18
+ * This test guards all three via source inspection so a future refactor
19
+ * cannot silently reintroduce the false-merge path.
20
+ */
21
+
22
+ import test from "node:test";
23
+ import assert from "node:assert/strict";
24
+ import { readFileSync } from "node:fs";
25
+ import { join } from "node:path";
26
+
27
+ const gsdDir = join(import.meta.dirname, "..");
28
+ const autoSrc = readFileSync(join(gsdDir, "auto.ts"), "utf-8");
29
+ const postUnitSrc = readFileSync(join(gsdDir, "auto-post-unit.ts"), "utf-8");
30
+ const timeoutSrc = readFileSync(join(gsdDir, "auto-timeout-recovery.ts"), "utf-8");
31
+
32
+ test("#4175: stopAuto uses DB status as the authoritative milestone-complete signal", () => {
33
+ const step4Idx = autoSrc.indexOf("Step 4: Auto-worktree exit");
34
+ assert.ok(step4Idx !== -1, "Step 4 comment exists in stopAuto");
35
+ const step5Idx = autoSrc.indexOf("Step 5:", step4Idx);
36
+ const step4Block = autoSrc.slice(step4Idx, step5Idx);
37
+
38
+ assert.ok(
39
+ step4Block.includes("isDbAvailable()"),
40
+ "Step 4 should branch on isDbAvailable() so DB is consulted when present",
41
+ );
42
+ assert.ok(
43
+ step4Block.includes("getMilestone(s.currentMilestoneId)"),
44
+ "Step 4 should read authoritative milestone status via getMilestone()",
45
+ );
46
+ assert.ok(
47
+ /status\s*===\s*"complete"/.test(step4Block),
48
+ 'Step 4 should compare the DB row status to "complete"',
49
+ );
50
+ });
51
+
52
+ test("#4175: stopAuto imports getMilestone from gsd-db", () => {
53
+ assert.ok(
54
+ /import\s*\{[^}]*\bgetMilestone\b[^}]*\}\s*from\s*"\.\/gsd-db\.js"/.test(autoSrc),
55
+ "auto.ts should import getMilestone from ./gsd-db.js",
56
+ );
57
+ });
58
+
59
+ test("#4175: stopAuto still falls back to SUMMARY presence when DB is unavailable", () => {
60
+ const step4Idx = autoSrc.indexOf("Step 4: Auto-worktree exit");
61
+ const step5Idx = autoSrc.indexOf("Step 5:", step4Idx);
62
+ const step4Block = autoSrc.slice(step4Idx, step5Idx);
63
+
64
+ assert.ok(
65
+ step4Block.includes("resolveMilestoneFile"),
66
+ "Step 4 should keep SUMMARY-file resolution for DB-unavailable projects",
67
+ );
68
+ assert.ok(
69
+ step4Block.includes("preserveBranch"),
70
+ "Step 4 should still preserve branch for incomplete milestones (fallback path)",
71
+ );
72
+ });
73
+
74
+ test("#4175: postUnitPreVerification pauses complete-milestone after retries exhausted", () => {
75
+ // The pause branch must live inside the retries-exhausted block, above the
76
+ // writeBlockerPlaceholder call — otherwise the stub SUMMARY is still written.
77
+ const retriesExhaustedIdx = postUnitSrc.indexOf(
78
+ "if (attempt > MAX_VERIFICATION_RETRIES)",
79
+ );
80
+ assert.ok(
81
+ retriesExhaustedIdx !== -1,
82
+ "retries-exhausted guard exists in postUnitPreVerification",
83
+ );
84
+
85
+ const blockerCallIdx = postUnitSrc.indexOf("writeBlockerPlaceholder", retriesExhaustedIdx);
86
+ assert.ok(
87
+ blockerCallIdx !== -1,
88
+ "blocker placeholder call still exists for non-milestone units",
89
+ );
90
+
91
+ const exhaustedBlock = postUnitSrc.slice(retriesExhaustedIdx, blockerCallIdx);
92
+
93
+ assert.ok(
94
+ /s\.currentUnit\.type\s*===\s*"complete-milestone"/.test(exhaustedBlock),
95
+ "retries-exhausted block should specifically handle complete-milestone",
96
+ );
97
+ assert.ok(
98
+ /pauseAuto\s*\(\s*ctx\s*,\s*pi\s*\)/.test(exhaustedBlock),
99
+ "complete-milestone path should call pauseAuto instead of falling through",
100
+ );
101
+ // The pause branch must return so execution never reaches writeBlockerPlaceholder.
102
+ assert.ok(
103
+ /return\s+"dispatched"\s*;/.test(exhaustedBlock),
104
+ "complete-milestone pause branch should return before the placeholder call",
105
+ );
106
+ });
107
+
108
+ test("#4175: recoverTimedOutUnit pauses complete-milestone instead of writing a blocker placeholder", () => {
109
+ // The complete-milestone pause branch must sit immediately above the
110
+ // "retries exhausted" writeBlockerPlaceholder call so a failed
111
+ // complete-milestone never produces a stub SUMMARY. Anchor on the
112
+ // comment that precedes that specific placeholder call rather than the
113
+ // function's earlier writeBlockerPlaceholder use sites or its import.
114
+ // Use lastIndexOf so we find the final retries-exhausted block in
115
+ // recoverTimedOutUnit, not an earlier helper with the same comment.
116
+ const exhaustedAnchor = "Retries exhausted — write a blocker placeholder";
117
+ const exhaustedIdx = timeoutSrc.lastIndexOf(exhaustedAnchor);
118
+ assert.ok(
119
+ exhaustedIdx !== -1,
120
+ "retries-exhausted blocker-placeholder path still exists for non-milestone units",
121
+ );
122
+
123
+ const guardIdx = timeoutSrc.lastIndexOf(
124
+ 'unitType === "complete-milestone"',
125
+ exhaustedIdx,
126
+ );
127
+ assert.ok(
128
+ guardIdx !== -1,
129
+ "complete-milestone guard should appear above the retries-exhausted placeholder call",
130
+ );
131
+
132
+ const guardBlock = timeoutSrc.slice(guardIdx, exhaustedIdx);
133
+ assert.ok(
134
+ /return\s+"paused"\s*;/.test(guardBlock),
135
+ "complete-milestone guard should return 'paused' before the placeholder call",
136
+ );
137
+ // The guard itself must not call writeBlockerPlaceholder.
138
+ assert.ok(
139
+ !guardBlock.includes("writeBlockerPlaceholder"),
140
+ "complete-milestone guard must not write a blocker placeholder",
141
+ );
142
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Regression test for #4129: tasks.completed_at stays NULL when status is
3
+ * reconciled to 'complete' via the file-existence path in state.ts.
4
+ *
5
+ * Root cause: reconcileSliceTasks called
6
+ * updateTaskStatus(milestoneId, sliceId, t.id, "complete")
7
+ * without a completedAt timestamp, so the column stays NULL.
8
+ *
9
+ * Fix: pass new Date().toISOString() as the 5th argument.
10
+ */
11
+
12
+ import { describe, test } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import { readFileSync } from "node:fs";
15
+ import { join, dirname } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ const __dirname = dirname(fileURLToPath(import.meta.url));
19
+ const stateSource = readFileSync(join(__dirname, "..", "state.ts"), "utf-8");
20
+
21
+ describe("completed-at reconcile (#4129)", () => {
22
+ test("reconcileSliceTasks passes a completedAt timestamp when setting status to complete", () => {
23
+ // Before the fix, state.ts had:
24
+ // updateTaskStatus(milestoneId, sliceId, t.id, "complete")
25
+ // which leaves completed_at NULL in the DB.
26
+ // After the fix, a timestamp must be passed as the 5th argument.
27
+ assert.doesNotMatch(
28
+ stateSource,
29
+ /updateTaskStatus\(\s*milestoneId\s*,\s*sliceId\s*,\s*t\.id\s*,\s*["']complete["']\s*\)/,
30
+ "updateTaskStatus must not be called without a completedAt timestamp when reconciling tasks to 'complete' (#4129)",
31
+ );
32
+ });
33
+
34
+ test("reconcileSliceTasks passes new Date().toISOString() as the completedAt argument", () => {
35
+ // Positive assertion: the fixed call must include a timestamp.
36
+ assert.match(
37
+ stateSource,
38
+ /updateTaskStatus\(\s*milestoneId\s*,\s*sliceId\s*,\s*t\.id\s*,\s*["']complete["']\s*,\s*new Date\(\)\.toISOString\(\)\s*\)/,
39
+ "reconcileSliceTasks must pass new Date().toISOString() as completedAt when setting task status to 'complete' (#4129)",
40
+ );
41
+ });
42
+ });
@@ -351,8 +351,9 @@ skills_used: []
351
351
  const dbState = await deriveStateFromDb(base);
352
352
 
353
353
  assertStatesEqual(dbState, fileState, 'E-blocked');
354
- assert.deepStrictEqual(dbState.phase, 'blocked', 'E-blocked: phase is blocked');
355
- assert.ok(dbState.blockers.length > 0, 'E-blocked: has blockers');
354
+ // With partial-dep fallback, circular deps no longer block — fallback picks first eligible slice
355
+ assert.deepStrictEqual(dbState.phase, 'planning', 'E-blocked: phase is planning (fallback picks a slice)');
356
+ assert.ok(dbState.activeSlice !== null, 'E-blocked: activeSlice is set via fallback');
356
357
 
357
358
  closeDatabase();
358
359
  } finally {
@@ -616,9 +616,10 @@ describe('derive-state-db', async () => {
616
616
  invalidateStateCache();
617
617
  const dbState = await deriveStateFromDb(base);
618
618
 
619
- assert.deepStrictEqual(dbState.phase, 'blocked', 'blocked-db: phase is blocked');
619
+ // With partial-dep fallback, circular deps no longer block — fallback picks first eligible slice
620
+ assert.deepStrictEqual(dbState.phase, 'planning', 'blocked-db: phase is planning (fallback picks a slice)');
620
621
  assert.deepStrictEqual(dbState.phase, fileState.phase, 'blocked-db: phase matches filesystem');
621
- assert.ok(dbState.blockers.length > 0, 'blocked-db: has blockers');
622
+ assert.ok(dbState.activeSlice !== null, 'blocked-db: activeSlice is set via fallback');
622
623
 
623
624
  closeDatabase();
624
625
  } finally {