gsd-pi 2.74.0-dev.2b524c3 → 2.74.0-dev.b741afb

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 (159) hide show
  1. package/dist/cli.js +85 -0
  2. package/dist/headless-query.js +4 -1
  3. package/dist/help-text.js +23 -0
  4. package/dist/resources/extensions/gsd/auto/detect-stuck.js +11 -4
  5. package/dist/resources/extensions/gsd/auto/phases.js +45 -1
  6. package/dist/resources/extensions/gsd/auto-post-unit.js +52 -56
  7. package/dist/resources/extensions/gsd/auto-prompts.js +12 -0
  8. package/dist/resources/extensions/gsd/auto.js +8 -2
  9. package/dist/resources/extensions/gsd/bootstrap/register-extension.js +21 -8
  10. package/dist/resources/extensions/gsd/commands/catalog.js +26 -1
  11. package/dist/resources/extensions/gsd/commands/handlers/ops.js +20 -0
  12. package/dist/resources/extensions/gsd/commands/handlers/workflow.js +68 -9
  13. package/dist/resources/extensions/gsd/commands-add-tests.js +111 -0
  14. package/dist/resources/extensions/gsd/commands-backlog.js +140 -0
  15. package/dist/resources/extensions/gsd/commands-do.js +79 -0
  16. package/dist/resources/extensions/gsd/commands-maintenance.js +6 -6
  17. package/dist/resources/extensions/gsd/commands-pr-branch.js +180 -0
  18. package/dist/resources/extensions/gsd/commands-session-report.js +82 -0
  19. package/dist/resources/extensions/gsd/commands-ship.js +187 -0
  20. package/dist/resources/extensions/gsd/db-writer.js +3 -5
  21. package/dist/resources/extensions/gsd/graph-context.js +66 -0
  22. package/dist/resources/extensions/gsd/gsd-db.js +321 -0
  23. package/dist/resources/extensions/gsd/index.js +15 -2
  24. package/dist/resources/extensions/gsd/md-importer.js +3 -4
  25. package/dist/resources/extensions/gsd/memory-store.js +19 -51
  26. package/dist/resources/extensions/gsd/milestone-validation-gates.js +13 -12
  27. package/dist/resources/extensions/gsd/native-git-bridge.js +7 -4
  28. package/dist/resources/extensions/gsd/prompts/add-tests.md +35 -0
  29. package/dist/resources/extensions/gsd/state.js +5 -1
  30. package/dist/resources/extensions/gsd/tools/complete-slice.js +15 -0
  31. package/dist/resources/extensions/gsd/tools/workflow-tool-executors.js +3 -14
  32. package/dist/resources/extensions/gsd/triage-resolution.js +2 -5
  33. package/dist/resources/extensions/gsd/workflow-manifest.js +8 -69
  34. package/dist/resources/extensions/gsd/workflow-migration.js +21 -22
  35. package/dist/resources/extensions/gsd/workflow-projections.js +4 -1
  36. package/dist/resources/extensions/gsd/workflow-reconcile.js +14 -11
  37. package/dist/tsconfig.extensions.tsbuildinfo +1 -0
  38. package/dist/web/standalone/.next/BUILD_ID +1 -1
  39. package/dist/web/standalone/.next/app-path-routes-manifest.json +7 -7
  40. package/dist/web/standalone/.next/build-manifest.json +2 -2
  41. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  42. package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
  43. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  44. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  45. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  46. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  47. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  48. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  49. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  50. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  51. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  52. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  53. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  54. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  55. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  56. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  57. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  58. package/dist/web/standalone/.next/server/app/index.html +1 -1
  59. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  60. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  61. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  62. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  63. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  64. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  65. package/dist/web/standalone/.next/server/app-paths-manifest.json +7 -7
  66. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  67. package/dist/web/standalone/.next/server/middleware-manifest.json +5 -5
  68. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  69. package/dist/web/standalone/.next/server/pages/500.html +1 -1
  70. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  71. package/package.json +3 -2
  72. package/packages/daemon/package.json +2 -2
  73. package/packages/mcp-server/dist/index.d.ts +3 -0
  74. package/packages/mcp-server/dist/index.d.ts.map +1 -1
  75. package/packages/mcp-server/dist/index.js +3 -0
  76. package/packages/mcp-server/dist/index.js.map +1 -1
  77. package/packages/mcp-server/dist/readers/graph.d.ts +87 -0
  78. package/packages/mcp-server/dist/readers/graph.d.ts.map +1 -0
  79. package/packages/mcp-server/dist/readers/graph.js +548 -0
  80. package/packages/mcp-server/dist/readers/graph.js.map +1 -0
  81. package/packages/mcp-server/dist/readers/index.d.ts +2 -0
  82. package/packages/mcp-server/dist/readers/index.d.ts.map +1 -1
  83. package/packages/mcp-server/dist/readers/index.js +1 -0
  84. package/packages/mcp-server/dist/readers/index.js.map +1 -1
  85. package/packages/mcp-server/dist/server.d.ts.map +1 -1
  86. package/packages/mcp-server/dist/server.js +65 -0
  87. package/packages/mcp-server/dist/server.js.map +1 -1
  88. package/packages/mcp-server/package.json +2 -2
  89. package/packages/mcp-server/src/index.ts +15 -0
  90. package/packages/mcp-server/src/readers/graph.test.ts +426 -0
  91. package/packages/mcp-server/src/readers/graph.ts +708 -0
  92. package/packages/mcp-server/src/readers/index.ts +12 -0
  93. package/packages/mcp-server/src/server.ts +83 -0
  94. package/packages/mcp-server/tsconfig.json +1 -0
  95. package/packages/mcp-server/tsconfig.tsbuildinfo +1 -0
  96. package/packages/native/package.json +2 -2
  97. package/packages/native/tsconfig.tsbuildinfo +1 -0
  98. package/packages/pi-agent-core/package.json +1 -1
  99. package/packages/pi-agent-core/tsconfig.json +1 -0
  100. package/packages/pi-agent-core/tsconfig.tsbuildinfo +1 -0
  101. package/packages/pi-ai/package.json +1 -1
  102. package/packages/pi-ai/tsconfig.json +1 -0
  103. package/packages/pi-ai/tsconfig.tsbuildinfo +1 -0
  104. package/packages/pi-coding-agent/tsconfig.json +1 -0
  105. package/packages/pi-coding-agent/tsconfig.tsbuildinfo +1 -0
  106. package/packages/pi-tui/package.json +1 -1
  107. package/packages/pi-tui/tsconfig.json +1 -0
  108. package/packages/pi-tui/tsconfig.tsbuildinfo +1 -0
  109. package/packages/rpc-client/package.json +1 -1
  110. package/packages/rpc-client/tsconfig.json +1 -0
  111. package/packages/rpc-client/tsconfig.tsbuildinfo +1 -0
  112. package/src/resources/extensions/gsd/auto/detect-stuck.ts +12 -4
  113. package/src/resources/extensions/gsd/auto/loop-deps.ts +6 -0
  114. package/src/resources/extensions/gsd/auto/phases.ts +68 -1
  115. package/src/resources/extensions/gsd/auto-post-unit.ts +60 -57
  116. package/src/resources/extensions/gsd/auto-prompts.ts +13 -0
  117. package/src/resources/extensions/gsd/auto.ts +7 -0
  118. package/src/resources/extensions/gsd/bootstrap/register-extension.ts +24 -8
  119. package/src/resources/extensions/gsd/commands/catalog.ts +26 -1
  120. package/src/resources/extensions/gsd/commands/handlers/ops.ts +20 -0
  121. package/src/resources/extensions/gsd/commands/handlers/workflow.ts +74 -9
  122. package/src/resources/extensions/gsd/commands-add-tests.ts +137 -0
  123. package/src/resources/extensions/gsd/commands-backlog.ts +182 -0
  124. package/src/resources/extensions/gsd/commands-do.ts +109 -0
  125. package/src/resources/extensions/gsd/commands-maintenance.ts +6 -6
  126. package/src/resources/extensions/gsd/commands-pr-branch.ts +234 -0
  127. package/src/resources/extensions/gsd/commands-session-report.ts +101 -0
  128. package/src/resources/extensions/gsd/commands-ship.ts +219 -0
  129. package/src/resources/extensions/gsd/db-writer.ts +3 -5
  130. package/src/resources/extensions/gsd/graph-context.ts +85 -0
  131. package/src/resources/extensions/gsd/gsd-db.ts +467 -0
  132. package/src/resources/extensions/gsd/index.ts +18 -2
  133. package/src/resources/extensions/gsd/md-importer.ts +3 -5
  134. package/src/resources/extensions/gsd/memory-store.ts +31 -62
  135. package/src/resources/extensions/gsd/milestone-validation-gates.ts +13 -14
  136. package/src/resources/extensions/gsd/native-git-bridge.ts +11 -12
  137. package/src/resources/extensions/gsd/prompts/add-tests.md +35 -0
  138. package/src/resources/extensions/gsd/state.ts +9 -2
  139. package/src/resources/extensions/gsd/tests/commands-backlog.test.ts +158 -0
  140. package/src/resources/extensions/gsd/tests/commands-do.test.ts +127 -0
  141. package/src/resources/extensions/gsd/tests/commands-pr-branch.test.ts +68 -0
  142. package/src/resources/extensions/gsd/tests/commands-session-report.test.ts +82 -0
  143. package/src/resources/extensions/gsd/tests/commands-ship.test.ts +71 -0
  144. package/src/resources/extensions/gsd/tests/commands-workflow-custom.test.ts +14 -0
  145. package/src/resources/extensions/gsd/tests/extension-bootstrap-isolation.test.ts +154 -0
  146. package/src/resources/extensions/gsd/tests/graph-context.test.ts +337 -0
  147. package/src/resources/extensions/gsd/tests/journal-integration.test.ts +68 -1
  148. package/src/resources/extensions/gsd/tests/native-git-bridge-exec-fallback.test.ts +140 -0
  149. package/src/resources/extensions/gsd/tests/single-writer-invariant.test.ts +180 -0
  150. package/src/resources/extensions/gsd/tests/workflow-logger-wiring.test.ts +223 -0
  151. package/src/resources/extensions/gsd/tools/complete-slice.ts +19 -0
  152. package/src/resources/extensions/gsd/tools/workflow-tool-executors.ts +3 -11
  153. package/src/resources/extensions/gsd/triage-resolution.ts +2 -7
  154. package/src/resources/extensions/gsd/workflow-manifest.ts +9 -104
  155. package/src/resources/extensions/gsd/workflow-migration.ts +21 -29
  156. package/src/resources/extensions/gsd/workflow-projections.ts +8 -1
  157. package/src/resources/extensions/gsd/workflow-reconcile.ts +15 -15
  158. /package/dist/web/standalone/.next/static/{YzIEI9sxJy4t5xgClF08g → XnHY5eXUsTCFmNodWHetD}/_buildManifest.js +0 -0
  159. /package/dist/web/standalone/.next/static/{YzIEI9sxJy4t5xgClF08g → XnHY5eXUsTCFmNodWHetD}/_ssgManifest.js +0 -0
@@ -25,6 +25,61 @@ const WORKFLOW_USAGE = [
25
25
  " pause — Pause custom workflow auto-mode",
26
26
  " resume — Resume paused custom workflow auto-mode",
27
27
  ].join("\n");
28
+ function splitWorkflowRunArgs(input) {
29
+ const tokens = [];
30
+ let current = "";
31
+ let quote = null;
32
+ let escapeNext = false;
33
+ for (const ch of input) {
34
+ if (escapeNext) {
35
+ current += ch;
36
+ escapeNext = false;
37
+ continue;
38
+ }
39
+ if (ch === "\\") {
40
+ escapeNext = true;
41
+ continue;
42
+ }
43
+ if (quote) {
44
+ if (ch === quote) {
45
+ quote = null;
46
+ }
47
+ else {
48
+ current += ch;
49
+ }
50
+ continue;
51
+ }
52
+ if (ch === '"' || ch === "'") {
53
+ quote = ch;
54
+ continue;
55
+ }
56
+ if (/\s/.test(ch)) {
57
+ if (current) {
58
+ tokens.push(current);
59
+ current = "";
60
+ }
61
+ continue;
62
+ }
63
+ current += ch;
64
+ }
65
+ if (escapeNext)
66
+ current += "\\";
67
+ if (current)
68
+ tokens.push(current);
69
+ return tokens;
70
+ }
71
+ export function parseWorkflowRunArgs(args) {
72
+ const parts = splitWorkflowRunArgs(args);
73
+ const defName = parts[0] ?? "";
74
+ const overrides = {};
75
+ for (let i = 1; i < parts.length; i++) {
76
+ const eqIdx = parts[i].indexOf("=");
77
+ if (eqIdx > 0) {
78
+ overrides[parts[i].slice(0, eqIdx)] = parts[i].slice(eqIdx + 1);
79
+ }
80
+ }
81
+ return { defName, overrides };
82
+ }
28
83
  async function handleCustomWorkflow(sub, ctx, pi) {
29
84
  // Bare `/gsd workflow` — show usage
30
85
  if (!sub) {
@@ -43,15 +98,7 @@ async function handleCustomWorkflow(sub, ctx, pi) {
43
98
  ctx.ui.notify("Usage: /gsd workflow run <name> [param=value ...]", "warning");
44
99
  return true;
45
100
  }
46
- const parts = args.split(/\s+/);
47
- const defName = parts[0];
48
- const overrides = {};
49
- for (let i = 1; i < parts.length; i++) {
50
- const eqIdx = parts[i].indexOf("=");
51
- if (eqIdx > 0) {
52
- overrides[parts[i].slice(0, eqIdx)] = parts[i].slice(eqIdx + 1);
53
- }
54
- }
101
+ const { defName, overrides } = parseWorkflowRunArgs(args);
55
102
  try {
56
103
  const base = projectRoot();
57
104
  const runDir = createRun(base, defName, Object.keys(overrides).length > 0 ? overrides : undefined);
@@ -146,6 +193,18 @@ async function handleCustomWorkflow(sub, ctx, pi) {
146
193
  return true;
147
194
  }
148
195
  export async function handleWorkflowCommand(trimmed, ctx, pi) {
196
+ // ── /gsd do — natural language routing (must be early to route to other commands) ──
197
+ if (trimmed === "do" || trimmed.startsWith("do ")) {
198
+ const { handleDo } = await import("../../commands-do.js");
199
+ await handleDo(trimmed.replace(/^do\s*/, "").trim(), ctx, pi);
200
+ return true;
201
+ }
202
+ // ── Backlog management ──
203
+ if (trimmed === "backlog" || trimmed.startsWith("backlog ")) {
204
+ const { handleBacklog } = await import("../../commands-backlog.js");
205
+ await handleBacklog(trimmed.replace(/^backlog\s*/, "").trim(), ctx, pi);
206
+ return true;
207
+ }
149
208
  // ── Custom workflow commands (`/gsd workflow ...`) ──
150
209
  if (trimmed === "workflow" || trimmed.startsWith("workflow ")) {
151
210
  const sub = trimmed.slice("workflow".length).trim();
@@ -0,0 +1,111 @@
1
+ /**
2
+ * GSD Command — /gsd add-tests
3
+ *
4
+ * Generates tests for a completed slice by dispatching an LLM prompt
5
+ * with implementation context (summaries, changed files, test patterns).
6
+ */
7
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { deriveState } from "./state.js";
10
+ import { gsdRoot, resolveSliceFile } from "./paths.js";
11
+ import { loadPrompt } from "./prompt-loader.js";
12
+ function findLastCompletedSlice(basePath, milestoneId) {
13
+ // Scan disk for slices that have a SUMMARY.md (indicating completion)
14
+ const slicesDir = join(gsdRoot(basePath), "milestones", milestoneId, "slices");
15
+ if (!existsSync(slicesDir))
16
+ return null;
17
+ try {
18
+ const entries = readdirSync(slicesDir, { withFileTypes: true })
19
+ .filter((e) => e.isDirectory() && /^S\d+$/.test(e.name))
20
+ .sort((a, b) => b.name.localeCompare(a.name)); // reverse order — latest first
21
+ for (const entry of entries) {
22
+ const summaryPath = join(slicesDir, entry.name, `${entry.name}-SUMMARY.md`);
23
+ if (existsSync(summaryPath))
24
+ return entry.name;
25
+ }
26
+ }
27
+ catch {
28
+ // non-fatal
29
+ }
30
+ return null;
31
+ }
32
+ function readSliceSummary(basePath, milestoneId, sliceId) {
33
+ const summaryPath = resolveSliceFile(basePath, milestoneId, sliceId, "SUMMARY");
34
+ if (summaryPath && existsSync(summaryPath)) {
35
+ const content = readFileSync(summaryPath, "utf-8");
36
+ const titleMatch = content.match(/^#\s+(.+)/m);
37
+ return { title: titleMatch?.[1] ?? sliceId, content };
38
+ }
39
+ return { title: sliceId, content: "(no summary available)" };
40
+ }
41
+ function detectTestPatterns(basePath) {
42
+ const patterns = [];
43
+ // Check for common test configs
44
+ const checks = [
45
+ { file: "jest.config.ts", name: "Jest" },
46
+ { file: "jest.config.js", name: "Jest" },
47
+ { file: "vitest.config.ts", name: "Vitest" },
48
+ { file: "vitest.config.js", name: "Vitest" },
49
+ { file: ".mocharc.yml", name: "Mocha" },
50
+ ];
51
+ for (const check of checks) {
52
+ if (existsSync(join(basePath, check.file))) {
53
+ patterns.push(`Framework: ${check.name} (${check.file})`);
54
+ }
55
+ }
56
+ // Look for existing test files to infer patterns
57
+ const testDirs = ["tests", "test", "src/__tests__", "__tests__"];
58
+ for (const dir of testDirs) {
59
+ const fullDir = join(basePath, dir);
60
+ if (existsSync(fullDir)) {
61
+ try {
62
+ const files = readdirSync(fullDir).filter((f) => f.endsWith(".test.ts") || f.endsWith(".spec.ts") || f.endsWith(".test.js"));
63
+ if (files.length > 0) {
64
+ patterns.push(`Test directory: ${dir}/ (${files.length} test files)`);
65
+ // Read first test file for patterns
66
+ const samplePath = join(fullDir, files[0]);
67
+ const sample = readFileSync(samplePath, "utf-8").slice(0, 500);
68
+ patterns.push(`Sample pattern from ${files[0]}:\n${sample}`);
69
+ break;
70
+ }
71
+ }
72
+ catch {
73
+ // non-fatal
74
+ }
75
+ }
76
+ }
77
+ return patterns.length > 0 ? patterns.join("\n") : "No test framework detected. Use Node.js built-in test runner.";
78
+ }
79
+ export async function handleAddTests(args, ctx, pi) {
80
+ const basePath = process.cwd();
81
+ const state = await deriveState(basePath);
82
+ if (!state.activeMilestone) {
83
+ ctx.ui.notify("No active milestone.", "warning");
84
+ return;
85
+ }
86
+ const milestoneId = state.activeMilestone.id;
87
+ // Determine target
88
+ const targetId = args.trim() || findLastCompletedSlice(basePath, milestoneId);
89
+ if (!targetId) {
90
+ ctx.ui.notify("No completed slices found. Specify a slice ID: /gsd add-tests S03", "warning");
91
+ return;
92
+ }
93
+ // Gather context
94
+ const summary = readSliceSummary(basePath, milestoneId, targetId);
95
+ const testPatterns = detectTestPatterns(basePath);
96
+ ctx.ui.notify(`Generating tests for ${targetId}: "${summary.title}"...`, "info");
97
+ try {
98
+ const prompt = loadPrompt("add-tests", {
99
+ sliceId: targetId,
100
+ sliceTitle: summary.title,
101
+ sliceSummary: summary.content,
102
+ existingTestPatterns: testPatterns,
103
+ workingDirectory: basePath,
104
+ });
105
+ pi.sendMessage({ customType: "gsd-add-tests", content: prompt, display: false }, { triggerTurn: true });
106
+ }
107
+ catch (err) {
108
+ const msg = err instanceof Error ? err.message : String(err);
109
+ ctx.ui.notify(`Failed to dispatch test generation: ${msg}`, "error");
110
+ }
111
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * GSD Command — /gsd backlog
3
+ *
4
+ * Structured backlog management with 999.x numbering.
5
+ * Items stored in .gsd/BACKLOG.md as markdown checklist.
6
+ * Items can be promoted to active slices via add-slice.
7
+ */
8
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
9
+ import { join, dirname } from "node:path";
10
+ import { gsdRoot } from "./paths.js";
11
+ function backlogPath(basePath) {
12
+ return join(gsdRoot(basePath), "BACKLOG.md");
13
+ }
14
+ function parseBacklog(basePath) {
15
+ const filePath = backlogPath(basePath);
16
+ if (!existsSync(filePath))
17
+ return [];
18
+ const content = readFileSync(filePath, "utf-8");
19
+ const items = [];
20
+ for (const line of content.split("\n")) {
21
+ const match = line.match(/^- \[([ x])\] (999\.\d+) — (.+?)(?:\s*\((.+)\))?$/);
22
+ if (match) {
23
+ items.push({
24
+ id: match[2],
25
+ title: match[3].trim(),
26
+ done: match[1] === "x",
27
+ note: match[4] ?? "",
28
+ });
29
+ }
30
+ }
31
+ return items;
32
+ }
33
+ function writeBacklog(basePath, items) {
34
+ const filePath = backlogPath(basePath);
35
+ mkdirSync(dirname(filePath), { recursive: true });
36
+ const lines = ["# Backlog\n"];
37
+ for (const item of items) {
38
+ const check = item.done ? "x" : " ";
39
+ const note = item.note ? ` (${item.note})` : "";
40
+ lines.push(`- [${check}] ${item.id} — ${item.title}${note}`);
41
+ }
42
+ lines.push(""); // trailing newline
43
+ writeFileSync(filePath, lines.join("\n"), "utf-8");
44
+ }
45
+ function nextBacklogId(items) {
46
+ let maxNum = 0;
47
+ for (const item of items) {
48
+ const match = item.id.match(/^999\.(\d+)$/);
49
+ if (match) {
50
+ const num = parseInt(match[1], 10);
51
+ if (num > maxNum)
52
+ maxNum = num;
53
+ }
54
+ }
55
+ return `999.${maxNum + 1}`;
56
+ }
57
+ async function listBacklog(basePath, ctx) {
58
+ const items = parseBacklog(basePath);
59
+ if (items.length === 0) {
60
+ ctx.ui.notify("Backlog is empty. Add items with /gsd backlog add <title>", "info");
61
+ return;
62
+ }
63
+ const lines = ["Backlog:\n"];
64
+ for (const item of items) {
65
+ const status = item.done ? "✓" : "○";
66
+ const note = item.note ? ` (${item.note})` : "";
67
+ lines.push(` ${status} ${item.id} — ${item.title}${note}`);
68
+ }
69
+ const pending = items.filter((i) => !i.done).length;
70
+ lines.push(`\n${pending} pending, ${items.length - pending} promoted/done`);
71
+ ctx.ui.notify(lines.join("\n"), "info");
72
+ }
73
+ async function addBacklogItem(basePath, title, ctx) {
74
+ if (!title) {
75
+ ctx.ui.notify("Usage: /gsd backlog add <title>", "warning");
76
+ return;
77
+ }
78
+ const items = parseBacklog(basePath);
79
+ const id = nextBacklogId(items);
80
+ const date = new Date().toISOString().slice(0, 10);
81
+ items.push({ id, title: title.replace(/^['"]|['"]$/g, ""), done: false, note: `added ${date}` });
82
+ writeBacklog(basePath, items);
83
+ ctx.ui.notify(`Added ${id}: "${title}"`, "success");
84
+ }
85
+ async function promoteBacklogItem(basePath, itemId, ctx, pi) {
86
+ if (!itemId) {
87
+ ctx.ui.notify("Usage: /gsd backlog promote <id>\nExample: /gsd backlog promote 999.1", "warning");
88
+ return;
89
+ }
90
+ const items = parseBacklog(basePath);
91
+ const item = items.find((i) => i.id === itemId);
92
+ if (!item) {
93
+ ctx.ui.notify(`Backlog item ${itemId} not found.`, "warning");
94
+ return;
95
+ }
96
+ if (item.done) {
97
+ ctx.ui.notify(`${itemId} is already promoted/done.`, "info");
98
+ return;
99
+ }
100
+ // Promote — currently requires single-writer engine (not yet available)
101
+ // Mark as promoted in backlog for now; slice creation will be available with the engine.
102
+ item.done = true;
103
+ item.note = `promoted ${new Date().toISOString().slice(0, 10)}`;
104
+ writeBacklog(basePath, items);
105
+ ctx.ui.notify(`Promoted ${itemId}: "${item.title}" — add it to the roadmap manually or wait for engine slice commands.`, "info");
106
+ }
107
+ async function removeBacklogItem(basePath, itemId, ctx) {
108
+ if (!itemId) {
109
+ ctx.ui.notify("Usage: /gsd backlog remove <id>", "warning");
110
+ return;
111
+ }
112
+ const items = parseBacklog(basePath);
113
+ const idx = items.findIndex((i) => i.id === itemId);
114
+ if (idx === -1) {
115
+ ctx.ui.notify(`Backlog item ${itemId} not found.`, "warning");
116
+ return;
117
+ }
118
+ const removed = items.splice(idx, 1)[0];
119
+ writeBacklog(basePath, items);
120
+ ctx.ui.notify(`Removed ${removed.id}: "${removed.title}"`, "success");
121
+ }
122
+ export async function handleBacklog(args, ctx, pi) {
123
+ const basePath = process.cwd();
124
+ const parts = args.trim().split(/\s+/);
125
+ const sub = parts[0] ?? "";
126
+ const rest = parts.slice(1).join(" ");
127
+ switch (sub) {
128
+ case "":
129
+ return listBacklog(basePath, ctx);
130
+ case "add":
131
+ return addBacklogItem(basePath, rest, ctx);
132
+ case "promote":
133
+ return promoteBacklogItem(basePath, rest.trim(), ctx, pi);
134
+ case "remove":
135
+ return removeBacklogItem(basePath, rest.trim(), ctx);
136
+ default:
137
+ // Treat as implicit add
138
+ return addBacklogItem(basePath, args, ctx);
139
+ }
140
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * GSD Command — /gsd do
3
+ *
4
+ * Routes freeform natural language to the correct /gsd subcommand
5
+ * using keyword matching. Falls back to /gsd quick for task-like input.
6
+ */
7
+ const ROUTES = [
8
+ { keywords: ["progress", "status", "dashboard", "how far", "where are we"], command: "status" },
9
+ { keywords: ["auto", "autonomous", "run all", "keep going", "start auto"], command: "auto" },
10
+ { keywords: ["stop", "halt", "abort"], command: "stop" },
11
+ { keywords: ["pause", "break", "take a break"], command: "pause" },
12
+ { keywords: ["history", "past", "what happened", "previous"], command: "history" },
13
+ { keywords: ["doctor", "health", "diagnose", "check health"], command: "doctor" },
14
+ { keywords: ["clean up", "cleanup", "remove old", "prune", "tidy"], command: "cleanup" },
15
+ { keywords: ["export", "report", "share results"], command: "export" },
16
+ { keywords: ["ship", "pull request", "create pr", "open pr", "merge"], command: "ship" },
17
+ { keywords: ["discuss", "talk about", "architecture", "design"], command: "discuss" },
18
+ { keywords: ["undo", "revert", "rollback", "take back"], command: "undo" },
19
+ { keywords: ["skip", "skip task", "skip this"], command: "skip" },
20
+ { keywords: ["queue", "reorder", "milestone order", "order milestones"], command: "queue" },
21
+ { keywords: ["visualize", "viz", "graph", "chart", "show graph"], command: "visualize" },
22
+ { keywords: ["capture", "note", "idea", "thought", "remember"], command: "capture" },
23
+ { keywords: ["inspect", "database", "sqlite", "db state"], command: "inspect" },
24
+ { keywords: ["knowledge", "rule", "pattern", "lesson"], command: "knowledge" },
25
+ { keywords: ["session report", "session summary", "cost summary", "how much"], command: "session-report" },
26
+ { keywords: ["backlog", "parking lot", "later", "someday"], command: "backlog" },
27
+ { keywords: ["pr branch", "clean branch", "filter commits"], command: "pr-branch" },
28
+ { keywords: ["add tests", "write tests", "generate tests", "test coverage"], command: "add-tests" },
29
+ { keywords: ["next", "step", "next step", "what's next"], command: "next" },
30
+ { keywords: ["migrate", "migration", "convert", "upgrade"], command: "migrate" },
31
+ { keywords: ["steer", "change direction", "pivot", "redirect"], command: "steer" },
32
+ { keywords: ["park", "shelve", "set aside"], command: "park" },
33
+ { keywords: ["widget", "toggle widget"], command: "widget" },
34
+ { keywords: ["logs", "debug logs", "log files"], command: "logs" },
35
+ ];
36
+ function matchRoute(input) {
37
+ const lower = input.toLowerCase();
38
+ let bestMatch = null;
39
+ for (const route of ROUTES) {
40
+ for (const keyword of route.keywords) {
41
+ if (lower.includes(keyword)) {
42
+ const score = keyword.length; // Longer match = higher confidence
43
+ if (!bestMatch || score > bestMatch.score) {
44
+ // Strip the matched keyword from input to get remaining args
45
+ const idx = lower.indexOf(keyword);
46
+ const remaining = (input.slice(0, idx) + input.slice(idx + keyword.length)).trim();
47
+ bestMatch = { command: route.command, remainingArgs: remaining, score };
48
+ }
49
+ }
50
+ }
51
+ }
52
+ return bestMatch;
53
+ }
54
+ export async function handleDo(args, ctx, pi) {
55
+ if (!args.trim()) {
56
+ ctx.ui.notify("Usage: /gsd do <what you want to do>\n\n" +
57
+ "Examples:\n" +
58
+ " /gsd do show me progress\n" +
59
+ " /gsd do run autonomously\n" +
60
+ " /gsd do clean up old branches\n" +
61
+ " /gsd do fix the login bug", "warning");
62
+ return;
63
+ }
64
+ const match = matchRoute(args);
65
+ if (match) {
66
+ const fullCommand = match.remainingArgs
67
+ ? `${match.command} ${match.remainingArgs}`
68
+ : match.command;
69
+ ctx.ui.notify(`→ /gsd ${fullCommand}`, "info");
70
+ // Re-dispatch through the main dispatcher
71
+ const { handleGSDCommand } = await import("./commands/dispatcher.js");
72
+ await handleGSDCommand(fullCommand, ctx, pi);
73
+ return;
74
+ }
75
+ // No keyword match → treat as quick task
76
+ ctx.ui.notify(`→ /gsd quick ${args}`, "info");
77
+ const { handleQuick } = await import("./quick.js");
78
+ await handleQuick(args, ctx, pi);
79
+ }
@@ -449,7 +449,7 @@ export async function handleCleanupProjects(args, ctx) {
449
449
  * Prints counts of recovered items and the resulting project phase.
450
450
  */
451
451
  export async function handleRecover(ctx, basePath) {
452
- const { isDbAvailable: dbAvailable, _getAdapter, transaction: dbTransaction } = await import("./gsd-db.js");
452
+ const { isDbAvailable: dbAvailable, clearEngineHierarchy, transaction: dbTransaction } = await import("./gsd-db.js");
453
453
  const { migrateHierarchyToDb } = await import("./md-importer.js");
454
454
  const { invalidateStateCache } = await import("./state.js");
455
455
  if (!dbAvailable()) {
@@ -457,12 +457,12 @@ export async function handleRecover(ctx, basePath) {
457
457
  return;
458
458
  }
459
459
  try {
460
- // 1. Delete + re-populate inside a single transaction for atomicity
461
- const db = _getAdapter();
460
+ // 1. Delete + re-populate inside a single transaction for atomicity.
461
+ // clearEngineHierarchy() uses transaction() internally but transaction()
462
+ // is re-entrant, so wrapping in dbTransaction() keeps the whole
463
+ // clear+repopulate atomic.
462
464
  const counts = dbTransaction(() => {
463
- db.exec("DELETE FROM tasks");
464
- db.exec("DELETE FROM slices");
465
- db.exec("DELETE FROM milestones");
465
+ clearEngineHierarchy();
466
466
  return migrateHierarchyToDb(basePath);
467
467
  });
468
468
  // 3. Invalidate state cache so deriveState() picks up fresh DB data
@@ -0,0 +1,180 @@
1
+ /**
2
+ * GSD Command — /gsd pr-branch
3
+ *
4
+ * Creates a clean PR branch by cherry-picking commits while stripping
5
+ * any changes to .gsd/, .planning/, and PLAN.md paths. Useful for
6
+ * upstream PRs where planning artifacts should not be included.
7
+ */
8
+ import { execFileSync } from "node:child_process";
9
+ import { nativeGetCurrentBranch, nativeDetectMainBranch, nativeBranchExists, } from "./native-git-bridge.js";
10
+ const EXCLUDED_PATHS = [".gsd", ".planning", "PLAN.md"];
11
+ function git(basePath, args) {
12
+ return execFileSync("git", args, { cwd: basePath, encoding: "utf-8" }).trim();
13
+ }
14
+ function gitAllowFail(basePath, args) {
15
+ try {
16
+ execFileSync("git", args, { cwd: basePath, encoding: "utf-8", stdio: "pipe" });
17
+ }
18
+ catch {
19
+ // ignored — caller opts into non-fatal behavior
20
+ }
21
+ }
22
+ function hasStagedChanges(basePath) {
23
+ try {
24
+ execFileSync("git", ["diff", "--cached", "--quiet"], {
25
+ cwd: basePath,
26
+ stdio: "pipe",
27
+ });
28
+ return false;
29
+ }
30
+ catch {
31
+ return true;
32
+ }
33
+ }
34
+ function isValidBranchName(name) {
35
+ try {
36
+ execFileSync("git", ["check-ref-format", "--branch", name], { stdio: "pipe" });
37
+ return true;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ function getCodeOnlyCommits(basePath, base, head) {
44
+ try {
45
+ const allCommits = git(basePath, ["log", "--format=%H", `${base}..${head}`])
46
+ .split("\n")
47
+ .filter(Boolean);
48
+ const codeCommits = [];
49
+ for (const sha of allCommits) {
50
+ const files = git(basePath, ["diff-tree", "--no-commit-id", "--name-only", "-r", sha])
51
+ .split("\n")
52
+ .filter(Boolean);
53
+ const hasCodeChanges = files.some((f) => !f.startsWith(".gsd/") && !f.startsWith(".planning/") && f !== "PLAN.md");
54
+ if (hasCodeChanges) {
55
+ codeCommits.push(sha);
56
+ }
57
+ }
58
+ return codeCommits.reverse(); // chronological for cherry-picking
59
+ }
60
+ catch {
61
+ return [];
62
+ }
63
+ }
64
+ /**
65
+ * Cherry-pick a commit while stripping excluded paths from the resulting
66
+ * commit. Returns true if a commit was produced, false if nothing remained
67
+ * after filtering.
68
+ */
69
+ function cherryPickFiltered(basePath, sha) {
70
+ git(basePath, ["cherry-pick", "--no-commit", "--allow-empty", sha]);
71
+ // Unstage any excluded paths introduced by the cherry-pick.
72
+ gitAllowFail(basePath, ["reset", "HEAD", "--", ...EXCLUDED_PATHS]);
73
+ // Restore worktree state for excluded paths from HEAD (if tracked),
74
+ // then remove any newly introduced untracked files under those paths.
75
+ gitAllowFail(basePath, ["checkout", "HEAD", "--", ...EXCLUDED_PATHS]);
76
+ gitAllowFail(basePath, ["clean", "-fdq", "--", ...EXCLUDED_PATHS]);
77
+ if (!hasStagedChanges(basePath)) {
78
+ // Nothing remained after filtering — discard worktree residue and skip.
79
+ git(basePath, ["reset", "--hard", "HEAD"]);
80
+ return false;
81
+ }
82
+ git(basePath, ["commit", "-C", sha]);
83
+ return true;
84
+ }
85
+ function assertNoExcludedPaths(basePath, base) {
86
+ const files = git(basePath, [
87
+ "diff",
88
+ "--name-only",
89
+ `${base}..HEAD`,
90
+ ])
91
+ .split("\n")
92
+ .filter(Boolean);
93
+ const leaked = files.filter((f) => f.startsWith(".gsd/") || f.startsWith(".planning/") || f === "PLAN.md");
94
+ if (leaked.length > 0) {
95
+ throw new Error(`PR branch still contains excluded paths: ${leaked.slice(0, 5).join(", ")}${leaked.length > 5 ? ` (+${leaked.length - 5} more)` : ""}`);
96
+ }
97
+ }
98
+ export async function handlePrBranch(args, ctx) {
99
+ const basePath = process.cwd();
100
+ const dryRun = args.includes("--dry-run");
101
+ const nameMatch = args.match(/--name\s+(\S+)/);
102
+ const currentBranch = nativeGetCurrentBranch(basePath);
103
+ const mainBranch = nativeDetectMainBranch(basePath);
104
+ // Determine base ref (prefer upstream/main if available)
105
+ let baseRef;
106
+ try {
107
+ git(basePath, ["rev-parse", "--verify", "upstream/main"]);
108
+ baseRef = "upstream/main";
109
+ }
110
+ catch {
111
+ baseRef = mainBranch;
112
+ }
113
+ // Find commits with code changes
114
+ const commits = getCodeOnlyCommits(basePath, baseRef, "HEAD");
115
+ if (commits.length === 0) {
116
+ ctx.ui.notify("No code-only commits found (all commits only touch .gsd/ files).", "info");
117
+ return;
118
+ }
119
+ if (dryRun) {
120
+ const lines = [`Would create PR branch with ${commits.length} commits (filtering .gsd/ paths):\n`];
121
+ for (const sha of commits) {
122
+ const msg = git(basePath, ["log", "--format=%s", "-1", sha]);
123
+ lines.push(` ${sha.slice(0, 8)} ${msg}`);
124
+ }
125
+ ctx.ui.notify(lines.join("\n"), "info");
126
+ return;
127
+ }
128
+ const requestedName = nameMatch?.[1];
129
+ if (requestedName && !isValidBranchName(requestedName)) {
130
+ ctx.ui.notify(`Invalid branch name: ${requestedName}. Must satisfy git check-ref-format.`, "error");
131
+ return;
132
+ }
133
+ const defaultName = `pr/${currentBranch}`;
134
+ const prBranch = requestedName ?? defaultName;
135
+ if (!isValidBranchName(prBranch)) {
136
+ ctx.ui.notify(`Derived branch name is invalid: ${prBranch}. Use --name to override.`, "error");
137
+ return;
138
+ }
139
+ if (nativeBranchExists(basePath, prBranch)) {
140
+ ctx.ui.notify(`Branch ${prBranch} already exists. Use --name to specify a different name, or delete it first.`, "warning");
141
+ return;
142
+ }
143
+ try {
144
+ // Create clean branch from base
145
+ git(basePath, ["checkout", "-b", prBranch, baseRef]);
146
+ // Cherry-pick with path filter
147
+ let picked = 0;
148
+ let skipped = 0;
149
+ for (const sha of commits) {
150
+ try {
151
+ if (cherryPickFiltered(basePath, sha)) {
152
+ picked++;
153
+ }
154
+ else {
155
+ skipped++;
156
+ }
157
+ }
158
+ catch (pickErr) {
159
+ gitAllowFail(basePath, ["cherry-pick", "--abort"]);
160
+ gitAllowFail(basePath, ["reset", "--hard", "HEAD"]);
161
+ const detail = pickErr instanceof Error ? pickErr.message : String(pickErr);
162
+ ctx.ui.notify(`Cherry-pick conflict at ${sha.slice(0, 8)}. Picked ${picked}/${commits.length} commits. Resolve manually.\n${detail}`, "warning");
163
+ git(basePath, ["checkout", currentBranch]);
164
+ return;
165
+ }
166
+ }
167
+ // Post-condition: no excluded paths should appear in the PR branch diff.
168
+ assertNoExcludedPaths(basePath, baseRef);
169
+ const skippedMsg = skipped > 0 ? ` (${skipped} skipped — contained only planning artifacts)` : "";
170
+ ctx.ui.notify(`Created ${prBranch} with ${picked} commits${skippedMsg} (no .gsd/ artifacts).\nSwitch back: git checkout ${currentBranch}`, "success");
171
+ }
172
+ catch (err) {
173
+ // Restore original branch on failure
174
+ gitAllowFail(basePath, ["cherry-pick", "--abort"]);
175
+ gitAllowFail(basePath, ["reset", "--hard", "HEAD"]);
176
+ gitAllowFail(basePath, ["checkout", currentBranch]);
177
+ const msg = err instanceof Error ? err.message : String(err);
178
+ ctx.ui.notify(`Failed to create PR branch: ${msg}`, "error");
179
+ }
180
+ }