@opengsd/gsd-pi 1.3.0-dev.72e3af2a → 1.3.0-dev.965d1788

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 (110) hide show
  1. package/README.md +1 -1
  2. package/dist/resources/.managed-resources-content-hash +1 -1
  3. package/dist/resources/extensions/gsd/auto/verification-retry-policy.js +1 -1
  4. package/dist/resources/extensions/gsd/auto-post-unit.js +1 -1
  5. package/dist/resources/extensions/gsd/auto-verification.js +5 -2
  6. package/dist/resources/extensions/gsd/bootstrap/register-hooks.js +6 -0
  7. package/dist/resources/extensions/gsd/closeout-consistency-gate.js +3 -1
  8. package/dist/resources/extensions/gsd/doctor-runtime-checks.js +3 -0
  9. package/dist/resources/extensions/gsd/flat-phase-migration.js +45 -0
  10. package/dist/resources/extensions/gsd/git-service.js +1 -0
  11. package/dist/resources/extensions/gsd/gitignore.js +3 -0
  12. package/dist/resources/extensions/gsd/json-persistence.js +20 -0
  13. package/dist/resources/extensions/gsd/knowledge-backfill.js +18 -11
  14. package/dist/resources/extensions/gsd/memory-backfill.js +28 -21
  15. package/dist/resources/extensions/gsd/metrics.js +4 -4
  16. package/dist/resources/extensions/gsd/orphan-stash-audit.js +92 -16
  17. package/dist/resources/extensions/gsd/prompts/plan-slice.md +1 -1
  18. package/dist/resources/extensions/gsd/safety/file-change-validator.js +5 -2
  19. package/dist/resources/extensions/gsd/tools/complete-milestone.js +4 -2
  20. package/dist/resources/extensions/gsd/undo.js +43 -6
  21. package/dist/resources/extensions/gsd/verification-gate.js +7 -0
  22. package/dist/resources/extensions/gsd/workflow-manifest.js +4 -1
  23. package/dist/tsconfig.extensions.tsbuildinfo +1 -1
  24. package/dist/web/standalone/.next/BUILD_ID +1 -1
  25. package/dist/web/standalone/.next/app-path-routes-manifest.json +10 -10
  26. package/dist/web/standalone/.next/build-manifest.json +2 -2
  27. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  28. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  29. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  30. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  31. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  32. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  33. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  34. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  35. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  36. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  37. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  38. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  39. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  40. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  41. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  42. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  43. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  44. package/dist/web/standalone/.next/server/app/index.html +1 -1
  45. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  46. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  47. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  48. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  49. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  50. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  51. package/dist/web/standalone/.next/server/app-paths-manifest.json +10 -10
  52. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  53. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  54. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  55. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  56. package/package.json +1 -1
  57. package/packages/cloud-mcp-gateway/package.json +2 -2
  58. package/packages/contracts/package.json +1 -1
  59. package/packages/daemon/package.json +4 -4
  60. package/packages/gsd-agent-core/package.json +5 -5
  61. package/packages/gsd-agent-modes/package.json +7 -7
  62. package/packages/mcp-server/package.json +4 -4
  63. package/packages/native/package.json +1 -1
  64. package/packages/pi-agent-core/package.json +1 -1
  65. package/packages/pi-ai/package.json +1 -1
  66. package/packages/pi-coding-agent/package.json +7 -7
  67. package/packages/pi-tui/package.json +2 -2
  68. package/packages/rpc-client/package.json +2 -2
  69. package/pkg/package.json +1 -1
  70. package/src/resources/extensions/gsd/auto/session.ts +1 -0
  71. package/src/resources/extensions/gsd/auto/verification-retry-policy.ts +3 -1
  72. package/src/resources/extensions/gsd/auto-post-unit.ts +1 -1
  73. package/src/resources/extensions/gsd/auto-verification.ts +5 -1
  74. package/src/resources/extensions/gsd/bootstrap/register-hooks.ts +9 -0
  75. package/src/resources/extensions/gsd/closeout-consistency-gate.ts +2 -1
  76. package/src/resources/extensions/gsd/doctor-runtime-checks.ts +3 -0
  77. package/src/resources/extensions/gsd/flat-phase-migration.ts +44 -0
  78. package/src/resources/extensions/gsd/git-service.ts +1 -0
  79. package/src/resources/extensions/gsd/gitignore.ts +3 -0
  80. package/src/resources/extensions/gsd/json-persistence.ts +20 -0
  81. package/src/resources/extensions/gsd/knowledge-backfill.ts +16 -10
  82. package/src/resources/extensions/gsd/memory-backfill.ts +26 -20
  83. package/src/resources/extensions/gsd/metrics.ts +4 -4
  84. package/src/resources/extensions/gsd/orphan-stash-audit.ts +108 -20
  85. package/src/resources/extensions/gsd/prompts/plan-slice.md +1 -1
  86. package/src/resources/extensions/gsd/safety/file-change-validator.ts +8 -2
  87. package/src/resources/extensions/gsd/tests/artifact-retry-cap.test.ts +4 -3
  88. package/src/resources/extensions/gsd/tests/complete-milestone.test.ts +28 -0
  89. package/src/resources/extensions/gsd/tests/complete-slice-reopen-handoff.test.ts +69 -0
  90. package/src/resources/extensions/gsd/tests/decisions-projection-from-memories.test.ts +51 -0
  91. package/src/resources/extensions/gsd/tests/file-change-validator.test.ts +40 -0
  92. package/src/resources/extensions/gsd/tests/flat-phase-migration.test.ts +37 -2
  93. package/src/resources/extensions/gsd/tests/gitignore-bg-shell-runtime.test.ts +4 -0
  94. package/src/resources/extensions/gsd/tests/integration/git-service.test.ts +11 -2
  95. package/src/resources/extensions/gsd/tests/json-persistence-atomic.test.ts +47 -0
  96. package/src/resources/extensions/gsd/tests/knowledge-backfill-projection.test.ts +35 -0
  97. package/src/resources/extensions/gsd/tests/merge-closeout-consistency-gate.test.ts +31 -1
  98. package/src/resources/extensions/gsd/tests/metrics-prune-cache-invalidation.test.ts +6 -0
  99. package/src/resources/extensions/gsd/tests/metrics.test.ts +1 -0
  100. package/src/resources/extensions/gsd/tests/orphan-stash-audit.test.ts +91 -7
  101. package/src/resources/extensions/gsd/tests/plan-slice-prompt.test.ts +10 -0
  102. package/src/resources/extensions/gsd/tests/undo.test.ts +74 -0
  103. package/src/resources/extensions/gsd/tests/verification-retry-policy.test.ts +69 -4
  104. package/src/resources/extensions/gsd/tests/workflow-manifest.test.ts +54 -0
  105. package/src/resources/extensions/gsd/tools/complete-milestone.ts +3 -2
  106. package/src/resources/extensions/gsd/undo.ts +47 -6
  107. package/src/resources/extensions/gsd/verification-gate.ts +8 -0
  108. package/src/resources/extensions/gsd/workflow-manifest.ts +4 -1
  109. /package/dist/web/standalone/.next/static/{O7xDYXO0r4zFhIzY1hrWV → -ji77QJck2IKIwrGza1Bs}/_buildManifest.js +0 -0
  110. /package/dist/web/standalone/.next/static/{O7xDYXO0r4zFhIzY1hrWV → -ji77QJck2IKIwrGza1Bs}/_ssgManifest.js +0 -0
@@ -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
  *
@@ -360,6 +360,7 @@ export interface PreMergeCheckResult {
360
360
  */
361
361
  export const RUNTIME_EXCLUSION_PATHS: readonly string[] = [
362
362
  ".gsd-worktrees/",
363
+ ".gsd-backups/**",
363
364
  ".gsd/activity/",
364
365
  ".gsd/audit/",
365
366
  ".gsd/forensics/",
@@ -26,6 +26,7 @@ import { GIT_NO_PROMPT_ENV } from "./git-constants.js";
26
26
  */
27
27
  const GSD_RUNTIME_PATTERNS = [
28
28
  ".gsd-worktrees/",
29
+ ".gsd-backups/",
29
30
  ".gsd/activity/",
30
31
  ".gsd/audit/",
31
32
  ".gsd/forensics/",
@@ -51,6 +52,8 @@ const BASELINE_PATTERNS = [
51
52
  ".gsd",
52
53
  // Worktree container sibling — NOT covered by the ".gsd" pattern above.
53
54
  ".gsd-worktrees/",
55
+ // Flat-phase migration snapshots — NOT covered by the ".gsd" pattern above.
56
+ ".gsd-backups/",
54
57
  ".gsd-id",
55
58
  ".mcp.json",
56
59
  ".bg-shell/",
@@ -62,6 +62,26 @@ export function saveJsonFile<T>(filePath: string, data: T): void {
62
62
  }
63
63
  }
64
64
 
65
+ /**
66
+ * Save a JSON file atomically using compact serialization.
67
+ *
68
+ * Intended for machine-only ledgers where pretty-printing has no consumer.
69
+ * Keeps the same write-tmp-rename safety and non-fatal error behavior as
70
+ * saveJsonFile.
71
+ */
72
+ export function saveJsonFileCompact<T>(filePath: string, data: T): void {
73
+ try {
74
+ mkdirSync(dirname(filePath), { recursive: true });
75
+ // Use randomized tmp suffix to prevent concurrent-write data loss
76
+ const tmp = `${filePath}.tmp.${randomBytes(4).toString("hex")}`;
77
+ writeFileSync(tmp, JSON.stringify(data) + "\n", "utf-8");
78
+ renameSync(tmp, filePath);
79
+ // No cleanup needed — renameSync atomically removes tmp on success
80
+ } catch {
81
+ // Non-fatal — don't let persistence failures break operation
82
+ }
83
+ }
84
+
65
85
  /**
66
86
  * Write a JSON file atomically (write to .tmp, then rename).
67
87
  * Creates parent directories as needed. Non-fatal on error.
@@ -35,8 +35,8 @@ interface SynthesizedRow {
35
35
  * - Idempotent (per-row): each migrated memory carries
36
36
  * `structured_fields.sourceKnowledgeId = "<P|L>NNN"`. Rows whose ID is
37
37
  * already present in the memory store are skipped.
38
- * - Best-effort: never throws. Logs and returns 0 on failure so a broken
39
- * backfill cannot block agent startup.
38
+ * - Best-effort: never throws. Failed memory inserts are logged and skipped;
39
+ * setup/read failures log and return 0 so backfill cannot block startup.
40
40
  * - Rules (K###) are intentionally skipped — they remain manually maintained
41
41
  * in `KNOWLEDGE.md` per ADR-013.
42
42
  *
@@ -69,14 +69,20 @@ export function backfillKnowledgeToMemories(basePath: string): number {
69
69
  const matchPattern = `%"sourceKnowledgeId":"${synth.id}"%`;
70
70
  if (checkExisting.get({ ":pattern": matchPattern })) continue;
71
71
 
72
- const id = createMemory({
73
- category: synth.category,
74
- content: synth.content,
75
- scope: synth.scope,
76
- confidence: 0.85,
77
- structuredFields: synth.structuredFields,
78
- });
79
- if (id) written += 1;
72
+ try {
73
+ const id = createMemory({
74
+ category: synth.category,
75
+ content: synth.content,
76
+ scope: synth.scope,
77
+ confidence: 0.85,
78
+ structuredFields: synth.structuredFields,
79
+ });
80
+ if (id) written += 1;
81
+ } catch (rowErr) {
82
+ const message = rowErr instanceof Error ? rowErr.message : String(rowErr);
83
+ logWarning("knowledge-backfill", `KNOWLEDGE.md -> memories backfill skipped ${synth.id}: ${message}`);
84
+ continue;
85
+ }
80
86
  }
81
87
 
82
88
  return written;
@@ -49,8 +49,8 @@ type DecisionContentFields = Pick<DecisionRow, "decision" | "choice" | "rational
49
49
  * decision is checked individually; only decisions whose id is already
50
50
  * present in the memory store are skipped. A user-authored memory with
51
51
  * their own `sourceDecisionId` does NOT abort the backfill.
52
- * - Best-effort: never throws. Logs and returns 0 on failure so a broken
53
- * backfill cannot block agent startup.
52
+ * - Best-effort: never throws. Failed memory inserts are logged and skipped;
53
+ * setup/read failures log and return 0 so backfill cannot block startup.
54
54
  * - Full migration (ADR-013 Stage 2a): both active and superseded rows are
55
55
  * migrated. `structured_fields.superseded_by` preserves the supersedes
56
56
  * chain so the DECISIONS.md projection regen can source from memories
@@ -146,24 +146,30 @@ export function backfillDecisionsToMemories(): number {
146
146
  }
147
147
 
148
148
  const content = synthesizeDecisionMemoryContent(row);
149
- const id = createMemory({
150
- category: "architecture",
151
- content,
152
- scope: row.scope || "project",
153
- confidence: 0.85,
154
- structuredFields: {
155
- sourceDecisionId: row.id,
156
- when_context: row.when_context,
157
- scope: row.scope,
158
- decision: row.decision,
159
- choice: row.choice,
160
- rationale: row.rationale,
161
- made_by: row.made_by,
162
- revisable: row.revisable,
163
- superseded_by: row.superseded_by,
164
- },
165
- });
166
- if (id) written += 1;
149
+ try {
150
+ const id = createMemory({
151
+ category: "architecture",
152
+ content,
153
+ scope: row.scope || "project",
154
+ confidence: 0.85,
155
+ structuredFields: {
156
+ sourceDecisionId: row.id,
157
+ when_context: row.when_context,
158
+ scope: row.scope,
159
+ decision: row.decision,
160
+ choice: row.choice,
161
+ rationale: row.rationale,
162
+ made_by: row.made_by,
163
+ revisable: row.revisable,
164
+ superseded_by: row.superseded_by,
165
+ },
166
+ });
167
+ if (id) written += 1;
168
+ } catch (rowErr) {
169
+ const message = rowErr instanceof Error ? rowErr.message : String(rowErr);
170
+ logWarning("memory-backfill", `decisions->memories backfill skipped ${row.id}: ${message}`);
171
+ continue;
172
+ }
167
173
  }
168
174
 
169
175
  if (healed > 0) {
@@ -19,7 +19,7 @@ import { openSync, closeSync, unlinkSync, statSync, writeFileSync } from "node:f
19
19
  import type { ExtensionContext } from "@gsd/pi-coding-agent";
20
20
  import { gsdRoot } from "./paths.js";
21
21
  import { getAndClearSkills } from "./skill-telemetry.js";
22
- import { loadJsonFile, loadJsonFileOrNull, saveJsonFile } from "./json-persistence.js";
22
+ import { loadJsonFile, loadJsonFileOrNull, saveJsonFileCompact } from "./json-persistence.js";
23
23
  import { parseUnitId } from "./unit-id.js";
24
24
  import { buildAuditEnvelope, emitUokAuditEvent } from "./uok/audit.js";
25
25
  import { isUnifiedAuditEnabled } from "./uok/audit-toggle.js";
@@ -873,7 +873,7 @@ export function pruneMetricsLedger(base: string, keepCount: number): number {
873
873
  if (!disk || disk.units.length <= keepCount) return 0;
874
874
  const removed = disk.units.length - keepCount;
875
875
  disk.units = keepNewestUnits(disk.units, keepCount);
876
- saveJsonFile(metricsPath(base), disk);
876
+ saveJsonFileCompact(metricsPath(base), disk);
877
877
  // Keep the in-memory ledger in sync if it is loaded for this session.
878
878
  if (ledger) {
879
879
  ledger.units = keepNewestUnits(ledger.units, keepCount);
@@ -1041,7 +1041,7 @@ function saveLedger(base: string, data: MetricsLedger): void {
1041
1041
  : dataUnits;
1042
1042
  merged.sort(compareUnitsByTime);
1043
1043
  data.units = keepNewestUnits(merged);
1044
- saveJsonFile(path, data);
1044
+ saveJsonFileCompact(path, data);
1045
1045
  } finally {
1046
1046
  releaseLock(lockPath);
1047
1047
  }
@@ -1053,6 +1053,6 @@ function saveLedger(base: string, data: MetricsLedger): void {
1053
1053
  // read-merge-write sequence without mutual exclusion.
1054
1054
  logWarning("fs", "saveLedger: lock not acquired — falling back to direct write (no merge)");
1055
1055
  data.units = keepNewestUnits(data.units);
1056
- saveJsonFile(path, data);
1056
+ saveJsonFileCompact(path, data);
1057
1057
  }
1058
1058
  }
@@ -33,16 +33,87 @@ function _isAlreadyRestoredApplyError(err: unknown): boolean {
33
33
 
34
34
  export { _isAlreadyRestoredApplyError };
35
35
 
36
+ function gitOutput(basePath: string, args: string[]): string {
37
+ return execFileSync("git", args, {
38
+ cwd: basePath,
39
+ stdio: ["ignore", "pipe", "pipe"],
40
+ encoding: "utf-8",
41
+ env: GIT_NO_PROMPT_ENV,
42
+ });
43
+ }
44
+
45
+ function listStashUntrackedPaths(basePath: string, stashRef: string): string[] | null {
46
+ try {
47
+ return gitOutput(basePath, ["ls-tree", "-r", "-z", "--name-only", `${stashRef}^3`]).split("\0").filter(Boolean);
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ function listStashTrackedPaths(basePath: string, stashRef: string): string[] | null {
54
+ try {
55
+ return gitOutput(basePath, ["diff", "--name-only", "-z", `${stashRef}^1`, stashRef]).split("\0").filter(Boolean);
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ interface PorcelainEntry {
62
+ code: string;
63
+ path: string;
64
+ }
65
+
66
+ function readWorkingTreeStatus(basePath: string): PorcelainEntry[] | null {
67
+ try {
68
+ return gitOutput(basePath, ["status", "--porcelain", "-z", "--untracked-files=all"])
69
+ .split("\0")
70
+ .filter(Boolean)
71
+ .map((entry) => ({ code: entry.slice(0, 2), path: entry.slice(3) }));
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ function isAlreadyRestoredUntrackedStatus(basePath: string, stashRef: string, statusEntries: PorcelainEntry[]): boolean {
78
+ if (statusEntries.length === 0 || statusEntries.some((entry) => entry.code !== "??")) return false;
79
+ const stashTrackedPaths = listStashTrackedPaths(basePath, stashRef);
80
+ if (!stashTrackedPaths || stashTrackedPaths.length > 0) return false;
81
+ const stashUntrackedPaths = listStashUntrackedPaths(basePath, stashRef);
82
+ if (!stashUntrackedPaths || stashUntrackedPaths.length === 0) return false;
83
+ const stashUntrackedPathSet = new Set(stashUntrackedPaths);
84
+ const workingTreeUntrackedPathSet = new Set(statusEntries.map((entry) => entry.path));
85
+ // "Already restored" requires the working tree's untracked paths to match the
86
+ // stash's untracked paths exactly, in BOTH directions:
87
+ // 1. every current untracked path comes from the stash (no unexplained user
88
+ // work that an apply would clobber), AND
89
+ // 2. every stash untracked path is already present in the working tree.
90
+ // Without (2), a partial restore (where only some stash files were recovered)
91
+ // would be misread as fully restored: the audit would no-op without applying
92
+ // or warning, leaving the remaining pre-merge files missing.
93
+ return (
94
+ statusEntries.every((entry) => stashUntrackedPathSet.has(entry.path)) &&
95
+ stashUntrackedPaths.every((path) => workingTreeUntrackedPathSet.has(path))
96
+ );
97
+ }
98
+
99
+ function manualApplyWarning(stashRef: string, milestoneId: string, reason: string): string {
100
+ return (
101
+ `Pre-merge stash ${stashRef} for milestone ${milestoneId} not auto-applied: ${reason}; ` +
102
+ `run \`git stash apply ${stashRef}\` manually to restore your pre-merge changes.`
103
+ );
104
+ }
105
+
36
106
  /**
37
107
  * Audit `git stash list` for orphaned `gsd-preflight-stash:M00x:*` entries.
38
108
  *
39
109
  * The matching merge code in `phases.ts` previously skipped the postflight
40
110
  * pop whenever `mergeAndExit` threw, leaking the user's pre-merge working
41
- * tree into the stash list. For every preflight-stash entry whose milestone
42
- * is now complete (per the supplied callback), `git stash apply` is invoked
111
+ * tree into the stash list. Completed-milestone stashes are only auto-applied
112
+ * when the working tree is clean and the stash does not modify tracked files.
113
+ * Dirty trees and tracked-file stashes are left untouched with a manual
114
+ * recovery warning. When auto-apply is safe, `git stash apply` is invoked —
43
115
  * NOT `pop`. The stash entry stays in the list so the user retains a backup
44
- * if the apply produces unexpected merge results. Idempotent across repeated
45
- * startup runs.
116
+ * if the apply produces unexpected merge results.
46
117
  *
47
118
  * Failures are best-effort: a list error (no repo, git unavailable) returns
48
119
  * an empty result. An apply error becomes a warning the user sees alongside
@@ -56,16 +127,7 @@ export function auditOrphanedPreflightStashes(
56
127
 
57
128
  let listOutput: string;
58
129
  try {
59
- listOutput = execFileSync(
60
- "git",
61
- ["stash", "list", "--format=%gd%x00%s"],
62
- {
63
- cwd: basePath,
64
- stdio: ["ignore", "pipe", "pipe"],
65
- encoding: "utf-8",
66
- env: GIT_NO_PROMPT_ENV,
67
- },
68
- );
130
+ listOutput = gitOutput(basePath, ["stash", "list", "--format=%gd%x00%s"]);
69
131
  } catch {
70
132
  return result;
71
133
  }
@@ -93,13 +155,39 @@ export function auditOrphanedPreflightStashes(
93
155
  }
94
156
  if (!complete) continue;
95
157
 
158
+ const statusEntries = readWorkingTreeStatus(basePath);
159
+ if (!statusEntries) {
160
+ result.warnings.push(
161
+ manualApplyWarning(ref, milestoneId, "could not verify working tree status"),
162
+ );
163
+ continue;
164
+ }
165
+ if (statusEntries.length > 0) {
166
+ if (isAlreadyRestoredUntrackedStatus(basePath, ref, statusEntries)) continue;
167
+ result.warnings.push(manualApplyWarning(ref, milestoneId, "working tree not clean"));
168
+ continue;
169
+ }
170
+
171
+ const trackedPaths = listStashTrackedPaths(basePath, ref);
172
+ if (trackedPaths === null) {
173
+ result.warnings.push(
174
+ manualApplyWarning(ref, milestoneId, "could not inspect tracked paths in stash"),
175
+ );
176
+ continue;
177
+ }
178
+ if (trackedPaths.length > 0) {
179
+ // A retained tracked-file stash has no durable marker showing whether a
180
+ // clean tree needs first recovery or would be re-mutated by an old backup.
181
+ const preview = trackedPaths.slice(0, 5).join(", ");
182
+ const suffix = trackedPaths.length > 5 ? `, and ${trackedPaths.length - 5} more` : "";
183
+ result.warnings.push(
184
+ manualApplyWarning(ref, milestoneId, `stash modifies tracked files (${preview}${suffix})`),
185
+ );
186
+ continue;
187
+ }
188
+
96
189
  try {
97
- execFileSync("git", ["stash", "apply", "--quiet", ref], {
98
- cwd: basePath,
99
- stdio: ["ignore", "pipe", "pipe"],
100
- encoding: "utf-8",
101
- env: GIT_NO_PROMPT_ENV,
102
- });
190
+ gitOutput(basePath, ["stash", "apply", "--quiet", ref]);
103
191
  result.applied.push({ milestoneId, stashRef: ref });
104
192
  } catch (err) {
105
193
  // Idempotent steady state: stash was already applied in a prior audit
@@ -45,7 +45,7 @@ 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.
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. 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
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.
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`.
@@ -76,8 +76,14 @@ export function validateFileChanges(
76
76
  const actualFiles = getChangedFilesFromLastCommit(basePath);
77
77
  if (!actualFiles) return null;
78
78
 
79
- // Filter out .gsd/ internal files — only validate project source files
80
- const projectFiles = actualFiles.filter(f => !f.startsWith(".gsd/") && !f.startsWith(".gsd\\"));
79
+ // Filter out GSD-internal paths — only validate project source files.
80
+ const projectFiles = actualFiles.filter(
81
+ (f) =>
82
+ !f.startsWith(".gsd/") &&
83
+ !f.startsWith(".gsd\\") &&
84
+ !f.startsWith(".gsd-backups/") &&
85
+ !f.startsWith(".gsd-backups\\"),
86
+ );
81
87
 
82
88
  // Normalize expected paths (strip leading ./ or /)
83
89
  const normalizedExpected = new Set(
@@ -29,21 +29,22 @@ test("#2007 bug 1: MAX_ARTIFACT_VERIFICATION_RETRIES constant is defined", () =>
29
29
  assert.equal(MAX_ARTIFACT_VERIFICATION_RETRIES, 3);
30
30
  });
31
31
 
32
- test("#2007 bug 1: retry state can represent each allowed attempt before exhaustion", () => {
32
+ test("#2007 bug 1: retry state keeps attempt separate from failure context", () => {
33
33
  const s = new AutoSession();
34
34
  const retryKey = "execute-task:M001/S01/T01";
35
+ const failureContext = "Missing expected artifact";
35
36
 
36
37
  for (let attempt = 1; attempt <= MAX_ARTIFACT_VERIFICATION_RETRIES; attempt++) {
37
38
  s.verificationRetryCount.set(retryKey, attempt);
38
39
  s.pendingVerificationRetry = {
39
40
  unitId: "M001/S01/T01",
40
- failureContext: `Missing expected artifact (attempt ${attempt}/${MAX_ARTIFACT_VERIFICATION_RETRIES}).`,
41
+ failureContext,
41
42
  attempt,
42
43
  };
43
44
 
44
45
  assert.equal(s.verificationRetryCount.get(retryKey), attempt);
45
46
  assert.equal(s.pendingVerificationRetry.attempt, attempt);
46
- assert.match(s.pendingVerificationRetry.failureContext, /attempt \d\/3/);
47
+ assert.equal(s.pendingVerificationRetry.failureContext, failureContext);
47
48
  }
48
49
  });
49
50
 
@@ -312,6 +312,34 @@ console.log('\n=== complete-milestone: incomplete slices block closeout ===');
312
312
  cleanup(dbPath);
313
313
  }
314
314
 
315
+ // ═══════════════════════════════════════════════════════════════════════════
316
+ // complete-milestone: deferred slices are inactive for closeout
317
+ // ═══════════════════════════════════════════════════════════════════════════
318
+
319
+ console.log('\n=== complete-milestone: deferred slices do not block closeout ===');
320
+ {
321
+ const dbPath = tempDbPath();
322
+ openDatabase(dbPath);
323
+ const { basePath } = createTempProject();
324
+ seedCompletedMilestone({ basePath, validationVerdict: 'pass' });
325
+ insertSlice({ id: 'S02', milestoneId: 'M001', title: 'Deferred Slice', status: 'deferred' });
326
+ insertTask({
327
+ id: 'T02',
328
+ sliceId: 'S02',
329
+ milestoneId: 'M001',
330
+ status: 'pending',
331
+ title: 'Deferred Slice Task',
332
+ });
333
+
334
+ const result = await handleCompleteMilestone(makeValidParams(), basePath);
335
+
336
+ assertTrue(!('error' in result), 'deferred slice should not block milestone completion');
337
+ assertEq(getMilestone('M001')!.status, 'complete', 'milestone should complete with deferred inactive slice');
338
+
339
+ cleanupDir(basePath);
340
+ cleanup(dbPath);
341
+ }
342
+
315
343
  // ═══════════════════════════════════════════════════════════════════════════
316
344
  // complete-milestone: deep task check (slice closed, task not)
317
345
  // ═══════════════════════════════════════════════════════════════════════════
@@ -7,6 +7,10 @@ import { join } from "node:path";
7
7
 
8
8
  import { postUnitPreVerification } from "../auto-post-unit.ts";
9
9
  import { AutoSession } from "../auto/session.ts";
10
+ import {
11
+ decideVerificationRetry,
12
+ hashVerificationFailureContext,
13
+ } from "../auto/verification-retry-policy.ts";
10
14
  import { cleanup, makeTempRepo } from "./test-utils.ts";
11
15
 
12
16
  function makePostUnitContext(base: string, s: AutoSession, notifications: string[]) {
@@ -227,3 +231,68 @@ test("complete-slice with gsd_replan_slice but no REPLAN artifact retries", asyn
227
231
  cleanup(base);
228
232
  }
229
233
  });
234
+
235
+ test("artifact retry context stays stable across attempts while notifications show attempt count", async () => {
236
+ const base = makeTempRepo("gsd-artifact-retry-stable-context-");
237
+ try {
238
+ mkdirSync(join(base, ".gsd", "milestones", "M001", "slices", "S01"), { recursive: true });
239
+
240
+ const s = new AutoSession();
241
+ s.active = true;
242
+ s.basePath = base;
243
+ s.currentUnit = { type: "complete-slice", id: "M001/S01", startedAt: Date.now() };
244
+
245
+ const notifications: string[] = [];
246
+ const pctx = makePostUnitContext(base, s, notifications);
247
+ const opts = {
248
+ skipSettleDelay: true,
249
+ skipWorktreeSync: true,
250
+ agentEndMessages: [
251
+ {
252
+ role: "toolResult",
253
+ toolName: "gsd_replan_slice",
254
+ isError: false,
255
+ content: "Slice replanned with reopened task T02.",
256
+ },
257
+ ],
258
+ };
259
+
260
+ assert.equal(await postUnitPreVerification(pctx, opts), "retry");
261
+ const firstRetry = s.pendingVerificationRetry;
262
+ assert.ok(firstRetry);
263
+ assert.equal(firstRetry.attempt, 1);
264
+ assert.doesNotMatch(firstRetry.failureContext, /\(attempt \d\/3\)\.$/);
265
+ const firstFailureHash = hashVerificationFailureContext(firstRetry.failureContext);
266
+
267
+ assert.equal(await postUnitPreVerification(pctx, opts), "retry");
268
+ const secondRetry = s.pendingVerificationRetry;
269
+ assert.ok(secondRetry);
270
+ assert.equal(secondRetry.attempt, 2);
271
+ assert.equal(secondRetry.failureContext, firstRetry.failureContext);
272
+ assert.equal(hashVerificationFailureContext(secondRetry.failureContext), firstFailureHash);
273
+ assert.deepEqual(
274
+ decideVerificationRetry({
275
+ unitType: s.currentUnit.type,
276
+ retryInfo: secondRetry,
277
+ previousFailureHash: firstFailureHash,
278
+ random: () => 0.5,
279
+ }),
280
+ {
281
+ action: "pause",
282
+ reason: "duplicate-failure-context",
283
+ key: "complete-slice:M001/S01",
284
+ failureHash: firstFailureHash,
285
+ },
286
+ );
287
+ assert.ok(
288
+ notifications.some((message) => message.includes("Retrying (attempt 1/3).")),
289
+ `expected first attempt notification, got: ${notifications.join("\n")}`,
290
+ );
291
+ assert.ok(
292
+ notifications.some((message) => message.includes("Retrying (attempt 2/3).")),
293
+ `expected second attempt notification, got: ${notifications.join("\n")}`,
294
+ );
295
+ } finally {
296
+ cleanup(base);
297
+ }
298
+ });
@@ -142,6 +142,57 @@ test("backfill is idempotent — re-running over migrated rows is a no-op", () =
142
142
  }
143
143
  });
144
144
 
145
+ test("backfill skips a decision whose memory insert throws and continues later rows", () => {
146
+ const base = makeTmpBase();
147
+ try {
148
+ seedRawDecision({
149
+ id: "D001",
150
+ when_context: "M001",
151
+ scope: "M001",
152
+ decision: "before poison",
153
+ choice: "A",
154
+ rationale: "first row",
155
+ });
156
+ seedRawDecision({
157
+ id: "D002",
158
+ when_context: "M001",
159
+ scope: "M001",
160
+ decision: "poison",
161
+ choice: "B",
162
+ rationale: "this insert throws",
163
+ });
164
+ seedRawDecision({
165
+ id: "D003",
166
+ when_context: "M001",
167
+ scope: "M001",
168
+ decision: "after poison",
169
+ choice: "C",
170
+ rationale: "tail row",
171
+ });
172
+
173
+ const adapter = _getAdapter();
174
+ assert.ok(adapter);
175
+ adapter.exec(`
176
+ CREATE TRIGGER fail_d002_memory_insert
177
+ BEFORE INSERT ON memories
178
+ WHEN json_extract(NEW.structured_fields, '$.sourceDecisionId') = 'D002'
179
+ BEGIN
180
+ SELECT RAISE(ABORT, 'poison decision D002');
181
+ END
182
+ `);
183
+
184
+ const written = backfillDecisionsToMemories();
185
+ assert.equal(written, 2, "one poisoned row should not abort the batch");
186
+ assert.deepEqual(
187
+ getAllDecisionsFromMemories().map((d) => d.id),
188
+ ["D001", "D003"],
189
+ "rows after the poisoned decision should still be migrated",
190
+ );
191
+ } finally {
192
+ cleanup(base);
193
+ }
194
+ });
195
+
145
196
  // ─── Drift auto-heal ───────────────────────────────────────────────────────
146
197
 
147
198
  test("backfill auto-heals when a source decision's superseded_by changes after migration", () => {