@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
@@ -33,8 +33,8 @@ import { logWarning } from "./workflow-logger.js";
33
33
  * decision is checked individually; only decisions whose id is already
34
34
  * present in the memory store are skipped. A user-authored memory with
35
35
  * their own `sourceDecisionId` does NOT abort the backfill.
36
- * - Best-effort: never throws. Logs and returns 0 on failure so a broken
37
- * backfill cannot block agent startup.
36
+ * - Best-effort: never throws. Failed memory inserts are logged and skipped;
37
+ * setup/read failures log and return 0 so backfill cannot block startup.
38
38
  * - Full migration (ADR-013 Stage 2a): both active and superseded rows are
39
39
  * migrated. `structured_fields.superseded_by` preserves the supersedes
40
40
  * chain so the DECISIONS.md projection regen can source from memories
@@ -117,25 +117,32 @@ export function backfillDecisionsToMemories() {
117
117
  continue;
118
118
  }
119
119
  const content = synthesizeDecisionMemoryContent(row);
120
- const id = createMemory({
121
- category: "architecture",
122
- content,
123
- scope: row.scope || "project",
124
- confidence: 0.85,
125
- structuredFields: {
126
- sourceDecisionId: row.id,
127
- when_context: row.when_context,
128
- scope: row.scope,
129
- decision: row.decision,
130
- choice: row.choice,
131
- rationale: row.rationale,
132
- made_by: row.made_by,
133
- revisable: row.revisable,
134
- superseded_by: row.superseded_by,
135
- },
136
- });
137
- if (id)
138
- written += 1;
120
+ try {
121
+ const id = createMemory({
122
+ category: "architecture",
123
+ content,
124
+ scope: row.scope || "project",
125
+ confidence: 0.85,
126
+ structuredFields: {
127
+ sourceDecisionId: row.id,
128
+ when_context: row.when_context,
129
+ scope: row.scope,
130
+ decision: row.decision,
131
+ choice: row.choice,
132
+ rationale: row.rationale,
133
+ made_by: row.made_by,
134
+ revisable: row.revisable,
135
+ superseded_by: row.superseded_by,
136
+ },
137
+ });
138
+ if (id)
139
+ written += 1;
140
+ }
141
+ catch (rowErr) {
142
+ const message = rowErr instanceof Error ? rowErr.message : String(rowErr);
143
+ logWarning("memory-backfill", `decisions->memories backfill skipped ${row.id}: ${message}`);
144
+ continue;
145
+ }
139
146
  }
140
147
  if (healed > 0) {
141
148
  logWarning("memory-backfill", `decisions->memories drift healed: ${healed} row${healed === 1 ? "" : "s"} updated superseded_by`);
@@ -17,7 +17,7 @@ import { join } from "node:path";
17
17
  import { openSync, closeSync, unlinkSync, statSync, writeFileSync } from "node:fs";
18
18
  import { gsdRoot } from "./paths.js";
19
19
  import { getAndClearSkills } from "./skill-telemetry.js";
20
- import { loadJsonFile, loadJsonFileOrNull, saveJsonFile } from "./json-persistence.js";
20
+ import { loadJsonFile, loadJsonFileOrNull, saveJsonFileCompact } from "./json-persistence.js";
21
21
  import { parseUnitId } from "./unit-id.js";
22
22
  import { buildAuditEnvelope, emitUokAuditEvent } from "./uok/audit.js";
23
23
  import { isUnifiedAuditEnabled } from "./uok/audit-toggle.js";
@@ -636,7 +636,7 @@ export function pruneMetricsLedger(base, keepCount) {
636
636
  return 0;
637
637
  const removed = disk.units.length - keepCount;
638
638
  disk.units = keepNewestUnits(disk.units, keepCount);
639
- saveJsonFile(metricsPath(base), disk);
639
+ saveJsonFileCompact(metricsPath(base), disk);
640
640
  // Keep the in-memory ledger in sync if it is loaded for this session.
641
641
  if (ledger) {
642
642
  ledger.units = keepNewestUnits(ledger.units, keepCount);
@@ -799,7 +799,7 @@ function saveLedger(base, data) {
799
799
  : dataUnits;
800
800
  merged.sort(compareUnitsByTime);
801
801
  data.units = keepNewestUnits(merged);
802
- saveJsonFile(path, data);
802
+ saveJsonFileCompact(path, data);
803
803
  }
804
804
  finally {
805
805
  releaseLock(lockPath);
@@ -813,6 +813,6 @@ function saveLedger(base, data) {
813
813
  // read-merge-write sequence without mutual exclusion.
814
814
  logWarning("fs", "saveLedger: lock not acquired — falling back to direct write (no merge)");
815
815
  data.units = keepNewestUnits(data.units);
816
- saveJsonFile(path, data);
816
+ saveJsonFileCompact(path, data);
817
817
  }
818
818
  }
@@ -110,6 +110,7 @@ export function migrateToExternalState(basePath) {
110
110
  }
111
111
  // Copy contents to external dir, skipping worktrees/
112
112
  const entries = readdirSync(migratingPath, { withFileTypes: true });
113
+ const copyFailures = [];
113
114
  for (const entry of entries) {
114
115
  if (entry.name === "worktrees")
115
116
  continue; // worktrees stay local
@@ -123,10 +124,18 @@ export function migrateToExternalState(basePath) {
123
124
  cpSync(src, dst, { force: true });
124
125
  }
125
126
  }
126
- catch {
127
- // Non-fatal: continue with other files
127
+ catch (copyErr) {
128
+ copyFailures.push(`${entry.name}: ${getErrorMessage(copyErr)}`);
128
129
  }
129
130
  }
131
+ if (copyFailures.length > 0) {
132
+ try {
133
+ rmSync(localGsd, { force: true });
134
+ }
135
+ catch { /* may not exist */ }
136
+ renameSync(migratingPath, localGsd);
137
+ return { migrated: false, error: `Migration copy failed: ${copyFailures.join("; ")}` };
138
+ }
130
139
  // Create symlink .gsd -> external path
131
140
  symlinkSync(externalPath, localGsd, "junction");
132
141
  // Verify the symlink resolves correctly before removing the backup (#1377).
@@ -26,16 +26,78 @@ function _isAlreadyRestoredApplyError(err) {
26
26
  return /already exists, no checkout/i.test(message);
27
27
  }
28
28
  export { _isAlreadyRestoredApplyError };
29
+ function gitOutput(basePath, args) {
30
+ return execFileSync("git", args, {
31
+ cwd: basePath,
32
+ stdio: ["ignore", "pipe", "pipe"],
33
+ encoding: "utf-8",
34
+ env: GIT_NO_PROMPT_ENV,
35
+ });
36
+ }
37
+ function listStashUntrackedPaths(basePath, stashRef) {
38
+ try {
39
+ return gitOutput(basePath, ["ls-tree", "-r", "-z", "--name-only", `${stashRef}^3`]).split("\0").filter(Boolean);
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ function listStashTrackedPaths(basePath, stashRef) {
46
+ try {
47
+ return gitOutput(basePath, ["diff", "--name-only", "-z", `${stashRef}^1`, stashRef]).split("\0").filter(Boolean);
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ function readWorkingTreeStatus(basePath) {
54
+ try {
55
+ return gitOutput(basePath, ["status", "--porcelain", "-z", "--untracked-files=all"])
56
+ .split("\0")
57
+ .filter(Boolean)
58
+ .map((entry) => ({ code: entry.slice(0, 2), path: entry.slice(3) }));
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ function isAlreadyRestoredUntrackedStatus(basePath, stashRef, statusEntries) {
65
+ if (statusEntries.length === 0 || statusEntries.some((entry) => entry.code !== "??"))
66
+ return false;
67
+ const stashTrackedPaths = listStashTrackedPaths(basePath, stashRef);
68
+ if (!stashTrackedPaths || stashTrackedPaths.length > 0)
69
+ return false;
70
+ const stashUntrackedPaths = listStashUntrackedPaths(basePath, stashRef);
71
+ if (!stashUntrackedPaths || stashUntrackedPaths.length === 0)
72
+ return false;
73
+ const stashUntrackedPathSet = new Set(stashUntrackedPaths);
74
+ const workingTreeUntrackedPathSet = new Set(statusEntries.map((entry) => entry.path));
75
+ // "Already restored" requires the working tree's untracked paths to match the
76
+ // stash's untracked paths exactly, in BOTH directions:
77
+ // 1. every current untracked path comes from the stash (no unexplained user
78
+ // work that an apply would clobber), AND
79
+ // 2. every stash untracked path is already present in the working tree.
80
+ // Without (2), a partial restore (where only some stash files were recovered)
81
+ // would be misread as fully restored: the audit would no-op without applying
82
+ // or warning, leaving the remaining pre-merge files missing.
83
+ return (statusEntries.every((entry) => stashUntrackedPathSet.has(entry.path)) &&
84
+ stashUntrackedPaths.every((path) => workingTreeUntrackedPathSet.has(path)));
85
+ }
86
+ function manualApplyWarning(stashRef, milestoneId, reason) {
87
+ return (`Pre-merge stash ${stashRef} for milestone ${milestoneId} not auto-applied: ${reason}; ` +
88
+ `run \`git stash apply ${stashRef}\` manually to restore your pre-merge changes.`);
89
+ }
29
90
  /**
30
91
  * Audit `git stash list` for orphaned `gsd-preflight-stash:M00x:*` entries.
31
92
  *
32
93
  * The matching merge code in `phases.ts` previously skipped the postflight
33
94
  * pop whenever `mergeAndExit` threw, leaking the user's pre-merge working
34
- * tree into the stash list. For every preflight-stash entry whose milestone
35
- * is now complete (per the supplied callback), `git stash apply` is invoked
95
+ * tree into the stash list. Completed-milestone stashes are only auto-applied
96
+ * when the working tree is clean and the stash does not modify tracked files.
97
+ * Dirty trees and tracked-file stashes are left untouched with a manual
98
+ * recovery warning. When auto-apply is safe, `git stash apply` is invoked —
36
99
  * NOT `pop`. The stash entry stays in the list so the user retains a backup
37
- * if the apply produces unexpected merge results. Idempotent across repeated
38
- * startup runs.
100
+ * if the apply produces unexpected merge results.
39
101
  *
40
102
  * Failures are best-effort: a list error (no repo, git unavailable) returns
41
103
  * an empty result. An apply error becomes a warning the user sees alongside
@@ -45,12 +107,7 @@ export function auditOrphanedPreflightStashes(basePath, isMilestoneComplete) {
45
107
  const result = { applied: [], warnings: [] };
46
108
  let listOutput;
47
109
  try {
48
- listOutput = execFileSync("git", ["stash", "list", "--format=%gd%x00%s"], {
49
- cwd: basePath,
50
- stdio: ["ignore", "pipe", "pipe"],
51
- encoding: "utf-8",
52
- env: GIT_NO_PROMPT_ENV,
53
- });
110
+ listOutput = gitOutput(basePath, ["stash", "list", "--format=%gd%x00%s"]);
54
111
  }
55
112
  catch {
56
113
  return result;
@@ -78,13 +135,32 @@ export function auditOrphanedPreflightStashes(basePath, isMilestoneComplete) {
78
135
  }
79
136
  if (!complete)
80
137
  continue;
138
+ const statusEntries = readWorkingTreeStatus(basePath);
139
+ if (!statusEntries) {
140
+ result.warnings.push(manualApplyWarning(ref, milestoneId, "could not verify working tree status"));
141
+ continue;
142
+ }
143
+ if (statusEntries.length > 0) {
144
+ if (isAlreadyRestoredUntrackedStatus(basePath, ref, statusEntries))
145
+ continue;
146
+ result.warnings.push(manualApplyWarning(ref, milestoneId, "working tree not clean"));
147
+ continue;
148
+ }
149
+ const trackedPaths = listStashTrackedPaths(basePath, ref);
150
+ if (trackedPaths === null) {
151
+ result.warnings.push(manualApplyWarning(ref, milestoneId, "could not inspect tracked paths in stash"));
152
+ continue;
153
+ }
154
+ if (trackedPaths.length > 0) {
155
+ // A retained tracked-file stash has no durable marker showing whether a
156
+ // clean tree needs first recovery or would be re-mutated by an old backup.
157
+ const preview = trackedPaths.slice(0, 5).join(", ");
158
+ const suffix = trackedPaths.length > 5 ? `, and ${trackedPaths.length - 5} more` : "";
159
+ result.warnings.push(manualApplyWarning(ref, milestoneId, `stash modifies tracked files (${preview}${suffix})`));
160
+ continue;
161
+ }
81
162
  try {
82
- execFileSync("git", ["stash", "apply", "--quiet", ref], {
83
- cwd: basePath,
84
- stdio: ["ignore", "pipe", "pipe"],
85
- encoding: "utf-8",
86
- env: GIT_NO_PROMPT_ENV,
87
- });
163
+ gitOutput(basePath, ["stash", "apply", "--quiet", ref]);
88
164
  result.applied.push({ milestoneId, stashRef: ref });
89
165
  }
90
166
  catch (err) {
@@ -104,8 +104,8 @@ If the preference is off, ignore this section and plan every slice fully.
104
104
 
105
105
  If the roadmap has one slice, also plan S01 and its tasks inline:
106
106
 
107
- 1. After `gsd_plan_milestone` returns, call `gsd_plan_slice` for S01 with full task breakdown.
108
- 2. Use inlined **Slice Plan** and **Task Plan** templates for tool parameters.
107
+ 1. After `gsd_plan_milestone` returns, call `gsd_plan_slice` for S01 with slice metadata only; omit `tasks`.
108
+ 2. Then call `gsd_plan_task` once per S01 task. Use inlined **Slice Plan** and **Task Plan** templates for tool parameters.
109
109
  3. Keep simple slices lean. Omit Proof Level, Integration Closure, and Observability if all would be "none"; executable verification commands are enough.
110
110
 
111
111
  Do **not** write plan files manually; use DB-backed tools so state stays consistent.
@@ -45,8 +45,8 @@ If slice research is inlined, trust its architectural findings, but verify every
45
45
  6. Include Threat Surface (Q3), Requirement Impact (Q4), proof level, observability, integration closure, Failure Modes (Q5), Load Profile (Q6), and Negative Tests (Q7) only where applicable.
46
46
  7. Right-size tasks. Simple slices can be one task; split only when context, ownership, or verification boundaries justify it.
47
47
  8. Task `verify` commands must be safe, simple commands. Do not use shell pipes, redirects, semicolons, backticks, command substitution, output trimming, or grep regex alternation with `|`. If multiple checks are needed, create a small test file and run it with `node --test` or a package test script, or use separate simple commands joined only with `&&`. For absence checks, verify a pattern does not exist with `! grep -q 'pattern' file` or `! rg -q 'pattern' file`; do not use `grep -c` or `rg -c` to assert zero matches because count commands exit 1 when they find zero matches, and the verification gate treats that as failure.
48
- 9. Each task needs the exact `gsd_plan_slice.tasks[]` shape: `taskId`, `title`, `description`, `estimate`, `files`, `verify`, `inputs`, `expectedOutput`, and optional `observabilityImpact`. `description` should contain the Why / Do / Done-when narrative. `files`, `inputs`, and `expectedOutput` must be JSON arrays of strings, even when there is only one path (for example, `"inputs": ["src/index.ts"]`, never `"inputs": "src/index.ts"`). Use paths relative to `{{workingDirectory}}`; do not put absolute paths to the original checkout or any directory outside `{{workingDirectory}}` in `files`, `inputs`, `expectedOutput`, or verification commands. **`expectedOutput` must only list files the task actually creates or overwrites on disk.** Do NOT include files the task merely reads, verifies, tests, or describes — those belong in `inputs`, `verify`, `description`, or slice success criteria. If a task is a pure verification or test task that produces no new files, `expectedOutput` must be `[]`; if it writes a test-result log or assertion output file, list only that concrete file path. A file that does not yet exist on disk and is needed as an `input` must be produced by an earlier task's `expectedOutput` — if no prior task creates it, add a task before this one that does. Never list GSD planning artifacts — anything under `.gsd/`, `.planning/`, or `.audits/`, or artifact names like `M001-CONTEXT.md` / `S01-PLAN.md` — in `inputs`, `files`, or `expectedOutput`: their content is preloaded as context, and they are written by workflow tools, not by tasks.
49
- 10. Persist with `gsd_plan_slice` using `milestoneId`, `sliceId`, `goal`, optional `successCriteria`/`proofLevel`/`integrationClosure`/`observabilityImpact`, and `tasks`. `gsd_plan_slice` handles task persistence transactionally and renders `{{outputPath}}` plus task plans; do not call `gsd_plan_task`. The DB-backed tool is the canonical write path. Do **not** rely on direct `PLAN.md` writes as the source of truth.
48
+ 9. Each task persisted with `gsd_plan_task` needs the exact shape: `milestoneId`, `sliceId`, `taskId`, `title`, `description`, `estimate`, `files`, `verify`, `inputs`, `expectedOutput`, and optional `observabilityImpact`. `description` should contain the Why / Do / Done-when narrative. Any npm package name in a task description's install/add instructions (`npm install`, `yarn add`, `pnpm add`) or in `require('...')` or `import ... from '...'` code examples is subject to pre-execution registry validation; reference only packages that exist on the public npm registry, and remove or correct any package name that is not real. `files`, `inputs`, and `expectedOutput` must be JSON arrays of strings, even when there is only one path (for example, `"inputs": ["src/index.ts"]`, never `"inputs": "src/index.ts"`). Use paths relative to `{{workingDirectory}}`; do not put absolute paths to the original checkout or any directory outside `{{workingDirectory}}` in `files`, `inputs`, `expectedOutput`, or verification commands. **`expectedOutput` must only list files the task actually creates or overwrites on disk.** Do NOT include files the task merely reads, verifies, tests, or describes — those belong in `inputs`, `verify`, `description`, or slice success criteria. If a task is a pure verification or test task that produces no new files, `expectedOutput` must be `[]`; if it writes a test-result log or assertion output file, list only that concrete file path. A file that does not yet exist on disk and is needed as an `input` must be produced by an earlier task's `expectedOutput` — if no prior task creates it, add a task before this one that does. Never list GSD planning artifacts — anything under `.gsd/`, `.planning/`, or `.audits/`, or artifact names like `M001-CONTEXT.md` / `S01-PLAN.md` — in `inputs`, `files`, or `expectedOutput`: their content is preloaded as context, and they are written by workflow tools, not by tasks.
49
+ 10. Persist incrementally through DB-backed tools. First call `gsd_plan_slice` with `milestoneId`, `sliceId`, `goal`, and optional `successCriteria`/`proofLevel`/`integrationClosure`/`observabilityImpact`; omit `tasks` for this metadata call. Then call `gsd_plan_task` once per task, using the task shape above. Each successful tool call saves progress and re-renders `{{outputPath}}` from DB. The DB-backed tools are the canonical write path. Do **not** rely on direct `PLAN.md` writes as the source of truth.
50
50
  11. Self-audit before finishing: goal/demo closure, requirement coverage, deliverable coverage audit (cross-check every file listed in CONTEXT.md `## Scope` / `### In Scope` against task `files` or `expectedOutput`), locked decisions, concrete paths, dependency order, wiring, scope size, proof truthfulness, feature completeness, and quality gates. Quality gates: non-trivial slices/tasks include specific Q3-Q7 coverage where applicable.
51
51
  12. If planning creates structural decisions, call `gsd_decision_save` for each; the tool persists the decision and regenerates `.gsd/DECISIONS.md`.
52
52
  13. {{commitInstruction}}
@@ -55,6 +55,6 @@ The slice directory already exists. Do not mkdir.
55
55
 
56
56
  **Autonomous execution:** no human is available. Do not call `ask_user_questions` or `secure_env_collect`; make reasonable assumptions and document them.
57
57
 
58
- **You MUST call `gsd_plan_slice` to persist planning state before finishing, unless the stale-path safety rule above stops the unit before safe planning can occur.**
58
+ **You MUST call `gsd_plan_slice` and then `gsd_plan_task` once for each planned task before finishing, unless the stale-path safety rule above stops the unit before safe planning can occur.**
59
59
 
60
60
  When done, say: "Slice {{sliceId}} planned." Say this exactly once — if you already said it in a prior message, do not repeat it.
@@ -4,9 +4,15 @@ import { execFileSync } from "node:child_process";
4
4
  import { createHash } from "node:crypto";
5
5
  import { existsSync, readFileSync, statSync } from "node:fs";
6
6
  import { join } from "node:path";
7
+ import { GSD_RUNTIME_PATTERNS } from "./gitignore.js";
7
8
  const MAX_SYNC_FINGERPRINT_BYTES = 1_500_000_000;
9
+ const ROOT_RUNTIME_PATH_PREFIXES = Array.from(new Set(GSD_RUNTIME_PATTERNS.map((pattern) => {
10
+ const path = pattern.replace(/\/+$/, "");
11
+ const slash = path.indexOf("/");
12
+ return slash === -1 ? path : path.slice(0, slash);
13
+ })));
8
14
  function isRootRuntimePath(path) {
9
- return path === ".gsd" || path.startsWith(".gsd/");
15
+ return ROOT_RUNTIME_PATH_PREFIXES.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
10
16
  }
11
17
  function fileFingerprint(rootPath, relPath) {
12
18
  const absPath = join(rootPath, relPath);
@@ -20,14 +20,21 @@ const DESTRUCTIVE_PATTERNS = [
20
20
  { pattern: /\baws\s+\w+\s+(delete|create|put|remove|terminate)\b/i, label: "AWS mutation" },
21
21
  { pattern: /\bkubectl\s+(delete|apply)\b/i, label: "kubectl mutation" },
22
22
  ];
23
+ function stripQuotedAndComments(command) {
24
+ return command
25
+ .replace(/"(?:[^"\\]|\\.)*"/g, '""')
26
+ .replace(/'(?:[^'\\]|\\.)*'/g, "''")
27
+ .replace(/(^|\s)#.*$/g, "$1");
28
+ }
23
29
  /**
24
30
  * Classify a bash command for destructive operations.
25
31
  * Returns the list of matched destructive pattern labels.
26
32
  */
27
33
  export function classifyCommand(command) {
34
+ const commandToClassify = stripQuotedAndComments(command);
28
35
  const labels = [];
29
36
  for (const { pattern, label } of DESTRUCTIVE_PATTERNS) {
30
- if (pattern.test(command)) {
37
+ if (pattern.test(commandToClassify)) {
31
38
  // Deduplicate labels (e.g., two force-push patterns)
32
39
  if (!labels.includes(label))
33
40
  labels.push(label);
@@ -27,10 +27,14 @@ const EXECUTION_TOOL_NAMES = new Set([
27
27
  const MCP_EXECUTION_TOOL_RE = /^mcp__.+__gsd_(?:uat_)?exec(?:_search)?$/;
28
28
  // ─── Module State ───────────────────────────────────────────────────────────
29
29
  let unitEvidence = [];
30
+ let lastWritePath = null;
31
+ let lastWriteSig = null;
30
32
  // ─── Public API ─────────────────────────────────────────────────────────────
31
33
  /** Reset all evidence for a new unit. Call at unit start. */
32
34
  export function resetEvidence() {
33
35
  unitEvidence = [];
36
+ lastWritePath = null;
37
+ lastWriteSig = null;
34
38
  }
35
39
  /** Get a read-only view of all evidence collected for the current unit. */
36
40
  export function getEvidence() {
@@ -95,10 +99,15 @@ function isEvidenceArray(data) {
95
99
  export function saveEvidenceToDisk(basePath, milestoneId, sliceId, taskId) {
96
100
  try {
97
101
  const path = evidencePath(basePath, milestoneId, sliceId, taskId);
102
+ const body = JSON.stringify(unitEvidence, null, 2) + "\n";
103
+ if (path === lastWritePath && body === lastWriteSig)
104
+ return;
98
105
  mkdirSync(dirname(path), { recursive: true });
99
106
  const tmp = `${path}.tmp.${randomBytes(4).toString("hex")}`;
100
- writeFileSync(tmp, JSON.stringify(unitEvidence, null, 2) + "\n", "utf-8");
107
+ writeFileSync(tmp, body, "utf-8");
101
108
  renameSync(tmp, path);
109
+ lastWritePath = path;
110
+ lastWriteSig = body;
102
111
  }
103
112
  catch {
104
113
  // Non-fatal — don't let persistence failures break unit execution
@@ -112,6 +121,8 @@ export function saveEvidenceToDisk(basePath, milestoneId, sliceId, taskId) {
112
121
  */
113
122
  export function loadEvidenceFromDisk(basePath, milestoneId, sliceId, taskId) {
114
123
  try {
124
+ lastWritePath = null;
125
+ lastWriteSig = null;
115
126
  const path = evidencePath(basePath, milestoneId, sliceId, taskId);
116
127
  if (!existsSync(path))
117
128
  return;
@@ -136,6 +147,10 @@ export function clearEvidenceFromDisk(basePath, milestoneId, sliceId, taskId) {
136
147
  if (existsSync(path)) {
137
148
  unlinkSync(path);
138
149
  }
150
+ if (path === lastWritePath) {
151
+ lastWritePath = null;
152
+ lastWriteSig = null;
153
+ }
139
154
  }
140
155
  catch {
141
156
  // Non-fatal
@@ -44,8 +44,11 @@ export function validateFileChanges(basePath, expectedOutput, plannedFiles, file
44
44
  const actualFiles = getChangedFilesFromLastCommit(basePath);
45
45
  if (!actualFiles)
46
46
  return null;
47
- // Filter out .gsd/ internal files — only validate project source files
48
- const projectFiles = actualFiles.filter(f => !f.startsWith(".gsd/") && !f.startsWith(".gsd\\"));
47
+ // Filter out GSD-internal paths — only validate project source files.
48
+ const projectFiles = actualFiles.filter((f) => !f.startsWith(".gsd/") &&
49
+ !f.startsWith(".gsd\\") &&
50
+ !f.startsWith(".gsd-backups/") &&
51
+ !f.startsWith(".gsd-backups\\"));
49
52
  // Normalize expected paths (strip leading ./ or /)
50
53
  const normalizedExpected = new Set([...allExpected].map((f) => normalizePlannedFileReference(f).replace(/^\.\//, "").replace(/^\//, "")));
51
54
  // Build allowlist matchers once (dot: true so patterns like `**/.hidden` work).
@@ -13,7 +13,7 @@ import { existsSync } from "node:fs";
13
13
  import { transaction, getMilestone, getMilestoneSlices, getSliceTasks, getLatestAssessmentByScope, updateMilestoneStatus, } from "../gsd-db.js";
14
14
  import { clearPathCache, relMilestoneFile } from "../paths.js";
15
15
  import { resolveCanonicalMilestoneRoot } from "../worktree-manager.js";
16
- import { isClosedStatus } from "../status-guards.js";
16
+ import { isClosedStatus, isDeferredStatus } from "../status-guards.js";
17
17
  import { saveFile, clearParseCache } from "../files.js";
18
18
  import { invalidateStateCache } from "../state.js";
19
19
  import { stripIdPrefix } from "../workflow-projections.js";
@@ -118,7 +118,7 @@ export async function handleCompleteMilestone(params, basePath) {
118
118
  guardError = `no slices found for milestone ${params.milestoneId}`;
119
119
  return;
120
120
  }
121
- const incompleteSlices = slices.filter(s => !isClosedStatus(s.status));
121
+ const incompleteSlices = slices.filter(s => !isClosedStatus(s.status) && !isDeferredStatus(s.status));
122
122
  if (incompleteSlices.length > 0) {
123
123
  const incompleteIds = incompleteSlices.map(s => `${s.id} (status: ${s.status})`).join(", ");
124
124
  guardError = `incomplete slices: ${incompleteIds}`;
@@ -126,6 +126,8 @@ export async function handleCompleteMilestone(params, basePath) {
126
126
  }
127
127
  // Deep check: verify all tasks in all slices are complete
128
128
  for (const slice of slices) {
129
+ if (isDeferredStatus(slice.status))
130
+ continue;
129
131
  const tasks = getSliceTasks(params.milestoneId, slice.id);
130
132
  const incompleteTasks = tasks.filter(t => !isClosedStatus(t.status));
131
133
  if (incompleteTasks.length > 0) {
@@ -28,9 +28,13 @@ function validateRepositoryTargetIds(field, value) {
28
28
  return deduped;
29
29
  }
30
30
  function validateTasks(value) {
31
- if (!Array.isArray(value) || value.length === 0) {
32
- throw new Error("tasks must be a non-empty array");
31
+ if (value === undefined)
32
+ return undefined;
33
+ if (!Array.isArray(value)) {
34
+ throw new Error("tasks must be an array");
33
35
  }
36
+ if (value.length === 0)
37
+ return undefined;
34
38
  const seen = new Set();
35
39
  return value.map((entry, index) => {
36
40
  if (!entry || typeof entry !== "object") {
@@ -129,7 +133,7 @@ function validateReferencedRepositories(params, registry, defaultTargets) {
129
133
  };
130
134
  for (const id of params.targetRepositories ?? defaultTargets)
131
135
  noteMissing(id);
132
- for (const task of params.tasks) {
136
+ for (const task of params.tasks ?? []) {
133
137
  for (const id of task.targetRepositories ?? params.targetRepositories ?? defaultTargets)
134
138
  noteMissing(id);
135
139
  }
@@ -141,7 +145,7 @@ function resolveAllowedRootsForPathScope(params, registry, defaultTargets) {
141
145
  const requested = new Set();
142
146
  for (const id of params.targetRepositories ?? defaultTargets)
143
147
  requested.add(id);
144
- for (const task of params.tasks) {
148
+ for (const task of params.tasks ?? []) {
145
149
  for (const id of task.targetRepositories ?? params.targetRepositories ?? defaultTargets)
146
150
  requested.add(id);
147
151
  }
@@ -153,7 +157,7 @@ function resolveAllowedRootsForPathScope(params, registry, defaultTargets) {
153
157
  return roots.length > 0 ? roots : [registry.projectRoot];
154
158
  }
155
159
  function toTaskRows(params, defaultTargets) {
156
- return params.tasks.map((task, index) => ({
160
+ return (params.tasks ?? []).map((task, index) => ({
157
161
  milestone_id: params.milestoneId,
158
162
  slice_id: params.sliceId,
159
163
  id: task.taskId,
@@ -230,19 +234,21 @@ export async function handlePlanSlice(rawParams, basePath) {
230
234
  return { error: `validation failed: ${message}` };
231
235
  }
232
236
  const defaultTargets = defaultRepositoryTargets(repositoryRegistry);
237
+ const taskPayload = params.tasks ?? [];
238
+ const hasTaskPayload = taskPayload.length > 0;
233
239
  const repoValidationError = validateReferencedRepositories(params, repositoryRegistry, defaultTargets);
234
240
  if (repoValidationError) {
235
241
  return { error: `validation failed: ${repoValidationError}` };
236
242
  }
237
243
  const allowedAbsoluteRoots = resolveAllowedRootsForPathScope(params, repositoryRegistry, defaultTargets);
238
- const pathOnlyError = validatePathOnlyPlanningFields(params.tasks.map((task, index) => ({
244
+ const pathOnlyError = validatePathOnlyPlanningFields(taskPayload.map((task, index) => ({
239
245
  field: `tasks[${index}].expectedOutput`,
240
246
  values: task.expectedOutput,
241
247
  })));
242
248
  if (pathOnlyError) {
243
249
  return { error: `validation failed: ${pathOnlyError}` };
244
250
  }
245
- const pathScopeError = validatePlanningPathScope(basePath, params.tasks.flatMap((task, index) => [
251
+ const pathScopeError = validatePlanningPathScope(basePath, taskPayload.flatMap((task, index) => [
246
252
  { field: `tasks[${index}].files`, values: task.files },
247
253
  { field: `tasks[${index}].inputs`, values: task.inputs },
248
254
  { field: `tasks[${index}].expectedOutput`, values: task.expectedOutput },
@@ -279,15 +285,17 @@ export async function handlePlanSlice(rawParams, basePath) {
279
285
  guardError = `cannot re-plan slice ${params.sliceId}: it is already complete — use gsd_slice_reopen first`;
280
286
  return;
281
287
  }
282
- const newTaskIds = new Set(params.tasks.map((task) => task.taskId));
288
+ const newTaskIds = new Set(taskPayload.map((task) => task.taskId));
283
289
  const existingTasks = getSliceTasks(params.milestoneId, params.sliceId);
284
- omittedTaskIds = existingTasks
285
- .filter((task) => !newTaskIds.has(task.id))
286
- .map((task) => task.id);
287
- for (const task of existingTasks) {
288
- if (!newTaskIds.has(task.id) && isClosedStatus(task.status)) {
289
- guardError = `cannot remove completed task ${task.id}`;
290
- return;
290
+ if (hasTaskPayload) {
291
+ omittedTaskIds = existingTasks
292
+ .filter((task) => !newTaskIds.has(task.id))
293
+ .map((task) => task.id);
294
+ for (const task of existingTasks) {
295
+ if (!newTaskIds.has(task.id) && isClosedStatus(task.status)) {
296
+ guardError = `cannot remove completed task ${task.id}`;
297
+ return;
298
+ }
291
299
  }
292
300
  }
293
301
  if (isDeferredStatus(parentSlice.status)) {
@@ -301,34 +309,36 @@ export async function handlePlanSlice(rawParams, basePath) {
301
309
  observabilityImpact: params.observabilityImpact,
302
310
  targetRepositories: params.targetRepositories ?? defaultTargets,
303
311
  });
304
- for (const taskId of omittedTaskIds) {
305
- deleteTask(params.milestoneId, params.sliceId, taskId);
306
- }
307
- const existingTaskById = new Map(existingTasks.map((task) => [task.id, task]));
308
- for (const task of params.tasks) {
309
- const planning = {
310
- title: task.title,
311
- description: task.description,
312
- estimate: task.estimate,
313
- files: task.files,
314
- verify: task.verify,
315
- inputs: task.inputs,
316
- expectedOutput: task.expectedOutput,
317
- observabilityImpact: task.observabilityImpact ?? "",
318
- fullPlanMd: task.fullPlanMd,
319
- targetRepositories: task.targetRepositories ?? params.targetRepositories ?? defaultTargets,
320
- };
321
- const existingTask = existingTaskById.get(task.taskId);
322
- if (!existingTask || !isClosedStatus(existingTask.status)) {
323
- insertTask({
324
- id: task.taskId,
325
- sliceId: params.sliceId,
326
- milestoneId: params.milestoneId,
312
+ if (hasTaskPayload) {
313
+ for (const taskId of omittedTaskIds) {
314
+ deleteTask(params.milestoneId, params.sliceId, taskId);
315
+ }
316
+ const existingTaskById = new Map(existingTasks.map((task) => [task.id, task]));
317
+ for (const task of taskPayload) {
318
+ const planning = {
327
319
  title: task.title,
328
- status: "pending",
329
- });
320
+ description: task.description,
321
+ estimate: task.estimate,
322
+ files: task.files,
323
+ verify: task.verify,
324
+ inputs: task.inputs,
325
+ expectedOutput: task.expectedOutput,
326
+ observabilityImpact: task.observabilityImpact ?? "",
327
+ fullPlanMd: task.fullPlanMd,
328
+ targetRepositories: task.targetRepositories ?? params.targetRepositories ?? defaultTargets,
329
+ };
330
+ const existingTask = existingTaskById.get(task.taskId);
331
+ if (!existingTask || !isClosedStatus(existingTask.status)) {
332
+ insertTask({
333
+ id: task.taskId,
334
+ sliceId: params.sliceId,
335
+ milestoneId: params.milestoneId,
336
+ title: task.title,
337
+ status: "pending",
338
+ });
339
+ }
340
+ upsertTaskPlanning(params.milestoneId, params.sliceId, task.taskId, planning);
330
341
  }
331
- upsertTaskPlanning(params.milestoneId, params.sliceId, task.taskId, planning);
332
342
  }
333
343
  // Seed quality gate rows inside the transaction — all-or-nothing with
334
344
  // the plan data so a crash can't leave orphaned gates without tasks.
@@ -337,7 +347,7 @@ export async function handlePlanSlice(rawParams, basePath) {
337
347
  insertGateRow({ milestoneId: params.milestoneId, sliceId: params.sliceId, gateId: gid, scope: "slice" });
338
348
  }
339
349
  const taskGates = resolveTaskGates(gateEvaluation);
340
- for (const task of params.tasks) {
350
+ for (const task of taskPayload) {
341
351
  for (const gid of taskGates) {
342
352
  insertGateRow({ milestoneId: params.milestoneId, sliceId: params.sliceId, gateId: gid, scope: "task", taskId: task.taskId });
343
353
  }
@@ -360,8 +370,13 @@ export async function handlePlanSlice(rawParams, basePath) {
360
370
  const artifactPath = relative(gsdProjectionRoot(basePath), taskPlanPath).replace(/\\/g, "/");
361
371
  deleteArtifactByPath(artifactPath);
362
372
  }
363
- const renderResult = await renderPlanFromDb(basePath, params.milestoneId, params.sliceId);
364
- setSliceSketchFlag(params.milestoneId, params.sliceId, false);
373
+ const sliceTasks = getSliceTasks(params.milestoneId, params.sliceId);
374
+ const renderResult = sliceTasks.length === 0
375
+ ? { planPath: "", taskPlanPaths: [] }
376
+ : await renderPlanFromDb(basePath, params.milestoneId, params.sliceId);
377
+ if (sliceTasks.length > 0) {
378
+ setSliceSketchFlag(params.milestoneId, params.sliceId, false);
379
+ }
365
380
  invalidateStateCache();
366
381
  clearParseCache();
367
382
  // ── Post-mutation hook: manifest, event log ─────────────────────────