@opengsd/gsd-pi 1.3.0-dev.72e3af2a → 1.3.0-dev.738160b9

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 (213) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +17 -4
  3. package/dist/headless-answers.js +1 -1
  4. package/dist/headless-ui.d.ts +1 -1
  5. package/dist/headless-ui.js +1 -1
  6. package/dist/headless.js +1 -1
  7. package/dist/resources/.managed-resources-content-hash +1 -1
  8. package/dist/resources/extensions/claude-code-cli/models.js +9 -0
  9. package/dist/resources/extensions/gsd/auto/session.js +8 -0
  10. package/dist/resources/extensions/gsd/auto/verification-retry-policy.js +1 -1
  11. package/dist/resources/extensions/gsd/auto-budget.js +5 -1
  12. package/dist/resources/extensions/gsd/auto-dispatch.js +14 -1
  13. package/dist/resources/extensions/gsd/auto-post-unit.js +1 -1
  14. package/dist/resources/extensions/gsd/auto-prompts.js +3 -3
  15. package/dist/resources/extensions/gsd/auto-recovery.js +3 -3
  16. package/dist/resources/extensions/gsd/auto-verification.js +5 -2
  17. package/dist/resources/extensions/gsd/auto.js +19 -10
  18. package/dist/resources/extensions/gsd/bootstrap/core-session-tools.js +1 -0
  19. package/dist/resources/extensions/gsd/bootstrap/db-tools.js +5 -4
  20. package/dist/resources/extensions/gsd/bootstrap/register-extension.js +2 -0
  21. package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +31 -2
  22. package/dist/resources/extensions/gsd/bootstrap/tool-call-loop-guard.js +32 -4
  23. package/dist/resources/extensions/gsd/closeout-consistency-gate.js +3 -1
  24. package/dist/resources/extensions/gsd/commands/handlers/auto.js +1 -1
  25. package/dist/resources/extensions/gsd/commands-prefs-wizard.js +1 -1
  26. package/dist/resources/extensions/gsd/commands-usage.js +1 -1
  27. package/dist/resources/extensions/gsd/db/engine.js +4 -1
  28. package/dist/resources/extensions/gsd/db-memory-fts-schema.js +34 -0
  29. package/dist/resources/extensions/gsd/delegation-policy.js +1 -1
  30. package/dist/resources/extensions/gsd/docs/preferences-reference.md +2 -2
  31. package/dist/resources/extensions/gsd/doctor-engine-checks.js +192 -4
  32. package/dist/resources/extensions/gsd/doctor-runtime-checks.js +3 -0
  33. package/dist/resources/extensions/gsd/exec-sandbox.js +8 -2
  34. package/dist/resources/extensions/gsd/flat-phase-migration.js +45 -0
  35. package/dist/resources/extensions/gsd/git-service.js +57 -0
  36. package/dist/resources/extensions/gsd/gitignore.js +4 -1
  37. package/dist/resources/extensions/gsd/json-persistence.js +20 -0
  38. package/dist/resources/extensions/gsd/knowledge-backfill.js +18 -11
  39. package/dist/resources/extensions/gsd/memory-backfill.js +28 -21
  40. package/dist/resources/extensions/gsd/metrics.js +4 -4
  41. package/dist/resources/extensions/gsd/migrate-external.js +11 -2
  42. package/dist/resources/extensions/gsd/orphan-stash-audit.js +92 -16
  43. package/dist/resources/extensions/gsd/prompts/plan-milestone.md +2 -2
  44. package/dist/resources/extensions/gsd/prompts/plan-slice.md +3 -3
  45. package/dist/resources/extensions/gsd/root-write-leak-guard.js +7 -1
  46. package/dist/resources/extensions/gsd/safety/destructive-guard.js +8 -1
  47. package/dist/resources/extensions/gsd/safety/evidence-collector.js +16 -1
  48. package/dist/resources/extensions/gsd/safety/file-change-validator.js +5 -2
  49. package/dist/resources/extensions/gsd/tools/complete-milestone.js +4 -2
  50. package/dist/resources/extensions/gsd/tools/plan-slice.js +59 -44
  51. package/dist/resources/extensions/gsd/tools/plan-task.js +28 -5
  52. package/dist/resources/extensions/gsd/undo.js +43 -6
  53. package/dist/resources/extensions/gsd/unit-registry.js +4 -2
  54. package/dist/resources/extensions/gsd/verification-gate.js +7 -0
  55. package/dist/resources/extensions/gsd/workflow-manifest.js +126 -13
  56. package/dist/tsconfig.extensions.tsbuildinfo +1 -1
  57. package/dist/web/standalone/.next/BUILD_ID +1 -1
  58. package/dist/web/standalone/.next/app-path-routes-manifest.json +9 -9
  59. package/dist/web/standalone/.next/build-manifest.json +2 -2
  60. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  61. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  62. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  63. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  64. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  65. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  66. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  67. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  68. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  69. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  70. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  71. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  72. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  73. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  74. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  75. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  76. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  77. package/dist/web/standalone/.next/server/app/index.html +1 -1
  78. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  79. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  80. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  81. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  82. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  83. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  84. package/dist/web/standalone/.next/server/app-paths-manifest.json +9 -9
  85. package/dist/web/standalone/.next/server/chunks/8357.js +1 -1
  86. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  87. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  88. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  89. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  90. package/package.json +1 -1
  91. package/packages/cloud-mcp-gateway/package.json +2 -2
  92. package/packages/contracts/package.json +1 -1
  93. package/packages/daemon/package.json +4 -4
  94. package/packages/gsd-agent-core/package.json +5 -5
  95. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.d.ts +2 -0
  96. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  97. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.js +23 -5
  98. package/packages/gsd-agent-modes/dist/modes/rpc/rpc-client.js.map +1 -1
  99. package/packages/gsd-agent-modes/package.json +7 -7
  100. package/packages/mcp-server/dist/workflow-tools.js +1 -1
  101. package/packages/mcp-server/dist/workflow-tools.js.map +1 -1
  102. package/packages/mcp-server/package.json +4 -4
  103. package/packages/native/package.json +1 -1
  104. package/packages/pi-agent-core/dist/agent-loop.js +3 -2
  105. package/packages/pi-agent-core/dist/agent-loop.js.map +1 -1
  106. package/packages/pi-agent-core/package.json +1 -1
  107. package/packages/pi-ai/dist/models.generated.d.ts +46 -0
  108. package/packages/pi-ai/dist/models.generated.d.ts.map +1 -1
  109. package/packages/pi-ai/dist/models.generated.js +38 -0
  110. package/packages/pi-ai/dist/models.generated.js.map +1 -1
  111. package/packages/pi-ai/package.json +1 -1
  112. package/packages/pi-coding-agent/package.json +7 -7
  113. package/packages/pi-tui/package.json +2 -2
  114. package/packages/rpc-client/package.json +2 -2
  115. package/pkg/package.json +1 -1
  116. package/src/resources/extensions/claude-code-cli/models.ts +9 -0
  117. package/src/resources/extensions/claude-code-cli/tests/index.test.ts +14 -0
  118. package/src/resources/extensions/gsd/auto/loop-deps.ts +1 -0
  119. package/src/resources/extensions/gsd/auto/session.ts +9 -0
  120. package/src/resources/extensions/gsd/auto/verification-retry-policy.ts +3 -1
  121. package/src/resources/extensions/gsd/auto-budget.ts +12 -1
  122. package/src/resources/extensions/gsd/auto-dispatch.ts +14 -1
  123. package/src/resources/extensions/gsd/auto-post-unit.ts +1 -1
  124. package/src/resources/extensions/gsd/auto-prompts.ts +3 -3
  125. package/src/resources/extensions/gsd/auto-recovery.ts +3 -3
  126. package/src/resources/extensions/gsd/auto-verification.ts +5 -1
  127. package/src/resources/extensions/gsd/auto.ts +23 -8
  128. package/src/resources/extensions/gsd/bootstrap/core-session-tools.ts +1 -0
  129. package/src/resources/extensions/gsd/bootstrap/db-tools.ts +5 -4
  130. package/src/resources/extensions/gsd/bootstrap/register-extension.ts +2 -0
  131. package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +41 -2
  132. package/src/resources/extensions/gsd/bootstrap/tool-call-loop-guard.ts +34 -4
  133. package/src/resources/extensions/gsd/closeout-consistency-gate.ts +2 -1
  134. package/src/resources/extensions/gsd/commands/handlers/auto.ts +1 -1
  135. package/src/resources/extensions/gsd/commands-prefs-wizard.ts +1 -1
  136. package/src/resources/extensions/gsd/commands-usage.ts +1 -1
  137. package/src/resources/extensions/gsd/db/engine.ts +8 -1
  138. package/src/resources/extensions/gsd/db-memory-fts-schema.ts +45 -0
  139. package/src/resources/extensions/gsd/delegation-policy.ts +1 -1
  140. package/src/resources/extensions/gsd/docs/preferences-reference.md +2 -2
  141. package/src/resources/extensions/gsd/doctor-engine-checks.ts +233 -5
  142. package/src/resources/extensions/gsd/doctor-runtime-checks.ts +3 -0
  143. package/src/resources/extensions/gsd/doctor-types.ts +3 -0
  144. package/src/resources/extensions/gsd/exec-sandbox.ts +7 -2
  145. package/src/resources/extensions/gsd/flat-phase-migration.ts +44 -0
  146. package/src/resources/extensions/gsd/git-service.ts +64 -0
  147. package/src/resources/extensions/gsd/gitignore.ts +4 -1
  148. package/src/resources/extensions/gsd/json-persistence.ts +20 -0
  149. package/src/resources/extensions/gsd/knowledge-backfill.ts +16 -10
  150. package/src/resources/extensions/gsd/memory-backfill.ts +26 -20
  151. package/src/resources/extensions/gsd/metrics.ts +4 -4
  152. package/src/resources/extensions/gsd/migrate-external.ts +8 -2
  153. package/src/resources/extensions/gsd/orphan-stash-audit.ts +108 -20
  154. package/src/resources/extensions/gsd/prompts/plan-milestone.md +2 -2
  155. package/src/resources/extensions/gsd/prompts/plan-slice.md +3 -3
  156. package/src/resources/extensions/gsd/root-write-leak-guard.ts +13 -1
  157. package/src/resources/extensions/gsd/safety/destructive-guard.ts +9 -1
  158. package/src/resources/extensions/gsd/safety/evidence-collector.ts +16 -1
  159. package/src/resources/extensions/gsd/safety/file-change-validator.ts +8 -2
  160. package/src/resources/extensions/gsd/tests/artifact-retry-cap.test.ts +4 -3
  161. package/src/resources/extensions/gsd/tests/auto-budget-alerts.test.ts +14 -5
  162. package/src/resources/extensions/gsd/tests/auto-pause-double-entry-guard.test.ts +36 -0
  163. package/src/resources/extensions/gsd/tests/auto-paused-ui-cleanup.test.ts +182 -4
  164. package/src/resources/extensions/gsd/tests/auto-recovery.test.ts +35 -0
  165. package/src/resources/extensions/gsd/tests/auto-retry-mcp-churn-fixes.test.ts +30 -0
  166. package/src/resources/extensions/gsd/tests/complete-milestone.test.ts +28 -0
  167. package/src/resources/extensions/gsd/tests/complete-slice-reopen-handoff.test.ts +69 -0
  168. package/src/resources/extensions/gsd/tests/db-memory-fts-schema.test.ts +58 -3
  169. package/src/resources/extensions/gsd/tests/decisions-projection-from-memories.test.ts +51 -0
  170. package/src/resources/extensions/gsd/tests/destructive-guard.test.ts +44 -0
  171. package/src/resources/extensions/gsd/tests/dispatch-missing-task-plans.test.ts +143 -0
  172. package/src/resources/extensions/gsd/tests/doctor-scope-db-unavailable.test.ts +239 -2
  173. package/src/resources/extensions/gsd/tests/exec-sandbox.test.ts +16 -0
  174. package/src/resources/extensions/gsd/tests/file-change-validator.test.ts +40 -0
  175. package/src/resources/extensions/gsd/tests/flat-phase-migration.test.ts +37 -2
  176. package/src/resources/extensions/gsd/tests/gitignore-bg-shell-runtime.test.ts +4 -0
  177. package/src/resources/extensions/gsd/tests/integration/git-service.test.ts +11 -2
  178. package/src/resources/extensions/gsd/tests/json-persistence-atomic.test.ts +47 -0
  179. package/src/resources/extensions/gsd/tests/knowledge-backfill-projection.test.ts +35 -0
  180. package/src/resources/extensions/gsd/tests/memory-store.test.ts +48 -0
  181. package/src/resources/extensions/gsd/tests/merge-closeout-consistency-gate.test.ts +31 -1
  182. package/src/resources/extensions/gsd/tests/metrics-prune-cache-invalidation.test.ts +6 -0
  183. package/src/resources/extensions/gsd/tests/metrics.test.ts +1 -0
  184. package/src/resources/extensions/gsd/tests/migrate-external-worktree.test.ts +57 -0
  185. package/src/resources/extensions/gsd/tests/orphan-stash-audit.test.ts +91 -7
  186. package/src/resources/extensions/gsd/tests/parsers-legacy-importers.test.ts +2 -0
  187. package/src/resources/extensions/gsd/tests/plan-slice-prompt.test.ts +10 -0
  188. package/src/resources/extensions/gsd/tests/plan-slice.test.ts +103 -4
  189. package/src/resources/extensions/gsd/tests/plan-task.test.ts +44 -1
  190. package/src/resources/extensions/gsd/tests/post-mutation-hook.test.ts +4 -2
  191. package/src/resources/extensions/gsd/tests/prompt-budget-enforcement.test.ts +58 -0
  192. package/src/resources/extensions/gsd/tests/prompt-contracts.test.ts +8 -6
  193. package/src/resources/extensions/gsd/tests/register-hooks-loop-guard-auto.test.ts +103 -0
  194. package/src/resources/extensions/gsd/tests/root-write-leak-guard.test.ts +20 -1
  195. package/src/resources/extensions/gsd/tests/runtime-invariant-modules.test.ts +8 -3
  196. package/src/resources/extensions/gsd/tests/tool-call-loop-guard.test.ts +62 -5
  197. package/src/resources/extensions/gsd/tests/tool-param-optionality.test.ts +6 -3
  198. package/src/resources/extensions/gsd/tests/undo.test.ts +74 -0
  199. package/src/resources/extensions/gsd/tests/uok-gitops-turn-action.test.ts +38 -0
  200. package/src/resources/extensions/gsd/tests/verification-retry-policy.test.ts +69 -4
  201. package/src/resources/extensions/gsd/tests/workflow-manifest.test.ts +96 -15
  202. package/src/resources/extensions/gsd/tests/workflow-mcp-preflight.test.ts +1 -0
  203. package/src/resources/extensions/gsd/tests/workflow-mcp.test.ts +8 -4
  204. package/src/resources/extensions/gsd/tests/workflow-tool-executors.test.ts +6 -5
  205. package/src/resources/extensions/gsd/tools/complete-milestone.ts +3 -2
  206. package/src/resources/extensions/gsd/tools/plan-slice.ts +60 -47
  207. package/src/resources/extensions/gsd/tools/plan-task.ts +30 -5
  208. package/src/resources/extensions/gsd/undo.ts +47 -6
  209. package/src/resources/extensions/gsd/unit-registry.ts +4 -2
  210. package/src/resources/extensions/gsd/verification-gate.ts +8 -0
  211. package/src/resources/extensions/gsd/workflow-manifest.ts +141 -7
  212. /package/dist/web/standalone/.next/static/{O7xDYXO0r4zFhIzY1hrWV → 2A_WqqCS-EoYZxN9_v3d2}/_buildManifest.js +0 -0
  213. /package/dist/web/standalone/.next/static/{O7xDYXO0r4zFhIzY1hrWV → 2A_WqqCS-EoYZxN9_v3d2}/_ssgManifest.js +0 -0
@@ -14,10 +14,12 @@
14
14
  * to stop tooling for the rest of that turn and answer in text.
15
15
  *
16
16
  * The per-tool-name check (#783 Brief C) tracks call counts within a
17
- * turn regardless of args. This catches improvisation
17
+ * turn regardless of args, decaying after successful state-mutating tools.
18
+ * This catches improvisation
18
19
  * loops where the model attempts the same missing workflow tool through
19
20
  * varied surfaces (bash → `node -e` → CLI), each with a different
20
- * signature, so the identical-args streak never trips. Whichever guard
21
+ * signature, so the identical-args streak never trips, while allowing
22
+ * tool-heavy turns that are making file-mutation progress. Whichever guard
21
23
  * trips first blocks.
22
24
  */
23
25
 
@@ -42,6 +44,8 @@ const MAX_CONSECUTIVE_STRICT = 1;
42
44
  */
43
45
  const PER_TOOL_DEFAULT_CAP = 6;
44
46
  const PER_TOOL_REPEATABLE_CAP = 15;
47
+ const PER_TOOL_CAP_EXEMPT_TOOLS = new Set(["find", "glob", "grep", "ls", "read", "search_and_read"]);
48
+ const STATE_MUTATING_TOOL_SET = new Set(["edit", "write", "multi_edit", "notebook_edit"]);
45
49
 
46
50
  let consecutiveCount = 0;
47
51
  let lastSignature = "";
@@ -50,6 +54,8 @@ let enabled = true;
50
54
 
51
55
  /** Per-tool-name call counts within the current turn (#783 Brief C). */
52
56
  const perToolCounts = new Map<string, number>();
57
+ let mutationEpoch = 0;
58
+ const perToolLastMutationEpoch = new Map<string, number>();
53
59
 
54
60
  /** Hash tool name + args into a compact signature for comparison. */
55
61
  function hashToolCall(toolName: string, args: Record<string, unknown>): string {
@@ -77,7 +83,8 @@ function hashToolCall(toolName: string, args: Record<string, unknown>): string {
77
83
  * 1. Identical-signature streak (MAX_CONSECUTIVE_IDENTICAL_CALLS, strict for
78
84
  * ask_user_questions).
79
85
  * 2. Per-tool-name cap (PER_TOOL_DEFAULT_CAP / PER_TOOL_REPEATABLE_CAP),
80
- * independent of args catches improvisation loops (#783).
86
+ * independent of args, reset after file-mutation progress — catches
87
+ * improvisation loops (#783).
81
88
  */
82
89
  export function checkToolCallLoop(
83
90
  toolName: string,
@@ -114,8 +121,20 @@ export function checkToolCallLoop(
114
121
  // ── Guard 2: per-tool-name cap, independent of args (#783 Brief C) ──
115
122
  // Catches improvisation loops where the same tool is invoked many times with
116
123
  // varied args (e.g. retrying a missing workflow tool via bash/node -e/CLI).
117
- const perToolCount = (perToolCounts.get(toolName) ?? 0) + 1;
124
+ const priorPerToolCount =
125
+ (perToolLastMutationEpoch.get(toolName) ?? mutationEpoch) < mutationEpoch
126
+ ? 0
127
+ : (perToolCounts.get(toolName) ?? 0);
128
+ const perToolCount = priorPerToolCount + 1;
118
129
  perToolCounts.set(toolName, perToolCount);
130
+ perToolLastMutationEpoch.set(toolName, mutationEpoch);
131
+
132
+ // Read-only navigation tools are normal context gathering; Guard 1 still
133
+ // catches true reread loops with identical arguments.
134
+ if (PER_TOOL_CAP_EXEMPT_TOOLS.has(toolName)) {
135
+ return { block: false, count: consecutiveCount };
136
+ }
137
+
119
138
  const perToolCap = INHERENTLY_REPEATABLE_TOOL_SET.has(toolName)
120
139
  ? PER_TOOL_REPEATABLE_CAP
121
140
  : PER_TOOL_DEFAULT_CAP;
@@ -135,6 +154,13 @@ export function checkToolCallLoop(
135
154
  return { block: false, count: consecutiveCount };
136
155
  }
137
156
 
157
+ /** Record successful mutation progress so Guard 2 can decay on the next count. */
158
+ export function recordToolCallLoopMutation(toolName: string): void {
159
+ if (!enabled) return;
160
+ if (!STATE_MUTATING_TOOL_SET.has(toolName)) return;
161
+ mutationEpoch++;
162
+ }
163
+
138
164
  /** Reset the guard state. Call at agent turn boundaries. */
139
165
  export function resetToolCallLoopGuard(): void {
140
166
  consecutiveCount = 0;
@@ -142,6 +168,8 @@ export function resetToolCallLoopGuard(): void {
142
168
  lastToolName = "";
143
169
  enabled = true;
144
170
  perToolCounts.clear();
171
+ mutationEpoch = 0;
172
+ perToolLastMutationEpoch.clear();
145
173
  }
146
174
 
147
175
  /** Disable the guard (e.g. during shutdown). */
@@ -151,6 +179,8 @@ export function disableToolCallLoopGuard(): void {
151
179
  lastSignature = "";
152
180
  lastToolName = "";
153
181
  perToolCounts.clear();
182
+ mutationEpoch = 0;
183
+ perToolLastMutationEpoch.clear();
154
184
  }
155
185
 
156
186
  /** Get current consecutive count for diagnostics. */
@@ -18,7 +18,7 @@ import {
18
18
  getWorkflowDatabasePath,
19
19
  refreshWorkflowDatabaseFromDisk,
20
20
  } from "./db-workspace.js";
21
- import { isClosedStatus } from "./status-guards.js";
21
+ import { isClosedStatus, isDeferredStatus } from "./status-guards.js";
22
22
  import { closeQualityGatesFromEvidence } from "./quality-gate-closure.js";
23
23
  import { insertMilestoneValidationGates } from "./milestone-validation-gates.js";
24
24
  import { relMilestoneFile, resolveSliceFile } from "./paths.js";
@@ -229,6 +229,7 @@ export function checkCloseoutConsistencyGate(
229
229
  }
230
230
 
231
231
  for (const slice of slices) {
232
+ if (isDeferredStatus(slice.status)) continue;
232
233
  if (!isClosedStatus(slice.status)) {
233
234
  return blocked(
234
235
  "slice-open",
@@ -200,7 +200,7 @@ export async function handleAutoCommand(trimmed: string, ctx: ExtensionCommandCo
200
200
  }
201
201
  return true;
202
202
  }
203
- await pauseAuto(ctx, pi);
203
+ await pauseAuto(ctx, pi, undefined, { abortActiveTurn: true });
204
204
  return true;
205
205
  }
206
206
 
@@ -1228,7 +1228,7 @@ async function configureContextCodebase(ctx: ExtensionCommandContext, prefs: Rec
1228
1228
  const maskTurns = await promptInteger(ctx, "Observation mask turns (1–50)", cm.observation_mask_turns, "8");
1229
1229
  if (maskTurns !== undefined && maskTurns !== "clear") cm.observation_mask_turns = maskTurns;
1230
1230
  else if (maskTurns === "clear") delete cm.observation_mask_turns;
1231
- const thresh = await promptNumber(ctx, "Compaction threshold percent (0.5–0.95)", cm.compaction_threshold_percent, "0.60");
1231
+ const thresh = await promptNumber(ctx, "Soft context warning threshold percent (0.5–0.95)", cm.compaction_threshold_percent, "0.60");
1232
1232
  if (thresh !== undefined && thresh !== "clear") cm.compaction_threshold_percent = thresh;
1233
1233
  else if (thresh === "clear") delete cm.compaction_threshold_percent;
1234
1234
  const toolMax = await promptInteger(ctx, "Tool result max chars (200–10000)", cm.tool_result_max_chars, "800");
@@ -112,7 +112,7 @@ function formatThresholdLines(): string[] {
112
112
 
113
113
  const compactionThreshold = prefs?.context_management?.compaction_threshold_percent;
114
114
  if (typeof compactionThreshold === "number") {
115
- lines.push(`Compaction: ${Math.round(compactionThreshold * 100)}%`);
115
+ lines.push(`Soft context warning: ${Math.round(compactionThreshold * 100)}%`);
116
116
  }
117
117
 
118
118
  return lines;
@@ -47,7 +47,11 @@ import {
47
47
  applyMigrationV28MemoryLastHitAt,
48
48
  applyMigrationV29RepositoryTargets,
49
49
  } from "../db-migration-steps.js";
50
- import { isMemoriesFtsAvailableSchema, tryCreateMemoriesFtsSchema } from "../db-memory-fts-schema.js";
50
+ import {
51
+ isMemoriesFtsAvailableSchema,
52
+ rebuildMemoriesFtsSchemaOnce,
53
+ tryCreateMemoriesFtsSchema,
54
+ } from "../db-memory-fts-schema.js";
51
55
  import { createDbOpenState, type DbOpenPhase } from "../db-open-state.js";
52
56
  import { createRuntimeKvTableV25 } from "../db-runtime-kv-schema.js";
53
57
  import { getCurrentSchemaVersion, recordSchemaVersion } from "../db-schema-metadata.js";
@@ -134,6 +138,9 @@ function initSchema(db: DbAdapter, fileBacked: boolean, dbPath: string | null):
134
138
  }
135
139
 
136
140
  migrateSchema(db, dbPath);
141
+ rebuildMemoriesFtsSchemaOnce(db, {
142
+ onRebuildFailed: (message) => logWarning("db", message),
143
+ });
137
144
  }
138
145
 
139
146
  export function _isLikelyWslDrvFsPathForTest(dbPath: string | null): boolean {
@@ -2,11 +2,18 @@
2
2
  // File Purpose: Memory FTS5 SQLite schema helpers for the GSD database facade.
3
3
 
4
4
  import type { DbAdapter } from "./db-adapter.js";
5
+ import { createRuntimeKvTableV25 } from "./db-runtime-kv-schema.js";
6
+
7
+ export const MEMORIES_FTS_REBUILT_KEY = "memories_fts_rebuilt_at";
5
8
 
6
9
  export interface MemoryFtsSchemaOptions {
7
10
  onUnavailable?: (message: string) => void;
8
11
  }
9
12
 
13
+ export interface MemoryFtsRebuildOptions {
14
+ onRebuildFailed?: (message: string) => void;
15
+ }
16
+
10
17
  function formatFtsUnavailableError(err: unknown): string {
11
18
  const message = err instanceof Error ? err.message : String(err);
12
19
  return message.replace(/\bmoduel\s*:\s*/gi, "module: ");
@@ -64,3 +71,41 @@ export function isMemoriesFtsAvailableSchema(db: DbAdapter): boolean {
64
71
  return false;
65
72
  }
66
73
  }
74
+
75
+ export function rebuildMemoriesFtsSchemaOnce(
76
+ db: DbAdapter,
77
+ options: MemoryFtsRebuildOptions = {},
78
+ ): void {
79
+ if (!isMemoriesFtsAvailableSchema(db)) return;
80
+
81
+ createRuntimeKvTableV25(db);
82
+ const marker = db.prepare(
83
+ "SELECT 1 as present FROM runtime_kv WHERE scope = 'global' AND scope_id = '' AND key = :key",
84
+ ).get({ ":key": MEMORIES_FTS_REBUILT_KEY });
85
+ if (marker) return;
86
+
87
+ const now = new Date().toISOString();
88
+ try {
89
+ db.exec("BEGIN");
90
+ db.exec("INSERT INTO memories_fts(memories_fts) VALUES('rebuild')");
91
+ db.prepare(
92
+ `INSERT INTO runtime_kv (scope, scope_id, key, value_json, updated_at)
93
+ VALUES ('global', '', :key, :value_json, :updated_at)
94
+ ON CONFLICT (scope, scope_id, key) DO UPDATE SET
95
+ value_json = excluded.value_json,
96
+ updated_at = excluded.updated_at`,
97
+ ).run({
98
+ ":key": MEMORIES_FTS_REBUILT_KEY,
99
+ ":value_json": JSON.stringify(now),
100
+ ":updated_at": now,
101
+ });
102
+ db.exec("COMMIT");
103
+ } catch (err) {
104
+ try {
105
+ db.exec("ROLLBACK");
106
+ } catch {
107
+ // Best effort: leave startup alive and retry the rebuild on next open.
108
+ }
109
+ options.onRebuildFailed?.(`FTS5 rebuild failed: ${(err as Error).message}`);
110
+ }
111
+ }
@@ -121,7 +121,7 @@ const POLICY: Record<string, DelegationPolicyEntry> = {
121
121
  toolName: "gsd_plan_task",
122
122
  verdict: "no",
123
123
  rationale:
124
- "plan-slice prompt explicitly forbids calling gsd_plan_task separately; per-task granularity multiplies manifest writes and projection re-renders with no payoff.",
124
+ "Incremental task planning mutates the active slice plan and re-renders projections; keep it ordered in the foreground plan-slice unit.",
125
125
  },
126
126
  };
127
127
 
@@ -273,10 +273,10 @@ This config sets a parent workspace with two child repositories. The implicit `p
273
273
  - `audit_unified.enabled`: boolean — dual-write unified audit envelope events. Default: `true`.
274
274
  - `plan_v2.enabled`: boolean — enable bounded clarify/research/draft/compile planning flow. Default: `true`.
275
275
 
276
- - `context_management`: configures context hygiene for auto-mode sessions. Keys:
276
+ - `context_management`: configures context hygiene for auto-mode sessions. In step mode, the configurable threshold is a soft warning; automatic session re-rooting happens only at the fixed 90% hard context boundary. Keys:
277
277
  - `observation_masking`: boolean — mask old tool results to reduce context bloat. Default: `true`.
278
278
  - `observation_mask_turns`: number — keep this many recent turns verbatim (1-50). Default: `8`.
279
- - `compaction_threshold_percent`: number — trigger compaction at this % of context window (0.5-0.95). Lower values fire compaction earlier, reducing drift. Default: `0.60`.
279
+ - `compaction_threshold_percent`: number — show a soft context warning at this fraction of the context window (0.5-0.95). Lower values warn earlier so operators can compact manually before drift accumulates. Default: `0.60`.
280
280
  - `tool_result_max_chars`: number — max chars per tool result in GSD sessions (200-10000). Default: `800`.
281
281
 
282
282
  - `auto_visualize`: boolean — show a visualizer hint after each milestone completion in auto-mode. Default: `false`.
@@ -1,14 +1,148 @@
1
- import { existsSync, statSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { isAbsolute, join, relative } from "node:path";
3
3
 
4
4
  import type { DoctorIssue } from "./doctor-types.js";
5
- import { isDbAvailable, _getAdapter } from "./gsd-db.js";
5
+ import {
6
+ getAllMilestones,
7
+ getMilestoneSlices,
8
+ getSliceTasks,
9
+ isDbAvailable,
10
+ isMemoriesFtsAvailable,
11
+ _getAdapter,
12
+ } from "./gsd-db.js";
13
+ import { MEMORIES_FTS_REBUILT_KEY } from "./db-memory-fts-schema.js";
6
14
  import { isAfter, latestExplicitReopenAt } from "./milestone-reopen-events.js";
7
- import { resolveGsdPathContract, resolveMilestoneFile } from "./paths.js";
15
+ import { gsdProjectionRoot, gsdRoot, resolveGsdPathContract, resolveMilestoneFile, resolveSliceFile } from "./paths.js";
8
16
  import { deriveState } from "./state.js";
17
+ import { isClosedStatus } from "./status-guards.js";
9
18
  import { workflowEventLogPath } from "./workflow-event-ledger.js";
10
19
  import { readEvents } from "./workflow-events.js";
11
20
  import { flushWorkflowProjections } from "./projection-flush.js";
21
+ import { parseRoadmapSlices } from "./roadmap-slices.js";
22
+ import { parsePlan } from "./parsers-legacy.js";
23
+
24
+ function relativeFile(basePath: string, filePath: string): string {
25
+ return relative(basePath, filePath).split("\\").join("/");
26
+ }
27
+
28
+ function reportCheckboxDbStatusDivergence(
29
+ issues: DoctorIssue[],
30
+ basePath: string,
31
+ filePath: string,
32
+ scope: "slice" | "task",
33
+ unitId: string,
34
+ status: string,
35
+ checkboxDone: boolean,
36
+ ): void {
37
+ const dbDone = isClosedStatus(status);
38
+ if (checkboxDone === dbDone) return;
39
+
40
+ issues.push({
41
+ severity: "error",
42
+ code: "checkbox_db_status_divergence",
43
+ scope,
44
+ unitId,
45
+ message: `${scope === "slice" ? "Slice" : "Task"} ${unitId} is ${dbDone ? "closed" : "open"} in the database (status: ${status}) but the markdown checkbox is ${checkboxDone ? "checked" : "unchecked"}.`,
46
+ file: relativeFile(basePath, filePath),
47
+ fixable: false,
48
+ });
49
+ }
50
+
51
+ function checkProjectionCheckboxDbStatus(basePath: string, milestoneIds: string[], issues: DoctorIssue[]): void {
52
+ for (const milestoneId of milestoneIds) {
53
+ const roadmapPath = resolveMilestoneFile(basePath, milestoneId, "ROADMAP");
54
+ const slices = getMilestoneSlices(milestoneId);
55
+
56
+ if (roadmapPath && existsSync(roadmapPath)) {
57
+ try {
58
+ const roadmap = readFileSync(roadmapPath, "utf-8");
59
+ const sliceDoneById = new Map(parseRoadmapSlices(roadmap).map((entry) => [entry.id, entry.done]));
60
+ for (const slice of slices) {
61
+ const checkboxDone = sliceDoneById.get(slice.id);
62
+ if (checkboxDone === undefined) continue;
63
+ reportCheckboxDbStatusDivergence(
64
+ issues,
65
+ basePath,
66
+ roadmapPath,
67
+ "slice",
68
+ `${milestoneId}/${slice.id}`,
69
+ slice.status,
70
+ checkboxDone,
71
+ );
72
+ }
73
+ } catch {
74
+ // Non-fatal — checkbox drift diagnostics must never block doctor.
75
+ }
76
+ }
77
+
78
+ for (const slice of slices) {
79
+ const planPath = resolveSliceFile(basePath, milestoneId, slice.id, "PLAN");
80
+ if (!planPath || !existsSync(planPath)) continue;
81
+ try {
82
+ const plan = readFileSync(planPath, "utf-8");
83
+ // parsePlan reads the authoritative task checkboxes (the flat-phase
84
+ // <tasks> block / ## Tasks section), so a stray task-style checkbox
85
+ // line elsewhere in PLAN.md (e.g. a Must-Haves or Verification bullet
86
+ // above <tasks>) can no longer hide real drift or fake a divergence.
87
+ const taskDoneById = new Map(parsePlan(plan).tasks.map((entry) => [entry.id, entry.done]));
88
+ for (const task of getSliceTasks(milestoneId, slice.id)) {
89
+ const checkboxDone = taskDoneById.get(task.id);
90
+ if (checkboxDone === undefined) continue;
91
+ reportCheckboxDbStatusDivergence(
92
+ issues,
93
+ basePath,
94
+ planPath,
95
+ "task",
96
+ `${milestoneId}/${slice.id}/${task.id}`,
97
+ task.status,
98
+ checkboxDone,
99
+ );
100
+ }
101
+ } catch {
102
+ // Non-fatal — checkbox drift diagnostics must never block doctor.
103
+ }
104
+ }
105
+ }
106
+ }
107
+
108
+ function isClearedByMilestoneShellProjectionFlush(
109
+ basePath: string,
110
+ issue: DoctorIssue,
111
+ reRenderedMilestoneIds: Set<string>,
112
+ ): boolean {
113
+ if (issue.code !== "checkbox_db_status_divergence") return false;
114
+ if (issue.scope !== "slice") return false;
115
+
116
+ const milestoneId = issue.unitId.split("/")[0] ?? "";
117
+ if (!reRenderedMilestoneIds.has(milestoneId)) return false;
118
+
119
+ const roadmapPath = resolveMilestoneFile(basePath, milestoneId, "ROADMAP");
120
+ if (!roadmapPath || !issue.file) return false;
121
+
122
+ return issue.file === relativeFile(basePath, roadmapPath);
123
+ }
124
+
125
+ function artifactExistsOnDisk(basePath: string, artifactPath: string): boolean {
126
+ if (isAbsolute(artifactPath)) return existsSync(artifactPath);
127
+ return [
128
+ join(gsdProjectionRoot(basePath), artifactPath),
129
+ join(gsdRoot(basePath), artifactPath),
130
+ ].some((candidate) => existsSync(candidate));
131
+ }
132
+
133
+ function artifactUnitId(row: { milestone_id: string | null; slice_id: string | null; task_id: string | null }): string {
134
+ if (!row.milestone_id) return "project";
135
+ if (row.slice_id && row.task_id) return `${row.milestone_id}/${row.slice_id}/${row.task_id}`;
136
+ if (row.slice_id) return `${row.milestone_id}/${row.slice_id}`;
137
+ return row.milestone_id;
138
+ }
139
+
140
+ function artifactScope(row: { milestone_id: string | null; slice_id: string | null; task_id: string | null }): DoctorIssue["scope"] {
141
+ if (row.task_id) return "task";
142
+ if (row.slice_id) return "slice";
143
+ if (row.milestone_id) return "milestone";
144
+ return "project";
145
+ }
12
146
 
13
147
  export async function checkEngineHealth(
14
148
  basePath: string,
@@ -34,6 +168,32 @@ export async function checkEngineHealth(
34
168
  if (isDbAvailable()) {
35
169
  const adapter = _getAdapter()!;
36
170
 
171
+ try {
172
+ if (isMemoriesFtsAvailable(adapter)) {
173
+ const runtimeKv = adapter
174
+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='runtime_kv'")
175
+ .get();
176
+ const marker = runtimeKv
177
+ ? adapter.prepare(
178
+ "SELECT 1 as present FROM runtime_kv WHERE scope = 'global' AND scope_id = '' AND key = :key",
179
+ ).get({ ":key": MEMORIES_FTS_REBUILT_KEY })
180
+ : undefined;
181
+ if (!marker) {
182
+ issues.push({
183
+ severity: "warning",
184
+ code: "memories_fts_rebuild_missing",
185
+ scope: "project",
186
+ unitId: "project",
187
+ message: `Memory full-text index exists but runtime_kv has no ${MEMORIES_FTS_REBUILT_KEY} marker. The index may be stale or incomplete, so memory search can silently degrade to the LIKE fallback.`,
188
+ file: ".gsd/gsd.db",
189
+ fixable: false,
190
+ });
191
+ }
192
+ }
193
+ } catch {
194
+ // Non-fatal — memory FTS health check failed
195
+ }
196
+
37
197
  // a. Orphaned tasks (task.slice_id points to non-existent slice)
38
198
  try {
39
199
  const orphanedTasks = adapter
@@ -196,7 +356,41 @@ export async function checkEngineHealth(
196
356
  // Non-fatal — completed-milestone reopen check failed
197
357
  }
198
358
 
199
- // f. Completion artifacts disagree with open DB hierarchy rows.
359
+ // f. Artifact rows reference files that no longer exist on disk.
360
+ try {
361
+ const artifactRows = adapter
362
+ .prepare(
363
+ `SELECT path, artifact_type, milestone_id, slice_id, task_id
364
+ FROM artifacts
365
+ WHERE path != ''
366
+ ORDER BY path`,
367
+ )
368
+ .all() as Array<{
369
+ path: string;
370
+ artifact_type: string;
371
+ milestone_id: string | null;
372
+ slice_id: string | null;
373
+ task_id: string | null;
374
+ }>;
375
+
376
+ for (const row of artifactRows) {
377
+ if (artifactExistsOnDisk(basePath, row.path)) continue;
378
+ const unitId = artifactUnitId(row);
379
+ issues.push({
380
+ severity: "error",
381
+ code: "artifact_file_missing",
382
+ scope: artifactScope(row),
383
+ unitId,
384
+ message: `Artifact ${row.path} is recorded in the database as ${row.artifact_type || "UNKNOWN"} but no matching file exists on disk`,
385
+ file: row.path,
386
+ fixable: false,
387
+ });
388
+ }
389
+ } catch {
390
+ // Non-fatal — artifact file existence check failed
391
+ }
392
+
393
+ // g. Completion artifacts disagree with open DB hierarchy rows.
200
394
  try {
201
395
  const rows = adapter
202
396
  .prepare(
@@ -225,6 +419,7 @@ export async function checkEngineHealth(
225
419
 
226
420
  const seen = new Set<string>();
227
421
  for (const row of rows) {
422
+ if (!artifactExistsOnDisk(basePath, row.path)) continue;
228
423
  const reopenAt = latestExplicitReopenAt(basePath, row.milestone_id);
229
424
  if (!isAfter(row.imported_at, reopenAt)) continue;
230
425
  const isSliceSummary = row.slice_id && !row.task_id && row.slice_status && !["complete", "done", "skipped", "closed"].includes(row.slice_status);
@@ -256,9 +451,24 @@ export async function checkEngineHealth(
256
451
  // Non-fatal — DB constraint checks failed entirely
257
452
  }
258
453
 
454
+ // Checkbox-vs-DB divergence detection runs before projection drift auto-fix
455
+ // so stale re-renders cannot overwrite manually edited markdown first. Runs
456
+ // inside its own try/catch: getAllMilestones / getMilestoneSlices /
457
+ // getSliceTasks issue prepared queries that can throw on a corrupt or locked
458
+ // DB, and like every other DB-touching check here this diagnostic must never
459
+ // block doctor.
460
+ try {
461
+ if (isDbAvailable()) {
462
+ checkProjectionCheckboxDbStatus(basePath, getAllMilestones().map((milestone) => milestone.id), issues);
463
+ }
464
+ } catch {
465
+ // Non-fatal: checkbox-vs-DB divergence check must never block doctor
466
+ }
467
+
259
468
  // ── Projection drift detection ──────────────────────────────────────────
260
469
  // If the DB is available, check whether markdown projections are stale
261
470
  // relative to the event log and re-render them.
471
+ const reRenderedMilestoneIds: string[] = [];
262
472
  try {
263
473
  if (isDbAvailable()) {
264
474
  const eventLogPath = workflowEventLogPath(basePath);
@@ -273,6 +483,7 @@ export async function checkEngineHealth(
273
483
  try {
274
484
  await flushWorkflowProjections(basePath, { milestoneId: milestone.id });
275
485
  fixesApplied.push(`re-rendered missing projections for ${milestone.id}`);
486
+ reRenderedMilestoneIds.push(milestone.id);
276
487
  } catch {
277
488
  // Non-fatal — projection re-render failed
278
489
  }
@@ -283,6 +494,7 @@ export async function checkEngineHealth(
283
494
  try {
284
495
  await flushWorkflowProjections(basePath, { milestoneId: milestone.id });
285
496
  fixesApplied.push(`re-rendered stale projections for ${milestone.id}`);
497
+ reRenderedMilestoneIds.push(milestone.id);
286
498
  } catch {
287
499
  // Non-fatal — projection re-render failed
288
500
  }
@@ -293,4 +505,20 @@ export async function checkEngineHealth(
293
505
  } catch {
294
506
  // Non-fatal — projection drift check must never block doctor
295
507
  }
508
+
509
+ if (reRenderedMilestoneIds.length > 0) {
510
+ const reRendered = new Set(reRenderedMilestoneIds);
511
+ for (let i = issues.length - 1; i >= 0; i--) {
512
+ const issue = issues[i]!;
513
+ // flushWorkflowProjections re-renders milestone shell projections (not
514
+ // slice PLAN.md files), so only clear stale ROADMAP checkbox diagnostics.
515
+ if (isClearedByMilestoneShellProjectionFlush(basePath, issue, reRendered)) {
516
+ issues.splice(i, 1);
517
+ continue;
518
+ }
519
+ if (issue.code === "artifact_file_missing" && issue.file && artifactExistsOnDisk(basePath, issue.file)) {
520
+ issues.splice(i, 1);
521
+ }
522
+ }
523
+ }
296
524
  }
@@ -408,6 +408,9 @@ export async function checkRuntimeHealth(
408
408
  if (!existingLines.has(".gsd-worktrees/") && !existingLines.has(".gsd-worktrees")) {
409
409
  missing.push(".gsd-worktrees/");
410
410
  }
411
+ if (!existingLines.has(".gsd-backups/") && !existingLines.has(".gsd-backups")) {
412
+ missing.push(".gsd-backups/");
413
+ }
411
414
  if (!hasBlanketIgnore) {
412
415
  missing.push(...criticalPatterns.filter(p => !existingLines.has(p)));
413
416
  }
@@ -84,10 +84,13 @@ export type DoctorIssueCode =
84
84
  | "db_orphaned_task"
85
85
  | "db_orphaned_slice"
86
86
  | "db_done_task_no_summary"
87
+ | "artifact_file_missing"
87
88
  | "artifact_db_status_divergence"
89
+ | "checkbox_db_status_divergence"
88
90
  | "completed_milestone_reopened"
89
91
  | "db_duplicate_id"
90
92
  | "db_unavailable"
93
+ | "memories_fts_rebuild_missing"
91
94
  | "projection_drift"
92
95
  // Milestone filesystem/DB drift (#4996)
93
96
  | "orphan_milestone_dir"
@@ -12,7 +12,7 @@ import { spawn } from "node:child_process";
12
12
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
13
13
  import { randomUUID } from "node:crypto";
14
14
  import { resolve } from "node:path";
15
- import { killProcessTree, SIGKILL_GRACE_MS, HARD_DEADLINE_MS } from "@gsd/pi-coding-agent";
15
+ import { getShellConfig, killProcessTree, SIGKILL_GRACE_MS, HARD_DEADLINE_MS } from "@gsd/pi-coding-agent";
16
16
 
17
17
  export interface ExecSandboxRequest {
18
18
  /** Interpreter to use. */
@@ -138,7 +138,12 @@ function clampTimeout(request: ExecSandboxRequest, opts: ExecSandboxOptions): nu
138
138
  function resolveCommand(runtime: ExecSandboxRequest["runtime"]): { cmd: string; args: string[] } {
139
139
  switch (runtime) {
140
140
  case "bash":
141
- return { cmd: "bash", args: ["-c"] };
141
+ try {
142
+ const { shell, args } = getShellConfig();
143
+ return { cmd: shell, args };
144
+ } catch {
145
+ return { cmd: "bash", args: ["-c"] };
146
+ }
142
147
  case "node":
143
148
  return { cmd: process.execPath, args: ["-e"] };
144
149
  case "python":
@@ -70,6 +70,50 @@ export function needsFlatPhaseMigration(basePath: string): boolean {
70
70
  return hasLegacyMilestoneSubdirs(legacyMigratingPath(basePath));
71
71
  }
72
72
 
73
+ /** Retention window before flat-phase migration backups are auto-pruned. */
74
+ export const FLAT_PHASE_BACKUP_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
75
+
76
+ /**
77
+ * Remove stale flat-phase migration backups after the retention window.
78
+ * Only runs when migration is complete (.gsd/phases/ exists, legacy layout gone).
79
+ * Returns the number of migrate-* directories removed.
80
+ */
81
+ export function pruneStaleFlatPhaseBackups(basePath: string): number {
82
+ if (needsFlatPhaseMigration(basePath)) return 0;
83
+
84
+ const phasesPath = join(basePath, ".gsd", LAYOUT_SEGMENTS.level1);
85
+ if (!existsSync(phasesPath)) return 0;
86
+
87
+ const backupRoot = join(basePath, ".gsd-backups");
88
+ if (!existsSync(backupRoot)) return 0;
89
+
90
+ const now = Date.now();
91
+ let removed = 0;
92
+ for (const entry of readdirSync(backupRoot)) {
93
+ if (!entry.startsWith("migrate-")) continue;
94
+ const dirPath = join(backupRoot, entry);
95
+ try {
96
+ const st = statSync(dirPath);
97
+ if (!st.isDirectory()) continue;
98
+ if (now - st.mtimeMs < FLAT_PHASE_BACKUP_RETENTION_MS) continue;
99
+ rmSync(dirPath, { recursive: true, force: true });
100
+ removed++;
101
+ } catch {
102
+ // Non-fatal: leave backup for manual recovery.
103
+ }
104
+ }
105
+
106
+ try {
107
+ if (readdirSync(backupRoot).length === 0) {
108
+ rmSync(backupRoot, { recursive: true, force: true });
109
+ }
110
+ } catch {
111
+ // Non-fatal.
112
+ }
113
+
114
+ return removed;
115
+ }
116
+
73
117
  /**
74
118
  * Migrate from legacy nested .gsd/milestones/ to flat-phase .gsd/phases/.
75
119
  *