ralphctl 0.2.4 → 0.3.0

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 (58) hide show
  1. package/README.md +21 -9
  2. package/dist/add-GX7P7XTT.mjs +16 -0
  3. package/dist/add-JGUOR4Z5.mjs +18 -0
  4. package/dist/bootstrap-FMHG6DRY.mjs +11 -0
  5. package/dist/chunk-3QBEBKMZ.mjs +103 -0
  6. package/dist/chunk-4GHVNKLV.mjs +5088 -0
  7. package/dist/{chunk-EDJX7TT6.mjs → chunk-57UWLHRH.mjs} +22 -2
  8. package/dist/chunk-747KW2RW.mjs +24 -0
  9. package/dist/chunk-CDOPLXFK.mjs +5485 -0
  10. package/dist/{chunk-7TG3EAQ2.mjs → chunk-CFUVE2BP.mjs} +1 -5
  11. package/dist/{chunk-IB6OCKZW.mjs → chunk-CTP2A436.mjs} +60 -55
  12. package/dist/{chunk-UBPZHHCD.mjs → chunk-D2YGPLIV.mjs} +84 -41
  13. package/dist/{chunk-QBXHAXHI.mjs → chunk-FKMKOWLA.mjs} +154 -208
  14. package/dist/chunk-HL4ZMHCQ.mjs +261 -0
  15. package/dist/{chunk-OEUJDSHY.mjs → chunk-IWXBJD2D.mjs} +1 -1
  16. package/dist/chunk-JXMHLW42.mjs +227 -0
  17. package/dist/{chunk-EUNAUHC3.mjs → chunk-NUYQK5MN.mjs} +80 -29
  18. package/dist/{chunk-JRFOUFD3.mjs → chunk-YCDUVPRT.mjs} +32 -52
  19. package/dist/cli.mjs +168 -3978
  20. package/dist/create-7WFSCMP4.mjs +15 -0
  21. package/dist/{handle-TA4MYNQJ.mjs → handle-BBAZJ44Y.mjs} +2 -2
  22. package/dist/mount-XZPBDRPZ.mjs +6751 -0
  23. package/dist/{project-YONEJICR.mjs → project-2IE7VWDB.mjs} +9 -5
  24. package/dist/prompts/harness-context.md +5 -0
  25. package/dist/prompts/ideate-auto.md +34 -19
  26. package/dist/prompts/ideate.md +21 -4
  27. package/dist/prompts/plan-auto.md +19 -24
  28. package/dist/prompts/plan-common.md +42 -17
  29. package/dist/prompts/plan-interactive.md +16 -21
  30. package/dist/prompts/signals-evaluation.md +6 -0
  31. package/dist/prompts/signals-planning.md +5 -0
  32. package/dist/prompts/signals-task.md +7 -0
  33. package/dist/prompts/sprint-feedback.md +48 -0
  34. package/dist/prompts/task-evaluation-resume.md +27 -13
  35. package/dist/prompts/task-evaluation.md +44 -34
  36. package/dist/prompts/task-execution.md +46 -46
  37. package/dist/prompts/ticket-refine.md +6 -5
  38. package/dist/prompts/validation-checklist.md +14 -0
  39. package/dist/{resolver-RXEY6EJE.mjs → resolver-EOE5WUMV.mjs} +5 -5
  40. package/dist/{sprint-FGLWYWKX.mjs → sprint-OGOFEJJH.mjs} +7 -9
  41. package/dist/start-MMWC7QLI.mjs +17 -0
  42. package/package.json +15 -13
  43. package/dist/add-3T225IX5.mjs +0 -16
  44. package/dist/add-6A5432U2.mjs +0 -16
  45. package/dist/chunk-742XQ7FL.mjs +0 -551
  46. package/dist/chunk-7LZ6GOGN.mjs +0 -53
  47. package/dist/chunk-DUU5346E.mjs +0 -59
  48. package/dist/chunk-U62BX47C.mjs +0 -4231
  49. package/dist/create-MYGOWO2F.mjs +0 -12
  50. package/dist/multiline-OHSNFCRG.mjs +0 -40
  51. package/dist/wizard-HWOH2HPV.mjs +0 -193
  52. package/schemas/config.schema.json +0 -30
  53. package/schemas/ideate-output.schema.json +0 -22
  54. package/schemas/projects.schema.json +0 -58
  55. package/schemas/requirements-output.schema.json +0 -24
  56. package/schemas/sprint.schema.json +0 -109
  57. package/schemas/task-import.schema.json +0 -56
  58. package/schemas/tasks.schema.json +0 -98
package/dist/cli.mjs CHANGED
@@ -1,3832 +1,96 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- addCheckScriptToRepository,
4
- projectAddCommand
5
- } from "./chunk-UBPZHHCD.mjs";
6
- import {
7
- addTask,
8
- areAllTasksDone,
9
- branchExists,
10
- buildHeadlessAiRequest,
11
- buildIdeateAutoPrompt,
12
- buildIdeatePrompt,
13
- buildTicketRefinePrompt,
14
- exportRequirementsToMarkdown,
15
- extractJsonArray,
16
- extractJsonObject,
17
- formatTicketForPrompt,
18
- getActiveProvider,
19
- getCurrentBranch,
20
- getDefaultBranch,
21
- getNextTask,
22
- getTask,
23
- getTaskImportSchema,
24
- getTasks,
25
- importTasks,
26
- inputPositiveInt,
27
- isGhAvailable,
28
- isGlabAvailable,
29
- listTasks,
30
- parsePlanningBlocked,
31
- parseRequirementsFile,
32
- parseTasksJson,
33
- providerDisplayName,
34
- removeTask,
35
- renderParsedTasksTable,
36
- reorderByDependencies,
37
- reorderTask,
38
- resolveProvider,
39
- runAiSession,
40
- saveTasks,
41
- selectProject,
42
- selectProjectPaths,
43
- selectProjectRepository,
44
- selectSprint,
45
- selectTask,
46
- selectTaskStatus,
47
- selectTicket,
48
- spawnHeadless,
49
- spawnInteractive,
50
- sprintPlanCommand,
51
- sprintRefineCommand,
52
- sprintStartCommand,
53
- updateTaskStatus,
54
- validateImportTasks
55
- } from "./chunk-U62BX47C.mjs";
56
- import {
57
- escapableSelect
58
- } from "./chunk-7LZ6GOGN.mjs";
59
- import {
60
- sprintCreateCommand
61
- } from "./chunk-DUU5346E.mjs";
62
- import {
63
- addTicket,
64
- allRequirementsApproved,
65
- editorInput,
66
- fetchIssueFromUrl,
67
- formatIssueContext,
68
- formatTicketDisplay,
69
- getPendingRequirements,
70
- getTicket,
71
- groupTicketsByProject,
72
- listTickets,
73
- removeTicket,
74
- ticketAddCommand,
75
- updateTicket
76
- } from "./chunk-742XQ7FL.mjs";
77
- import {
78
- EXIT_ERROR,
79
- exitWithCode
80
- } from "./chunk-7TG3EAQ2.mjs";
81
- import {
82
- addProjectRepo,
83
- getProject,
84
- listProjects,
85
- removeProject,
86
- removeProjectRepo
87
- } from "./chunk-EUNAUHC3.mjs";
88
- import {
89
- DEFAULT_EVALUATION_ITERATIONS,
90
- assertSprintStatus,
91
- closeSprint,
92
- deleteSprint,
93
- getAiProvider,
94
- getConfig,
95
- getCurrentSprint,
96
- getCurrentSprintOrThrow,
97
- getEditor,
98
- getEvaluationIterations,
99
- getProgress,
100
- getSprint,
101
- listSprints,
102
- logProgress,
103
- resolveSprintId,
104
- saveSprint,
105
- setAiProvider,
106
- setCurrentSprint,
107
- setEditor,
108
- setEvaluationIterations,
109
- withFileLock
110
- } from "./chunk-JRFOUFD3.mjs";
111
- import {
112
- ensureError,
113
- wrapAsync
114
- } from "./chunk-OEUJDSHY.mjs";
115
- import {
116
- AiProviderSchema,
117
- IdeateOutputSchema,
118
- ImportTasksSchema,
119
- RequirementStatusSchema,
120
- SprintSchema,
121
- SprintStatusSchema,
122
- TaskStatusSchema,
123
- TasksSchema,
124
- assertSafeCwd,
125
- ensureDir,
126
- expandTilde,
127
- fileExists,
128
- getDataDir,
129
- getIdeateDir,
130
- getRefinementDir,
131
- getSchemaPath,
132
- getSprintDir,
133
- getSprintFilePath,
134
- getTasksFilePath,
135
- readValidatedJson,
136
- validateProjectPath
137
- } from "./chunk-IB6OCKZW.mjs";
138
- import {
139
- DomainError,
140
- NoCurrentSprintError,
141
- ProjectNotFoundError,
142
- SprintNotFoundError,
143
- SprintStatusError,
144
- TaskNotFoundError,
145
- TicketNotFoundError
146
- } from "./chunk-EDJX7TT6.mjs";
147
- import {
148
- DETAIL_LABEL_WIDTH,
149
- badge,
150
- boxChars,
151
- clearScreen,
152
- colors,
153
- createSpinner,
154
- emoji,
155
- error,
156
- field,
157
- fieldMultiline,
158
- formatSprintStatus,
159
- formatTaskStatus,
160
- getQuoteForContext,
161
- horizontalLine,
162
- icons,
163
- labelValue,
164
- log,
165
- muted,
166
- printCountSummary,
167
- printHeader,
168
- printSeparator,
169
- progressBar,
170
- renderCard,
171
- renderTable,
172
- showBanner,
173
- showEmpty,
174
- showError,
175
- showInfo,
176
- showNextStep,
177
- showNextSteps,
178
- showRandomQuote,
179
- showSuccess,
180
- showTip,
181
- showWarning,
182
- success,
183
- terminalBell
184
- } from "./chunk-QBXHAXHI.mjs";
185
-
186
- // src/cli.ts
187
- import { Command } from "commander";
188
-
189
- // src/interactive/menu.ts
190
- import { Separator } from "@inquirer/prompts";
191
- var SEPARATOR_WIDTH = 48;
192
- function titled(label) {
193
- const lineLen = Math.max(2, SEPARATOR_WIDTH - label.length - 4);
194
- return new Separator(colors.muted(`
195
- \u2500\u2500 ${label} ${"\u2500".repeat(lineLen)}`));
196
- }
197
- function line() {
198
- return new Separator(colors.muted("\u2500".repeat(SEPARATOR_WIDTH)));
199
- }
200
- var WORKFLOW_ACTIONS = {
201
- sprint: /* @__PURE__ */ new Set(["create", "refine", "ideate", "plan", "start", "close"]),
202
- ticket: /* @__PURE__ */ new Set(["add", "refine"]),
203
- task: /* @__PURE__ */ new Set(["add", "import"]),
204
- progress: /* @__PURE__ */ new Set(["log"])
205
- };
206
- function isWorkflowAction(group, subCommand) {
207
- return WORKFLOW_ACTIONS[group]?.has(subCommand) ?? false;
208
- }
209
- function buildPlanActions(ctx) {
210
- const items = [];
211
- const isDraft = ctx.currentSprintStatus === "draft";
212
- const hasSprint = ctx.currentSprintId !== null;
213
- items.push({ name: "Create Sprint", value: "action:sprint:create", description: "Start a new sprint" });
214
- const addTicketDisabled = !hasSprint ? "create a sprint first" : !isDraft ? "need draft sprint" : !ctx.hasProjects ? "add a project first" : false;
215
- items.push({
216
- name: "Add Ticket",
217
- value: "action:ticket:add",
218
- description: "Add work to current sprint",
219
- disabled: addTicketDisabled
220
- });
221
- let refineDisabled = false;
222
- let refineDesc = "Clarify ticket requirements";
223
- if (!hasSprint) {
224
- refineDisabled = "create a sprint first";
225
- } else if (!isDraft) {
226
- refineDisabled = "need draft sprint";
227
- } else if (ctx.ticketCount === 0) {
228
- refineDisabled = "add tickets first";
229
- } else if (ctx.pendingRequirements === 0) {
230
- refineDisabled = "all tickets refined";
231
- } else {
232
- refineDesc = `${String(ctx.pendingRequirements)} ticket${ctx.pendingRequirements !== 1 ? "s" : ""} pending`;
233
- }
234
- items.push({
235
- name: "Refine Requirements",
236
- value: "action:sprint:refine",
237
- description: refineDesc,
238
- disabled: refineDisabled
239
- });
240
- let planDisabled = false;
241
- const planDesc = "Generate tasks from requirements";
242
- if (!hasSprint) {
243
- planDisabled = "create a sprint first";
244
- } else if (!isDraft) {
245
- planDisabled = "need draft sprint";
246
- } else if (ctx.ticketCount === 0) {
247
- planDisabled = "add tickets first";
248
- } else if (!ctx.allRequirementsApproved) {
249
- planDisabled = "refine all tickets first";
250
- }
251
- items.push({
252
- name: ctx.taskCount > 0 ? "Re-Plan Tasks" : "Plan Tasks",
253
- value: "action:sprint:plan",
254
- description: planDesc,
255
- disabled: planDisabled
256
- });
257
- const ideateDisabled = !hasSprint ? "create a sprint first" : !isDraft ? "need draft sprint" : !ctx.hasProjects ? "add a project first" : false;
258
- items.push({
259
- name: "Ideate",
260
- value: "action:sprint:ideate",
261
- description: "Quick idea to tasks",
262
- disabled: ideateDisabled
263
- });
264
- return items;
265
- }
266
- function buildExecuteActions(ctx) {
267
- const items = [];
268
- const isDraft = ctx.currentSprintStatus === "draft";
269
- const isActive = ctx.currentSprintStatus === "active";
270
- const hasSprint = ctx.currentSprintId !== null;
271
- let startDisabled = false;
272
- if (!hasSprint) {
273
- startDisabled = "create a sprint first";
274
- } else if (!isDraft && !isActive) {
275
- startDisabled = "need draft or active sprint";
276
- } else if (ctx.taskCount === 0) {
277
- startDisabled = "plan tasks first";
278
- }
279
- items.push({
280
- name: "Start Sprint",
281
- value: "action:sprint:start",
282
- description: "Begin implementation",
283
- disabled: startDisabled
284
- });
285
- items.push({
286
- name: "Health Check",
287
- value: "action:sprint:health",
288
- description: "Diagnose blockers and stale tasks",
289
- disabled: !hasSprint ? "no sprint" : false
290
- });
291
- items.push({
292
- name: "Close Sprint",
293
- value: "action:sprint:close",
294
- description: "Close the current sprint",
295
- disabled: !isActive ? "need active sprint" : false
296
- });
297
- return items;
298
- }
299
- function buildMainMenu(ctx) {
300
- const items = [];
301
- let defaultValue;
302
- if (ctx.nextAction) {
303
- const actionValue = `action:${ctx.nextAction.group}:${ctx.nextAction.subCommand}`;
304
- items.push({
305
- name: `\u2192 ${ctx.nextAction.label}`,
306
- value: actionValue,
307
- description: ctx.nextAction.description
308
- });
309
- defaultValue = actionValue;
310
- }
311
- items.push(titled("PLAN"));
312
- for (const action of buildPlanActions(ctx)) {
313
- items.push(action);
314
- }
315
- items.push(titled("EXECUTE"));
316
- for (const action of buildExecuteActions(ctx)) {
317
- items.push(action);
318
- }
319
- items.push(titled("BROWSE"));
320
- items.push({ name: "Sprints", value: "sprint", description: "List, show, switch" });
321
- items.push({ name: "Tickets", value: "ticket", description: "List, show, edit" });
322
- items.push({ name: "Tasks", value: "task", description: "List, show, manage" });
323
- items.push(titled("SETUP"));
324
- items.push({ name: "Projects", value: "project", description: "Manage projects & repositories" });
325
- items.push({ name: "Configuration", value: "config", description: "AI provider, settings" });
326
- items.push({ name: "Doctor", value: "action:doctor:run", description: "Check environment health" });
327
- items.push(titled("SESSION"));
328
- if (!ctx.currentSprintId) {
329
- items.push({ name: "Quick Start Wizard", value: "wizard", description: "Guided sprint setup" });
330
- }
331
- items.push({ name: "Exit", value: "exit" });
332
- return { items, defaultValue };
333
- }
334
- function buildSprintSubMenu(ctx) {
335
- const items = [];
336
- items.push(titled("BROWSE"));
337
- items.push({ name: "List", value: "list", description: "List all sprints" });
338
- items.push({ name: "Show", value: "show", description: "Show sprint details" });
339
- items.push({ name: "Set Current", value: "current", description: "Set current sprint" });
340
- items.push(titled("EXPORT"));
341
- items.push({
342
- name: "Requirements",
343
- value: "requirements",
344
- description: "Export refined requirements"
345
- });
346
- items.push({ name: "Context", value: "context", description: "Output full sprint context" });
347
- items.push({ name: "Progress", value: "progress show", description: "View progress log" });
348
- items.push(titled("MANAGE"));
349
- items.push({ name: "Log Progress", value: "progress log", description: "Add progress entry" });
350
- items.push({ name: "Delete", value: "delete", description: "Delete a sprint permanently" });
351
- items.push(line());
352
- items.push({ name: "Back", value: "back", description: "Return to main menu" });
353
- const titleSuffix = ctx.currentSprintName ? ` \u2014 ${ctx.currentSprintName} (${ctx.currentSprintStatus ?? "unknown"})` : "";
354
- return { title: `Sprint${titleSuffix}`, items };
355
- }
356
- function buildTicketSubMenu(ctx) {
357
- const items = [];
358
- items.push({
359
- name: "Add",
360
- value: "add",
361
- description: ctx.hasProjects ? "Add a ticket" : "Add a ticket (add a project first)",
362
- disabled: !ctx.hasProjects ? "add a project first" : false
363
- });
364
- items.push({ name: "Edit", value: "edit", description: "Edit a ticket" });
365
- items.push({ name: "List", value: "list", description: "List all tickets" });
366
- items.push({ name: "Show", value: "show", description: "Show ticket details" });
367
- const approvedCount = ctx.ticketCount - ctx.pendingRequirements;
368
- let refineDisabled = false;
369
- if (ctx.currentSprintStatus !== "draft") {
370
- refineDisabled = "need draft sprint";
371
- } else if (approvedCount === 0) {
372
- refineDisabled = "no approved tickets";
373
- }
374
- items.push({
375
- name: "Refine",
376
- value: "refine",
377
- description: "Re-refine approved requirements",
378
- disabled: refineDisabled
379
- });
380
- items.push(line());
381
- items.push({ name: "Remove", value: "remove", description: "Remove a ticket" });
382
- items.push({ name: "Back", value: "back", description: "Return to main menu" });
383
- const titleSuffix = ctx.currentSprintName ? ` \u2014 ${ctx.currentSprintName}` : "";
384
- return { title: `Ticket${titleSuffix}`, items };
385
- }
386
- function buildTaskSubMenu(ctx) {
387
- const items = [];
388
- items.push(titled("VIEW"));
389
- items.push({ name: "List", value: "list", description: "List all tasks" });
390
- items.push({ name: "Show", value: "show", description: "Show task details" });
391
- items.push({ name: "Next", value: "next", description: "Get next task" });
392
- items.push(titled("MANAGE"));
393
- items.push({ name: "Add", value: "add", description: "Add a new task" });
394
- items.push({ name: "Import", value: "import", description: "Import from JSON" });
395
- items.push({ name: "Status", value: "status", description: "Update status" });
396
- items.push({ name: "Reorder", value: "reorder", description: "Change priority" });
397
- items.push(line());
398
- items.push({ name: "Remove", value: "remove", description: "Remove a task" });
399
- items.push({ name: "Back", value: "back", description: "Return to main menu" });
400
- const titleSuffix = ctx.currentSprintName ? ` \u2014 ${ctx.currentSprintName}` : "";
401
- return { title: `Task${titleSuffix}`, items };
402
- }
403
- function buildProjectSubMenu() {
404
- const items = [];
405
- items.push({ name: "Add", value: "add", description: "Add a new project" });
406
- items.push({ name: "List", value: "list", description: "List all projects" });
407
- items.push({ name: "Show", value: "show", description: "Show project details" });
408
- items.push(titled("REPOSITORIES"));
409
- items.push({
410
- name: "Add Repository",
411
- value: "repo add",
412
- description: "Add repository to project"
413
- });
414
- items.push({ name: "Remove Repository", value: "repo remove", description: "Remove repository" });
415
- items.push(line());
416
- items.push({ name: "Remove", value: "remove", description: "Remove a project" });
417
- items.push({ name: "Back", value: "back", description: "Return to main menu" });
418
- return { title: "Project", items };
419
- }
420
- function buildConfigSubMenu() {
421
- const items = [];
422
- items.push({ name: "Show Settings", value: "show", description: "View current configuration" });
423
- items.push({ name: "Set AI Provider", value: "set provider", description: "Choose Claude Code or GitHub Copilot" });
424
- items.push({ name: "Set Editor", value: "set editor", description: "Editor for refinement sessions" });
425
- items.push({
426
- name: "Set Evaluation Iterations",
427
- value: "set evaluationIterations",
428
- description: "Generator-evaluator loop count (0 = disabled)"
429
- });
430
- items.push(line());
431
- items.push({ name: "Back", value: "back", description: "Return to main menu" });
432
- return { title: "Configuration", items };
433
- }
434
- function buildSubMenu(group, ctx) {
435
- switch (group) {
436
- case "sprint":
437
- return buildSprintSubMenu(ctx);
438
- case "ticket":
439
- return buildTicketSubMenu(ctx);
440
- case "task":
441
- return buildTaskSubMenu(ctx);
442
- case "project":
443
- return buildProjectSubMenu();
444
- case "config":
445
- return buildConfigSubMenu();
446
- default:
447
- return null;
448
- }
449
- }
450
-
451
- // src/interactive/dashboard.ts
452
- async function loadDashboardData() {
453
- const sprintId = await getCurrentSprint();
454
- if (!sprintId) return null;
455
- const r = await wrapAsync(async () => {
456
- const sprint = await getSprint(sprintId);
457
- const tasks = await getTasks(sprintId);
458
- const pendingTickets = getPendingRequirements(sprint.tickets);
459
- const pendingCount = pendingTickets.length;
460
- const approvedCount = sprint.tickets.length - pendingCount;
461
- const doneIds = new Set(tasks.filter((t) => t.status === "done").map((t) => t.id));
462
- const blockedCount = tasks.filter(
463
- (t) => t.status !== "done" && t.blockedBy.length > 0 && !t.blockedBy.every((id) => doneIds.has(id))
464
- ).length;
465
- const ticketIdsWithTasks = new Set(tasks.map((t) => t.ticketId).filter(Boolean));
466
- const plannedTicketCount = sprint.tickets.filter((t) => ticketIdsWithTasks.has(t.id)).length;
467
- const aiProvider = await getAiProvider();
468
- return { sprint, tasks, approvedCount, pendingCount, blockedCount, plannedTicketCount, aiProvider };
469
- }, ensureError);
470
- return r.ok ? r.value : null;
471
- }
472
- function getNextAction(data) {
473
- const { sprint, tasks, pendingCount, approvedCount } = data;
474
- const ticketCount = sprint.tickets.length;
475
- const totalTasks = tasks.length;
476
- const allDone = totalTasks > 0 && tasks.every((t) => t.status === "done");
477
- if (sprint.status === "draft") {
478
- if (ticketCount === 0) {
479
- return { label: "Add Ticket", description: "No tickets yet", group: "ticket", subCommand: "add" };
480
- }
481
- if (pendingCount > 0) {
482
- return {
483
- label: "Refine Requirements",
484
- description: `${String(pendingCount)} ticket${pendingCount !== 1 ? "s" : ""} pending`,
485
- group: "sprint",
486
- subCommand: "refine"
487
- };
488
- }
489
- if (approvedCount > 0 && totalTasks === 0) {
490
- return { label: "Plan Tasks", description: "Requirements approved", group: "sprint", subCommand: "plan" };
491
- }
492
- if (totalTasks > 0 && data.plannedTicketCount < ticketCount) {
493
- const unplanned = ticketCount - data.plannedTicketCount;
494
- return {
495
- label: "Re-Plan Tasks",
496
- description: `${String(unplanned)} unplanned ticket${unplanned !== 1 ? "s" : ""}`,
497
- group: "sprint",
498
- subCommand: "plan"
499
- };
500
- }
501
- if (totalTasks > 0) {
502
- return {
503
- label: "Start Sprint",
504
- description: `${String(totalTasks)} task${totalTasks !== 1 ? "s" : ""} ready`,
505
- group: "sprint",
506
- subCommand: "start"
507
- };
508
- }
509
- }
510
- if (sprint.status === "active") {
511
- if (allDone) {
512
- return { label: "Close Sprint", description: "All tasks done", group: "sprint", subCommand: "close" };
513
- }
514
- return {
515
- label: "Continue Work",
516
- description: `${String(totalTasks - tasks.filter((t) => t.status === "done").length)} task${totalTasks - tasks.filter((t) => t.status === "done").length !== 1 ? "s" : ""} remaining`,
517
- group: "sprint",
518
- subCommand: "start"
519
- };
520
- }
521
- return null;
522
- }
523
- function renderStatusHeader(data) {
524
- if (!data) return [];
525
- const { sprint, tasks, approvedCount, aiProvider } = data;
526
- const totalTasks = tasks.length;
527
- const ticketCount = sprint.tickets.length;
528
- const lines = [];
529
- const sprintLabel = colors.highlight(sprint.name);
530
- const statusBadge = formatSprintStatus(sprint.status);
531
- const ticketPart = `${String(ticketCount)} ticket${ticketCount !== 1 ? "s" : ""}`;
532
- const taskPart = `${String(totalTasks)} task${totalTasks !== 1 ? "s" : ""}`;
533
- const providerPart = aiProvider === "claude" ? "Claude" : aiProvider === "copilot" ? "Copilot" : null;
534
- const providerSuffix = providerPart ? ` | ${providerPart}` : "";
535
- lines.push(
536
- ` ${icons.sprint} ${sprintLabel} ${statusBadge} ${colors.muted(`| ${ticketPart} | ${taskPart}${providerSuffix}`)}`
537
- );
538
- if ((sprint.status === "active" || sprint.status === "closed") && totalTasks > 0) {
539
- const doneCount = tasks.filter((t) => t.status === "done").length;
540
- const bar = progressBar(doneCount, totalTasks, { width: 15 });
541
- const inProgressCount = tasks.filter((t) => t.status === "in_progress").length;
542
- const todoCount = tasks.filter((t) => t.status === "todo").length;
543
- lines.push(
544
- ` ${bar} ${colors.muted(`${String(doneCount)} done, ${String(inProgressCount)} active, ${String(todoCount)} todo`)}`
545
- );
546
- } else if (sprint.status === "draft" && ticketCount > 0) {
547
- const refinedColor = approvedCount === ticketCount ? colors.success : colors.warning;
548
- const refinedPart = refinedColor(`Refined: ${String(approvedCount)}/${String(ticketCount)}`);
549
- const plannedColor = data.plannedTicketCount === ticketCount ? colors.success : colors.muted;
550
- const plannedPart = plannedColor(`Planned: ${String(data.plannedTicketCount)}/${String(ticketCount)}`);
551
- lines.push(` ${refinedPart} ${colors.muted("|")} ${plannedPart}`);
552
- }
553
- return lines;
554
- }
555
- function renderDashboard(data) {
556
- const { sprint, tasks, approvedCount, blockedCount } = data;
557
- const chars = boxChars.rounded;
558
- const todoCount = tasks.filter((t) => t.status === "todo").length;
559
- const inProgressCount = tasks.filter((t) => t.status === "in_progress").length;
560
- const doneCount = tasks.filter((t) => t.status === "done").length;
561
- const totalTasks = tasks.length;
562
- const ticketCount = sprint.tickets.length;
563
- const lines = [];
564
- const sprintLabel = colors.highlight(sprint.name);
565
- const statusBadge = formatSprintStatus(sprint.status);
566
- lines.push(` ${icons.sprint} ${sprintLabel} ${statusBadge}`);
567
- const ticketSummary = `${String(ticketCount)} ticket${ticketCount !== 1 ? "s" : ""}`;
568
- const taskSummary = `${String(totalTasks)} task${totalTasks !== 1 ? "s" : ""}`;
569
- lines.push(` ${colors.muted(`${ticketSummary} ${chars.vertical} ${taskSummary}`)}`);
570
- if (totalTasks > 0) {
571
- const bar = progressBar(doneCount, totalTasks);
572
- const detail = colors.muted(
573
- `${String(doneCount)} done, ${String(inProgressCount)} active, ${String(todoCount)} todo`
574
- );
575
- lines.push(` ${bar} ${detail}`);
576
- }
577
- if (sprint.status === "draft" && ticketCount > 0) {
578
- const refinedColor = approvedCount === ticketCount ? colors.success : colors.warning;
579
- const refinedPart = refinedColor(`Refined: ${String(approvedCount)}/${String(ticketCount)}`);
580
- const plannedColor = data.plannedTicketCount === ticketCount ? colors.success : colors.muted;
581
- const plannedPart = plannedColor(`Planned: ${String(data.plannedTicketCount)}/${String(ticketCount)}`);
582
- lines.push(` ${refinedPart} ${colors.muted("|")} ${plannedPart}`);
583
- }
584
- if (blockedCount > 0) {
585
- lines.push(
586
- ` ${colors.warning(icons.warning)} ${colors.warning(`${String(blockedCount)} blocked task${blockedCount !== 1 ? "s" : ""}`)}`
587
- );
588
- }
589
- const nextAction = getNextAction(data);
590
- if (nextAction) {
591
- lines.push(
592
- ` ${colors.muted(icons.tip)} ${colors.muted(nextAction.label + ":")} ${colors.highlight(nextAction.description)}`
593
- );
594
- }
595
- return lines;
596
- }
597
- function renderEmptyDashboard() {
598
- const quote = getQuoteForContext("idle");
599
- return [
600
- ` ${emoji.donut} ${colors.muted("No current sprint")}`,
601
- ` ${colors.muted(`"${quote}"`)}`,
602
- "",
603
- ` ${colors.muted(icons.tip)} ${colors.muted("Get started:")}`,
604
- ` ${colors.muted("1.")} ${colors.muted("Add a project:")} ${colors.highlight("ralphctl project add")}`,
605
- ` ${colors.muted("2.")} ${colors.muted("Create a sprint:")} ${colors.highlight("ralphctl sprint create")}`
606
- ];
607
- }
608
- async function showDashboard() {
609
- const data = await loadDashboardData();
610
- console.log("");
611
- if (data) {
612
- const lines = renderDashboard(data);
613
- for (const line2 of lines) {
614
- console.log(line2);
615
- }
616
- } else {
617
- const lines = renderEmptyDashboard();
618
- for (const line2 of lines) {
619
- console.log(line2);
620
- }
621
- }
622
- console.log("");
623
- }
624
-
625
- // src/interactive/index.ts
626
- import { input as input5, select as select3 } from "@inquirer/prompts";
627
-
628
- // src/commands/project/list.ts
629
- async function projectListCommand() {
630
- const projects = await listProjects();
631
- if (projects.length === 0) {
632
- showEmpty("projects", "Add one with: ralphctl project add");
633
- return;
634
- }
635
- printHeader("Projects", icons.project);
636
- for (const project of projects) {
637
- const repoCount = muted(
638
- `(${String(project.repositories.length)} repo${project.repositories.length !== 1 ? "s" : ""})`
639
- );
640
- log.raw(`${colors.highlight(project.name)} ${project.displayName} ${repoCount}`);
641
- for (const repo of project.repositories) {
642
- log.item(`${repo.name} ${muted("\u2192")} ${muted(repo.path)}`);
643
- }
644
- if (project.description) {
645
- log.dim(` ${project.description}`);
646
- }
647
- log.newline();
648
- }
649
- log.dim(`Showing ${String(projects.length)} project(s)`);
650
- log.newline();
651
- }
652
-
653
- // src/commands/project/show.ts
654
- async function projectShowCommand(args) {
655
- let projectName = args[0];
656
- if (!projectName) {
657
- const selected = await selectProject("Select project to show:");
658
- if (!selected) return;
659
- projectName = selected;
660
- }
661
- const projectR = await wrapAsync(() => getProject(projectName), ensureError);
662
- if (!projectR.ok) {
663
- if (projectR.error instanceof ProjectNotFoundError) {
664
- showError(`Project not found: ${projectName}`);
665
- log.newline();
666
- } else {
667
- throw projectR.error;
668
- }
669
- return;
670
- }
671
- const project = projectR.value;
672
- const infoLines = [labelValue("Name", project.name), labelValue("Display Name", project.displayName)];
673
- if (project.description) {
674
- infoLines.push(labelValue("Description", project.description));
675
- }
676
- infoLines.push(labelValue("Repositories", String(project.repositories.length)));
677
- log.newline();
678
- console.log(renderCard(`${icons.project} ${project.displayName}`, infoLines));
679
- for (const repo of project.repositories) {
680
- log.newline();
681
- const repoLines = [labelValue("Path", repo.path)];
682
- if (repo.checkScript) {
683
- repoLines.push(labelValue("Check", colors.info(repo.checkScript)));
684
- } else {
685
- repoLines.push(muted("No check script configured"));
686
- }
687
- console.log(renderCard(` ${repo.name}`, repoLines));
688
- }
689
- log.newline();
690
- }
691
-
692
- // src/commands/project/remove.ts
693
- import { confirm } from "@inquirer/prompts";
694
- async function projectRemoveCommand(args) {
695
- const skipConfirm = args.includes("-y") || args.includes("--yes");
696
- let projectName = args.find((a) => !a.startsWith("-"));
697
- if (!projectName) {
698
- const selected = await selectProject("Select project to remove:");
699
- if (!selected) return;
700
- projectName = selected;
701
- }
702
- const projectR = await wrapAsync(() => getProject(projectName), ensureError);
703
- if (!projectR.ok) {
704
- if (projectR.error instanceof ProjectNotFoundError) {
705
- showError(`Project not found: ${projectName}`);
706
- console.log("");
707
- } else {
708
- throw projectR.error;
709
- }
710
- return;
711
- }
712
- const project = projectR.value;
713
- if (!skipConfirm) {
714
- const confirmed = await confirm({
715
- message: `Remove project "${project.displayName}" (${project.name})?`,
716
- default: false
717
- });
718
- if (!confirmed) {
719
- console.log(muted("\nProject removal cancelled.\n"));
720
- return;
721
- }
722
- }
723
- await removeProject(projectName);
724
- showSuccess("Project removed", [["Name", projectName]]);
725
- console.log("");
726
- }
727
-
728
- // src/commands/project/repo.ts
729
- import { basename, resolve } from "path";
730
- import { confirm as confirm2, input, select } from "@inquirer/prompts";
731
- async function projectRepoAddCommand(args) {
732
- let projectName = args[0];
733
- let path = args[1];
734
- if (!projectName) {
735
- const selected = await selectProject("Select project to add repository to:");
736
- if (!selected) return;
737
- projectName = selected;
738
- }
739
- path ??= await input({
740
- message: `${emoji.donut} Repository path to add:`,
741
- validate: (v) => v.trim().length > 0 ? true : "Path is required"
742
- });
743
- const resolvedPath = resolve(expandTilde(path));
744
- const bareRepo = { name: basename(resolvedPath), path: resolvedPath };
745
- log.info(`
746
- Configuring: ${bareRepo.name}`);
747
- const repoWithScripts = await addCheckScriptToRepository(bareRepo);
748
- const addR = await wrapAsync(() => addProjectRepo(projectName, repoWithScripts), ensureError);
749
- if (!addR.ok) {
750
- if (addR.error instanceof ProjectNotFoundError) {
751
- showError(`Project not found: ${projectName}`);
752
- } else {
753
- showError(addR.error.message);
754
- }
755
- log.newline();
756
- return;
757
- }
758
- showSuccess("Repository added", [["Project", projectName]]);
759
- log.newline();
760
- log.info("Current repositories:");
761
- for (const repo of addR.value.repositories) {
762
- log.item(`${repo.name} \u2192 ${repo.path}`);
763
- }
764
- log.newline();
765
- }
766
- async function projectRepoRemoveCommand(args) {
767
- const skipConfirm = args.includes("-y") || args.includes("--yes");
768
- const filteredArgs = args.filter((a) => !a.startsWith("-"));
769
- let projectName = filteredArgs[0];
770
- let path = filteredArgs[1];
771
- if (!projectName) {
772
- const selected = await selectProject("Select project to remove repository from:");
773
- if (!selected) return;
774
- projectName = selected;
775
- }
776
- const projectR = await wrapAsync(() => getProject(projectName), ensureError);
777
- if (!projectR.ok) {
778
- if (projectR.error instanceof ProjectNotFoundError) {
779
- showError(`Project not found: ${projectName}`);
780
- } else {
781
- showError(projectR.error.message);
782
- }
783
- log.newline();
784
- return;
785
- }
786
- const project = projectR.value;
787
- if (!path) {
788
- if (project.repositories.length === 0) {
789
- console.log(muted("\nNo repositories to remove.\n"));
790
- return;
791
- }
792
- path = await select({
793
- message: `${emoji.donut} Select repository to remove:`,
794
- choices: project.repositories.map((r) => ({
795
- name: `${r.name} (${r.path})`,
796
- value: r.path
797
- }))
798
- });
799
- }
800
- if (!skipConfirm) {
801
- const confirmed = await confirm2({
802
- message: `Remove repository "${path}" from project "${project.displayName}"?`,
803
- default: false
804
- });
805
- if (!confirmed) {
806
- console.log(muted("\nRepository removal cancelled.\n"));
807
- return;
808
- }
809
- }
810
- const removeR = await wrapAsync(() => removeProjectRepo(projectName, path), ensureError);
811
- if (!removeR.ok) {
812
- if (removeR.error instanceof ProjectNotFoundError) {
813
- showError(`Project not found: ${projectName}`);
814
- } else {
815
- showError(removeR.error.message);
816
- }
817
- log.newline();
818
- return;
819
- }
820
- showSuccess("Repository removed", [["Project", projectName]]);
821
- log.newline();
822
- log.info("Remaining repositories:");
823
- for (const repo of removeR.value.repositories) {
824
- log.item(`${repo.name} \u2192 ${repo.path}`);
825
- }
826
- log.newline();
827
- }
828
-
829
- // src/commands/sprint/list.ts
830
- async function sprintListCommand(args = []) {
831
- let statusFilter;
832
- for (let i = 0; i < args.length; i++) {
833
- if (args[i] === "--status" && args[i + 1]) {
834
- statusFilter = args[i + 1];
835
- i++;
836
- }
837
- }
838
- if (statusFilter) {
839
- const result = SprintStatusSchema.safeParse(statusFilter);
840
- if (!result.success) {
841
- showError(`Invalid status: "${statusFilter}". Valid values: draft, active, closed`);
842
- return;
843
- }
844
- }
845
- const sprints = await listSprints();
846
- if (sprints.length === 0) {
847
- showEmpty("sprints", "Create one with: ralphctl sprint create");
848
- return;
849
- }
850
- const filtered = statusFilter ? sprints.filter((s) => s.status === statusFilter) : sprints;
851
- const isFiltered = filtered.length !== sprints.length;
852
- const filterStr = statusFilter ? ` (filtered: status=${statusFilter})` : "";
853
- if (filtered.length === 0) {
854
- showEmpty("matching sprints", "Try adjusting your filters");
855
- return;
856
- }
857
- printHeader("Sprints", icons.sprint);
858
- const currentSprintId = await getCurrentSprint();
859
- const rows = filtered.map((sprint) => {
860
- const isCurrent = sprint.id === currentSprintId;
861
- const marker = isCurrent ? badge("current", "success") : "";
862
- return [marker, sprint.id, formatSprintStatus(sprint.status), sprint.name, String(sprint.tickets.length)];
863
- });
864
- console.log(
865
- renderTable(
866
- [
867
- { header: "", minWidth: 0 },
868
- { header: "ID" },
869
- { header: "Status" },
870
- { header: "Name" },
871
- { header: "Tickets", align: "right" }
872
- ],
873
- rows
874
- )
875
- );
876
- log.newline();
877
- const showingLabel = isFiltered ? `Showing ${String(filtered.length)} of ${String(sprints.length)} sprint(s)${filterStr}` : `Showing ${String(sprints.length)} sprint(s)`;
878
- log.dim(showingLabel);
879
- const hasActive = sprints.some((s) => s.status === "active");
880
- if (!hasActive) {
881
- log.newline();
882
- showNextStep("ralphctl sprint start", "start a sprint");
883
- }
884
- log.newline();
885
- }
886
-
887
- // src/commands/sprint/show.ts
888
- async function sprintShowCommand(args) {
889
- const sprintId = args[0];
890
- let id;
891
- const idR = await wrapAsync(() => resolveSprintId(sprintId), ensureError);
892
- if (!idR.ok) {
893
- const selected = await selectSprint("Select sprint to show:");
894
- if (!selected) return;
895
- id = selected;
896
- } else {
897
- id = idR.value;
898
- }
899
- const sprint = await getSprint(id);
900
- const tasks = await listTasks(id);
901
- const currentSprintId = await getCurrentSprint();
902
- const isCurrent = sprint.id === currentSprintId;
903
- const infoLines = [
904
- labelValue("ID", sprint.id + (isCurrent ? " " + badge("current", "success") : "")),
905
- labelValue("Status", formatSprintStatus(sprint.status)),
906
- labelValue("Created", new Date(sprint.createdAt).toLocaleString())
907
- ];
908
- if (sprint.activatedAt) {
909
- infoLines.push(labelValue("Activated", new Date(sprint.activatedAt).toLocaleString()));
910
- }
911
- if (sprint.closedAt) {
912
- infoLines.push(labelValue("Closed", new Date(sprint.closedAt).toLocaleString()));
913
- }
914
- if (sprint.branch) {
915
- infoLines.push(labelValue("Branch", sprint.branch));
916
- }
917
- log.newline();
918
- console.log(renderCard(`${icons.sprint} ${sprint.name}`, infoLines));
919
- log.newline();
920
- const ticketLines = [];
921
- if (sprint.tickets.length === 0) {
922
- ticketLines.push(muted("No tickets yet"));
923
- ticketLines.push(muted(`${icons.tip} Add with: ralphctl ticket add`));
924
- } else {
925
- const ticketsByProject = groupTicketsByProject(sprint.tickets);
926
- let first = true;
927
- for (const [projectName, tickets] of ticketsByProject) {
928
- if (!first) ticketLines.push("");
929
- first = false;
930
- ticketLines.push(`${colors.info(icons.project)} ${colors.info(projectName)}`);
931
- for (const ticket of tickets) {
932
- const reqBadge = ticket.requirementStatus === "approved" ? badge("approved", "success") : badge("pending", "warning");
933
- ticketLines.push(` ${icons.bullet} ${formatTicketDisplay(ticket)} ${reqBadge}`);
934
- }
935
- }
936
- }
937
- console.log(renderCard(`${icons.ticket} Tickets (${String(sprint.tickets.length)})`, ticketLines));
938
- log.newline();
939
- const taskLines = [];
940
- const tasksByStatus = {
941
- todo: tasks.filter((t) => t.status === "todo").length,
942
- in_progress: tasks.filter((t) => t.status === "in_progress").length,
943
- done: tasks.filter((t) => t.status === "done").length
944
- };
945
- if (tasks.length === 0) {
946
- taskLines.push(muted("No tasks yet"));
947
- taskLines.push(muted(`${icons.tip} Plan with: ralphctl sprint plan`));
948
- } else {
949
- taskLines.push(
950
- `${formatTaskStatus("todo")} ${String(tasksByStatus.todo)} ${formatTaskStatus("in_progress")} ${String(tasksByStatus.in_progress)} ${formatTaskStatus("done")} ${String(tasksByStatus.done)}`
951
- );
952
- taskLines.push(colors.muted(horizontalLine(40, "rounded")));
953
- for (const task of tasks) {
954
- const statusIcon = task.status === "done" ? icons.success : task.status === "in_progress" ? icons.active : icons.inactive;
955
- const statusColor = task.status === "done" ? "success" : task.status === "in_progress" ? "warning" : "muted";
956
- taskLines.push(`${muted(String(task.order) + ".")} ${badge(statusIcon, statusColor)} ${task.name}`);
957
- }
958
- }
959
- console.log(renderCard(`${icons.task} Tasks (${String(tasks.length)})`, taskLines));
960
- if (tasks.length > 0) {
961
- printCountSummary("Progress", tasksByStatus.done, tasks.length);
962
- }
963
- log.newline();
964
- if (sprint.status === "draft") {
965
- const pendingCount = getPendingRequirements(sprint.tickets).length;
966
- if (sprint.tickets.length === 0) {
967
- showNextStep("ralphctl ticket add --project <name>", "add tickets to this sprint");
968
- } else if (pendingCount > 0) {
969
- showNextStep("ralphctl sprint refine", "refine ticket requirements");
970
- } else if (tasks.length === 0) {
971
- showNextStep("ralphctl sprint plan", "generate tasks from tickets");
972
- } else {
973
- showNextStep("ralphctl sprint start", "begin implementation");
974
- }
975
- } else if (sprint.status === "active") {
976
- if (tasksByStatus.done === tasks.length && tasks.length > 0) {
977
- showNextStep("ralphctl sprint close", "all tasks done \u2014 close the sprint");
978
- } else {
979
- showNextStep("ralphctl sprint start", "continue implementation");
980
- }
981
- }
982
- log.newline();
983
- }
984
-
985
- // src/commands/sprint/context.ts
986
- async function sprintContextCommand(args) {
987
- const sprintId = args[0];
988
- let id;
989
- const idR = await wrapAsync(() => resolveSprintId(sprintId), ensureError);
990
- if (!idR.ok) {
991
- const selected = await selectSprint("Select sprint to show context for:");
992
- if (!selected) {
993
- showWarning("No sprints available.");
994
- showNextStep("ralphctl sprint create", "create a sprint first");
995
- log.newline();
996
- return;
997
- }
998
- id = selected;
999
- } else {
1000
- id = idR.value;
1001
- }
1002
- const sprint = await getSprint(id);
1003
- const tasks = await listTasks(id);
1004
- console.log(`# Sprint: ${sprint.name}`);
1005
- console.log(`ID: ${sprint.id}`);
1006
- console.log(`Status: ${sprint.status}`);
1007
- console.log("");
1008
- console.log("## Tickets");
1009
- console.log("");
1010
- if (sprint.tickets.length === 0) {
1011
- console.log("_No tickets defined_");
1012
- } else {
1013
- const ticketsByProject = groupTicketsByProject(sprint.tickets);
1014
- for (const [projectName, tickets] of ticketsByProject) {
1015
- console.log(`### Project: ${projectName}`);
1016
- const projectR = await wrapAsync(() => getProject(projectName), ensureError);
1017
- if (projectR.ok) {
1018
- const repoPaths = projectR.value.repositories.map((r) => `${r.name} (${r.path})`);
1019
- console.log(`Repositories: ${repoPaths.join(", ")}`);
1020
- } else {
1021
- console.log("Repositories: (project not found)");
1022
- }
1023
- console.log("");
1024
- for (const ticket of tickets) {
1025
- const reqBadge = ticket.requirementStatus === "approved" ? " [approved]" : " [pending]";
1026
- console.log(`#### ${formatTicketDisplay(ticket)}${reqBadge}`);
1027
- if (ticket.description) {
1028
- console.log("");
1029
- console.log(ticket.description);
1030
- }
1031
- if (ticket.link) {
1032
- console.log("");
1033
- console.log(`Link: ${ticket.link}`);
1034
- }
1035
- if (ticket.requirements) {
1036
- console.log("");
1037
- console.log("**Refined Requirements:**");
1038
- console.log("");
1039
- console.log(ticket.requirements);
1040
- }
1041
- console.log("");
1042
- }
1043
- }
1044
- }
1045
- console.log("## Tasks");
1046
- console.log("");
1047
- if (tasks.length === 0) {
1048
- console.log("_No tasks defined yet_");
1049
- } else {
1050
- for (const task of tasks) {
1051
- const ticketRef = task.ticketId ? ` [${task.ticketId}]` : "";
1052
- console.log(`### ${task.id}: ${task.name}${ticketRef}`);
1053
- console.log(`Status: ${task.status} | Order: ${String(task.order)} | Project: ${task.projectPath}`);
1054
- if (task.blockedBy.length > 0) {
1055
- console.log(`Blocked By: ${task.blockedBy.join(", ")}`);
1056
- }
1057
- if (task.description) {
1058
- console.log("");
1059
- console.log(task.description);
1060
- }
1061
- if (task.steps.length > 0) {
1062
- console.log("");
1063
- console.log("Steps:");
1064
- task.steps.forEach((step, i) => {
1065
- console.log(`${String(i + 1)}. ${step}`);
1066
- });
1067
- }
1068
- console.log("");
1069
- }
1070
- }
1071
- }
1072
-
1073
- // src/commands/sprint/current.ts
1074
- async function sprintCurrentCommand(args) {
1075
- const sprintId = args[0];
1076
- if (!sprintId) {
1077
- const currentSprintId = await getCurrentSprint();
1078
- if (!currentSprintId) {
1079
- showWarning("No current sprint set.");
1080
- showNextStep("ralphctl sprint create", "create a new sprint");
1081
- log.newline();
1082
- return;
1083
- }
1084
- const sprintR = await wrapAsync(() => getSprint(currentSprintId), ensureError);
1085
- if (sprintR.ok) {
1086
- printHeader("Current Sprint");
1087
- console.log(field("ID", sprintR.value.id));
1088
- console.log(field("Name", sprintR.value.name));
1089
- console.log(field("Status", formatSprintStatus(sprintR.value.status)));
1090
- log.newline();
1091
- } else {
1092
- showWarning(`Current sprint "${currentSprintId}" no longer exists.`);
1093
- showNextStep("ralphctl sprint current -", "select a different sprint");
1094
- log.newline();
1095
- }
1096
- return;
1097
- }
1098
- if (sprintId === "-" || sprintId === "--select") {
1099
- const selectedId = await selectSprint("Select current sprint:", ["draft", "active"]);
1100
- if (!selectedId) return;
1101
- await setCurrentSprint(selectedId);
1102
- const sprint = await getSprint(selectedId);
1103
- showSuccess("Current sprint set!", [
1104
- ["ID", sprint.id],
1105
- ["Name", sprint.name]
1106
- ]);
1107
- log.newline();
1108
- } else {
1109
- const setR = await wrapAsync(async () => {
1110
- const sprint = await getSprint(sprintId);
1111
- await setCurrentSprint(sprintId);
1112
- return sprint;
1113
- }, ensureError);
1114
- if (setR.ok) {
1115
- showSuccess("Current sprint set!", [
1116
- ["ID", setR.value.id],
1117
- ["Name", setR.value.name]
1118
- ]);
1119
- log.newline();
1120
- } else if (setR.error instanceof SprintNotFoundError) {
1121
- showError(`Sprint not found: ${sprintId}`);
1122
- showNextStep("ralphctl sprint list", "see available sprints");
1123
- log.newline();
1124
- } else {
1125
- throw setR.error;
1126
- }
1127
- }
1128
- }
1129
-
1130
- // src/commands/sprint/ideate.ts
1131
- import { mkdir, readFile, writeFile } from "fs/promises";
1132
- import { join } from "path";
1133
- import { input as input2, select as select2 } from "@inquirer/prompts";
1134
- import { Result } from "typescript-result";
1135
- function parseArgs(args) {
1136
- const options = {
1137
- auto: false,
1138
- allPaths: false
1139
- };
1140
- let sprintId;
1141
- for (let i = 0; i < args.length; i++) {
1142
- const arg = args[i];
1143
- const nextArg = args[i + 1];
1144
- if (arg === "--auto") {
1145
- options.auto = true;
1146
- } else if (arg === "--all-paths") {
1147
- options.allPaths = true;
1148
- } else if (arg === "--project") {
1149
- options.project = nextArg;
1150
- i++;
1151
- } else if (!arg?.startsWith("-")) {
1152
- sprintId = arg;
1153
- }
1154
- }
1155
- return { sprintId, options };
1156
- }
1157
- async function invokeAiInteractive(prompt, repoPaths, ideateDir) {
1158
- const contextFile = join(ideateDir, "ideate-context.md");
1159
- await writeFile(contextFile, prompt, "utf-8");
1160
- const provider = await getActiveProvider();
1161
- const startPrompt = `I have a quick idea I want to implement. The full context is in ideate-context.md. Please read that file and help me refine the idea into requirements and then plan implementation tasks.`;
1162
- const args = repoPaths.flatMap((path) => ["--add-dir", path]);
1163
- const result = spawnInteractive(
1164
- startPrompt,
1165
- {
1166
- cwd: ideateDir,
1167
- args,
1168
- env: provider.getSpawnEnv()
1169
- },
1170
- provider
1171
- );
1172
- if (result.error) {
1173
- throw new Error(result.error);
1174
- }
1175
- }
1176
- async function invokeAiAuto(prompt, repoPaths, ideateDir) {
1177
- const provider = await getActiveProvider();
1178
- const request = buildHeadlessAiRequest(repoPaths, prompt);
1179
- return spawnHeadless(
1180
- {
1181
- cwd: ideateDir,
1182
- args: request.args,
1183
- prompt: request.prompt,
1184
- env: provider.getSpawnEnv()
1185
- },
1186
- provider
1187
- );
1188
- }
1189
- function parseIdeateOutput(output) {
1190
- const firstBrace = output.indexOf("{");
1191
- const firstBracket = output.indexOf("[");
1192
- const objectFirst = firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket);
1193
- if (objectFirst) {
1194
- return parseIdeateObject(output);
1195
- }
1196
- if (firstBracket !== -1) {
1197
- const arrayR = Result.try(() => extractJsonArray(output));
1198
- if (arrayR.ok) {
1199
- const parseR = Result.try(() => JSON.parse(arrayR.value));
1200
- if (parseR.ok && Array.isArray(parseR.value)) {
1201
- return { requirements: "", tasks: parseR.value };
1202
- }
1203
- }
1204
- }
1205
- throw new Error("No valid ideate output found \u2014 expected { requirements, tasks } object or a tasks array");
1206
- }
1207
- function parseIdeateObject(output) {
1208
- const jsonStr = extractJsonObject(output);
1209
- const parsed = JSON.parse(jsonStr);
1210
- const result = IdeateOutputSchema.safeParse(parsed);
1211
- if (result.success) {
1212
- return result.data;
1213
- }
1214
- if (typeof parsed === "object" && parsed !== null && "tasks" in parsed) {
1215
- const obj = parsed;
1216
- if (Array.isArray(obj["tasks"])) {
1217
- const requirements = typeof obj["requirements"] === "string" ? obj["requirements"] : "";
1218
- return { requirements, tasks: obj["tasks"] };
1219
- }
1220
- }
1221
- const issues = result.error.issues.map((issue) => {
1222
- const path = issue.path.length > 0 ? `[${issue.path.join(".")}]` : "";
1223
- return ` ${path}: ${issue.message}`;
1224
- }).join("\n");
1225
- throw new Error(`Invalid ideate output format:
1226
- ${issues}`);
1227
- }
1228
- async function sprintIdeateCommand(args) {
1229
- const { sprintId, options } = parseArgs(args);
1230
- const idR = await wrapAsync(() => resolveSprintId(sprintId), ensureError);
1231
- if (!idR.ok) {
1232
- showWarning("No sprint specified and no current sprint set.");
1233
- showNextStep("ralphctl sprint create", "create a new sprint");
1234
- log.newline();
1235
- return;
1236
- }
1237
- const id = idR.value;
1238
- const sprint = await getSprint(id);
1239
- try {
1240
- assertSprintStatus(sprint, ["draft"], "ideate");
1241
- } catch (err) {
1242
- showError(err instanceof Error ? err.message : String(err));
1243
- log.newline();
1244
- return;
1245
- }
1246
- const projects = await listProjects();
1247
- if (projects.length === 0) {
1248
- showWarning("No projects configured.");
1249
- showNextStep("ralphctl project add", "add a project first");
1250
- log.newline();
1251
- return;
1252
- }
1253
- printHeader("Quick Ideation", icons.ticket);
1254
- console.log(field("Sprint", sprint.name));
1255
- console.log(field("ID", sprint.id));
1256
- console.log(field("Mode", options.auto ? "Auto (headless)" : "Interactive"));
1257
- log.newline();
1258
- let projectName = options.project;
1259
- if (!projectName) {
1260
- if (projects.length === 1) {
1261
- projectName = projects[0]?.name;
1262
- console.log(field("Project", projectName ?? "(unknown)"));
1263
- } else {
1264
- projectName = await select2({
1265
- message: "Select project:",
1266
- choices: projects.map((p) => ({ name: p.displayName, value: p.name }))
1267
- });
1268
- }
1269
- }
1270
- if (!projectName) {
1271
- showError("No project selected.");
1272
- log.newline();
1273
- return;
1274
- }
1275
- const projectR = await wrapAsync(() => getProject(projectName), ensureError);
1276
- if (!projectR.ok) {
1277
- showError(`Project '${projectName}' not found.`);
1278
- log.newline();
1279
- return;
1280
- }
1281
- const project = projectR.value;
1282
- const ideaTitle = await input2({
1283
- message: "Idea title (short summary):",
1284
- validate: (value) => value.trim().length > 0 ? true : "Title is required"
1285
- });
1286
- const editorR = await editorInput({
1287
- message: "Idea description (what you want to build):"
1288
- });
1289
- if (!editorR.ok) {
1290
- showError(`Editor input failed: ${editorR.error.message}`);
1291
- log.newline();
1292
- return;
1293
- }
1294
- const ideaDescription = editorR.value;
1295
- if (!ideaDescription.trim()) {
1296
- showError("Description is required.");
1297
- log.newline();
1298
- return;
1299
- }
1300
- log.newline();
1301
- showInfo("Creating ticket...");
1302
- const ticket = await addTicket(
1303
- {
1304
- title: ideaTitle,
1305
- description: ideaDescription,
1306
- projectName
1307
- },
1308
- id
1309
- );
1310
- console.log(field("Ticket ID", ticket.id));
1311
- log.newline();
1312
- const providerName = providerDisplayName(await resolveProvider());
1313
- let selectedPaths;
1314
- const totalRepos = project.repositories.length;
1315
- if (options.allPaths) {
1316
- selectedPaths = project.repositories.map((r) => r.path);
1317
- } else if (options.auto) {
1318
- selectedPaths = project.repositories.slice(0, 1).map((r) => r.path);
1319
- } else if (totalRepos === 1) {
1320
- selectedPaths = [project.repositories[0]?.path ?? ""];
1321
- } else {
1322
- const reposByProject = /* @__PURE__ */ new Map();
1323
- reposByProject.set(projectName, project.repositories);
1324
- selectedPaths = await selectProjectPaths(reposByProject, "Select paths to explore:");
1325
- }
1326
- const updatedSprint = await getSprint(id);
1327
- const savedTicket = updatedSprint.tickets.find((t) => t.id === ticket.id);
1328
- if (savedTicket) {
1329
- savedTicket.affectedRepositories = selectedPaths;
1330
- }
1331
- await saveSprint(updatedSprint);
1332
- if (selectedPaths.length > 1) {
1333
- console.log(muted(`Paths: ${selectedPaths.join(", ")}`));
1334
- } else {
1335
- console.log(muted(`Path: ${selectedPaths[0] ?? process.cwd()}`));
1336
- }
1337
- const repositoriesText = selectedPaths.map((path) => `- ${path}`).join("\n");
1338
- const schema = await getTaskImportSchema();
1339
- const ideateDir = getIdeateDir(id, ticket.id);
1340
- await mkdir(ideateDir, { recursive: true });
1341
- if (options.auto) {
1342
- const prompt = buildIdeateAutoPrompt(ideaTitle, ideaDescription, projectName, repositoriesText, schema);
1343
- const spinner = createSpinner(`${providerName} is refining idea and planning tasks...`);
1344
- spinner.start();
1345
- const outputR = await wrapAsync(() => invokeAiAuto(prompt, selectedPaths, ideateDir), ensureError);
1346
- if (!outputR.ok) {
1347
- spinner.fail(`${providerName} session failed`);
1348
- showError(`Failed to invoke ${providerName}: ${outputR.error.message}`);
1349
- showTip(`Make sure the ${providerName.toLowerCase()} CLI is installed and configured.`);
1350
- log.newline();
1351
- return;
1352
- }
1353
- spinner.succeed(`${providerName} finished`);
1354
- const output = outputR.value;
1355
- const blockedReason = parsePlanningBlocked(output);
1356
- if (blockedReason) {
1357
- showWarning(`Planning blocked: ${blockedReason}`);
1358
- log.newline();
1359
- return;
1360
- }
1361
- log.dim("Parsing response...");
1362
- const ideateR = Result.try(() => parseIdeateOutput(output));
1363
- if (!ideateR.ok) {
1364
- showError(`Failed to parse ${providerName} output: ${ideateR.error.message}`);
1365
- log.dim("Raw output:");
1366
- console.log(output);
1367
- log.newline();
1368
- return;
1369
- }
1370
- const ideateOutput = ideateR.value;
1371
- const autoSprint = await getSprint(id);
1372
- const autoTicket = autoSprint.tickets.find((t) => t.id === ticket.id);
1373
- if (autoTicket) {
1374
- autoTicket.requirements = ideateOutput.requirements;
1375
- autoTicket.requirementStatus = "approved";
1376
- }
1377
- await saveSprint(autoSprint);
1378
- showSuccess("Requirements approved and saved!");
1379
- log.newline();
1380
- const parsedTasksR = Result.try(() => parseTasksJson(JSON.stringify(ideateOutput.tasks)));
1381
- if (!parsedTasksR.ok) {
1382
- showError(`Failed to parse tasks: ${parsedTasksR.error.message}`);
1383
- log.newline();
1384
- return;
1385
- }
1386
- const parsedTasks = parsedTasksR.value;
1387
- for (const task of parsedTasks) {
1388
- task.ticketId ??= ticket.id;
1389
- }
1390
- if (parsedTasks.length === 0) {
1391
- showWarning("No tasks generated.");
1392
- log.newline();
1393
- return;
1394
- }
1395
- showSuccess(`Generated ${String(parsedTasks.length)} task(s):`);
1396
- log.newline();
1397
- console.log(renderParsedTasksTable(parsedTasks));
1398
- console.log("");
1399
- const existingTasks = await getTasks(id);
1400
- const ticketIds = new Set(autoSprint.tickets.map((t) => t.id));
1401
- const validationErrors = validateImportTasks(parsedTasks, existingTasks, ticketIds);
1402
- if (validationErrors.length > 0) {
1403
- showError("Validation failed");
1404
- for (const err of validationErrors) {
1405
- log.item(error(err));
1406
- }
1407
- log.newline();
1408
- return;
1409
- }
1410
- if (ideateOutput.requirements === "") {
1411
- showWarning("AI output was a bare tasks array \u2014 requirements not captured.");
1412
- }
1413
- showInfo("Importing tasks...");
1414
- const imported = await importTasks(parsedTasks, id);
1415
- await reorderByDependencies(id);
1416
- log.dim("Tasks reordered by dependencies.");
1417
- terminalBell();
1418
- showSuccess(`Imported ${String(imported)}/${String(parsedTasks.length)} tasks.`);
1419
- log.newline();
1420
- } else {
1421
- const outputFile = join(ideateDir, "output.json");
1422
- const prompt = buildIdeatePrompt(ideaTitle, ideaDescription, projectName, repositoriesText, outputFile, schema);
1423
- showInfo(`Starting interactive ${providerName} session...`);
1424
- console.log(muted(` Exploring: ${selectedPaths.join(", ")}`));
1425
- console.log(muted(`
1426
- ${providerName} will guide you through requirements refinement and task planning.`));
1427
- console.log(muted(` When done, ask ${providerName} to write the output to: ${outputFile}
1428
- `));
1429
- const interactiveR = await wrapAsync(() => invokeAiInteractive(prompt, selectedPaths, ideateDir), ensureError);
1430
- if (!interactiveR.ok) {
1431
- showError(`Failed to invoke ${providerName}: ${interactiveR.error.message}`);
1432
- showTip(`Make sure the ${providerName.toLowerCase()} CLI is installed and configured.`);
1433
- log.newline();
1434
- return;
1435
- }
1436
- console.log("");
1437
- if (await fileExists(outputFile)) {
1438
- showInfo("Output file found. Processing...");
1439
- const contentR = await wrapAsync(() => readFile(outputFile, "utf-8"), ensureError);
1440
- if (!contentR.ok) {
1441
- showError(`Failed to read output file: ${outputFile}`);
1442
- log.newline();
1443
- return;
1444
- }
1445
- const ideateR = Result.try(() => parseIdeateOutput(contentR.value));
1446
- if (!ideateR.ok) {
1447
- showError(`Failed to parse output file: ${ideateR.error.message}`);
1448
- log.newline();
1449
- return;
1450
- }
1451
- const ideateOutput = ideateR.value;
1452
- const interactiveSprint = await getSprint(id);
1453
- const interactiveTicket = interactiveSprint.tickets.find((t) => t.id === ticket.id);
1454
- if (interactiveTicket) {
1455
- interactiveTicket.requirements = ideateOutput.requirements;
1456
- interactiveTicket.requirementStatus = "approved";
1457
- }
1458
- await saveSprint(interactiveSprint);
1459
- showSuccess("Requirements approved and saved!");
1460
- log.newline();
1461
- const parsedTasksR = Result.try(() => parseTasksJson(JSON.stringify(ideateOutput.tasks)));
1462
- if (!parsedTasksR.ok) {
1463
- showError(`Failed to parse tasks: ${parsedTasksR.error.message}`);
1464
- log.newline();
1465
- return;
1466
- }
1467
- const parsedTasks = parsedTasksR.value;
1468
- for (const task of parsedTasks) {
1469
- task.ticketId ??= ticket.id;
1470
- }
1471
- if (parsedTasks.length === 0) {
1472
- showWarning("No tasks in file.");
1473
- log.newline();
1474
- return;
1475
- }
1476
- showSuccess(`Found ${String(parsedTasks.length)} task(s):`);
1477
- log.newline();
1478
- console.log(renderParsedTasksTable(parsedTasks));
1479
- console.log("");
1480
- const existingTasks = await getTasks(id);
1481
- const ticketIds = new Set(interactiveSprint.tickets.map((t) => t.id));
1482
- const validationErrors = validateImportTasks(parsedTasks, existingTasks, ticketIds);
1483
- if (validationErrors.length > 0) {
1484
- showError("Validation failed");
1485
- for (const err of validationErrors) {
1486
- log.item(error(err));
1487
- }
1488
- log.newline();
1489
- return;
1490
- }
1491
- if (ideateOutput.requirements === "") {
1492
- showWarning("AI output was a bare tasks array \u2014 requirements not captured.");
1493
- }
1494
- showInfo("Importing tasks...");
1495
- const imported = await importTasks(parsedTasks, id);
1496
- await reorderByDependencies(id);
1497
- log.dim("Tasks reordered by dependencies.");
1498
- terminalBell();
1499
- showSuccess(`Imported ${String(imported)}/${String(parsedTasks.length)} tasks.`);
1500
- log.newline();
1501
- } else {
1502
- showWarning("No output file found.");
1503
- showTip(`Expected: ${outputFile}`);
1504
- showNextStep("ralphctl sprint ideate", "run ideation again");
1505
- log.newline();
1506
- }
1507
- }
1508
- }
1509
-
1510
- // src/commands/sprint/close.ts
1511
- import { spawnSync } from "child_process";
1512
- import { confirm as confirm3 } from "@inquirer/prompts";
1513
- import { Result as Result2 } from "typescript-result";
1514
- async function sprintCloseCommand(args) {
1515
- let sprintId;
1516
- let createPr = false;
1517
- const positionalArgs = [];
1518
- for (const arg of args) {
1519
- if (arg === "--create-pr") {
1520
- createPr = true;
1521
- } else {
1522
- positionalArgs.push(arg);
1523
- }
1524
- }
1525
- if (positionalArgs[0]) {
1526
- sprintId = positionalArgs[0];
1527
- } else {
1528
- const sprints = await listSprints();
1529
- const activeSprints = sprints.filter((s) => s.status === "active");
1530
- if (activeSprints.length === 0) {
1531
- showError("No active sprints to close.");
1532
- log.newline();
1533
- return;
1534
- } else if (activeSprints.length === 1 && activeSprints[0]) {
1535
- sprintId = activeSprints[0].id;
1536
- } else {
1537
- const selected = await selectSprint("Select sprint to close:", ["active"]);
1538
- if (!selected) return;
1539
- sprintId = selected;
1540
- }
1541
- }
1542
- const allDone = await areAllTasksDone(sprintId);
1543
- if (!allDone) {
1544
- const tasks = await listTasks(sprintId);
1545
- const remaining = tasks.filter((t) => t.status !== "done");
1546
- log.newline();
1547
- showWarning(`${String(remaining.length)} task(s) are not done:`);
1548
- for (const task of remaining) {
1549
- log.item(`${task.id}: ${task.name} (${task.status})`);
1550
- }
1551
- log.newline();
1552
- const proceed = await confirm3({
1553
- message: "Close sprint anyway?",
1554
- default: false
1555
- });
1556
- if (!proceed) {
1557
- console.log(muted("\nSprint close cancelled.\n"));
1558
- return;
1559
- }
1560
- }
1561
- const closeR = await wrapAsync(async () => {
1562
- const sprintBeforeClose2 = await getSprint(sprintId);
1563
- const sprint2 = await closeSprint(sprintId);
1564
- return { sprintBeforeClose: sprintBeforeClose2, sprint: sprint2 };
1565
- }, ensureError);
1566
- if (!closeR.ok) {
1567
- const err = closeR.error;
1568
- if (err instanceof SprintNotFoundError) {
1569
- showError(`Sprint not found: ${sprintId}`);
1570
- log.newline();
1571
- } else if (err instanceof SprintStatusError) {
1572
- showError(err.message);
1573
- log.newline();
1574
- } else {
1575
- throw err;
1576
- }
1577
- return;
1578
- }
1579
- const { sprintBeforeClose, sprint } = closeR.value;
1580
- showSuccess("Sprint closed!", [
1581
- ["ID", sprint.id],
1582
- ["Name", sprint.name],
1583
- ["Status", formatSprintStatus(sprint.status)]
1584
- ]);
1585
- showRandomQuote();
1586
- log.newline();
1587
- if (createPr && sprintBeforeClose.branch) {
1588
- await createPullRequests(sprintId, sprintBeforeClose.branch, sprint.name);
1589
- } else if (createPr && !sprintBeforeClose.branch) {
1590
- log.dim("No sprint branch set \u2014 skipping PR creation.");
1591
- log.newline();
1592
- }
1593
- }
1594
- async function createPullRequests(sprintId, branchName, sprintName) {
1595
- if (!isGhAvailable()) {
1596
- showWarning("GitHub CLI (gh) not found. Install it to create PRs automatically.");
1597
- log.dim(` Manual: gh pr create --head ${branchName} --title "Sprint: ${sprintName}"`);
1598
- log.newline();
1599
- return;
1600
- }
1601
- const tasks = await listTasks(sprintId);
1602
- const uniquePaths = [...new Set(tasks.map((t) => t.projectPath))];
1603
- for (const projectPath of uniquePaths) {
1604
- const prR = Result2.try(() => {
1605
- assertSafeCwd(projectPath);
1606
- return { branchExists: branchExists(projectPath, branchName) };
1607
- });
1608
- if (!prR.ok) {
1609
- showWarning(`Error creating PR for ${projectPath}: ${prR.error.message}`);
1610
- continue;
1611
- }
1612
- if (!prR.value.branchExists) {
1613
- log.dim(`Branch '${branchName}' not found in ${projectPath} \u2014 skipping`);
1614
- continue;
1615
- }
1616
- const baseBranch = getDefaultBranch(projectPath);
1617
- const title = `Sprint: ${sprintName}`;
1618
- log.info(`Creating PR in ${projectPath}...`);
1619
- const pushResult = spawnSync("git", ["push", "-u", "origin", branchName], {
1620
- cwd: projectPath,
1621
- encoding: "utf-8",
1622
- stdio: ["pipe", "pipe", "pipe"]
1623
- });
1624
- if (pushResult.status !== 0) {
1625
- showWarning(`Failed to push branch in ${projectPath}: ${pushResult.stderr.trim()}`);
1626
- log.dim(
1627
- ` Manual: cd ${projectPath} && git push -u origin ${branchName} && gh pr create --base ${baseBranch} --head ${branchName} --title "${title}"`
1628
- );
1629
- continue;
1630
- }
1631
- const result = spawnSync(
1632
- "gh",
1633
- [
1634
- "pr",
1635
- "create",
1636
- "--base",
1637
- baseBranch,
1638
- "--head",
1639
- branchName,
1640
- "--title",
1641
- title,
1642
- "--body",
1643
- `Sprint: ${sprintName}
1644
- ID: ${sprintId}`
1645
- ],
1646
- {
1647
- cwd: projectPath,
1648
- encoding: "utf-8",
1649
- stdio: ["pipe", "pipe", "pipe"]
1650
- }
1651
- );
1652
- if (result.status === 0) {
1653
- const prUrl = result.stdout.trim();
1654
- showSuccess(`PR created: ${prUrl}`);
1655
- } else {
1656
- showWarning(`Failed to create PR in ${projectPath}: ${result.stderr.trim()}`);
1657
- log.dim(
1658
- ` Manual: cd ${projectPath} && gh pr create --base ${baseBranch} --head ${branchName} --title "${title}"`
1659
- );
1660
- }
1661
- }
1662
- log.newline();
1663
- }
1664
-
1665
- // src/commands/sprint/delete.ts
1666
- import { confirm as confirm4 } from "@inquirer/prompts";
1667
- async function sprintDeleteCommand(args) {
1668
- const skipConfirm = args.includes("-y") || args.includes("--yes");
1669
- let sprintId = args.find((a) => !a.startsWith("-"));
1670
- if (!sprintId) {
1671
- const selected = await selectSprint("Select sprint to delete:");
1672
- if (!selected) return;
1673
- sprintId = selected;
1674
- }
1675
- const sprintR = await wrapAsync(() => getSprint(sprintId), ensureError);
1676
- if (!sprintR.ok) {
1677
- if (sprintR.error instanceof SprintNotFoundError) {
1678
- showError(`Sprint not found: ${sprintId}`);
1679
- log.newline();
1680
- } else {
1681
- throw sprintR.error;
1682
- }
1683
- return;
1684
- }
1685
- const sprint = sprintR.value;
1686
- let taskCount = 0;
1687
- const tasksR = await wrapAsync(() => listTasks(sprintId), ensureError);
1688
- if (tasksR.ok) {
1689
- taskCount = tasksR.value.length;
1690
- }
1691
- if (!skipConfirm) {
1692
- log.newline();
1693
- log.warn("This will permanently delete the sprint and all its data.");
1694
- log.item(`Name: ${sprint.name}`);
1695
- log.item(`Status: ${formatSprintStatus(sprint.status)}`);
1696
- log.item(`Tickets: ${String(sprint.tickets.length)}`);
1697
- log.item(`Tasks: ${String(taskCount)}`);
1698
- log.newline();
1699
- const confirmed = await confirm4({
1700
- message: `Delete sprint "${sprint.name}"?`,
1701
- default: false
1702
- });
1703
- if (!confirmed) {
1704
- console.log(muted("\nSprint deletion cancelled.\n"));
1705
- return;
1706
- }
1707
- }
1708
- const currentSprintId = await getCurrentSprint();
1709
- await deleteSprint(sprintId);
1710
- if (currentSprintId === sprintId) {
1711
- await setCurrentSprint(null);
1712
- showTip('Current sprint was cleared. Use "ralphctl sprint current" to set a new one.');
1713
- }
1714
- showSuccess("Sprint deleted", [
1715
- ["Name", sprint.name],
1716
- ["ID", sprint.id]
1717
- ]);
1718
- showRandomQuote();
1719
- log.newline();
1720
- }
1721
-
1722
- // src/commands/sprint/requirements.ts
1723
- import { join as join2 } from "path";
1724
- async function sprintRequirementsCommand(args = []) {
1725
- const sprintId = args.find((a) => !a.startsWith("-"));
1726
- let id;
1727
- const idR = await wrapAsync(() => resolveSprintId(sprintId), ensureError);
1728
- if (!idR.ok) {
1729
- const selected = await selectSprint("Select sprint to export requirements from:");
1730
- if (!selected) return;
1731
- id = selected;
1732
- } else {
1733
- id = idR.value;
1734
- }
1735
- const sprint = await getSprint(id);
1736
- if (sprint.tickets.length === 0) {
1737
- showEmpty("tickets in this sprint", "Add tickets first: ralphctl ticket add --project <name>");
1738
- return;
1739
- }
1740
- const approvedTickets = sprint.tickets.filter((t) => t.requirementStatus === "approved");
1741
- if (approvedTickets.length === 0) {
1742
- showWarning("No approved requirements to export.");
1743
- log.dim("Refine requirements first: ralphctl sprint refine");
1744
- log.newline();
1745
- return;
1746
- }
1747
- printHeader("Export Requirements", icons.sprint);
1748
- console.log(field("Sprint", sprint.name));
1749
- console.log(field("Tickets", `${String(sprint.tickets.length)} total, ${String(approvedTickets.length)} approved`));
1750
- log.newline();
1751
- const sprintDir = getSprintDir(id);
1752
- const outputPath = join2(sprintDir, "requirements.md");
1753
- const exportR = await wrapAsync(() => exportRequirementsToMarkdown(sprint, outputPath), ensureError);
1754
- if (!exportR.ok) {
1755
- showError(`Failed to write requirements: ${exportR.error.message}`);
1756
- return;
1757
- }
1758
- showSuccess("Requirements written to:");
1759
- log.item(outputPath);
1760
- log.newline();
1761
- }
1762
-
1763
- // src/commands/sprint/health.ts
1764
- import { Result as Result3 } from "typescript-result";
1765
- function checkBlockers(tasks) {
1766
- const doneTasks = new Set(tasks.filter((t) => t.status === "done").map((t) => t.id));
1767
- const allTaskIds = new Set(tasks.map((t) => t.id));
1768
- const blocked = [];
1769
- for (const task of tasks) {
1770
- if (task.status === "done") continue;
1771
- const unresolvedDeps = task.blockedBy.filter((depId) => allTaskIds.has(depId) && !doneTasks.has(depId));
1772
- if (unresolvedDeps.length > 0) {
1773
- blocked.push(`${task.name} ${colors.muted(`(${task.id})`)} blocked by ${unresolvedDeps.join(", ")}`);
1774
- }
1775
- }
1776
- return {
1777
- name: "Blockers",
1778
- status: blocked.length > 0 ? "fail" : "pass",
1779
- items: blocked
1780
- };
1781
- }
1782
- function checkStaleTasks(tasks) {
1783
- const stale = tasks.filter((t) => t.status === "in_progress");
1784
- const items = stale.map((t) => `${t.name} ${colors.muted(`(${t.id})`)}`);
1785
- return {
1786
- name: "Stale Tasks",
1787
- status: items.length > 0 ? "warn" : "pass",
1788
- items
1789
- };
1790
- }
1791
- function checkOrphanedDeps(tasks) {
1792
- const allTaskIds = new Set(tasks.map((t) => t.id));
1793
- const orphaned = [];
1794
- for (const task of tasks) {
1795
- const missingDeps = task.blockedBy.filter((depId) => !allTaskIds.has(depId));
1796
- if (missingDeps.length > 0) {
1797
- orphaned.push(`${task.name} ${colors.muted(`(${task.id})`)} references missing: ${missingDeps.join(", ")}`);
1798
- }
1799
- }
1800
- return {
1801
- name: "Orphaned Dependencies",
1802
- status: orphaned.length > 0 ? "fail" : "pass",
1803
- items: orphaned
1804
- };
1805
- }
1806
- function checkTicketsWithoutTasks(sprint, tasks) {
1807
- const ticketIdsWithTasks = new Set(tasks.map((t) => t.ticketId).filter(Boolean));
1808
- const orphanedTickets = sprint.tickets.filter((t) => !ticketIdsWithTasks.has(t.id));
1809
- const items = orphanedTickets.map((t) => `${t.title} ${colors.muted(`(${t.id})`)}`);
1810
- return {
1811
- name: "Tickets Without Tasks",
1812
- status: items.length > 0 ? "warn" : "pass",
1813
- items
1814
- };
1815
- }
1816
- function checkDuplicateOrders(tasks) {
1817
- const orderCounts = /* @__PURE__ */ new Map();
1818
- for (const task of tasks) {
1819
- const existing = orderCounts.get(task.order) ?? [];
1820
- existing.push(`${task.name} ${colors.muted(`(${task.id})`)}`);
1821
- orderCounts.set(task.order, existing);
1822
- }
1823
- const items = [];
1824
- for (const [order, taskNames] of orderCounts) {
1825
- if (taskNames.length > 1) {
1826
- items.push(`Order ${String(order)}: ${taskNames.join(", ")}`);
1827
- }
1828
- }
1829
- return {
1830
- name: "Duplicate Task Orders",
1831
- status: items.length > 0 ? "warn" : "pass",
1832
- items
1833
- };
1834
- }
1835
- function checkPendingRequirementsOnActive(sprint) {
1836
- if (sprint.status !== "active") {
1837
- return { name: "Pending Requirements", status: "pass", items: [] };
1838
- }
1839
- const pending = sprint.tickets.filter((t) => t.requirementStatus === "pending");
1840
- const items = pending.map((t) => `${t.title} ${colors.muted(`(${t.id})`)} \u2014 refine before planning`);
1841
- return {
1842
- name: "Pending Requirements",
1843
- status: items.length > 0 ? "warn" : "pass",
1844
- items
1845
- };
1846
- }
1847
- function checkBranchConsistency(sprint, tasks) {
1848
- if (!sprint.branch) {
1849
- return { name: "Branch Consistency", status: "pass", items: [] };
1850
- }
1851
- const remainingTasks = tasks.filter((t) => t.status !== "done");
1852
- const uniquePaths = [...new Set(remainingTasks.map((t) => t.projectPath))];
1853
- const items = [];
1854
- for (const projectPath of uniquePaths) {
1855
- const branchR = Result3.try(() => getCurrentBranch(projectPath));
1856
- if (!branchR.ok) {
1857
- items.push(`${projectPath} \u2014 unable to determine branch`);
1858
- } else if (branchR.value !== sprint.branch) {
1859
- items.push(`${projectPath} \u2014 on '${branchR.value}', expected '${sprint.branch}'`);
1860
- }
1861
- }
1862
- return {
1863
- name: "Branch Consistency",
1864
- status: items.length > 0 ? "warn" : "pass",
1865
- items
1866
- };
1867
- }
1868
- function checkTasksWithoutSteps(tasks) {
1869
- const empty = tasks.filter((t) => t.steps.length === 0);
1870
- const items = empty.map((t) => `${t.name} ${colors.muted(`(${t.id})`)}`);
1871
- return {
1872
- name: "Tasks Without Steps",
1873
- status: items.length > 0 ? "warn" : "pass",
1874
- items
1875
- };
1876
- }
1877
- function renderCheckCard(check) {
1878
- const colorFn = check.status === "pass" ? colors.success : check.status === "warn" ? colors.warning : colors.error;
1879
- const statusIcon = check.status === "pass" ? icons.success : check.status === "warn" ? icons.warning : icons.error;
1880
- const lines = [];
1881
- if (check.items.length === 0) {
1882
- lines.push(colors.success(`${icons.success} No issues found`));
1883
- } else {
1884
- for (const item of check.items) {
1885
- lines.push(`${colorFn(statusIcon)} ${item}`);
1886
- }
1887
- }
1888
- return renderCard(check.name, lines, { colorFn });
1889
- }
1890
- async function sprintHealthCommand() {
1891
- const sprintR = await wrapAsync(() => getCurrentSprintOrThrow(), ensureError);
1892
- if (!sprintR.ok) {
1893
- showError(sprintR.error.message);
1894
- return;
1895
- }
1896
- const sprint = sprintR.value;
1897
- const tasks = await getTasks(sprint.id);
1898
- printHeader(`Sprint Health: ${sprint.name}`, icons.sprint);
1899
- const checks = [
1900
- checkBlockers(tasks),
1901
- checkStaleTasks(tasks),
1902
- checkOrphanedDeps(tasks),
1903
- checkTicketsWithoutTasks(sprint, tasks),
1904
- checkTasksWithoutSteps(tasks),
1905
- checkDuplicateOrders(tasks),
1906
- checkPendingRequirementsOnActive(sprint),
1907
- checkBranchConsistency(sprint, tasks)
1908
- ];
1909
- for (const check of checks) {
1910
- console.log(renderCheckCard(check));
1911
- log.newline();
1912
- }
1913
- const passing = checks.filter((c) => c.status === "pass").length;
1914
- const total = checks.length;
1915
- const bar = progressBar(passing, total);
1916
- log.info(`Health Score: ${bar} ${colors.muted(`${String(passing)}/${String(total)} checks passing`)}`);
1917
- log.newline();
1918
- const category = passing === total ? "success" : "error";
1919
- const quote = getQuoteForContext(category);
1920
- console.log(colors.muted(` "${quote}"`));
1921
- log.newline();
1922
- }
1923
-
1924
- // src/commands/ticket/edit.ts
1925
- import { input as input3 } from "@inquirer/prompts";
1926
- function validateUrl(url) {
1927
- try {
1928
- new URL(url);
1929
- return true;
1930
- } catch {
1931
- return false;
1932
- }
1933
- }
1934
- async function ticketEditCommand(ticketId, options = {}) {
1935
- const isInteractive = options.interactive !== false;
1936
- let resolvedId = ticketId;
1937
- if (!resolvedId) {
1938
- if (!isInteractive) {
1939
- showError("Ticket ID is required in non-interactive mode");
1940
- exitWithCode(EXIT_ERROR);
1941
- }
1942
- const selected = await selectTicket("Select ticket to edit:");
1943
- if (!selected) {
1944
- return;
1945
- }
1946
- resolvedId = selected;
1947
- }
1948
- const ticketR = await wrapAsync(() => getTicket(resolvedId), ensureError);
1949
- if (!ticketR.ok) {
1950
- if (ticketR.error instanceof TicketNotFoundError) {
1951
- showError(`Ticket not found: ${resolvedId}`);
1952
- showNextStep("ralphctl ticket list", "see available tickets");
1953
- if (!isInteractive) exitWithCode(EXIT_ERROR);
1954
- return;
1955
- }
1956
- throw ticketR.error;
1957
- }
1958
- const ticket = ticketR.value;
1959
- let newTitle;
1960
- let newDescription;
1961
- let newLink;
1962
- if (isInteractive) {
1963
- console.log(`
1964
- Editing: ${formatTicketDisplay(ticket)}`);
1965
- console.log(muted(` Project: ${ticket.projectName} (read-only)
1966
- `));
1967
- newTitle = await input3({
1968
- message: `${icons.ticket} Title:`,
1969
- default: ticket.title,
1970
- validate: (v) => v.trim().length > 0 ? true : "Title is required"
1971
- });
1972
- const descR = await editorInput({
1973
- message: "Description:",
1974
- default: ticket.description
1975
- });
1976
- if (!descR.ok) {
1977
- showError(`Editor input failed: ${descR.error.message}`);
1978
- return;
1979
- }
1980
- newDescription = descR.value;
1981
- newLink = await input3({
1982
- message: `${icons.info} Link:`,
1983
- default: ticket.link ?? "",
1984
- validate: (v) => {
1985
- if (!v) return true;
1986
- return validateUrl(v) ? true : "Invalid URL format";
1987
- }
1988
- });
1989
- newTitle = newTitle.trim();
1990
- newDescription = newDescription.trim() || void 0;
1991
- newLink = newLink.trim() || void 0;
1992
- } else {
1993
- if (options.title !== void 0) {
1994
- const trimmed = options.title.trim();
1995
- if (trimmed.length === 0) {
1996
- showError("--title cannot be empty");
1997
- exitWithCode(EXIT_ERROR);
1998
- }
1999
- newTitle = trimmed;
2000
- }
2001
- if (options.description !== void 0) {
2002
- newDescription = options.description.trim() || void 0;
2003
- }
2004
- if (options.link !== void 0) {
2005
- const trimmed = options.link.trim();
2006
- if (trimmed && !validateUrl(trimmed)) {
2007
- showError("--link must be a valid URL");
2008
- exitWithCode(EXIT_ERROR);
2009
- }
2010
- newLink = trimmed || void 0;
2011
- }
2012
- if (newTitle === void 0 && newDescription === void 0 && newLink === void 0) {
2013
- showError("No updates provided. Use --title, --description, or --link.");
2014
- exitWithCode(EXIT_ERROR);
2015
- }
2016
- }
2017
- const updates = {};
2018
- if (newTitle !== void 0 && newTitle !== ticket.title) {
2019
- updates.title = newTitle;
2020
- }
2021
- if (newDescription !== void 0 && newDescription !== ticket.description) {
2022
- updates.description = newDescription;
2023
- }
2024
- if (newLink !== void 0 && newLink !== ticket.link) {
2025
- updates.link = newLink;
2026
- }
2027
- if (Object.keys(updates).length === 0) {
2028
- console.log(muted("\n No changes made.\n"));
2029
- return;
2030
- }
2031
- const updateR = await wrapAsync(() => updateTicket(ticket.id, updates), ensureError);
2032
- if (!updateR.ok) {
2033
- if (updateR.error instanceof SprintStatusError) {
2034
- showError(updateR.error.message);
2035
- } else {
2036
- throw updateR.error;
2037
- }
2038
- if (!isInteractive) exitWithCode(EXIT_ERROR);
2039
- return;
2040
- }
2041
- const updated = updateR.value;
2042
- showSuccess("Ticket updated!", [
2043
- ["ID", updated.id],
2044
- ["Title", updated.title],
2045
- ["Project", updated.projectName]
2046
- ]);
2047
- if (updated.description) {
2048
- console.log(fieldMultiline("Description", updated.description));
2049
- }
2050
- if (updated.link) {
2051
- console.log(field("Link", updated.link));
2052
- }
2053
- console.log("");
2054
- }
2055
-
2056
- // src/commands/ticket/list.ts
2057
- function parseListArgs(args) {
2058
- const result = {
2059
- brief: false
2060
- };
2061
- for (let i = 0; i < args.length; i++) {
2062
- const arg = args[i];
2063
- const next = args[i + 1];
2064
- if (arg === "-b" || arg === "--brief") result.brief = true;
2065
- else if (arg === "--project" && next) {
2066
- result.projectFilter = next;
2067
- i++;
2068
- } else if (arg === "--status" && next) {
2069
- result.statusFilter = next;
2070
- i++;
2071
- }
2072
- }
2073
- return result;
2074
- }
2075
- function buildFilterSummary(filters) {
2076
- const parts = [];
2077
- if (filters.projectFilter) parts.push(`project=${filters.projectFilter}`);
2078
- if (filters.statusFilter) parts.push(`status=${filters.statusFilter}`);
2079
- return parts.length > 0 ? ` (filtered: ${parts.join(", ")})` : "";
2080
- }
2081
- async function ticketListCommand(args) {
2082
- const { brief, projectFilter, statusFilter } = parseListArgs(args);
2083
- if (statusFilter) {
2084
- const result = RequirementStatusSchema.safeParse(statusFilter);
2085
- if (!result.success) {
2086
- showError(`Invalid status: "${statusFilter}". Valid values: pending, approved`);
2087
- return;
2088
- }
2089
- }
2090
- const tickets = await listTickets();
2091
- if (tickets.length === 0) {
2092
- showEmpty("tickets", "Add one with: ralphctl ticket add --project <project-name>");
2093
- return;
2094
- }
2095
- let filtered = tickets;
2096
- if (projectFilter) filtered = filtered.filter((t) => t.projectName === projectFilter);
2097
- if (statusFilter) filtered = filtered.filter((t) => t.requirementStatus === statusFilter);
2098
- const filterStr = buildFilterSummary({ brief, projectFilter, statusFilter });
2099
- const isFiltered = filtered.length !== tickets.length;
2100
- if (filtered.length === 0) {
2101
- showEmpty("matching tickets", "Try adjusting your filters");
2102
- return;
2103
- }
2104
- if (brief) {
2105
- const countLabel = isFiltered ? `${String(filtered.length)} of ${String(tickets.length)}` : String(tickets.length);
2106
- console.log(`
2107
- # Tickets (${countLabel})${filterStr}
2108
- `);
2109
- for (const ticket of filtered) {
2110
- const display = `[${ticket.id}] ${ticket.title}`;
2111
- const reqBadge = ticket.requirementStatus === "approved" ? " [approved]" : " [pending]";
2112
- console.log(`- ${display}${reqBadge} (${ticket.projectName})`);
2113
- }
2114
- console.log("");
2115
- return;
2116
- }
2117
- const ticketsByProject = groupTicketsByProject(filtered);
2118
- printHeader(`Tickets (${String(filtered.length)})`, icons.ticket);
2119
- for (const [projectName, projectTickets] of ticketsByProject) {
2120
- log.raw(`${colors.info(icons.project)} ${colors.info(projectName)}`);
2121
- const projectR = await wrapAsync(() => getProject(projectName), ensureError);
2122
- if (projectR.ok) {
2123
- for (const repo of projectR.value.repositories) {
2124
- log.raw(` ${muted(repo.name)} ${muted("\u2192")} ${muted(repo.path)}`, 1);
2125
- }
2126
- } else {
2127
- log.raw(` ${muted("(project not found)")}`, 1);
2128
- }
2129
- log.newline();
2130
- for (const ticket of projectTickets) {
2131
- const reqBadge = ticket.requirementStatus === "approved" ? badge("approved", "success") : badge("pending", "muted");
2132
- log.raw(` ${icons.bullet} ${formatTicketDisplay(ticket)} ${reqBadge}`);
2133
- if (ticket.description) {
2134
- const preview = ticket.description.split("\n")[0] ?? "";
2135
- const truncated = preview.length > 60 ? preview.slice(0, 57) + "..." : preview;
2136
- log.raw(` ${muted(truncated)}`, 1);
2137
- }
2138
- }
2139
- log.newline();
2140
- }
2141
- const approved = filtered.filter((t) => t.requirementStatus === "approved").length;
2142
- log.dim(
2143
- `Requirements: ${success(`${String(approved)} approved`)} / ${muted(`${String(filtered.length - approved)} pending`)}`
2144
- );
2145
- const showingLabel = isFiltered ? `Showing ${String(filtered.length)} of ${String(tickets.length)} ticket(s)${filterStr}` : `Showing ${String(tickets.length)} ticket(s)`;
2146
- log.dim(showingLabel);
2147
- log.newline();
2148
- }
2149
-
2150
- // src/commands/ticket/show.ts
2151
- async function ticketShowCommand(args) {
2152
- let ticketId = args[0];
2153
- if (!ticketId) {
2154
- const selected = await selectTicket("Select ticket to show:");
2155
- if (!selected) return;
2156
- ticketId = selected;
2157
- }
2158
- const ticketR = await wrapAsync(() => getTicket(ticketId), ensureError);
2159
- if (!ticketR.ok) {
2160
- if (ticketR.error instanceof TicketNotFoundError) {
2161
- showError(`Ticket not found: ${ticketId}`);
2162
- showNextStep("ralphctl ticket list", "see available tickets");
2163
- log.newline();
2164
- } else {
2165
- throw ticketR.error;
2166
- }
2167
- return;
2168
- }
2169
- const ticket = ticketR.value;
2170
- const reqBadge = ticket.requirementStatus === "approved" ? badge("approved", "success") : badge("pending", "muted");
2171
- const infoLines = [labelValue("ID", ticket.id)];
2172
- infoLines.push(labelValue("Project", ticket.projectName));
2173
- infoLines.push(labelValue("Requirements", reqBadge));
2174
- if (ticket.link) {
2175
- infoLines.push(labelValue("Link", ticket.link));
2176
- }
2177
- const projectR = await wrapAsync(() => getProject(ticket.projectName), ensureError);
2178
- if (projectR.ok) {
2179
- infoLines.push("");
2180
- for (const repo of projectR.value.repositories) {
2181
- infoLines.push(` ${icons.bullet} ${repo.name} ${muted("\u2192")} ${muted(repo.path)}`);
2182
- }
2183
- } else {
2184
- infoLines.push(labelValue("Repositories", muted("(project not found)")));
2185
- }
2186
- log.newline();
2187
- console.log(renderCard(`${icons.ticket} ${ticket.title}`, infoLines));
2188
- if (ticket.description) {
2189
- log.newline();
2190
- const descLines = [];
2191
- for (const line2 of ticket.description.split("\n")) {
2192
- descLines.push(line2);
2193
- }
2194
- console.log(renderCard(`${icons.edit} Description`, descLines));
2195
- }
2196
- if (ticket.affectedRepositories && ticket.affectedRepositories.length > 0) {
2197
- log.newline();
2198
- const affectedLines = [];
2199
- for (const repoPath of ticket.affectedRepositories) {
2200
- affectedLines.push(`${icons.bullet} ${repoPath}`);
2201
- }
2202
- console.log(renderCard(`${icons.project} Affected Repositories`, affectedLines));
2203
- }
2204
- log.newline();
2205
- }
2206
-
2207
- // src/commands/ticket/remove.ts
2208
- import { confirm as confirm5 } from "@inquirer/prompts";
2209
- async function ticketRemoveCommand(args) {
2210
- const skipConfirm = args.includes("-y") || args.includes("--yes");
2211
- let ticketId = args.find((a) => !a.startsWith("-"));
2212
- if (!ticketId) {
2213
- const selected = await selectTicket("Select ticket to remove:");
2214
- if (!selected) return;
2215
- ticketId = selected;
2216
- }
2217
- const opR = await wrapAsync(async () => {
2218
- const ticket = await getTicket(ticketId);
2219
- if (!skipConfirm) {
2220
- const confirmed = await confirm5({
2221
- message: `Remove ticket ${formatTicketDisplay(ticket)}?`,
2222
- default: false
2223
- });
2224
- if (!confirmed) {
2225
- console.log(muted("\nTicket removal cancelled.\n"));
2226
- return null;
2227
- }
2228
- }
2229
- await removeTicket(ticketId);
2230
- return ticket;
2231
- }, ensureError);
2232
- if (!opR.ok) {
2233
- if (opR.error instanceof TicketNotFoundError) {
2234
- showError(`Ticket not found: ${ticketId}`);
2235
- showNextStep("ralphctl ticket list", "see available tickets");
2236
- log.newline();
2237
- } else if (opR.error instanceof SprintStatusError) {
2238
- showError(opR.error.message);
2239
- log.newline();
2240
- } else {
2241
- throw opR.error;
2242
- }
2243
- return;
2244
- }
2245
- if (opR.value !== null) {
2246
- showSuccess("Ticket removed", [["ID", ticketId]]);
2247
- log.newline();
2248
- }
2249
- }
2250
-
2251
- // src/commands/ticket/refine.ts
2252
- import { mkdir as mkdir2, readFile as readFile2 } from "fs/promises";
2253
- import { join as join3 } from "path";
2254
- import { confirm as confirm6 } from "@inquirer/prompts";
2255
- import { Result as Result4 } from "typescript-result";
2256
- async function ticketRefineCommand(ticketId, options = {}) {
2257
- const isInteractive = options.interactive !== false;
2258
- const sprintIdR = await wrapAsync(() => resolveSprintId(), ensureError);
2259
- if (!sprintIdR.ok) {
2260
- showWarning("No current sprint set.");
2261
- showTip("Create a sprint first or set one with: ralphctl sprint current");
2262
- log.newline();
2263
- return;
2264
- }
2265
- const sprintId = sprintIdR.value;
2266
- const sprint = await getSprint(sprintId);
2267
- try {
2268
- assertSprintStatus(sprint, ["draft"], "refine ticket");
2269
- } catch (err) {
2270
- showError(err instanceof Error ? err.message : String(err));
2271
- log.newline();
2272
- return;
2273
- }
2274
- const approvedTickets = sprint.tickets.filter((t) => t.requirementStatus === "approved");
2275
- if (approvedTickets.length === 0) {
2276
- showWarning("No approved tickets to re-refine.");
2277
- showTip('Run "ralphctl sprint refine" to refine pending tickets first.');
2278
- log.newline();
2279
- return;
2280
- }
2281
- let resolvedId = ticketId;
2282
- if (!resolvedId) {
2283
- if (!isInteractive) {
2284
- showError("Ticket ID is required in non-interactive mode");
2285
- exitWithCode(EXIT_ERROR);
2286
- }
2287
- const selected = await selectTicket("Select ticket to re-refine:", (t) => t.requirementStatus === "approved");
2288
- if (!selected) return;
2289
- resolvedId = selected;
2290
- }
2291
- const ticket = sprint.tickets.find((t) => t.id === resolvedId);
2292
- if (!ticket) {
2293
- showError(`Ticket not found: ${resolvedId}`);
2294
- if (!isInteractive) exitWithCode(EXIT_ERROR);
2295
- return;
2296
- }
2297
- if (ticket.requirementStatus !== "approved") {
2298
- showError('Only approved tickets can be re-refined. Run "ralphctl sprint refine" for pending tickets.');
2299
- if (!isInteractive) exitWithCode(EXIT_ERROR);
2300
- return;
2301
- }
2302
- printHeader("Re-Refine Ticket", icons.ticket);
2303
- console.log(field("Sprint", sprint.name));
2304
- console.log(field("Ticket", formatTicketDisplay(ticket)));
2305
- console.log(field("Project", ticket.projectName));
2306
- if (ticket.link) {
2307
- console.log(field("Link", ticket.link));
2308
- }
2309
- if (ticket.description) {
2310
- console.log(fieldMultiline("Description", ticket.description));
2311
- }
2312
- log.newline();
2313
- const schemaPath = getSchemaPath("requirements-output.schema.json");
2314
- const schema = await readFile2(schemaPath, "utf-8");
2315
- const providerName = providerDisplayName(await resolveProvider());
2316
- const proceed = await confirm6({
2317
- message: `${emoji.donut} Start ${providerName} re-refinement session?`,
2318
- default: true
2319
- });
2320
- if (!proceed) {
2321
- log.dim("Cancelled.");
2322
- log.newline();
2323
- return;
2324
- }
2325
- let issueContext = "";
2326
- if (ticket.link) {
2327
- const ticketLink = ticket.link;
2328
- const fetchSpinner = createSpinner("Fetching issue data...");
2329
- fetchSpinner.start();
2330
- const fetchR = Result4.try(() => fetchIssueFromUrl(ticketLink));
2331
- if (!fetchR.ok) {
2332
- fetchSpinner.fail("Could not fetch issue data");
2333
- showWarning(`${fetchR.error.message} \u2014 continuing without issue context`);
2334
- } else if (fetchR.value) {
2335
- issueContext = formatIssueContext(fetchR.value);
2336
- fetchSpinner.succeed(`Issue data fetched (${String(fetchR.value.comments.length)} comment(s))`);
2337
- } else {
2338
- fetchSpinner.stop();
2339
- }
2340
- }
2341
- const refineDir = getRefinementDir(sprintId, ticket.id);
2342
- await mkdir2(refineDir, { recursive: true });
2343
- const outputFile = join3(refineDir, "requirements.json");
2344
- let ticketContent = formatTicketForPrompt(ticket);
2345
- if (ticket.requirements) {
2346
- ticketContent += "\n### Previously Approved Requirements\n\n";
2347
- ticketContent += ticket.requirements;
2348
- ticketContent += "\n";
2349
- }
2350
- const prompt = buildTicketRefinePrompt(ticketContent, outputFile, schema, issueContext);
2351
- log.dim(`Working directory: ${refineDir}`);
2352
- log.dim(`Requirements output: ${outputFile}`);
2353
- log.newline();
2354
- const spinner = createSpinner(`Starting ${providerName} session...`);
2355
- spinner.start();
2356
- const sessionR = await wrapAsync(() => runAiSession(refineDir, prompt, ticket.title), ensureError);
2357
- if (!sessionR.ok) {
2358
- spinner.fail(`${providerName} session failed`);
2359
- showError(sessionR.error.message);
2360
- log.newline();
2361
- return;
2362
- }
2363
- spinner.succeed(`${providerName} session completed`);
2364
- log.newline();
2365
- if (!await fileExists(outputFile)) {
2366
- showWarning("No requirements file found from AI session.");
2367
- log.newline();
2368
- return;
2369
- }
2370
- const contentR = await wrapAsync(() => readFile2(outputFile, "utf-8"), ensureError);
2371
- if (!contentR.ok) {
2372
- showError(`Failed to read requirements file: ${outputFile}`);
2373
- log.newline();
2374
- return;
2375
- }
2376
- const content = contentR.value;
2377
- const parseR = Result4.try(() => parseRequirementsFile(content));
2378
- if (!parseR.ok) {
2379
- showError(`Failed to parse requirements file: ${parseR.error.message}`);
2380
- log.newline();
2381
- return;
2382
- }
2383
- const refinedRequirements = parseR.value;
2384
- if (refinedRequirements.length === 0) {
2385
- showWarning("No requirements found in output file.");
2386
- log.newline();
2387
- return;
2388
- }
2389
- const matchingRequirements = refinedRequirements.filter((r) => r.ref === ticket.id || r.ref === ticket.title);
2390
- if (matchingRequirements.length === 0) {
2391
- showWarning("Requirement reference does not match this ticket.");
2392
- log.newline();
2393
- return;
2394
- }
2395
- const requirement = matchingRequirements.length === 1 ? {
2396
- ref: matchingRequirements[0]?.ref ?? "",
2397
- requirements: matchingRequirements[0]?.requirements ?? ""
2398
- } : {
2399
- ref: matchingRequirements[0]?.ref ?? "",
2400
- requirements: matchingRequirements.map((r, idx) => {
2401
- const text = r.requirements.trim();
2402
- if (/^#\s/.test(text)) return text;
2403
- return `# ${String(idx + 1)}. Section ${String(idx + 1)}
2404
-
2405
- ${text}`;
2406
- }).join("\n\n---\n\n")
2407
- };
2408
- const reqLines = requirement.requirements.split("\n");
2409
- console.log(renderCard(`${icons.ticket} Re-Refined Requirements`, reqLines));
2410
- log.newline();
2411
- const approveRequirement = await confirm6({
2412
- message: `${emoji.donut} Approve these requirements?`,
2413
- default: true
2414
- });
2415
- if (approveRequirement) {
2416
- const ticketIdx = sprint.tickets.findIndex((t) => t.id === ticket.id);
2417
- const ticketToSave = sprint.tickets[ticketIdx];
2418
- if (ticketIdx !== -1 && ticketToSave) {
2419
- ticketToSave.requirements = requirement.requirements;
2420
- }
2421
- await saveSprint(sprint);
2422
- showSuccess("Requirements updated and saved!");
2423
- } else {
2424
- log.dim("Requirements not approved. Previous requirements unchanged.");
2425
- }
2426
- log.newline();
2427
- }
2428
-
2429
- // src/commands/task/add.ts
2430
- import { resolve as resolve2 } from "path";
2431
- import { confirm as confirm7, input as input4 } from "@inquirer/prompts";
2432
- async function taskAddCommand(options = {}) {
2433
- const isInteractive = options.interactive !== false;
2434
- const statusCheckR = await wrapAsync(async () => {
2435
- const sprintId = await resolveSprintId();
2436
- const sprint = await getSprint(sprintId);
2437
- assertSprintStatus(sprint, ["draft"], "add tasks");
2438
- }, ensureError);
2439
- if (!statusCheckR.ok) {
2440
- const err = statusCheckR.error;
2441
- if (err instanceof SprintStatusError) {
2442
- const mainError = err.message.split("\n")[0] ?? err.message;
2443
- showError(mainError);
2444
- showNextSteps([
2445
- ["ralphctl sprint close", "close current sprint"],
2446
- ["ralphctl sprint create", "start a new draft sprint"]
2447
- ]);
2448
- log.newline();
2449
- if (!isInteractive) exitWithCode(EXIT_ERROR);
2450
- return;
2451
- }
2452
- if (err instanceof NoCurrentSprintError) {
2453
- showError("No current sprint set.");
2454
- showNextSteps([["ralphctl sprint create", "create a new sprint"]]);
2455
- log.newline();
2456
- if (!isInteractive) exitWithCode(EXIT_ERROR);
2457
- return;
2458
- }
2459
- throw err;
2460
- }
2461
- let name;
2462
- let description;
2463
- let steps;
2464
- let ticketId;
2465
- let projectPath;
2466
- if (options.interactive === false) {
2467
- const errors = [];
2468
- const trimmedName = options.name?.trim();
2469
- const trimmedProject = options.project?.trim();
2470
- if (!trimmedName) {
2471
- errors.push("--name is required");
2472
- }
2473
- if (!trimmedProject && !options.ticket) {
2474
- errors.push("--project is required (or --ticket to inherit from ticket)");
2475
- }
2476
- if (errors.length > 0 || !trimmedName) {
2477
- showError("Validation failed");
2478
- for (const e of errors) {
2479
- log.item(error(e));
2480
- }
2481
- log.newline();
2482
- exitWithCode(EXIT_ERROR);
2483
- }
2484
- name = trimmedName;
2485
- const trimmedDesc = options.description?.trim();
2486
- description = trimmedDesc === "" ? void 0 : trimmedDesc;
2487
- steps = options.steps ?? [];
2488
- const trimmedTicket = options.ticket?.trim();
2489
- ticketId = trimmedTicket === "" ? void 0 : trimmedTicket;
2490
- if (ticketId) {
2491
- const resolvedTicketId = ticketId;
2492
- const ticketProjectR = await wrapAsync(async () => {
2493
- const ticket = await getTicket(resolvedTicketId);
2494
- const project = await getProject(ticket.projectName);
2495
- return project.repositories[0]?.path;
2496
- }, ensureError);
2497
- if (ticketProjectR.ok) {
2498
- projectPath = ticketProjectR.value;
2499
- } else {
2500
- if (!trimmedProject) {
2501
- showError(`Ticket not found: ${ticketId}`);
2502
- console.log(muted(" Provide --project or a valid --ticket\n"));
2503
- exitWithCode(EXIT_ERROR);
2504
- }
2505
- const validation = await validateProjectPath(trimmedProject);
2506
- if (!validation.ok) {
2507
- showError(`Invalid project path: ${validation.error.message}`);
2508
- exitWithCode(EXIT_ERROR);
2509
- }
2510
- projectPath = resolve2(trimmedProject);
2511
- }
2512
- } else if (trimmedProject) {
2513
- const validation = await validateProjectPath(trimmedProject);
2514
- if (!validation.ok) {
2515
- showError(`Invalid project path: ${validation.error.message}`);
2516
- exitWithCode(EXIT_ERROR);
2517
- }
2518
- projectPath = resolve2(trimmedProject);
2519
- } else {
2520
- showError("--project is required");
2521
- exitWithCode(EXIT_ERROR);
2522
- }
2523
- } else {
2524
- name = await input4({
2525
- message: `${icons.task} Task name:`,
2526
- default: options.name?.trim(),
2527
- validate: (v) => v.trim().length > 0 ? true : "Name is required"
2528
- });
2529
- const descR = await editorInput({
2530
- message: "Description (optional):",
2531
- default: options.description?.trim()
2532
- });
2533
- if (!descR.ok) {
2534
- showError(`Editor input failed: ${descR.error.message}`);
2535
- return;
2536
- }
2537
- description = descR.value;
2538
- steps = options.steps ? [...options.steps] : [];
2539
- const addSteps = await confirm7({
2540
- message: `${emoji.donut} ${steps.length > 0 ? `Add more steps? (${String(steps.length)} pre-filled)` : "Add implementation steps?"}`,
2541
- default: steps.length === 0
2542
- });
2543
- if (addSteps) {
2544
- let stepNum = steps.length + 1;
2545
- let adding = true;
2546
- while (adding) {
2547
- const step = await input4({
2548
- message: ` Step ${String(stepNum)} (empty to finish):`
2549
- });
2550
- if (step.trim()) {
2551
- steps.push(step.trim());
2552
- stepNum++;
2553
- } else {
2554
- adding = false;
2555
- }
2556
- }
2557
- }
2558
- const tickets = await listTickets();
2559
- if (tickets.length > 0) {
2560
- const { select: select4 } = await import("@inquirer/prompts");
2561
- const defaultTicketValue = options.ticket ? tickets.find((t) => t.id === options.ticket)?.id ?? "" : "";
2562
- const ticketChoice = await select4({
2563
- message: `${icons.ticket} Link to ticket:`,
2564
- default: defaultTicketValue,
2565
- choices: [
2566
- { name: `${emoji.donut} None (select project/repo manually)`, value: "" },
2567
- ...tickets.map((t) => ({
2568
- name: `${icons.ticket} ${formatTicketDisplay(t)} ${muted(`(${t.projectName})`)}`,
2569
- value: t.id
2570
- }))
2571
- ]
2572
- });
2573
- if (ticketChoice) {
2574
- ticketId = ticketChoice;
2575
- const ticket = tickets.find((t) => t.id === ticketChoice);
2576
- if (ticket) {
2577
- const projR = await wrapAsync(() => getProject(ticket.projectName), ensureError);
2578
- if (projR.ok) {
2579
- const project = projR.value;
2580
- if (project.repositories.length === 1) {
2581
- projectPath = project.repositories[0]?.path;
2582
- } else {
2583
- const { select: selectRepo } = await import("@inquirer/prompts");
2584
- projectPath = await selectRepo({
2585
- message: `${emoji.donut} Select repository for this task:`,
2586
- choices: project.repositories.map((r) => ({
2587
- name: `${r.name} (${r.path})`,
2588
- value: r.path
2589
- }))
2590
- });
2591
- }
2592
- } else {
2593
- log.warn(`Project '${ticket.projectName}' not found, will prompt for path.`);
2594
- }
2595
- }
2596
- }
2597
- } else if (options.ticket) {
2598
- ticketId = options.ticket;
2599
- const resolvedTicketId = ticketId;
2600
- const tpR = await wrapAsync(async () => {
2601
- const ticket = await getTicket(resolvedTicketId);
2602
- const project = await getProject(ticket.projectName);
2603
- return project.repositories[0]?.path;
2604
- }, ensureError);
2605
- if (tpR.ok) {
2606
- projectPath = tpR.value;
2607
- }
2608
- }
2609
- if (projectPath === void 0) {
2610
- const projects = await listProjects();
2611
- if (projects.length > 0) {
2612
- const { select: select4 } = await import("@inquirer/prompts");
2613
- const choice = await select4({
2614
- message: `${icons.project} Select project:`,
2615
- choices: [
2616
- { name: `${icons.edit} Enter path manually`, value: "__manual__" },
2617
- { name: `${emoji.donut} Select project/repository`, value: "__select__" }
2618
- ]
2619
- });
2620
- if (choice === "__manual__") {
2621
- projectPath = await input4({
2622
- message: `${icons.project} Project path:`,
2623
- default: options.project?.trim() ?? process.cwd(),
2624
- validate: async (v) => {
2625
- const result = await validateProjectPath(v.trim());
2626
- return result.ok ? true : result.error.message;
2627
- }
2628
- });
2629
- projectPath = resolve2(expandTilde(projectPath.trim()));
2630
- } else {
2631
- const selectedPath = await selectProjectRepository("Select repository:");
2632
- if (!selectedPath) {
2633
- showError("No repository selected");
2634
- exitWithCode(EXIT_ERROR);
2635
- }
2636
- projectPath = selectedPath;
2637
- }
2638
- } else {
2639
- projectPath = await input4({
2640
- message: `${icons.project} Project path:`,
2641
- default: options.project?.trim() ?? process.cwd(),
2642
- validate: async (v) => {
2643
- const result = await validateProjectPath(v.trim());
2644
- return result.ok ? true : result.error.message;
2645
- }
2646
- });
2647
- projectPath = resolve2(expandTilde(projectPath.trim()));
2648
- }
2649
- }
2650
- name = name.trim();
2651
- const trimmedDescription = description.trim();
2652
- description = trimmedDescription === "" ? void 0 : trimmedDescription;
2653
- }
2654
- if (!projectPath) {
2655
- showError("Project path is required");
2656
- exitWithCode(EXIT_ERROR);
2657
- }
2658
- const addR = await wrapAsync(() => addTask({ name, description, steps, ticketId, projectPath }), ensureError);
2659
- if (!addR.ok) {
2660
- if (addR.error instanceof SprintStatusError) {
2661
- const mainError = addR.error.message.split("\n")[0] ?? addR.error.message;
2662
- showError(mainError);
2663
- showNextSteps([
2664
- ["ralphctl sprint close", "close current sprint"],
2665
- ["ralphctl sprint create", "start a new draft sprint"]
2666
- ]);
2667
- log.newline();
2668
- if (!isInteractive) exitWithCode(EXIT_ERROR);
2669
- return;
2670
- }
2671
- throw addR.error;
2672
- }
2673
- const task = addR.value;
2674
- showSuccess("Task added!", [
2675
- ["ID", task.id],
2676
- ["Name", task.name],
2677
- ["Project", task.projectPath],
2678
- ["Order", String(task.order)]
2679
- ]);
2680
- if (task.ticketId) {
2681
- console.log(field("Ticket", task.ticketId));
2682
- }
2683
- if (task.steps.length > 0) {
2684
- console.log(field("Steps", ""));
2685
- task.steps.forEach((step, i) => {
2686
- console.log(muted(` ${String(i + 1)}. ${step}`));
2687
- });
2688
- }
2689
- console.log("");
2690
- }
2691
-
2692
- // src/commands/task/import.ts
2693
- import { readFile as readFile3 } from "fs/promises";
2694
- import { Result as Result5 } from "typescript-result";
2695
- async function taskImportCommand(args) {
2696
- const filePath = args[0];
2697
- if (!filePath) {
2698
- showError("File path required.");
2699
- showNextStep("ralphctl task import <file.json>", "provide a task file");
2700
- log.dim("Expected JSON format:");
2701
- console.log(
2702
- muted(`[
2703
- {
2704
- "id": "1",
2705
- "name": "Task name",
2706
- "projectPath": "/path/to/repo",
2707
- "description": "Optional description",
2708
- "steps": ["Step 1", "Step 2"],
2709
- "ticketId": "abc12345",
2710
- "blockedBy": ["task-001"]
2711
- }
2712
- ]`)
2713
- );
2714
- log.dim("Note: projectPath is required for each task.");
2715
- log.newline();
2716
- return;
2717
- }
2718
- const contentR = await wrapAsync(() => readFile3(filePath, "utf-8"), ensureError);
2719
- if (!contentR.ok) {
2720
- showError(`Failed to read file: ${filePath}`);
2721
- log.newline();
2722
- return;
2723
- }
2724
- const dataR = Result5.try(() => JSON.parse(contentR.value));
2725
- if (!dataR.ok) {
2726
- showError("Invalid JSON format.");
2727
- log.newline();
2728
- return;
2729
- }
2730
- const data = dataR.value;
2731
- const result = ImportTasksSchema.safeParse(data);
2732
- if (!result.success) {
2733
- showError("Invalid task format");
2734
- for (const issue of result.error.issues) {
2735
- log.item(error(`${issue.path.join(".")}: ${issue.message}`));
2736
- }
2737
- log.newline();
2738
- return;
2739
- }
2740
- const tasks = result.data;
2741
- if (tasks.length === 0) {
2742
- showError("No tasks to import.");
2743
- log.newline();
2744
- return;
2745
- }
2746
- const existingTasks = await getTasks();
2747
- const sprintId = await resolveSprintId();
2748
- const sprint = await getSprint(sprintId);
2749
- const ticketIds = new Set(sprint.tickets.map((t) => t.id));
2750
- const validationErrors = validateImportTasks(tasks, existingTasks, ticketIds);
2751
- if (validationErrors.length > 0) {
2752
- showError("Dependency validation failed");
2753
- for (const err of validationErrors) {
2754
- log.item(error(err));
2755
- }
2756
- log.newline();
2757
- return;
2758
- }
2759
- const localToRealId = /* @__PURE__ */ new Map();
2760
- const createdTasks = [];
2761
- const spinner = createSpinner(`Importing ${String(tasks.length)} task(s)...`).start();
2762
- let imported = 0;
2763
- for (const taskInput of tasks) {
2764
- const addR = await wrapAsync(
2765
- () => addTask({
2766
- name: taskInput.name,
2767
- description: taskInput.description,
2768
- steps: taskInput.steps ?? [],
2769
- ticketId: taskInput.ticketId,
2770
- blockedBy: [],
2771
- // Set later
2772
- projectPath: taskInput.projectPath
2773
- }),
2774
- ensureError
2775
- );
2776
- if (!addR.ok) {
2777
- if (addR.error instanceof SprintStatusError) {
2778
- spinner.fail("Import failed");
2779
- showError(addR.error.message);
2780
- log.newline();
2781
- return;
2782
- }
2783
- log.itemError(`Failed to add: ${taskInput.name}`);
2784
- console.log(muted(` ${addR.error.message}`));
2785
- continue;
2786
- }
2787
- const task = addR.value;
2788
- if (taskInput.id) {
2789
- localToRealId.set(taskInput.id, task.id);
2790
- }
2791
- createdTasks.push({ task: taskInput, realId: task.id });
2792
- imported++;
2793
- spinner.text = `Importing tasks... (${String(imported)}/${String(tasks.length)})`;
2794
- }
2795
- spinner.text = "Resolving task dependencies...";
2796
- const tasksFilePath = getTasksFilePath(sprintId);
2797
- const lockR = await withFileLock(tasksFilePath, async () => {
2798
- const allTasks = await getTasks();
2799
- for (const { task: taskInput, realId } of createdTasks) {
2800
- const blockedBy = (taskInput.blockedBy ?? []).map((localId) => localToRealId.get(localId) ?? "").filter((id) => id !== "");
2801
- if (blockedBy.length > 0) {
2802
- const taskToUpdate = allTasks.find((t) => t.id === realId);
2803
- if (taskToUpdate) {
2804
- taskToUpdate.blockedBy = blockedBy;
2805
- }
2806
- }
2807
- }
2808
- await saveTasks(allTasks);
2809
- });
2810
- if (!lockR.ok) {
2811
- showError(`Failed to update dependencies: ${lockR.error.message}`);
2812
- log.newline();
2813
- return;
2814
- }
2815
- spinner.succeed(`Imported ${String(imported)}/${String(tasks.length)} tasks`);
2816
- for (const { task: taskInput, realId } of createdTasks) {
2817
- log.itemSuccess(`${realId}: ${taskInput.name}`);
2818
- }
2819
- }
2820
-
2821
- // src/commands/task/list.ts
2822
- function parseListArgs2(args) {
2823
- const result = {
2824
- brief: false,
2825
- blockedOnly: false
2826
- };
2827
- for (let i = 0; i < args.length; i++) {
2828
- const arg = args[i];
2829
- const next = args[i + 1];
2830
- if (arg === "-b" || arg === "--brief") result.brief = true;
2831
- else if (arg === "--status" && next) {
2832
- result.statusFilter = next;
2833
- i++;
2834
- } else if (arg === "--project" && next) {
2835
- result.projectFilter = next;
2836
- i++;
2837
- } else if (arg === "--ticket" && next) {
2838
- result.ticketFilter = next;
2839
- i++;
2840
- } else if (arg === "--blocked") result.blockedOnly = true;
2841
- }
2842
- return result;
2843
- }
2844
- function buildFilterSummary2(filters) {
2845
- const parts = [];
2846
- if (filters.statusFilter) parts.push(`status=${filters.statusFilter}`);
2847
- if (filters.projectFilter) parts.push(`project=${filters.projectFilter}`);
2848
- if (filters.ticketFilter) parts.push(`ticket=${filters.ticketFilter}`);
2849
- if (filters.blockedOnly) parts.push("blocked");
2850
- return parts.length > 0 ? ` (filtered: ${parts.join(", ")})` : "";
2851
- }
2852
- async function taskListCommand(args = []) {
2853
- const { brief, statusFilter, projectFilter, ticketFilter, blockedOnly } = parseListArgs2(args);
2854
- if (statusFilter) {
2855
- const result = TaskStatusSchema.safeParse(statusFilter);
2856
- if (!result.success) {
2857
- showError(`Invalid status: "${statusFilter}". Valid values: todo, in_progress, done`);
2858
- return;
2859
- }
2860
- }
2861
- const tasks = await listTasks();
2862
- if (tasks.length === 0) {
2863
- showEmpty("tasks", "Add one with: ralphctl task add");
2864
- return;
2865
- }
2866
- let filtered = tasks;
2867
- if (statusFilter) filtered = filtered.filter((t) => t.status === statusFilter);
2868
- if (projectFilter) filtered = filtered.filter((t) => t.projectPath.includes(projectFilter));
2869
- if (ticketFilter) filtered = filtered.filter((t) => t.ticketId === ticketFilter);
2870
- if (blockedOnly) filtered = filtered.filter((t) => t.blockedBy.length > 0);
2871
- const filterStr = buildFilterSummary2({ brief, statusFilter, projectFilter, ticketFilter, blockedOnly });
2872
- const isFiltered = filtered.length !== tasks.length;
2873
- if (filtered.length === 0) {
2874
- showEmpty("matching tasks", "Try adjusting your filters");
2875
- return;
2876
- }
2877
- if (brief) {
2878
- const countLabel = isFiltered ? `${String(filtered.length)} of ${String(tasks.length)}` : String(tasks.length);
2879
- console.log(`
2880
- # Tasks (${countLabel})${filterStr}
2881
- `);
2882
- for (const task of filtered) {
2883
- const ticketRef = task.ticketId ? ` [${task.ticketId}]` : "";
2884
- const blockedRef = task.blockedBy.length > 0 ? ` (blocked by: ${task.blockedBy.join(", ")})` : "";
2885
- console.log(
2886
- `- ${String(task.order)}. **[${task.status}]** ${task.id}: ${task.name} (${task.projectPath})${ticketRef}${blockedRef}`
2887
- );
2888
- }
2889
- console.log("");
2890
- return;
2891
- }
2892
- const tasksByStatus = {
2893
- todo: filtered.filter((t) => t.status === "todo").length,
2894
- in_progress: filtered.filter((t) => t.status === "in_progress").length,
2895
- done: filtered.filter((t) => t.status === "done").length
2896
- };
2897
- printHeader(`Tasks (${String(filtered.length)})`, icons.task);
2898
- log.raw(
2899
- `${formatTaskStatus("todo")} ${String(tasksByStatus.todo)} ${formatTaskStatus("in_progress")} ${String(tasksByStatus.in_progress)} ${formatTaskStatus("done")} ${String(tasksByStatus.done)}`
2900
- );
2901
- log.newline();
2902
- const rows = filtered.map((task) => {
2903
- const statusIcon = task.status === "done" ? icons.success : task.status === "in_progress" ? icons.active : icons.inactive;
2904
- const statusColor = task.status === "done" ? "success" : task.status === "in_progress" ? "warning" : "muted";
2905
- const blocked = task.blockedBy.length > 0 ? colors.warning("(blocked)") : "";
2906
- return [badge(statusIcon, statusColor), String(task.order), task.name, task.id, blocked];
2907
- });
2908
- console.log(
2909
- renderTable(
2910
- [
2911
- { header: "", minWidth: 0 },
2912
- { header: "#", align: "right" },
2913
- { header: "Name" },
2914
- { header: "ID" },
2915
- { header: "" }
2916
- ],
2917
- rows
2918
- )
2919
- );
2920
- const percent = filtered.length > 0 ? Math.round(tasksByStatus.done / filtered.length * 100) : 0;
2921
- const progressColor = percent === 100 ? colors.success : percent > 50 ? colors.warning : colors.muted;
2922
- const showingLabel = isFiltered ? `Showing ${String(filtered.length)} of ${String(tasks.length)} task(s)${filterStr}` : `Showing ${String(tasks.length)} task(s)`;
2923
- log.newline();
2924
- log.dim(
2925
- `Progress: ${progressColor(`${String(tasksByStatus.done)}/${String(filtered.length)} (${String(percent)}%)`)} | ${showingLabel}`
2926
- );
2927
- log.newline();
2928
- }
2929
-
2930
- // src/commands/task/show.ts
2931
- async function taskShowCommand(args) {
2932
- let taskId = args[0];
2933
- if (!taskId) {
2934
- const selected = await selectTask("Select task to show:");
2935
- if (!selected) return;
2936
- taskId = selected;
2937
- }
2938
- const taskR = await wrapAsync(() => getTask(taskId), ensureError);
2939
- if (!taskR.ok) {
2940
- if (taskR.error instanceof TaskNotFoundError) {
2941
- showError(`Task not found: ${taskId}`);
2942
- showNextStep("ralphctl task list", "see available tasks");
2943
- log.newline();
2944
- } else {
2945
- throw taskR.error;
2946
- }
2947
- return;
2948
- }
2949
- const task = taskR.value;
2950
- const infoLines = [
2951
- labelValue("ID", task.id),
2952
- labelValue("Status", formatTaskStatus(task.status)),
2953
- labelValue("Order", String(task.order)),
2954
- labelValue("Project", task.projectPath)
2955
- ];
2956
- if (task.ticketId) {
2957
- infoLines.push(labelValue("Ticket", task.ticketId));
2958
- }
2959
- if (task.description) {
2960
- infoLines.push("");
2961
- infoLines.push(labelValue("Description", ""));
2962
- for (const line2 of task.description.split("\n")) {
2963
- infoLines.push(`${" ".repeat(DETAIL_LABEL_WIDTH + 1)}${line2}`);
2964
- }
2965
- }
2966
- log.newline();
2967
- console.log(renderCard(`${icons.task} ${task.name}`, infoLines));
2968
- if (task.steps.length > 0) {
2969
- log.newline();
2970
- const stepLines = [];
2971
- for (let i = 0; i < task.steps.length; i++) {
2972
- const step = task.steps[i] ?? "";
2973
- const checkbox = task.status === "done" ? colors.success("[x]") : muted("[ ]");
2974
- stepLines.push(`${checkbox} ${muted(String(i + 1) + ".")} ${step}`);
2975
- }
2976
- console.log(renderCard(`${icons.bullet} Steps (${String(task.steps.length)})`, stepLines));
2977
- }
2978
- if (task.blockedBy.length > 0) {
2979
- log.newline();
2980
- const depLines = [];
2981
- for (const dep of task.blockedBy) {
2982
- depLines.push(`${icons.bullet} ${dep}`);
2983
- }
2984
- console.log(renderCard(`${icons.warning} Blocked By`, depLines));
2985
- }
2986
- if (task.ticketId) {
2987
- const taskTicketId = task.ticketId;
2988
- const ticketR = await wrapAsync(() => getTicket(taskTicketId), ensureError);
2989
- if (ticketR.ok && ticketR.value.requirements) {
2990
- log.newline();
2991
- const reqLines = ticketR.value.requirements.split("\n");
2992
- console.log(renderCard(`${icons.ticket} Requirements`, reqLines));
2993
- }
2994
- }
2995
- if (task.verified) {
2996
- log.newline();
2997
- const verifyLines = [`${colors.success(icons.success)} Verified`];
2998
- if (task.verificationOutput) {
2999
- verifyLines.push(colors.muted(horizontalLine(30, "rounded")));
3000
- for (const line2 of task.verificationOutput.split("\n").slice(0, 10)) {
3001
- verifyLines.push(muted(line2));
3002
- }
3003
- }
3004
- console.log(renderCard(`${icons.success} Verification`, verifyLines));
3005
- }
3006
- log.newline();
3007
- }
3008
-
3009
- // src/commands/task/status.ts
3010
- var VALID_STATUSES = ["todo", "in_progress", "done"];
3011
- async function taskStatusCommand(args, options = {}) {
3012
- let taskId = args[0] ?? options.taskId;
3013
- let newStatus = args[1] ?? options.status;
3014
- if (options.noInteractive) {
3015
- const errors = [];
3016
- if (!taskId?.trim()) {
3017
- errors.push("Task ID is required");
3018
- }
3019
- if (!newStatus?.trim()) {
3020
- errors.push("Status is required");
3021
- } else {
3022
- const result2 = TaskStatusSchema.safeParse(newStatus);
3023
- if (!result2.success) {
3024
- errors.push(`Invalid status: ${newStatus} (valid: ${VALID_STATUSES.join(", ")})`);
3025
- }
3026
- }
3027
- if (errors.length > 0) {
3028
- showError("Validation failed");
3029
- for (const e of errors) {
3030
- log.error(e);
3031
- }
3032
- log.newline();
3033
- exitWithCode(EXIT_ERROR);
3034
- }
3035
- }
3036
- if (!taskId) {
3037
- const selected = await selectTask("Select task to update:");
3038
- if (!selected) return;
3039
- taskId = selected;
3040
- }
3041
- if (!newStatus) {
3042
- const selected = await selectTaskStatus("Select new status:");
3043
- if (!selected) return;
3044
- newStatus = selected;
3045
- }
3046
- const result = TaskStatusSchema.safeParse(newStatus);
3047
- if (!result.success) {
3048
- showError(`Invalid status: ${newStatus}`);
3049
- log.dim(`Valid statuses: ${VALID_STATUSES.join(", ")}`);
3050
- log.newline();
3051
- if (options.noInteractive) {
3052
- exitWithCode(EXIT_ERROR);
3053
- }
3054
- return;
3055
- }
3056
- const updateR = await wrapAsync(() => updateTaskStatus(taskId, result.data), ensureError);
3057
- if (!updateR.ok) {
3058
- if (updateR.error instanceof TaskNotFoundError) {
3059
- showError(`Task not found: ${taskId}`);
3060
- showNextStep("ralphctl task list", "see available tasks");
3061
- log.newline();
3062
- if (options.noInteractive) {
3063
- exitWithCode(EXIT_ERROR);
3064
- }
3065
- } else if (updateR.error instanceof SprintStatusError) {
3066
- showError(updateR.error.message);
3067
- log.newline();
3068
- if (options.noInteractive) {
3069
- exitWithCode(EXIT_ERROR);
3070
- }
3071
- } else {
3072
- throw updateR.error;
3073
- }
3074
- return;
3075
- }
3076
- showSuccess("Task status updated!", [
3077
- ["ID", updateR.value.id],
3078
- ["Name", updateR.value.name],
3079
- ["Status", formatTaskStatus(updateR.value.status)]
3080
- ]);
3081
- log.newline();
3082
- }
3083
-
3084
- // src/commands/task/next.ts
3085
- async function taskNextCommand() {
3086
- const task = await getNextTask();
3087
- if (!task) {
3088
- showEmpty("pending tasks", "All tasks are done, or add more with: ralphctl task add");
3089
- return;
3090
- }
3091
- printHeader("Next Task");
3092
- console.log(field("ID", task.id));
3093
- console.log(field("Name", task.name));
3094
- console.log(field("Status", formatTaskStatus(task.status)));
3095
- console.log(field("Order", String(task.order)));
3096
- if (task.ticketId) {
3097
- console.log(field("Ticket", task.ticketId));
3098
- }
3099
- if (task.description) {
3100
- log.newline();
3101
- console.log(field("Description", ""));
3102
- log.raw(task.description, 2);
3103
- }
3104
- if (task.steps.length > 0) {
3105
- log.newline();
3106
- console.log(field("Steps", ""));
3107
- task.steps.forEach((step, i) => {
3108
- log.raw(`${String(i + 1)}. ${step}`, 2);
3109
- });
3110
- }
3111
- if (task.blockedBy.length > 0) {
3112
- log.newline();
3113
- console.log(field("Blocked By", ""));
3114
- task.blockedBy.forEach((dep) => {
3115
- log.item(dep);
3116
- });
3117
- }
3118
- showNextStep(`ralphctl task status ${task.id} in_progress`, "Start working on this task");
3119
- }
3120
-
3121
- // src/commands/task/reorder.ts
3122
- async function taskReorderCommand(args) {
3123
- let taskId = args[0];
3124
- let newOrder;
3125
- if (args[1]) {
3126
- newOrder = parseInt(args[1], 10);
3127
- }
3128
- if (!taskId) {
3129
- const selected = await selectTask("Select task to reorder:");
3130
- if (!selected) return;
3131
- taskId = selected;
3132
- }
3133
- if (newOrder === void 0 || isNaN(newOrder) || newOrder < 1) {
3134
- newOrder = await inputPositiveInt("New position (1 = highest priority):");
3135
- }
3136
- const reorderR = await wrapAsync(() => reorderTask(taskId, newOrder), ensureError);
3137
- if (!reorderR.ok) {
3138
- if (reorderR.error instanceof TaskNotFoundError) {
3139
- showError(`Task not found: ${taskId}`);
3140
- log.newline();
3141
- } else if (reorderR.error instanceof SprintStatusError) {
3142
- showError(reorderR.error.message);
3143
- log.newline();
3144
- } else {
3145
- throw reorderR.error;
3146
- }
3147
- return;
3148
- }
3149
- showSuccess("Task reordered!", [
3150
- ["ID", reorderR.value.id],
3151
- ["Name", reorderR.value.name],
3152
- ["New Order", String(reorderR.value.order)]
3153
- ]);
3154
- log.newline();
3155
- }
3156
-
3157
- // src/commands/task/remove.ts
3158
- import { confirm as confirm8 } from "@inquirer/prompts";
3159
- async function taskRemoveCommand(args) {
3160
- const skipConfirm = args.includes("-y") || args.includes("--yes");
3161
- let taskId = args.find((a) => !a.startsWith("-"));
3162
- if (!taskId) {
3163
- const selected = await selectTask("Select task to remove:");
3164
- if (!selected) return;
3165
- taskId = selected;
3166
- }
3167
- const opR = await wrapAsync(async () => {
3168
- const task = await getTask(taskId);
3169
- if (!skipConfirm) {
3170
- const confirmed = await confirm8({
3171
- message: `Remove task "${task.name}" (${task.id})?`,
3172
- default: false
3173
- });
3174
- if (!confirmed) {
3175
- console.log(muted("\nTask removal cancelled.\n"));
3176
- return null;
3177
- }
3178
- }
3179
- await removeTask(taskId);
3180
- return task;
3181
- }, ensureError);
3182
- if (!opR.ok) {
3183
- if (opR.error instanceof TaskNotFoundError) {
3184
- showError(`Task not found: ${taskId}`);
3185
- log.newline();
3186
- } else if (opR.error instanceof SprintStatusError) {
3187
- showError(opR.error.message);
3188
- log.newline();
3189
- } else {
3190
- throw opR.error;
3191
- }
3192
- return;
3193
- }
3194
- if (opR.value !== null) {
3195
- showSuccess("Task removed", [["ID", taskId]]);
3196
- log.newline();
3197
- }
3198
- }
3199
-
3200
- // src/commands/progress/log.ts
3201
- async function progressLogCommand(args) {
3202
- const statusCheckR = await wrapAsync(async () => {
3203
- const sprintId = await resolveSprintId();
3204
- const sprint = await getSprint(sprintId);
3205
- assertSprintStatus(sprint, ["active"], "log progress");
3206
- }, ensureError);
3207
- if (!statusCheckR.ok) {
3208
- const err = statusCheckR.error;
3209
- if (err instanceof SprintStatusError) {
3210
- const mainError = err.message.split("\n")[0] ?? err.message;
3211
- showError(mainError);
3212
- showNextStep("ralphctl sprint start", "activate the sprint");
3213
- log.newline();
3214
- return;
3215
- }
3216
- if (err instanceof NoCurrentSprintError) {
3217
- showError("No current sprint set.");
3218
- showNextStep("ralphctl sprint create", "create a new sprint");
3219
- log.newline();
3220
- return;
3221
- }
3222
- throw err;
3223
- }
3224
- let message = args.join(" ").trim();
3225
- if (!message) {
3226
- const editorR = await editorInput({
3227
- message: "Progress message:"
3228
- });
3229
- if (!editorR.ok) {
3230
- showError(`Editor input failed: ${editorR.error.message}`);
3231
- log.newline();
3232
- return;
3233
- }
3234
- message = editorR.value;
3235
- message = message.trim();
3236
- }
3237
- if (!message) {
3238
- showError("No message provided.");
3239
- log.newline();
3240
- return;
3241
- }
3242
- const logR = await wrapAsync(() => logProgress(message), ensureError);
3243
- if (!logR.ok) {
3244
- if (logR.error instanceof SprintStatusError) {
3245
- showError(logR.error.message);
3246
- log.newline();
3247
- } else {
3248
- throw logR.error;
3249
- }
3250
- return;
3251
- }
3252
- showSuccess("Progress logged.");
3253
- log.newline();
3254
- }
3255
-
3256
- // src/commands/progress/show.ts
3257
- async function progressShowCommand() {
3258
- const content = await getProgress();
3259
- if (!content.trim()) {
3260
- showEmpty("progress entries", "Log with: ralphctl progress log");
3261
- return;
3262
- }
3263
- printHeader("Progress Log");
3264
- console.log(content);
3265
- }
3266
-
3267
- // src/commands/config/config.ts
3268
- async function configSetCommand(args) {
3269
- if (args.length < 2) {
3270
- showError("Usage: ralphctl config set <key> <value>");
3271
- log.dim("Available keys: provider, editor, evaluationIterations");
3272
- log.newline();
3273
- return;
3274
- }
3275
- const [key, value] = args;
3276
- if (key === "provider") {
3277
- const parsed = AiProviderSchema.safeParse(value);
3278
- if (!parsed.success) {
3279
- showError(`Invalid provider: ${value ?? "(empty)"}`);
3280
- log.dim("Valid providers: claude, copilot");
3281
- log.newline();
3282
- return;
3283
- }
3284
- await setAiProvider(parsed.data);
3285
- showSuccess(`AI provider set to: ${parsed.data}`);
3286
- log.newline();
3287
- return;
3288
- }
3289
- if (key === "editor") {
3290
- const trimmed = value?.trim();
3291
- if (!trimmed) {
3292
- showError("Editor command cannot be empty");
3293
- log.dim('Examples: "subl -w", "code --wait", "vim", "nano"');
3294
- log.newline();
3295
- return;
3296
- }
3297
- await setEditor(trimmed);
3298
- showSuccess(`Editor set to: ${trimmed}`);
3299
- log.newline();
3300
- return;
3301
- }
3302
- if (key === "evaluationIterations") {
3303
- const parsed = Number.parseInt(value ?? "", 10);
3304
- if (Number.isNaN(parsed) || parsed < 0 || !Number.isInteger(parsed)) {
3305
- showError(`Invalid evaluation iterations: ${value ?? "(empty)"}`);
3306
- log.dim("Must be an integer >= 0 (0 = disabled)");
3307
- log.newline();
3308
- return;
3309
- }
3310
- await setEvaluationIterations(parsed);
3311
- showSuccess(`Evaluation iterations set to: ${String(parsed)}`);
3312
- log.newline();
3313
- return;
3314
- }
3315
- showError(`Unknown config key: ${key ?? "(empty)"}`);
3316
- log.dim("Available keys: provider, editor, evaluationIterations");
3317
- log.newline();
3318
- }
3319
- async function configShowCommand() {
3320
- const provider = await getAiProvider();
3321
- const editorCmd = await getEditor();
3322
- const evalIterations = await getEvaluationIterations();
3323
- printHeader("Configuration", icons.info);
3324
- console.log(field("AI Provider", provider ?? "(not set \u2014 will prompt on first use)"));
3325
- console.log(field("Editor", editorCmd ?? "(not set \u2014 will prompt on first use)"));
3326
- const evalDisplay = evalIterations === DEFAULT_EVALUATION_ITERATIONS ? `${String(evalIterations)} (default)` : evalIterations === 0 ? "0 (disabled)" : String(evalIterations);
3327
- console.log(field("Evaluation Iterations", evalDisplay));
3328
- log.newline();
3329
- }
3330
-
3331
- // src/commands/doctor/doctor.ts
3332
- import { access, constants } from "fs/promises";
3333
- import { join as join4 } from "path";
3334
- import { spawnSync as spawnSync2 } from "child_process";
3335
- var REQUIRED_NODE_MAJOR = 24;
3336
- function checkNodeVersion() {
3337
- const version = process.version;
3338
- const match = /^v(\d+)/.exec(version);
3339
- const major = match ? Number(match[1]) : 0;
3340
- if (major >= REQUIRED_NODE_MAJOR) {
3341
- return { name: "Node.js version", status: "pass", detail: version };
3342
- }
3343
- return {
3344
- name: "Node.js version",
3345
- status: "fail",
3346
- detail: `${version} (requires >= ${String(REQUIRED_NODE_MAJOR)}.0.0)`
3347
- };
3348
- }
3349
- function checkGitInstalled() {
3350
- const result = spawnSync2("git", ["--version"], {
3351
- encoding: "utf-8",
3352
- stdio: ["ignore", "pipe", "pipe"]
3353
- });
3354
- if (result.status === 0) {
3355
- const version = result.stdout.trim();
3356
- return { name: "Git installed", status: "pass", detail: version };
3357
- }
3358
- return { name: "Git installed", status: "fail", detail: "git not found in PATH" };
3359
- }
3360
- function checkGitIdentity() {
3361
- const nameResult = spawnSync2("git", ["config", "user.name"], {
3362
- encoding: "utf-8",
3363
- stdio: ["ignore", "pipe", "pipe"]
3364
- });
3365
- const emailResult = spawnSync2("git", ["config", "user.email"], {
3366
- encoding: "utf-8",
3367
- stdio: ["ignore", "pipe", "pipe"]
3368
- });
3369
- const name = nameResult.status === 0 ? nameResult.stdout.trim() : "";
3370
- const email = emailResult.status === 0 ? emailResult.stdout.trim() : "";
3371
- if (name && email) {
3372
- return { name: "Git identity", status: "pass", detail: `${name} <${email}>` };
3373
- }
3374
- const missing = [];
3375
- if (!name) missing.push("user.name");
3376
- if (!email) missing.push("user.email");
3377
- return { name: "Git identity", status: "warn", detail: `missing: ${missing.join(", ")}` };
3378
- }
3379
- async function checkAiProvider() {
3380
- const config = await getConfig();
3381
- const provider = config.aiProvider;
3382
- if (!provider) {
3383
- return { name: "AI provider binary", status: "skip", detail: "not configured" };
3384
- }
3385
- const binary = provider === "claude" ? "claude" : "copilot";
3386
- const result = spawnSync2("which", [binary], {
3387
- encoding: "utf-8",
3388
- stdio: ["ignore", "pipe", "pipe"]
3389
- });
3390
- if (result.status === 0) {
3391
- const detail = provider === "copilot" ? `${binary} found (public preview)` : `${binary} found`;
3392
- return { name: "AI provider binary", status: "pass", detail };
3393
- }
3394
- return {
3395
- name: "AI provider binary",
3396
- status: "fail",
3397
- detail: `${binary} not found in PATH (provider: ${provider})`
3398
- };
3399
- }
3400
- function checkGlabInstalled() {
3401
- if (isGlabAvailable()) {
3402
- return { name: "GitLab CLI (glab)", status: "pass", detail: "installed" };
3403
- }
3404
- return {
3405
- name: "GitLab CLI (glab)",
3406
- status: "skip",
3407
- detail: "not installed (optional \u2014 needed for GitLab issue enrichment)"
3408
- };
3409
- }
3410
- async function checkDataDirectory() {
3411
- const dataDir = getDataDir();
3412
- const accessR = await wrapAsync(() => access(dataDir, constants.R_OK | constants.W_OK), ensureError);
3413
- if (accessR.ok) {
3414
- return { name: "Data directory", status: "pass", detail: dataDir };
3415
- }
3416
- return { name: "Data directory", status: "fail", detail: `${dataDir} not accessible or writable` };
3417
- }
3418
- async function checkProjectPaths() {
3419
- const projects = await listProjects();
3420
- if (projects.length === 0) {
3421
- return { name: "Project paths", status: "skip", detail: "no projects registered" };
3422
- }
3423
- const issues = [];
3424
- for (const project of projects) {
3425
- for (const repo of project.repositories) {
3426
- const validation = await validateProjectPath(repo.path);
3427
- if (!validation.ok) {
3428
- issues.push(`${project.name}/${repo.name}: ${validation.error.message}`);
3429
- continue;
3430
- }
3431
- const gitDir = join4(repo.path, ".git");
3432
- if (!await fileExists(gitDir)) {
3433
- issues.push(`${project.name}/${repo.name}: not a git repository`);
3434
- }
3435
- }
3436
- }
3437
- if (issues.length === 0) {
3438
- const repoCount = projects.reduce((sum, p) => sum + p.repositories.length, 0);
3439
- return {
3440
- name: "Project paths",
3441
- status: "pass",
3442
- detail: `${String(repoCount)} repo${repoCount !== 1 ? "s" : ""} verified`
3443
- };
3444
- }
3445
- return { name: "Project paths", status: "fail", detail: issues.join("; ") };
3446
- }
3447
- async function checkEvaluationConfig() {
3448
- const config = await getConfig();
3449
- if (config.evaluationIterations == null) {
3450
- return {
3451
- name: "Evaluation config",
3452
- status: "warn",
3453
- detail: "evaluationIterations not set \u2014 defaulting to 1 (set via: ralphctl config set evaluationIterations <n>)"
3454
- };
3455
- }
3456
- return {
3457
- name: "Evaluation config",
3458
- status: "pass",
3459
- detail: `evaluationIterations: ${String(config.evaluationIterations)}`
3460
- };
3461
- }
3462
- async function checkCurrentSprint() {
3463
- const config = await getConfig();
3464
- const sprintId = config.currentSprint;
3465
- if (!sprintId) {
3466
- return { name: "Current sprint", status: "skip", detail: "no current sprint set" };
3467
- }
3468
- const sprintPath = getSprintFilePath(sprintId);
3469
- if (!await fileExists(sprintPath)) {
3470
- return { name: "Current sprint", status: "fail", detail: `sprint file missing: ${sprintId}` };
3471
- }
3472
- const result = await readValidatedJson(sprintPath, SprintSchema);
3473
- if (!result.ok) {
3474
- return { name: "Current sprint", status: "fail", detail: `invalid sprint data: ${result.error.message}` };
3475
- }
3476
- return { name: "Current sprint", status: "pass", detail: `${result.value.name} (${result.value.status})` };
3477
- }
3478
- async function doctorCommand() {
3479
- printHeader("System Health Check", icons.info);
3480
- const results = [];
3481
- results.push(checkNodeVersion());
3482
- results.push(checkGitInstalled());
3483
- results.push(checkGitIdentity());
3484
- results.push(checkGlabInstalled());
3485
- const asyncResults = await Promise.all([
3486
- checkAiProvider(),
3487
- checkDataDirectory(),
3488
- checkProjectPaths(),
3489
- checkCurrentSprint(),
3490
- checkEvaluationConfig()
3491
- ]);
3492
- results.push(...asyncResults);
3493
- for (const result of results) {
3494
- if (result.status === "pass") {
3495
- log.success(`${result.name}${result.detail ? colors.muted(` \u2014 ${result.detail}`) : ""}`);
3496
- } else if (result.status === "warn") {
3497
- log.warn(`${result.name}${result.detail ? colors.muted(` \u2014 ${result.detail}`) : ""}`);
3498
- } else if (result.status === "fail") {
3499
- log.error(result.name);
3500
- if (result.detail) {
3501
- log.dim(` ${result.detail}`);
3502
- }
3503
- } else {
3504
- log.raw(
3505
- `${icons.bullet} ${colors.muted(result.name)} ${colors.muted("\u2014")} ${colors.muted(result.detail ?? "skipped")}`
3506
- );
3507
- }
3508
- }
3509
- log.newline();
3510
- const passed = results.filter((r) => r.status === "pass").length;
3511
- const warned = results.filter((r) => r.status === "warn").length;
3512
- const failed = results.filter((r) => r.status === "fail").length;
3513
- const total = results.filter((r) => r.status !== "skip").length;
3514
- if (failed === 0 && warned === 0) {
3515
- log.success(`All checks passed (${String(passed)}/${String(total)})`);
3516
- log.newline();
3517
- const quote = getQuoteForContext("success");
3518
- log.dim(`"${quote}"`);
3519
- } else if (failed === 0) {
3520
- log.success(
3521
- `${String(passed)}/${String(total)} checks passed, ${String(warned)} warning${warned !== 1 ? "s" : ""}`
3522
- );
3523
- log.newline();
3524
- const quote = getQuoteForContext("success");
3525
- log.dim(`"${quote}"`);
3526
- } else {
3527
- log.error(`${String(passed)}/${String(total)} checks passed, ${String(failed)} failed`);
3528
- log.newline();
3529
- const quote = getQuoteForContext("error");
3530
- log.dim(`"${quote}"`);
3531
- process.exitCode = EXIT_ERROR;
3532
- }
3533
- log.newline();
3534
- }
3
+ cliMetadata,
4
+ configSetCommand,
5
+ configShowCommand,
6
+ createSharedDeps,
7
+ doctorCommand,
8
+ progressLogCommand,
9
+ progressShowCommand,
10
+ projectListCommand,
11
+ projectRemoveCommand,
12
+ projectRepoAddCommand,
13
+ projectRepoRemoveCommand,
14
+ projectShowCommand,
15
+ selectSprint,
16
+ showDashboard,
17
+ sprintCloseCommand,
18
+ sprintContextCommand,
19
+ sprintCurrentCommand,
20
+ sprintDeleteCommand,
21
+ sprintHealthCommand,
22
+ sprintIdeateCommand,
23
+ sprintListCommand,
24
+ sprintPlanCommand,
25
+ sprintRefineCommand,
26
+ sprintRequirementsCommand,
27
+ sprintShowCommand,
28
+ taskAddCommand,
29
+ taskImportCommand,
30
+ taskListCommand,
31
+ taskNextCommand,
32
+ taskRemoveCommand,
33
+ taskReorderCommand,
34
+ taskShowCommand,
35
+ taskStatusCommand,
36
+ ticketEditCommand,
37
+ ticketListCommand,
38
+ ticketRefineCommand,
39
+ ticketRemoveCommand,
40
+ ticketShowCommand
41
+ } from "./chunk-4GHVNKLV.mjs";
42
+ import {
43
+ projectAddCommand
44
+ } from "./chunk-D2YGPLIV.mjs";
45
+ import {
46
+ sprintCreateCommand
47
+ } from "./chunk-3QBEBKMZ.mjs";
48
+ import {
49
+ ticketAddCommand
50
+ } from "./chunk-JXMHLW42.mjs";
51
+ import "./chunk-NUYQK5MN.mjs";
52
+ import {
53
+ getTasks,
54
+ sprintStartCommand
55
+ } from "./chunk-CDOPLXFK.mjs";
56
+ import "./chunk-HL4ZMHCQ.mjs";
57
+ import {
58
+ EXIT_ERROR
59
+ } from "./chunk-CFUVE2BP.mjs";
60
+ import {
61
+ setSharedDeps
62
+ } from "./chunk-747KW2RW.mjs";
63
+ import {
64
+ getCurrentSprintOrThrow,
65
+ getSprint,
66
+ setCurrentSprint
67
+ } from "./chunk-YCDUVPRT.mjs";
68
+ import {
69
+ colors,
70
+ error,
71
+ icons,
72
+ log,
73
+ printBanner,
74
+ printHeader,
75
+ showError,
76
+ showSuccess
77
+ } from "./chunk-FKMKOWLA.mjs";
78
+ import {
79
+ ensureError,
80
+ wrapAsync
81
+ } from "./chunk-IWXBJD2D.mjs";
82
+ import {
83
+ ensureDir,
84
+ getDataDir
85
+ } from "./chunk-CTP2A436.mjs";
86
+ import {
87
+ DomainError
88
+ } from "./chunk-57UWLHRH.mjs";
3535
89
 
3536
- // src/interactive/index.ts
3537
- var selectTheme = {
3538
- icon: { cursor: emoji.donut },
3539
- style: {
3540
- highlight: (text) => colors.highlight(text),
3541
- description: (text) => colors.muted(text)
3542
- }
3543
- };
3544
- var commandMap = {
3545
- project: {
3546
- add: () => projectAddCommand({ interactive: true }),
3547
- list: () => projectListCommand(),
3548
- show: () => projectShowCommand([]),
3549
- remove: () => projectRemoveCommand([]),
3550
- "repo add": () => projectRepoAddCommand([]),
3551
- "repo remove": () => projectRepoRemoveCommand([])
3552
- },
3553
- sprint: {
3554
- create: () => sprintCreateCommand({ interactive: true }),
3555
- list: () => sprintListCommand(),
3556
- show: () => sprintShowCommand([]),
3557
- context: () => sprintContextCommand([]),
3558
- current: () => sprintCurrentCommand(["-"]),
3559
- refine: () => sprintRefineCommand([]),
3560
- ideate: () => sprintIdeateCommand([]),
3561
- plan: () => sprintPlanCommand([]),
3562
- start: () => sprintStartCommand([]),
3563
- requirements: () => sprintRequirementsCommand([]),
3564
- health: () => sprintHealthCommand(),
3565
- close: () => sprintCloseCommand([]),
3566
- delete: () => sprintDeleteCommand([]),
3567
- "progress show": () => progressShowCommand(),
3568
- "progress log": () => progressLogCommand([])
3569
- },
3570
- ticket: {
3571
- add: () => ticketAddCommand({ interactive: true }),
3572
- edit: () => ticketEditCommand(void 0, { interactive: true }),
3573
- list: () => ticketListCommand([]),
3574
- show: () => ticketShowCommand([]),
3575
- refine: () => ticketRefineCommand(void 0, { interactive: true }),
3576
- remove: () => ticketRemoveCommand([])
3577
- },
3578
- task: {
3579
- add: () => taskAddCommand({ interactive: true }),
3580
- import: () => taskImportCommand([]),
3581
- list: () => taskListCommand([]),
3582
- show: () => taskShowCommand([]),
3583
- status: () => taskStatusCommand([]),
3584
- next: () => taskNextCommand(),
3585
- reorder: () => taskReorderCommand([]),
3586
- remove: () => taskRemoveCommand([])
3587
- },
3588
- progress: {
3589
- log: () => progressLogCommand([]),
3590
- show: () => progressShowCommand()
3591
- },
3592
- doctor: {
3593
- run: () => doctorCommand()
3594
- },
3595
- config: {
3596
- show: () => configShowCommand(),
3597
- "set provider": async () => {
3598
- const choice = await select3({
3599
- message: `${emoji.donut} Which AI buddy should help with my homework?`,
3600
- choices: [
3601
- { name: "Claude Code", value: "claude" },
3602
- { name: "GitHub Copilot", value: "copilot" }
3603
- ],
3604
- default: await getAiProvider() ?? void 0,
3605
- theme: selectTheme
3606
- });
3607
- await configSetCommand(["provider", choice]);
3608
- },
3609
- "set editor": async () => {
3610
- const current = await getEditor();
3611
- const value = await input5({
3612
- message: `${emoji.donut} Which editor should open for refinement?`,
3613
- default: current ?? void 0,
3614
- theme: selectTheme
3615
- });
3616
- if (value.trim()) {
3617
- await configSetCommand(["editor", value.trim()]);
3618
- }
3619
- },
3620
- "set evaluationIterations": async () => {
3621
- const current = await getEvaluationIterations();
3622
- const value = await input5({
3623
- message: `${emoji.donut} How many evaluation loops? (0 = disabled)`,
3624
- default: String(current),
3625
- theme: selectTheme
3626
- });
3627
- await configSetCommand(["evaluationIterations", value.trim()]);
3628
- }
3629
- }
3630
- };
3631
- function showFarewell() {
3632
- const quote = getQuoteForContext("farewell");
3633
- console.log("");
3634
- printSeparator();
3635
- console.log(` ${emoji.donut} ${colors.muted(quote)}`);
3636
- console.log("");
3637
- }
3638
- async function pressEnterToContinue() {
3639
- const { createInterface } = await import("readline");
3640
- const rl = createInterface({ input: process.stdin, output: process.stdout });
3641
- await new Promise((resolve3) => {
3642
- rl.question(colors.muted(" Press Enter to continue..."), () => {
3643
- rl.close();
3644
- resolve3();
3645
- });
3646
- });
3647
- }
3648
- function showWelcomeBanner() {
3649
- showBanner();
3650
- }
3651
- async function readTasksSafe(sprintId) {
3652
- const result = await readValidatedJson(getTasksFilePath(sprintId), TasksSchema);
3653
- if (!result.ok) return [];
3654
- return result.value;
3655
- }
3656
- async function getMenuContext() {
3657
- let dashboardData = null;
3658
- const ctx = {
3659
- hasProjects: false,
3660
- projectCount: 0,
3661
- currentSprintId: null,
3662
- currentSprintName: null,
3663
- currentSprintStatus: null,
3664
- ticketCount: 0,
3665
- taskCount: 0,
3666
- tasksDone: 0,
3667
- tasksInProgress: 0,
3668
- pendingRequirements: 0,
3669
- allRequirementsApproved: false,
3670
- plannedTicketCount: 0,
3671
- nextAction: null,
3672
- aiProvider: null
3673
- };
3674
- const [config, projects] = await Promise.all([getConfig().catch(() => null), listProjects().catch(() => [])]);
3675
- ctx.hasProjects = projects.length > 0;
3676
- ctx.projectCount = projects.length;
3677
- ctx.aiProvider = config?.aiProvider ?? null;
3678
- const sprintId = config?.currentSprint ?? null;
3679
- if (!sprintId) return { ctx, dashboardData };
3680
- ctx.currentSprintId = sprintId;
3681
- const [sprint, tasks] = await Promise.all([getSprint(sprintId).catch(() => null), readTasksSafe(sprintId)]);
3682
- if (!sprint) return { ctx, dashboardData };
3683
- ctx.currentSprintName = sprint.name;
3684
- ctx.currentSprintStatus = sprint.status;
3685
- ctx.ticketCount = sprint.tickets.length;
3686
- const pendingTickets = getPendingRequirements(sprint.tickets);
3687
- ctx.pendingRequirements = pendingTickets.length;
3688
- ctx.allRequirementsApproved = allRequirementsApproved(sprint.tickets);
3689
- ctx.taskCount = tasks.length;
3690
- ctx.tasksDone = tasks.filter((t) => t.status === "done").length;
3691
- ctx.tasksInProgress = tasks.filter((t) => t.status === "in_progress").length;
3692
- const ticketIdsWithTasks = new Set(tasks.map((t) => t.ticketId).filter(Boolean));
3693
- ctx.plannedTicketCount = sprint.tickets.filter((t) => ticketIdsWithTasks.has(t.id)).length;
3694
- const doneIds = new Set(tasks.filter((t) => t.status === "done").map((t) => t.id));
3695
- const blockedCount = tasks.filter(
3696
- (t) => t.status !== "done" && t.blockedBy.length > 0 && !t.blockedBy.every((id) => doneIds.has(id))
3697
- ).length;
3698
- dashboardData = {
3699
- sprint,
3700
- tasks,
3701
- approvedCount: sprint.tickets.length - pendingTickets.length,
3702
- pendingCount: pendingTickets.length,
3703
- blockedCount,
3704
- plannedTicketCount: ctx.plannedTicketCount,
3705
- aiProvider: ctx.aiProvider
3706
- };
3707
- ctx.nextAction = getNextAction(dashboardData);
3708
- return { ctx, dashboardData };
3709
- }
3710
- async function interactiveMode() {
3711
- let escPressed = false;
3712
- while (true) {
3713
- const { ctx, dashboardData } = await getMenuContext();
3714
- clearScreen();
3715
- showWelcomeBanner();
3716
- const statusLines = renderStatusHeader(dashboardData);
3717
- if (statusLines.length > 0) {
3718
- for (const line2 of statusLines) {
3719
- console.log(line2);
3720
- }
3721
- log.newline();
3722
- }
3723
- const { items: mainMenu, defaultValue } = buildMainMenu(ctx);
3724
- const effectiveDefault = escPressed ? "exit" : defaultValue;
3725
- escPressed = false;
3726
- const commandResult = await wrapAsync(
3727
- () => escapableSelect(
3728
- {
3729
- message: `${emoji.donut} What would you like to do?`,
3730
- choices: mainMenu,
3731
- default: effectiveDefault,
3732
- pageSize: 30,
3733
- loop: true,
3734
- theme: selectTheme
3735
- },
3736
- { escLabel: "exit" }
3737
- ),
3738
- ensureError
3739
- );
3740
- if (!commandResult.ok) {
3741
- if (commandResult.error.name === "ExitPromptError") {
3742
- showFarewell();
3743
- break;
3744
- }
3745
- throw commandResult.error;
3746
- }
3747
- const command = commandResult.value;
3748
- if (command === null) {
3749
- escPressed = true;
3750
- continue;
3751
- }
3752
- if (command === "exit") {
3753
- showFarewell();
3754
- break;
3755
- }
3756
- if (command.startsWith("action:")) {
3757
- const parts = command.split(":");
3758
- const group = parts[1] ?? "";
3759
- const subCommand = parts[2] ?? "";
3760
- log.newline();
3761
- await executeCommand(group, subCommand);
3762
- log.newline();
3763
- await pressEnterToContinue();
3764
- continue;
3765
- }
3766
- if (command === "wizard") {
3767
- const { runWizard } = await import("./wizard-HWOH2HPV.mjs");
3768
- await runWizard();
3769
- continue;
3770
- }
3771
- const subMenu = buildSubMenu(command, ctx);
3772
- if (subMenu) {
3773
- await handleSubMenu(command, subMenu);
3774
- }
3775
- }
3776
- }
3777
- async function handleSubMenu(commandGroup, initialSubMenu) {
3778
- let currentTitle = initialSubMenu.title;
3779
- let currentItems = initialSubMenu.items;
3780
- while (true) {
3781
- log.newline();
3782
- const subCommandResult = await wrapAsync(
3783
- () => escapableSelect({
3784
- message: `${emoji.donut} ${currentTitle}`,
3785
- choices: currentItems,
3786
- pageSize: 30,
3787
- loop: true,
3788
- theme: selectTheme
3789
- }),
3790
- ensureError
3791
- );
3792
- if (!subCommandResult.ok) {
3793
- if (subCommandResult.error.name === "ExitPromptError") {
3794
- break;
3795
- }
3796
- throw subCommandResult.error;
3797
- }
3798
- const subCommand = subCommandResult.value;
3799
- if (subCommand === null || subCommand === "back") {
3800
- break;
3801
- }
3802
- log.newline();
3803
- await executeCommand(commandGroup, subCommand);
3804
- log.newline();
3805
- if (isWorkflowAction(commandGroup, subCommand)) {
3806
- break;
3807
- }
3808
- const { ctx: refreshedCtx } = await getMenuContext();
3809
- const refreshedMenu = buildSubMenu(commandGroup, refreshedCtx);
3810
- if (refreshedMenu) {
3811
- currentTitle = refreshedMenu.title;
3812
- currentItems = refreshedMenu.items;
3813
- }
3814
- }
3815
- }
3816
- async function executeCommand(group, subCommand) {
3817
- const groupHandlers = commandMap[group];
3818
- const handler = groupHandlers?.[subCommand];
3819
- if (!handler) {
3820
- log.error(`Unknown command: ${group} ${subCommand}`);
3821
- return;
3822
- }
3823
- const r = await wrapAsync(() => handler(), ensureError);
3824
- if (!r.ok) {
3825
- log.error(r.error.message);
3826
- }
3827
- }
90
+ // src/application/entrypoint.ts
91
+ import { Command } from "commander";
3828
92
 
3829
- // src/commands/project/index.ts
93
+ // src/integration/cli/commands/project/register.ts
3830
94
  function registerProjectCommands(program2) {
3831
95
  const project = program2.command("project").description("Manage projects");
3832
96
  project.addHelpText(
@@ -3886,7 +150,7 @@ Examples:
3886
150
  });
3887
151
  }
3888
152
 
3889
- // src/commands/sprint/switch.ts
153
+ // src/integration/cli/commands/sprint/switch.ts
3890
154
  async function sprintSwitchCommand() {
3891
155
  const selectedId = await selectSprint("Select sprint to switch to:");
3892
156
  if (!selectedId) return;
@@ -3899,9 +163,9 @@ async function sprintSwitchCommand() {
3899
163
  log.newline();
3900
164
  }
3901
165
 
3902
- // src/commands/sprint/insights.ts
3903
- import { writeFile as writeFile2 } from "fs/promises";
3904
- import { join as join5 } from "path";
166
+ // src/integration/cli/commands/sprint/insights.ts
167
+ import { writeFile } from "fs/promises";
168
+ import { join } from "path";
3905
169
  async function sprintInsightsCommand(args) {
3906
170
  const exportFlag = args.includes("--export");
3907
171
  const positionalArgs = args.filter((a) => !a.startsWith("--"));
@@ -3953,9 +217,9 @@ async function sprintInsightsCommand(args) {
3953
217
  }
3954
218
  }
3955
219
  async function exportInsights(sprint, tasks) {
3956
- const dir = join5(getDataDir(), "insights");
220
+ const dir = join(getDataDir(), "insights");
3957
221
  await ensureDir(dir);
3958
- const filePath = join5(dir, `${sprint.id}.md`);
222
+ const filePath = join(dir, `${sprint.id}.md`);
3959
223
  const evaluatedCount = tasks.filter((t) => t.evaluated).length;
3960
224
  const lines = [
3961
225
  `# Sprint Insights: ${sprint.name}`,
@@ -3976,11 +240,11 @@ async function exportInsights(sprint, tasks) {
3976
240
  lines.push("");
3977
241
  lines.push("---");
3978
242
  }
3979
- await writeFile2(filePath, lines.join("\n"), "utf-8");
243
+ await writeFile(filePath, lines.join("\n"), "utf-8");
3980
244
  log.success(`Insights exported to ${colors.accent(filePath)}`);
3981
245
  }
3982
246
 
3983
- // src/commands/sprint/index.ts
247
+ // src/integration/cli/commands/sprint/register.ts
3984
248
  function registerSprintCommands(program2) {
3985
249
  const sprint = program2.command("sprint").description("Manage sprints");
3986
250
  sprint.addHelpText(
@@ -3993,10 +257,10 @@ Examples:
3993
257
  $ ralphctl sprint start -s # Start with interactive session
3994
258
  `
3995
259
  );
3996
- sprint.command("create").description("Create a new sprint").option("--name <name>", "Sprint name").option("-n, --no-interactive", "Non-interactive mode (error on missing params)").action(async (opts) => {
260
+ sprint.command("create").description("Create a new sprint").option("--name <name>", "Sprint name").option("--project <name>", "Project to scope this sprint to (name or id)").option("-n, --no-interactive", "Non-interactive mode (error on missing params)").action(async (opts) => {
3997
261
  await sprintCreateCommand({
3998
262
  name: opts.name,
3999
- // --no-interactive sets interactive=false, otherwise true (prompt for missing)
263
+ project: opts.project,
4000
264
  interactive: opts.interactive !== false
4001
265
  });
4002
266
  });
@@ -4106,7 +370,7 @@ Branch Management:
4106
370
  );
4107
371
  }
4108
372
 
4109
- // src/commands/task/index.ts
373
+ // src/integration/cli/commands/task/register.ts
4110
374
  function registerTaskCommands(program2) {
4111
375
  const task = program2.command("task").description("Manage tasks");
4112
376
  task.addHelpText(
@@ -4119,15 +383,14 @@ Examples:
4119
383
  $ ralphctl task next
4120
384
  `
4121
385
  );
4122
- task.command("add").description("Add task to current sprint").option("--name <name>", "Task name").option("-d, --description <desc>", "Description").option("--step <step...>", "Implementation step (repeatable)").option("--ticket <id>", "Link to ticket ID").option("-p, --project <path>", "Project path").option("-n, --no-interactive", "Non-interactive mode (error on missing params)").action(
386
+ task.command("add").description("Add task to current sprint").option("--name <name>", "Task name").option("-d, --description <desc>", "Description").option("--step <step...>", "Implementation step (repeatable)").option("--ticket <id>", "Link to ticket ID").option("-r, --repo <name-or-id>", "Repository (within the sprint's project)").option("-n, --no-interactive", "Non-interactive mode (error on missing params)").action(
4123
387
  async (opts) => {
4124
388
  await taskAddCommand({
4125
389
  name: opts.name,
4126
390
  description: opts.description,
4127
391
  steps: opts.step,
4128
392
  ticket: opts.ticket,
4129
- project: opts.project,
4130
- // --no-interactive sets interactive=false, otherwise true (prompt for missing)
393
+ repo: opts.repo,
4131
394
  interactive: opts.interactive !== false
4132
395
  });
4133
396
  }
@@ -4135,17 +398,15 @@ Examples:
4135
398
  task.command("import <file>").description("Import tasks from JSON file").action(async (file) => {
4136
399
  await taskImportCommand([file]);
4137
400
  });
4138
- task.command("list").description("List tasks").option("-b, --brief", "Brief format").option("--status <status>", "Filter by status (todo, in_progress, done)").option("--project <name>", "Filter by project path").option("--ticket <id>", "Filter by ticket ID").option("--blocked", "Show only blocked tasks").action(
4139
- async (opts) => {
4140
- const args = [];
4141
- if (opts.brief) args.push("-b");
4142
- if (opts.status) args.push("--status", opts.status);
4143
- if (opts.project) args.push("--project", opts.project);
4144
- if (opts.ticket) args.push("--ticket", opts.ticket);
4145
- if (opts.blocked) args.push("--blocked");
4146
- await taskListCommand(args);
4147
- }
4148
- );
401
+ task.command("list").description("List tasks").option("-b, --brief", "Brief format").option("--status <status>", "Filter by status (todo, in_progress, done)").option("--repo <name-or-id>", "Filter by repo id").option("--ticket <id>", "Filter by ticket ID").option("--blocked", "Show only blocked tasks").action(async (opts) => {
402
+ const args = [];
403
+ if (opts.brief) args.push("-b");
404
+ if (opts.status) args.push("--status", opts.status);
405
+ if (opts.repo) args.push("--repo", opts.repo);
406
+ if (opts.ticket) args.push("--ticket", opts.ticket);
407
+ if (opts.blocked) args.push("--blocked");
408
+ await taskListCommand(args);
409
+ });
4149
410
  task.command("show [id]").description("Show task details").action(async (id) => {
4150
411
  await taskShowCommand(id ? [id] : []);
4151
412
  });
@@ -4171,31 +432,27 @@ Examples:
4171
432
  });
4172
433
  }
4173
434
 
4174
- // src/commands/ticket/index.ts
435
+ // src/integration/cli/commands/ticket/register.ts
4175
436
  function registerTicketCommands(program2) {
4176
437
  const ticket = program2.command("ticket").description("Manage tickets");
4177
438
  ticket.addHelpText(
4178
439
  "after",
4179
440
  `
4180
441
  Examples:
4181
- $ ralphctl ticket add --project api --title "Fix auth bug"
442
+ $ ralphctl ticket add --title "Fix auth bug"
4182
443
  $ ralphctl ticket edit abc123 --title "New title"
4183
444
  $ ralphctl ticket list -b
4184
445
  $ ralphctl ticket show abc123
4185
446
  `
4186
447
  );
4187
- ticket.command("add").description("Add ticket to current sprint").option("-p, --project <name>", "Project name").option("-t, --title <title>", "Ticket title").option("-d, --description <desc>", "Description").option("--link <url>", "Link to external issue").option("-n, --no-interactive", "Non-interactive mode (error on missing params)").action(
4188
- async (opts) => {
4189
- await ticketAddCommand({
4190
- project: opts.project,
4191
- title: opts.title,
4192
- description: opts.description,
4193
- link: opts.link,
4194
- // --no-interactive sets interactive=false, otherwise true (prompt for missing)
4195
- interactive: opts.interactive !== false
4196
- });
4197
- }
4198
- );
448
+ ticket.command("add").description("Add ticket to current sprint (project inherited from sprint)").option("-t, --title <title>", "Ticket title").option("-d, --description <desc>", "Description").option("--link <url>", "Link to external issue").option("-n, --no-interactive", "Non-interactive mode (error on missing params)").action(async (opts) => {
449
+ await ticketAddCommand({
450
+ title: opts.title,
451
+ description: opts.description,
452
+ link: opts.link,
453
+ interactive: opts.interactive !== false
454
+ });
455
+ });
4199
456
  ticket.command("edit [id]").description("Edit an existing ticket").option("--title <title>", "New title").option("--description <desc>", "New description").option("--link <url>", "New link").option("-n, --no-interactive", "Non-interactive mode").action(
4200
457
  async (id, opts) => {
4201
458
  await ticketEditCommand(id, {
@@ -4206,10 +463,9 @@ Examples:
4206
463
  });
4207
464
  }
4208
465
  );
4209
- ticket.command("list").description("List tickets").option("-b, --brief", "Brief one-liner format").option("--project <name>", "Filter by project").option("--status <status>", "Filter by requirement status (pending, approved)").action(async (opts) => {
466
+ ticket.command("list").description("List tickets").option("-b, --brief", "Brief one-liner format").option("--status <status>", "Filter by requirement status (pending, approved)").action(async (opts) => {
4210
467
  const args = [];
4211
468
  if (opts.brief) args.push("-b");
4212
- if (opts.project) args.push("--project", opts.project);
4213
469
  if (opts.status) args.push("--status", opts.status);
4214
470
  await ticketListCommand(args);
4215
471
  });
@@ -4227,7 +483,7 @@ Examples:
4227
483
  });
4228
484
  }
4229
485
 
4230
- // src/commands/progress/index.ts
486
+ // src/integration/cli/commands/progress/register.ts
4231
487
  function registerProgressCommands(program2) {
4232
488
  const progress = program2.command("progress").description("Log and view progress");
4233
489
  progress.addHelpText(
@@ -4244,17 +500,17 @@ Examples:
4244
500
  progress.command("show").description("Display progress log").action(progressShowCommand);
4245
501
  }
4246
502
 
4247
- // src/commands/dashboard/dashboard.ts
503
+ // src/integration/cli/commands/dashboard/dashboard.ts
4248
504
  async function dashboardCommand() {
4249
505
  await showDashboard();
4250
506
  }
4251
507
 
4252
- // src/commands/dashboard/index.ts
508
+ // src/integration/cli/commands/dashboard/register.ts
4253
509
  function registerDashboardCommands(program2) {
4254
510
  program2.command("status").description("Show current sprint overview").action(dashboardCommand);
4255
511
  }
4256
512
 
4257
- // src/commands/config/index.ts
513
+ // src/integration/cli/commands/config/register.ts
4258
514
  function registerConfigCommands(program2) {
4259
515
  const config = program2.command("config").description("Manage configuration");
4260
516
  config.addHelpText(
@@ -4277,7 +533,7 @@ Examples:
4277
533
  });
4278
534
  }
4279
535
 
4280
- // src/commands/completion/index.ts
536
+ // src/integration/cli/commands/completion/register.ts
4281
537
  function registerCompletionCommands(program2) {
4282
538
  const completion = program2.command("completion").description("Manage shell tab-completion");
4283
539
  completion.addHelpText(
@@ -4300,7 +556,7 @@ Examples:
4300
556
  });
4301
557
  }
4302
558
 
4303
- // src/commands/doctor/index.ts
559
+ // src/integration/cli/commands/doctor/register.ts
4304
560
  function registerDoctorCommands(program2) {
4305
561
  program2.command("doctor").description("Check environment health and diagnose setup issues").addHelpText(
4306
562
  "after",
@@ -4320,106 +576,8 @@ Checks performed:
4320
576
  });
4321
577
  }
4322
578
 
4323
- // package.json
4324
- var package_default = {
4325
- name: "ralphctl",
4326
- version: "0.2.4",
4327
- description: "Agent harness for long-running AI coding tasks \u2014 orchestrates Claude Code & GitHub Copilot across repositories",
4328
- homepage: "https://github.com/lukas-grigis/ralphctl",
4329
- type: "module",
4330
- license: "MIT",
4331
- author: "Lukas Grigis",
4332
- repository: {
4333
- type: "git",
4334
- url: "https://github.com/lukas-grigis/ralphctl.git"
4335
- },
4336
- bugs: {
4337
- url: "https://github.com/lukas-grigis/ralphctl/issues"
4338
- },
4339
- keywords: [
4340
- "cli",
4341
- "agent-harness",
4342
- "claude-code",
4343
- "github-copilot",
4344
- "ai-coding",
4345
- "task-orchestration",
4346
- "anthropic",
4347
- "developer-tools",
4348
- "long-running-agents",
4349
- "generator-evaluator"
4350
- ],
4351
- bin: {
4352
- ralphctl: "./dist/cli.mjs"
4353
- },
4354
- files: [
4355
- "dist/",
4356
- "schemas/"
4357
- ],
4358
- publishConfig: {
4359
- access: "public"
4360
- },
4361
- scripts: {
4362
- build: "tsup && mkdir -p dist/prompts && cp src/ai/prompts/*.md dist/prompts/",
4363
- prepublishOnly: "pnpm build",
4364
- dev: "tsx src/cli.ts",
4365
- lint: "eslint .",
4366
- "lint:fix": "eslint . --fix",
4367
- format: "prettier --write .",
4368
- "format:check": "prettier --check .",
4369
- typecheck: "tsc --noEmit",
4370
- test: "vitest run",
4371
- "test:watch": "vitest",
4372
- "test:coverage": "vitest run --coverage",
4373
- prepare: "husky"
4374
- },
4375
- packageManager: "pnpm@10.29.3",
4376
- engines: {
4377
- node: ">=24.0.0"
4378
- },
4379
- dependencies: {
4380
- "@inquirer/prompts": "^8.3.2",
4381
- colorette: "^2.0.20",
4382
- commander: "^14.0.3",
4383
- "gradient-string": "^3.0.0",
4384
- ora: "^9.3.0",
4385
- tabtab: "^3.0.2",
4386
- "typescript-result": "^3.5.2",
4387
- zod: "^4.3.6"
4388
- },
4389
- devDependencies: {
4390
- "@eslint/js": "^10.0.1",
4391
- "@types/node": "^25.5.2",
4392
- "@types/tabtab": "^3.0.4",
4393
- "@vitest/coverage-v8": "^4.1.2",
4394
- eslint: "^10.2.0",
4395
- "eslint-config-prettier": "^10.1.8",
4396
- globals: "^17.4.0",
4397
- husky: "^9.1.7",
4398
- "lint-staged": "^16.4.0",
4399
- prettier: "^3.8.1",
4400
- tsup: "^8.5.1",
4401
- tsx: "^4.21.0",
4402
- typescript: "^5.9.3",
4403
- "typescript-eslint": "^8.58.0",
4404
- vitest: "^4.1.2"
4405
- },
4406
- "lint-staged": {
4407
- "*.ts": [
4408
- "eslint --cache --fix",
4409
- "prettier --write"
4410
- ],
4411
- "*.{md,json,yml,yaml}": "prettier --write"
4412
- }
4413
- };
4414
-
4415
- // src/cli-metadata.ts
4416
- var cliMetadata = {
4417
- name: "ralphctl",
4418
- version: package_default.version,
4419
- description: "I'm helping! Plan sprints and execute tasks with AI"
4420
- };
4421
-
4422
- // src/cli.ts
579
+ // src/application/entrypoint.ts
580
+ setSharedDeps(createSharedDeps());
4423
581
  var program = new Command();
4424
582
  program.name(cliMetadata.name).description(cliMetadata.description).version(cliMetadata.version).addHelpText(
4425
583
  "after",
@@ -4445,15 +603,47 @@ registerCompletionCommands(program);
4445
603
  registerDoctorCommands(program);
4446
604
  async function main() {
4447
605
  if (process.env["COMP_CWORD"] && process.env["COMP_POINT"] && process.env["COMP_LINE"]) {
4448
- const { handleCompletionRequest } = await import("./handle-TA4MYNQJ.mjs");
606
+ const { handleCompletionRequest } = await import("./handle-BBAZJ44Y.mjs");
4449
607
  if (await handleCompletionRequest(program)) return;
4450
608
  }
4451
- if (process.argv.length <= 2 || process.argv[2] === "interactive") {
4452
- await interactiveMode();
4453
- } else {
4454
- showBanner();
4455
- await program.parseAsync(process.argv);
609
+ const argv = process.argv;
610
+ const isBare = argv.length <= 2;
611
+ const isInteractive = argv[2] === "interactive";
612
+ if (isBare || isInteractive) {
613
+ const { mountInkApp } = await import("./mount-XZPBDRPZ.mjs");
614
+ const { fallback } = await mountInkApp({ initialView: "repl" });
615
+ if (!fallback) return;
616
+ printBanner();
617
+ console.log("");
618
+ console.log("Interactive mode requires a TTY. Available commands:");
619
+ console.log("");
620
+ program.outputHelp();
621
+ return;
622
+ }
623
+ if (argv[2] === "sprint" && argv[3] === "start") {
624
+ const { parseSprintStartArgs } = await import("./start-MMWC7QLI.mjs");
625
+ const parsed = parseSprintStartArgs(argv.slice(4));
626
+ if (parsed.ok) {
627
+ const { mountInkApp } = await import("./mount-XZPBDRPZ.mjs");
628
+ const { getSharedDeps } = await import("./bootstrap-FMHG6DRY.mjs");
629
+ let sprintId;
630
+ try {
631
+ sprintId = await getSharedDeps().persistence.resolveSprintId(parsed.value.sprintId);
632
+ } catch {
633
+ sprintId = void 0;
634
+ }
635
+ if (sprintId) {
636
+ const { fallback } = await mountInkApp({
637
+ initialView: "execute",
638
+ sprintId,
639
+ executionOptions: parsed.value.options
640
+ });
641
+ if (!fallback) return;
642
+ }
643
+ }
4456
644
  }
645
+ printBanner();
646
+ await program.parseAsync(argv);
4457
647
  }
4458
648
  main().catch((err) => {
4459
649
  if (err instanceof DomainError) {