@dypt/cli 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,2621 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { realpathSync } from "fs";
5
+ import { fileURLToPath, pathToFileURL } from "url";
6
+ import { createInterface } from "readline/promises";
7
+ import { Command, Option } from "commander";
8
+
9
+ // src/commands/auth/login.ts
10
+ import { spawn } from "child_process";
11
+
12
+ // src/lib/config.ts
13
+ import os from "os";
14
+ import path from "path";
15
+ function getConfigDir() {
16
+ return path.join(os.homedir(), ".config", "dypt");
17
+ }
18
+ function getScopedTokenFilePath(baseUrl) {
19
+ const url = new URL(baseUrl);
20
+ const scope = `${url.hostname}${url.port ? `-${url.port}` : ""}`.replace(/[^a-zA-Z0-9.-]/g, "-").toLowerCase();
21
+ return path.join(getConfigDir(), "tokens", `${scope}.json`);
22
+ }
23
+ function getBaseUrl() {
24
+ return (process.env.DYPT_BASE_URL ?? process.env.NEXT_PUBLIC_URL ?? "https://dypt.app").replace(/\/$/, "");
25
+ }
26
+ function getDefaultDeviceLabel() {
27
+ const hostname = os.hostname().trim();
28
+ return hostname || "dypt-cli";
29
+ }
30
+
31
+ // src/lib/keychain.ts
32
+ import { execFile } from "child_process";
33
+ import { mkdir, readFile, rm, writeFile } from "fs/promises";
34
+ import path2 from "path";
35
+ import { promisify } from "util";
36
+ var execFileAsync = promisify(execFile);
37
+ var MACOS_SERVICE_NAME_PREFIX = "dypt-cli-token";
38
+ var MACOS_ACCOUNT_NAME_PREFIX = "dypt-cli";
39
+ function isMissingFileError(error) {
40
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
41
+ }
42
+ async function ensureParentDirectory(filePath) {
43
+ await mkdir(path2.dirname(filePath), { recursive: true });
44
+ }
45
+ function getCredentialScope(baseUrl = getBaseUrl()) {
46
+ const url = new URL(baseUrl);
47
+ return `${url.protocol}//${url.host}`;
48
+ }
49
+ function getMacOsServiceName(baseUrl) {
50
+ return `${MACOS_SERVICE_NAME_PREFIX}:${getCredentialScope(baseUrl)}`;
51
+ }
52
+ function getMacOsAccountName(baseUrl) {
53
+ return `${MACOS_ACCOUNT_NAME_PREFIX}:${getCredentialScope(baseUrl)}`;
54
+ }
55
+ async function readMacOsKeychainToken(baseUrl) {
56
+ if (process.platform !== "darwin") {
57
+ return null;
58
+ }
59
+ try {
60
+ const { stdout } = await execFileAsync("security", [
61
+ "find-generic-password",
62
+ "-a",
63
+ getMacOsAccountName(baseUrl),
64
+ "-s",
65
+ getMacOsServiceName(baseUrl),
66
+ "-w"
67
+ ]);
68
+ const parsed = JSON.parse(stdout.trim());
69
+ if (!parsed.accessToken || !parsed.expiresAt) {
70
+ return null;
71
+ }
72
+ return {
73
+ accessToken: parsed.accessToken,
74
+ expiresAt: parsed.expiresAt
75
+ };
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+ async function saveMacOsKeychainToken(accessToken, expiresAt, baseUrl) {
81
+ if (process.platform !== "darwin") {
82
+ return false;
83
+ }
84
+ try {
85
+ await execFileAsync("security", [
86
+ "add-generic-password",
87
+ "-a",
88
+ getMacOsAccountName(baseUrl),
89
+ "-s",
90
+ getMacOsServiceName(baseUrl),
91
+ "-w",
92
+ JSON.stringify({ accessToken, expiresAt }),
93
+ "-U"
94
+ ]);
95
+ return true;
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+ async function clearMacOsKeychainToken(baseUrl) {
101
+ if (process.platform !== "darwin") {
102
+ return false;
103
+ }
104
+ try {
105
+ await execFileAsync("security", [
106
+ "delete-generic-password",
107
+ "-a",
108
+ getMacOsAccountName(baseUrl),
109
+ "-s",
110
+ getMacOsServiceName(baseUrl)
111
+ ]);
112
+ return true;
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+ async function readCliToken(baseUrl = getBaseUrl(), filePath = getScopedTokenFilePath(baseUrl)) {
118
+ const keychainRecord = await readMacOsKeychainToken(baseUrl);
119
+ if (keychainRecord) {
120
+ return keychainRecord;
121
+ }
122
+ try {
123
+ const raw = await readFile(filePath, "utf8");
124
+ const parsed = JSON.parse(raw);
125
+ if (!parsed.accessToken || !parsed.expiresAt) {
126
+ return null;
127
+ }
128
+ return {
129
+ accessToken: parsed.accessToken,
130
+ expiresAt: parsed.expiresAt
131
+ };
132
+ } catch (error) {
133
+ if (isMissingFileError(error)) {
134
+ return null;
135
+ }
136
+ throw error;
137
+ }
138
+ }
139
+ async function saveCliToken(accessToken, expiresAt, baseUrl = getBaseUrl(), filePath = getScopedTokenFilePath(baseUrl)) {
140
+ const wroteToKeychain = await saveMacOsKeychainToken(
141
+ accessToken,
142
+ expiresAt,
143
+ baseUrl
144
+ );
145
+ if (wroteToKeychain) {
146
+ return;
147
+ }
148
+ await ensureParentDirectory(filePath);
149
+ await writeFile(
150
+ filePath,
151
+ `${JSON.stringify({ accessToken, expiresAt }, null, 2)}
152
+ `,
153
+ {
154
+ mode: 384
155
+ }
156
+ );
157
+ }
158
+ async function clearCliToken(baseUrl = getBaseUrl(), filePath = getScopedTokenFilePath(baseUrl)) {
159
+ const clearedKeychain = await clearMacOsKeychainToken(baseUrl);
160
+ if (clearedKeychain) {
161
+ return;
162
+ }
163
+ try {
164
+ await rm(filePath);
165
+ } catch (error) {
166
+ if (!isMissingFileError(error)) {
167
+ throw error;
168
+ }
169
+ }
170
+ }
171
+
172
+ // src/lib/trpc.ts
173
+ import {
174
+ createTRPCProxyClient,
175
+ httpBatchLink
176
+ } from "@trpc/client";
177
+ import superjson from "superjson";
178
+ function resolveBaseUrl(baseUrl) {
179
+ return (baseUrl ?? getBaseUrl()).replace(/\/$/, "");
180
+ }
181
+ async function resolveAccessToken(baseUrl, getAccessToken) {
182
+ if (getAccessToken) {
183
+ return getAccessToken();
184
+ }
185
+ const token = await readCliToken(baseUrl);
186
+ return token?.accessToken ?? null;
187
+ }
188
+ async function createCliTrpcClient(options = {}) {
189
+ const baseUrl = resolveBaseUrl(options.baseUrl);
190
+ const accessToken = await resolveAccessToken(
191
+ baseUrl,
192
+ options.getAccessToken
193
+ );
194
+ return createTRPCProxyClient({
195
+ links: [
196
+ httpBatchLink({
197
+ url: `${baseUrl}/api/trpc`,
198
+ transformer: superjson,
199
+ headers() {
200
+ return accessToken ? {
201
+ Authorization: `Bearer ${accessToken}`
202
+ } : {};
203
+ }
204
+ })
205
+ ]
206
+ });
207
+ }
208
+ async function postJson(path3, body, options = {}) {
209
+ const response = await fetch(new URL(path3, resolveBaseUrl(options.baseUrl)), {
210
+ method: "POST",
211
+ headers: {
212
+ "content-type": "application/json"
213
+ },
214
+ body: JSON.stringify(body)
215
+ });
216
+ return {
217
+ status: response.status,
218
+ json: await response.json()
219
+ };
220
+ }
221
+ async function startDeviceAuth(label, options = {}) {
222
+ const response = await postJson("/api/cli/auth/device-code", { label }, options);
223
+ if (response.status >= 400) {
224
+ throw new Error(response.json.error ?? "CLI_DEVICE_AUTH_START_FAILED");
225
+ }
226
+ return response.json;
227
+ }
228
+ function sleep(ms) {
229
+ return new Promise((resolve) => setTimeout(resolve, ms));
230
+ }
231
+ async function pollForToken(deviceCode, intervalSeconds = 2, options = {}) {
232
+ while (true) {
233
+ const response = await postJson("/api/cli/auth/poll", { deviceCode }, options);
234
+ if (response.status === 202 && response.json.error === "authorization_pending") {
235
+ await sleep(intervalSeconds * 1e3);
236
+ continue;
237
+ }
238
+ if (response.status >= 400) {
239
+ throw new Error(response.json.error ?? "CLI_DEVICE_AUTH_POLL_FAILED");
240
+ }
241
+ return response.json;
242
+ }
243
+ }
244
+ async function createCliApi(options = {}) {
245
+ const client = await createCliTrpcClient(options);
246
+ const cliClient = client;
247
+ return {
248
+ getAuthStatus: () => cliClient.cli.v1.auth.status.query(),
249
+ createTask: (input) => cliClient.cli.v1.tasks.create.mutate(input),
250
+ updateTask: (input) => cliClient.cli.v1.tasks.update.mutate(input),
251
+ archiveTask: (input) => cliClient.cli.v1.tasks.archive.mutate(input),
252
+ unarchiveTask: (input) => cliClient.cli.v1.tasks.unarchive.mutate(input),
253
+ updateManyTasks: (input) => cliClient.cli.v1.tasks.updateMany.mutate(input),
254
+ previewManyTasks: (input) => cliClient.cli.v1.tasks.previewUpdateMany.query(input),
255
+ previewCleanupPlan: (input) => cliClient.cli.v1.tasks.cleanupPreview.mutate(input),
256
+ applyCleanupPlan: (input) => cliClient.cli.v1.tasks.cleanupApply.mutate(input),
257
+ getTask: (input) => cliClient.cli.v1.tasks.get.query(input),
258
+ getTaskSummary: (input) => cliClient.cli.v1.tasks.summary.query(input),
259
+ getPlanningMetadataGaps: (input) => cliClient.cli.v1.tasks.planMetadata.query(input),
260
+ getBranchNextActions: (input) => cliClient.cli.v1.tasks.planNextActions.query(input),
261
+ getBranchFocusSignals: (input) => cliClient.cli.v1.tasks.planFocus.query(input),
262
+ listTasks: (input) => cliClient.cli.v1.tasks.list.query(input ?? {}),
263
+ searchTasks: (input) => cliClient.cli.v1.tasks.search.query(input),
264
+ getTaskTree: (input) => cliClient.cli.v1.tasks.tree.query(input),
265
+ deleteTasks: (input) => cliClient.cli.v1.tasks.deleteMany.mutate(input),
266
+ addDependency: (input) => cliClient.cli.v1.dependencies.add.mutate(input),
267
+ removeDependency: (input) => cliClient.cli.v1.dependencies.remove.mutate(input),
268
+ listDependencies: (input) => cliClient.cli.v1.dependencies.get.query(input),
269
+ setNote: (input) => cliClient.cli.v1.notes.set.mutate(input),
270
+ getNote: (input) => cliClient.cli.v1.notes.get.query(input),
271
+ searchNotes: (input) => cliClient.cli.v1.notes.search.query(input)
272
+ };
273
+ }
274
+
275
+ // src/commands/auth/login.ts
276
+ async function openBrowser(url) {
277
+ const platform = process.platform;
278
+ const command = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
279
+ const args = platform === "win32" ? ["/c", "start", "", url] : [url];
280
+ await new Promise((resolve, reject) => {
281
+ const child = spawn(command, args, {
282
+ stdio: "ignore",
283
+ detached: true
284
+ });
285
+ child.on("error", reject);
286
+ child.unref();
287
+ resolve();
288
+ });
289
+ }
290
+ function createDefaultLoginDeps() {
291
+ return {
292
+ startDeviceAuth,
293
+ pollForToken,
294
+ openBrowser,
295
+ saveToken: saveCliToken,
296
+ writeLine: (message) => {
297
+ process.stdout.write(`${message}
298
+ `);
299
+ }
300
+ };
301
+ }
302
+ async function runLogin(input, deps = createDefaultLoginDeps()) {
303
+ const label = input.label?.trim() || getDefaultDeviceLabel();
304
+ const started = await deps.startDeviceAuth(label);
305
+ const verificationUrl = new URL(started.verificationUri, getBaseUrl());
306
+ verificationUrl.searchParams.set("code", started.userCode);
307
+ deps.writeLine?.(
308
+ `Open ${verificationUrl.toString()} to approve CLI access for ${label}.`
309
+ );
310
+ await deps.openBrowser(verificationUrl.toString());
311
+ const token = await deps.pollForToken(
312
+ started.deviceCode,
313
+ started.intervalSeconds
314
+ );
315
+ await deps.saveToken(
316
+ token.accessToken,
317
+ token.expiresAt,
318
+ verificationUrl.origin
319
+ );
320
+ deps.writeLine?.("CLI access granted. Token saved locally.");
321
+ }
322
+
323
+ // src/commands/auth/logout.ts
324
+ function createDefaultLogoutDeps() {
325
+ return {
326
+ clearToken: () => clearCliToken(getBaseUrl()),
327
+ writeLine: (message) => {
328
+ process.stdout.write(`${message}
329
+ `);
330
+ }
331
+ };
332
+ }
333
+ async function runLogout(deps = createDefaultLogoutDeps()) {
334
+ await deps.clearToken();
335
+ deps.writeLine?.("Signed out of dypt CLI.");
336
+ }
337
+
338
+ // src/commands/auth/status.ts
339
+ async function runStatus(input, deps) {
340
+ const result = await deps.getStatus();
341
+ if (input.json) {
342
+ deps.printJson(result);
343
+ return;
344
+ }
345
+ deps.printTable(result);
346
+ }
347
+
348
+ // src/commands/dep/add.ts
349
+ async function runDependencyAdd(input, deps) {
350
+ const result = await deps.addDependency(input.taskRef, input.blockedByRef);
351
+ if (input.json) {
352
+ deps.printJson(result);
353
+ return;
354
+ }
355
+ deps.printTable(result);
356
+ }
357
+
358
+ // src/commands/dep/list.ts
359
+ async function runDependencyList(input, deps) {
360
+ const result = await deps.listDependencies(input.taskRef);
361
+ if (input.json) {
362
+ deps.printJson(result);
363
+ return;
364
+ }
365
+ deps.printTable(result);
366
+ }
367
+
368
+ // src/commands/dep/remove.ts
369
+ async function runDependencyRemove(input, deps) {
370
+ const result = await deps.removeDependency(input.taskRef, input.blockedByRef);
371
+ if (input.json) {
372
+ deps.printJson(result);
373
+ return;
374
+ }
375
+ deps.printTable(result);
376
+ }
377
+
378
+ // src/commands/note/get.ts
379
+ async function runNoteGet(input, deps) {
380
+ const result = await deps.getNote(input.taskRef);
381
+ if (input.json) {
382
+ deps.printJson(result);
383
+ return;
384
+ }
385
+ deps.printTable(result);
386
+ }
387
+
388
+ // src/commands/note/search.ts
389
+ async function runNoteSearch(input, deps) {
390
+ const result = await deps.searchNotes(input.query);
391
+ if (input.json) {
392
+ deps.printJson(result);
393
+ return;
394
+ }
395
+ deps.printTable(result);
396
+ }
397
+
398
+ // src/commands/note/set.ts
399
+ async function runNoteSet(input, deps) {
400
+ const result = await deps.setNote(input.taskRef, input.content);
401
+ if (input.json) {
402
+ deps.printJson(result);
403
+ return;
404
+ }
405
+ deps.printTable(result);
406
+ }
407
+
408
+ // src/commands/task/create.ts
409
+ async function runTaskCreate(input, deps) {
410
+ const result = await deps.createTask({
411
+ title: input.title,
412
+ parentId: input.parentId ? Number(input.parentId) : null
413
+ });
414
+ if (input.json) {
415
+ deps.printJson(result);
416
+ return;
417
+ }
418
+ deps.printTable(result);
419
+ }
420
+
421
+ // src/commands/task/archive.ts
422
+ async function runTaskArchive(input, deps) {
423
+ const result = await deps.updateTask({
424
+ ref: input.ref,
425
+ archivedAt: input.undo ? null : /* @__PURE__ */ new Date(),
426
+ subType: "archive"
427
+ });
428
+ if (input.json) {
429
+ deps.printJson(result);
430
+ return;
431
+ }
432
+ deps.printTable(result);
433
+ }
434
+
435
+ // src/commands/task/delete.ts
436
+ async function runTaskDelete(input, deps) {
437
+ if (deps.isTty && !input.yes) {
438
+ const accepted = await deps.confirm(`Delete task ${input.ref}?`);
439
+ if (!accepted) {
440
+ return;
441
+ }
442
+ }
443
+ await deps.removeTask(input.ref);
444
+ }
445
+
446
+ // src/commands/task/deleteMany.ts
447
+ async function runTaskDeleteMany(input, deps) {
448
+ if (deps.isTty && !input.yes) {
449
+ const accepted = await deps.confirm(
450
+ `Delete ${input.refs.length} tasks?`
451
+ );
452
+ if (!accepted) {
453
+ return;
454
+ }
455
+ }
456
+ const result = await deps.deleteTasks(input.refs);
457
+ if (input.json) {
458
+ deps.printJson(result);
459
+ return;
460
+ }
461
+ deps.printTable(result);
462
+ }
463
+
464
+ // src/commands/task/get.ts
465
+ async function runTaskGet(input, deps) {
466
+ const result = await deps.getTask(input.ref);
467
+ if (input.json) {
468
+ deps.printJson(result);
469
+ return;
470
+ }
471
+ deps.printTable(result);
472
+ }
473
+
474
+ // src/commands/task/list.ts
475
+ async function runTaskList(input, deps) {
476
+ const result = await deps.listTasks({
477
+ parent: input.parent,
478
+ scope: input.scope,
479
+ status: input.status,
480
+ priority: input.priority,
481
+ leaves: input.leaves,
482
+ archived: input.archived,
483
+ blocked: input.blocked,
484
+ blocking: input.blocking,
485
+ titleContains: input.titleContains,
486
+ deadlineFrom: input.deadlineFrom,
487
+ deadlineTo: input.deadlineTo,
488
+ createdFrom: input.createdFrom,
489
+ createdTo: input.createdTo,
490
+ expectedTimeFrom: input.expectedTimeFrom,
491
+ expectedTimeTo: input.expectedTimeTo,
492
+ actualTimeFrom: input.actualTimeFrom,
493
+ actualTimeTo: input.actualTimeTo,
494
+ showPath: input.showPath,
495
+ limit: input.limit ?? "50",
496
+ cursor: input.cursor
497
+ });
498
+ if (input.json) {
499
+ deps.printJson(result);
500
+ return;
501
+ }
502
+ deps.printTable({
503
+ ...typeof result === "object" && result !== null ? result : {},
504
+ meta: {
505
+ view: "list",
506
+ limit: Number.parseInt(input.limit ?? "50", 10),
507
+ parent: input.parent,
508
+ scope: input.scope,
509
+ showPath: Boolean(input.showPath)
510
+ }
511
+ });
512
+ }
513
+
514
+ // src/commands/task/planFocus.ts
515
+ async function runTaskPlanFocus(input, deps) {
516
+ const result = await deps.listFocusBranches({
517
+ ref: input.ref,
518
+ limit: input.limit
519
+ });
520
+ if (input.json) {
521
+ deps.printJson(result);
522
+ return;
523
+ }
524
+ deps.printTable(result);
525
+ }
526
+
527
+ // src/commands/task/planMetadata.ts
528
+ async function runTaskPlanMetadata(input, deps) {
529
+ const result = await deps.listPlanningMetadataGaps({
530
+ ref: input.ref,
531
+ priority: input.priority,
532
+ deadline: input.deadline,
533
+ expectedTime: input.expectedTime,
534
+ leavesOnly: input.leavesOnly,
535
+ limit: input.limit
536
+ });
537
+ if (input.json) {
538
+ deps.printJson(result);
539
+ return;
540
+ }
541
+ deps.printTable(result);
542
+ }
543
+
544
+ // src/commands/task/planNextActions.ts
545
+ async function runTaskPlanNextActions(input, deps) {
546
+ const result = await deps.listNextActions({
547
+ ref: input.ref,
548
+ limit: input.limit
549
+ });
550
+ if (input.json) {
551
+ deps.printJson(result);
552
+ return;
553
+ }
554
+ deps.printTable(result);
555
+ }
556
+
557
+ // src/commands/task/search.ts
558
+ async function runTaskSearch(input, deps) {
559
+ const result = await deps.searchTasks({
560
+ query: input.query,
561
+ parent: input.parent,
562
+ scope: input.scope,
563
+ limit: input.limit,
564
+ cursorScore: input.cursorScore,
565
+ cursorId: input.cursorId
566
+ });
567
+ if (input.json) {
568
+ deps.printJson(result);
569
+ return;
570
+ }
571
+ deps.printTable({
572
+ ...typeof result === "object" && result !== null ? result : {},
573
+ meta: {
574
+ limit: Number.parseInt(input.limit ?? "20", 10),
575
+ parent: input.parent,
576
+ query: input.query,
577
+ scope: input.scope,
578
+ view: "search"
579
+ }
580
+ });
581
+ }
582
+
583
+ // src/commands/task/summary.ts
584
+ async function runTaskSummary(input, deps) {
585
+ const result = await deps.getTaskSummary(input.ref);
586
+ if (input.json) {
587
+ deps.printJson(result);
588
+ return;
589
+ }
590
+ deps.printTable(result);
591
+ }
592
+
593
+ // src/commands/task/tree.ts
594
+ async function runTaskTree(input, deps) {
595
+ if (input.full && input.depth !== void 0) {
596
+ throw new Error("Cannot combine --depth and --full");
597
+ }
598
+ const defaultDepthApplied = input.ref === void 0 && input.depth === void 0 && !input.full ? 2 : void 0;
599
+ const effectiveDepth = input.full ? void 0 : input.depth ?? defaultDepthApplied;
600
+ const tree = await deps.getTaskTree(input.ref, effectiveDepth);
601
+ const result = defaultDepthApplied === void 0 ? tree : {
602
+ tree,
603
+ meta: {
604
+ isTruncated: true,
605
+ defaultDepthApplied
606
+ }
607
+ };
608
+ if (input.json) {
609
+ deps.printJson(result);
610
+ return;
611
+ }
612
+ deps.printTable(result);
613
+ }
614
+
615
+ // src/commands/task/update.ts
616
+ async function runTaskUpdate(input, deps) {
617
+ const result = await deps.updateTask({
618
+ ref: input.ref,
619
+ title: input.title,
620
+ status: input.status,
621
+ priority: input.priority,
622
+ deadline: input.deadline,
623
+ expectedTimeTaken: input.expectedTimeTaken,
624
+ actualTimeTaken: input.actualTimeTaken
625
+ });
626
+ if (input.json) {
627
+ deps.printJson(result);
628
+ return;
629
+ }
630
+ deps.printTable(result);
631
+ }
632
+
633
+ // src/commands/task/updateMany.ts
634
+ async function runTaskUpdateMany(input, deps) {
635
+ const hasMutations = input.status !== void 0 || input.priority !== void 0 || input.deadline !== void 0 || input.expectedTimeTaken !== void 0 || input.actualTimeTaken !== void 0 || input.archivedAt !== void 0 || input.parentRef !== void 0;
636
+ if (!hasMutations) {
637
+ throw new Error(
638
+ "No changes specified. Use --status, --priority, --deadline, --expected-time, --actual-time, --archive, --unarchive, or --parent."
639
+ );
640
+ }
641
+ const args = {
642
+ refs: input.refs,
643
+ status: input.status,
644
+ priority: input.priority,
645
+ deadline: input.deadline,
646
+ expectedTimeTaken: input.expectedTimeTaken,
647
+ actualTimeTaken: input.actualTimeTaken,
648
+ archivedAt: input.archivedAt,
649
+ parentRef: input.parentRef
650
+ };
651
+ const result = input.preview ? await deps.previewManyTasks(args) : await deps.updateManyTasks(args);
652
+ if (input.json) {
653
+ deps.printJson(result);
654
+ return;
655
+ }
656
+ deps.printTable(result);
657
+ }
658
+
659
+ // src/commands/task/cleanupPlan.ts
660
+ import { readFile as readFile2 } from "fs/promises";
661
+ async function loadCleanupPlan(input) {
662
+ if (input.plan && input.planFile) {
663
+ throw new Error("Use either --plan or --plan-file, not both.");
664
+ }
665
+ if (!input.plan && !input.planFile) {
666
+ throw new Error("Provide a cleanup plan with --plan or --plan-file.");
667
+ }
668
+ const raw = input.plan ?? await readFile2(input.planFile, "utf8");
669
+ try {
670
+ return JSON.parse(raw);
671
+ } catch {
672
+ throw new Error("Cleanup plan must be valid JSON.");
673
+ }
674
+ }
675
+ function summarizeCleanupPlan(plan) {
676
+ const taskCount = new Set(plan.operations.flatMap((operation) => operation.taskIds)).size;
677
+ return `${plan.operations.length} operation${plan.operations.length === 1 ? "" : "s"} across ${taskCount} task${taskCount === 1 ? "" : "s"}`;
678
+ }
679
+
680
+ // src/commands/task/cleanupApply.ts
681
+ async function runTaskCleanupApply(input, deps) {
682
+ const plan = await loadCleanupPlan({
683
+ plan: input.plan,
684
+ planFile: input.planFile
685
+ });
686
+ if (!input.yes && deps.isTty) {
687
+ const confirmed = await deps.confirm(
688
+ `Apply cleanup plan with ${summarizeCleanupPlan(plan)}?`
689
+ );
690
+ if (!confirmed) {
691
+ throw new Error("Cleanup apply cancelled.");
692
+ }
693
+ }
694
+ const result = await deps.applyCleanupPlan({ plan });
695
+ if (input.json) {
696
+ deps.printJson(result);
697
+ return;
698
+ }
699
+ deps.printTable(result);
700
+ }
701
+
702
+ // src/commands/task/cleanupRelocateCollapse.ts
703
+ async function loadAllActiveDirectChildren(wrapperId, deps) {
704
+ const items = [];
705
+ let cursor;
706
+ do {
707
+ const page = await deps.listActiveDirectChildren({ wrapperId, cursor });
708
+ items.push(...page.items);
709
+ cursor = page.nextCursor ?? void 0;
710
+ } while (cursor);
711
+ return items;
712
+ }
713
+ function dedupeTaskIds(taskIds) {
714
+ return [...new Set(taskIds)];
715
+ }
716
+ function buildRelocateAndCollapsePlan(input) {
717
+ const selectedTaskIds = new Set(input.movingTaskIds);
718
+ const remainingActiveChildren = input.activeDirectChildren.filter(
719
+ (child) => !selectedTaskIds.has(child.id)
720
+ );
721
+ const operations = [
722
+ {
723
+ type: "move",
724
+ taskIds: input.movingTaskIds,
725
+ toParentId: input.toParentId
726
+ }
727
+ ];
728
+ if (remainingActiveChildren.length === 0) {
729
+ operations.push({
730
+ type: "archive",
731
+ taskIds: [input.wrapperId]
732
+ });
733
+ }
734
+ return { operations };
735
+ }
736
+ function attachWorkflowMeta(result) {
737
+ if (typeof result !== "object" || result === null) {
738
+ return result;
739
+ }
740
+ const record = result;
741
+ const existingMeta = typeof record.meta === "object" && record.meta !== null ? record.meta : {};
742
+ return {
743
+ ...record,
744
+ meta: {
745
+ ...existingMeta,
746
+ workflow: "relocate-and-collapse"
747
+ }
748
+ };
749
+ }
750
+ async function runTaskCleanupRelocateCollapse(input, deps) {
751
+ if (input.preview && input.yes) {
752
+ throw new Error("Use either --preview or --yes, not both.");
753
+ }
754
+ if (input.tasks.length === 0) {
755
+ throw new Error(
756
+ "Provide at least one surviving task with --tasks <refs...>."
757
+ );
758
+ }
759
+ const wrapperId = await deps.resolveTaskRef(input.wrapper);
760
+ const toParentId = input.to === "root" ? null : await deps.resolveTaskRef(input.to);
761
+ if (toParentId === wrapperId) {
762
+ throw new Error("Destination cannot be the wrapper itself.");
763
+ }
764
+ const movingTaskIds = dedupeTaskIds(
765
+ await Promise.all(input.tasks.map((ref) => deps.resolveTaskRef(ref)))
766
+ );
767
+ if (toParentId !== null && movingTaskIds.includes(toParentId)) {
768
+ throw new Error("Destination cannot be one of the tasks being moved.");
769
+ }
770
+ const activeDirectChildren = await loadAllActiveDirectChildren(wrapperId, deps);
771
+ const activeDirectChildIds = new Set(
772
+ activeDirectChildren.map((child) => child.id)
773
+ );
774
+ const invalidTaskIds = movingTaskIds.filter(
775
+ (taskId) => !activeDirectChildIds.has(taskId)
776
+ );
777
+ if (invalidTaskIds.length > 0) {
778
+ throw new Error(
779
+ `Selected tasks must be active direct children of the wrapper: ${invalidTaskIds.map((taskId) => `#${taskId}`).join(", ")}`
780
+ );
781
+ }
782
+ const plan = buildRelocateAndCollapsePlan({
783
+ wrapperId,
784
+ movingTaskIds,
785
+ activeDirectChildren,
786
+ toParentId
787
+ });
788
+ const result = input.yes ? await deps.applyCleanupPlan({ plan }) : await deps.previewCleanupPlan({ plan });
789
+ const output = attachWorkflowMeta(result);
790
+ if (input.json) {
791
+ deps.printJson(output);
792
+ return;
793
+ }
794
+ deps.printTable(output);
795
+ }
796
+
797
+ // src/commands/task/cleanupPreview.ts
798
+ async function runTaskCleanupPreview(input, deps) {
799
+ const plan = await loadCleanupPlan({
800
+ plan: input.plan,
801
+ planFile: input.planFile
802
+ });
803
+ const result = await deps.previewCleanupPlan({ plan });
804
+ if (input.json) {
805
+ deps.printJson(result);
806
+ return;
807
+ }
808
+ deps.printTable(result);
809
+ }
810
+
811
+ // src/lib/banner.ts
812
+ var BANNER_LINES = [
813
+ " _ _ ",
814
+ " __| |_ _ _ __ | |_ ",
815
+ " / _` | | | | '_ \\| __|",
816
+ " | (_| | |_| | |_) | |_ ",
817
+ " \\__,_|\\__, | .__/ \\__|",
818
+ " |___/|_| "
819
+ ];
820
+ var ANSI_RESET = "\x1B[0m";
821
+ var GRADIENT_START = { r: 94, g: 102, b: 255 };
822
+ var GRADIENT_END = { r: 196, g: 148, b: 255 };
823
+ function shouldUseColor() {
824
+ if (process.env.NO_COLOR) return false;
825
+ if (process.env.FORCE_COLOR === "0") return false;
826
+ if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== "0") return true;
827
+ return Boolean(process.stdout.isTTY);
828
+ }
829
+ function gradientColor(position, maxPosition) {
830
+ if (maxPosition <= 0) {
831
+ return `\x1B[38;2;${GRADIENT_START.r};${GRADIENT_START.g};${GRADIENT_START.b}m`;
832
+ }
833
+ const ratio = position / maxPosition;
834
+ const r = Math.round(
835
+ GRADIENT_START.r + (GRADIENT_END.r - GRADIENT_START.r) * ratio
836
+ );
837
+ const g = Math.round(
838
+ GRADIENT_START.g + (GRADIENT_END.g - GRADIENT_START.g) * ratio
839
+ );
840
+ const b = Math.round(
841
+ GRADIENT_START.b + (GRADIENT_END.b - GRADIENT_START.b) * ratio
842
+ );
843
+ return `\x1B[38;2;${r};${g};${b}m`;
844
+ }
845
+ function renderGradientLine(line) {
846
+ const chars = Array.from(line);
847
+ const lastIndex = Math.max(chars.length - 1, 1);
848
+ return chars.map((char, index) => {
849
+ if (char === " ") return char;
850
+ return `${gradientColor(index, lastIndex)}${char}${ANSI_RESET}`;
851
+ }).join("");
852
+ }
853
+ function getCliBanner() {
854
+ if (!shouldUseColor()) {
855
+ return `${BANNER_LINES.join("\n")}
856
+
857
+ `;
858
+ }
859
+ return `${BANNER_LINES.map((line) => renderGradientLine(line)).join("\n")}
860
+
861
+ `;
862
+ }
863
+
864
+ // src/lib/output.ts
865
+ import stringWidth from "string-width";
866
+ var ANSI = {
867
+ reset: "\x1B[0m",
868
+ bold: "\x1B[1m",
869
+ italic: "\x1B[3m",
870
+ dim: "\x1B[2m",
871
+ green: "\x1B[32m",
872
+ yellow: "\x1B[33m",
873
+ red: "\x1B[31m",
874
+ blue: "\x1B[34m",
875
+ cyan: "\x1B[36m"
876
+ };
877
+ function colorize(text, color, enabled) {
878
+ if (!enabled) return text;
879
+ return `${ANSI[color]}${text}${ANSI.reset}`;
880
+ }
881
+ function emphasize(text, style, enabled) {
882
+ if (!enabled) return text;
883
+ return `${ANSI[style]}${text}${ANSI.reset}`;
884
+ }
885
+ function dim(text, enabled) {
886
+ return colorize(text, "dim", enabled);
887
+ }
888
+ function quoteCliArg(value) {
889
+ return /[\s"]/u.test(value) ? JSON.stringify(value) : value;
890
+ }
891
+ function isRecord(value) {
892
+ return typeof value === "object" && value !== null;
893
+ }
894
+ function isTaskLike(value) {
895
+ return isRecord(value) && typeof value.id === "number" && typeof value.title === "string";
896
+ }
897
+ function isNoteLike(value) {
898
+ return isRecord(value) && typeof value.id === "number" && typeof value.taskId === "number" && typeof value.content === "string";
899
+ }
900
+ function isDependencyLike(value) {
901
+ return isRecord(value) && typeof value.id === "number" && typeof value.title === "string";
902
+ }
903
+ function isDeleteManyLike(value) {
904
+ return isRecord(value) && Array.isArray(value.taskIds) && typeof value.tasksDeleted === "number";
905
+ }
906
+ function isUpdateManyLike(value) {
907
+ return isRecord(value) && Array.isArray(value.taskIds) && Array.isArray(value.tasks) && value.tasks.every(isTaskLike);
908
+ }
909
+ function isCleanupPreviewLike(value) {
910
+ return isRecord(value) && isRecord(value.summary) && typeof value.summary.taskCount === "number" && typeof value.summary.actionCount === "number" && Array.isArray(value.tasks) && Array.isArray(value.wrappersToEmpty);
911
+ }
912
+ function isCleanupPlanPreviewLike(value) {
913
+ if (!isCleanupPreviewLike(value) || !isRecord(value)) {
914
+ return false;
915
+ }
916
+ const record = value;
917
+ return Array.isArray(record.operations);
918
+ }
919
+ function isCleanupApplyLike(value) {
920
+ return isRecord(value) && value.applied === true && typeof value.operationCount === "number" && Array.isArray(value.affectedTaskIds) && Array.isArray(value.operations);
921
+ }
922
+ function isTaskSummaryLike(value) {
923
+ return isRecord(value) && isTaskLike(value.task) && isRecord(value.directChildren) && typeof value.directChildren.total === "number" && typeof value.directChildren.active === "number" && typeof value.directChildren.archived === "number" && isRecord(value.descendants) && typeof value.descendants.total === "number" && typeof value.descendants.active === "number" && typeof value.descendants.archived === "number" && isRecord(value.descendants.statuses) && isRecord(value.descendants.priorities) && isRecord(value.descendants.due) && typeof value.notesInBranchCount === "number" && Array.isArray(value.healthSignals);
924
+ }
925
+ function isPlanningMetadataGapsLike(value) {
926
+ return isRecord(value) && isTaskLike(value.task) && Array.isArray(value.items) && value.items.every(
927
+ (item) => isTaskLike(item) && Array.isArray(item.missing)
928
+ ) && isRecord(value.filters);
929
+ }
930
+ function isNextActionsLike(value) {
931
+ return isRecord(value) && isTaskLike(value.task) && Array.isArray(value.items) && value.items.every(
932
+ (item) => isTaskLike(item) && Array.isArray(item.reasons) && typeof item.score === "number"
933
+ ) && typeof value.limit === "number";
934
+ }
935
+ function isBranchFocusSignalsLike(value) {
936
+ return isRecord(value) && isTaskLike(value.task) && Array.isArray(value.items) && value.items.every(
937
+ (item) => isTaskLike(item) && Array.isArray(item.signals) && typeof item.missingMetadataCount === "number" && typeof item.descendantCount === "number" && typeof item.activeDescendantCount === "number"
938
+ ) && typeof value.limit === "number";
939
+ }
940
+ function getCleanupWorkflowLabel(value) {
941
+ if (!isRecord(value) || !isRecord(value.meta)) return null;
942
+ const workflow = value.meta.workflow;
943
+ return typeof workflow === "string" ? workflow : null;
944
+ }
945
+ function isTaskCollection(value) {
946
+ return isRecord(value) && Array.isArray(value.items) && value.items.every(isTaskLike);
947
+ }
948
+ function isAuthStatusLike(value) {
949
+ return isRecord(value) && isRecord(value.user) && typeof value.user.userId === "string" && isRecord(value.token) && typeof value.token.id === "number" && typeof value.token.label === "string" && typeof value.token.scope === "string";
950
+ }
951
+ function isTaskDetailLike(value) {
952
+ return isRecord(value) && isTaskLike(value.task) && (value.taskChildren === void 0 || Array.isArray(value.taskChildren) && value.taskChildren.every(isTaskLike)) && (value.taskParents === void 0 || Array.isArray(value.taskParents) && value.taskParents.every(isTaskLike));
953
+ }
954
+ function isTaskTreeResponseLike(value) {
955
+ return isRecord(value) && isTaskLike(value.tree) && (value.meta === void 0 || isRecord(value.meta));
956
+ }
957
+ function isDependencyCollection(value) {
958
+ return isRecord(value) && Array.isArray(value.blockers) && Array.isArray(value.dependents) && value.blockers.every(isDependencyLike) && value.dependents.every(isDependencyLike);
959
+ }
960
+ function parseDateValue(value) {
961
+ if (!value) return null;
962
+ if (value instanceof Date) return value;
963
+ const parsed = new Date(value);
964
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
965
+ }
966
+ function formatDateValue(value) {
967
+ const date = parseDateValue(value);
968
+ if (!date) return "-";
969
+ return new Intl.DateTimeFormat("en-GB", {
970
+ year: "numeric",
971
+ month: "short",
972
+ day: "numeric"
973
+ }).format(date);
974
+ }
975
+ function formatMinutes(value) {
976
+ if (value === null || value === void 0) return "-";
977
+ if (value < 60) return `${value}m`;
978
+ const hours = Math.floor(value / 60);
979
+ const minutes = value % 60;
980
+ return minutes === 0 ? `${hours}h` : `${hours}h ${minutes}m`;
981
+ }
982
+ function stripAnsi(text) {
983
+ return text.replace(/\u001b\[[0-9;]*m/g, "");
984
+ }
985
+ function getDisplayWidth(text) {
986
+ return stringWidth(stripAnsi(text));
987
+ }
988
+ function padCell(text, width) {
989
+ const visibleWidth = getDisplayWidth(text);
990
+ return visibleWidth >= width ? text : `${text}${" ".repeat(width - visibleWidth)}`;
991
+ }
992
+ function normalizeSingleLineText(text) {
993
+ const [firstLine = ""] = text.split(/\r?\n/, 1);
994
+ const collapsed = firstLine.replace(/\s+/g, " ").trim();
995
+ const hasAdditionalContent = text.split(/\r?\n/).slice(1).some((line) => line.trim().length > 0);
996
+ return {
997
+ text: collapsed,
998
+ hadAdditionalLines: hasAdditionalContent
999
+ };
1000
+ }
1001
+ function truncateText(text, maxWidth) {
1002
+ const normalized = normalizeSingleLineText(text);
1003
+ let needsEllipsis = normalized.hadAdditionalLines;
1004
+ let ellipsis = needsEllipsis ? "\u2026" : "";
1005
+ const target = `${normalized.text}${ellipsis}`;
1006
+ if (getDisplayWidth(target) <= maxWidth) return target;
1007
+ needsEllipsis = true;
1008
+ ellipsis = "\u2026";
1009
+ if (maxWidth <= 1) return "\u2026".slice(0, maxWidth);
1010
+ let truncated = "";
1011
+ for (const char of normalized.text) {
1012
+ const next = `${truncated}${char}${ellipsis}`;
1013
+ if (getDisplayWidth(next) > maxWidth) break;
1014
+ truncated += char;
1015
+ }
1016
+ if (!truncated) return "\u2026".slice(0, maxWidth);
1017
+ return `${truncated}${ellipsis}`;
1018
+ }
1019
+ function truncateDisplayText(text, maxWidth) {
1020
+ if (getDisplayWidth(text) <= maxWidth) return text;
1021
+ if (maxWidth <= 1) return "\u2026".slice(0, maxWidth);
1022
+ let truncated = "";
1023
+ for (const char of text) {
1024
+ const next = `${truncated}${char}\u2026`;
1025
+ if (getDisplayWidth(next) > maxWidth) break;
1026
+ truncated += char;
1027
+ }
1028
+ if (!truncated) return "\u2026".slice(0, maxWidth);
1029
+ return `${truncated}\u2026`;
1030
+ }
1031
+ function formatDateTimeValue(value) {
1032
+ const date = parseDateValue(value);
1033
+ if (!date) return "-";
1034
+ return new Intl.DateTimeFormat("en-GB", {
1035
+ year: "numeric",
1036
+ month: "short",
1037
+ day: "numeric",
1038
+ hour: "2-digit",
1039
+ minute: "2-digit",
1040
+ hour12: false,
1041
+ timeZone: "UTC",
1042
+ timeZoneName: "short"
1043
+ }).format(date);
1044
+ }
1045
+ function formatRelativeTimeUntil(value) {
1046
+ const date = parseDateValue(value);
1047
+ if (!date) return "-";
1048
+ const diffMs = date.getTime() - Date.now();
1049
+ if (diffMs <= 0) return "expired";
1050
+ const totalMinutes = Math.floor(diffMs / 6e4);
1051
+ const days = Math.floor(totalMinutes / (60 * 24));
1052
+ const hours = Math.floor(totalMinutes % (60 * 24) / 60);
1053
+ const minutes = totalMinutes % 60;
1054
+ if (days > 0) {
1055
+ return hours > 0 ? `${days}d ${hours}h` : `${days}d`;
1056
+ }
1057
+ if (hours > 0) {
1058
+ return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
1059
+ }
1060
+ return `${minutes}m`;
1061
+ }
1062
+ function formatStatus(status, color) {
1063
+ if (!status) return dim("-", color);
1064
+ if (status === "completed") {
1065
+ return colorize(status, "green", color);
1066
+ }
1067
+ if (status === "in progress") {
1068
+ return colorize(status, "yellow", color);
1069
+ }
1070
+ return dim(status, color);
1071
+ }
1072
+ function formatStatusGlyph(status, color) {
1073
+ if (status === "completed") {
1074
+ return colorize("\u2713", "green", color);
1075
+ }
1076
+ if (status === "in progress") {
1077
+ return colorize("\u25D0", "yellow", color);
1078
+ }
1079
+ return dim("\u25CB", color);
1080
+ }
1081
+ function formatTaskFlags(task, color) {
1082
+ const flags = [
1083
+ (task.blockerCount ?? 0) > 0 ? "blocked" : null,
1084
+ task.isBlocking ? "blocking" : null,
1085
+ task.archivedAt ? colorize("archived", "cyan", color) : null
1086
+ ].filter(Boolean);
1087
+ return flags.join(", ");
1088
+ }
1089
+ function formatPriority(priority, color) {
1090
+ if (!priority) return dim("-", color);
1091
+ if (priority === "high") return colorize(priority, "red", color);
1092
+ if (priority === "mid") return colorize("medium", "yellow", color);
1093
+ if (priority === "low") return colorize(priority, "blue", color);
1094
+ return priority;
1095
+ }
1096
+ function renderInlineMarkdown(text, color) {
1097
+ const codePlaceholders = [];
1098
+ let rendered = text.replace(/`([^`\n]+)`/g, (_, code) => {
1099
+ const index = codePlaceholders.push(
1100
+ color ? colorize(code, "cyan", color) : code
1101
+ ) - 1;
1102
+ return `\0CODE${index}\0`;
1103
+ });
1104
+ rendered = rendered.replace(
1105
+ /\*\*([^*\n]+)\*\*/g,
1106
+ (_, value) => emphasize(value, "bold", color)
1107
+ ).replace(
1108
+ /__([^_\n]+)__/g,
1109
+ (_, value) => emphasize(value, "bold", color)
1110
+ ).replace(
1111
+ /\*([^*\n]+)\*/g,
1112
+ (_, value) => emphasize(value, "italic", color)
1113
+ ).replace(
1114
+ /_([^_\n]+)_/g,
1115
+ (_, value) => emphasize(value, "italic", color)
1116
+ );
1117
+ return rendered.replace(/\u0000CODE(\d+)\u0000/g, (_, index) => {
1118
+ return codePlaceholders[Number(index)] ?? "";
1119
+ });
1120
+ }
1121
+ function renderMarkdownNote(content, color) {
1122
+ const lines = content.split("\n");
1123
+ const rendered = [];
1124
+ let inCodeBlock = false;
1125
+ for (const line of lines) {
1126
+ if (/^\s*```/.test(line)) {
1127
+ inCodeBlock = !inCodeBlock;
1128
+ continue;
1129
+ }
1130
+ if (inCodeBlock) {
1131
+ rendered.push(` ${colorize(line, "cyan", color)}`);
1132
+ continue;
1133
+ }
1134
+ if (line.trim() === "") {
1135
+ rendered.push("");
1136
+ continue;
1137
+ }
1138
+ const headingMatch = line.match(/^\s*(#{1,6})\s+(.+)$/);
1139
+ if (headingMatch) {
1140
+ const level = headingMatch[1].length;
1141
+ const text = renderInlineMarkdown(headingMatch[2] ?? "", color);
1142
+ const prefix = level <= 2 ? "" : "\u2022 ";
1143
+ rendered.push(emphasize(`${prefix}${text}`, "bold", color));
1144
+ continue;
1145
+ }
1146
+ const quoteMatch = line.match(/^\s*>\s?(.*)$/);
1147
+ if (quoteMatch) {
1148
+ rendered.push(
1149
+ `${dim("\u2502", color)} ${renderInlineMarkdown(quoteMatch[1] ?? "", color)}`
1150
+ );
1151
+ continue;
1152
+ }
1153
+ const bulletMatch = line.match(/^\s*[-*+]\s+(.*)$/);
1154
+ if (bulletMatch) {
1155
+ rendered.push(`\u2022 ${renderInlineMarkdown(bulletMatch[1] ?? "", color)}`);
1156
+ continue;
1157
+ }
1158
+ const numberedMatch = line.match(/^\s*(\d+)\.\s+(.*)$/);
1159
+ if (numberedMatch) {
1160
+ rendered.push(
1161
+ `${numberedMatch[1]}. ${renderInlineMarkdown(numberedMatch[2] ?? "", color)}`
1162
+ );
1163
+ continue;
1164
+ }
1165
+ rendered.push(renderInlineMarkdown(line, color));
1166
+ }
1167
+ return rendered.join("\n");
1168
+ }
1169
+ function formatTaskLine(task, color) {
1170
+ const title = truncateText(task.title, 120);
1171
+ const details = [
1172
+ task.priority ? formatPriority(task.priority, color) : null,
1173
+ task.deadline ? `due ${formatDateValue(task.deadline)}` : null,
1174
+ task.hasNote ? colorize("note", "yellow", color) : null,
1175
+ task.parentTitle ? `under ${task.parentTitle}` : null,
1176
+ task.childrenCount ? `${task.childrenCount} child${task.childrenCount === 1 ? "" : "ren"}` : null,
1177
+ formatTaskFlags(task, color) || null
1178
+ ].filter(Boolean);
1179
+ const suffix = details.length > 0 ? ` ${dim("\xB7", color)} ${details.join(` ${dim("\xB7", color)} `)}` : "";
1180
+ return `${colorize(`#${task.id}`, "cyan", color)} ${formatStatusGlyph(task.status, color)} ${title}${suffix}`;
1181
+ }
1182
+ function renderTaskList(value, color) {
1183
+ const items = value.items;
1184
+ if (items.length === 0) return "No tasks found.";
1185
+ const showPath = value.meta?.view === "search" || Boolean(value.meta?.showPath);
1186
+ const limit = value.meta?.limit ?? items.length;
1187
+ const rows = items.map((task) => ({
1188
+ task: `${colorize(`#${task.id}`, "cyan", color)}`,
1189
+ taskPlain: `#${task.id}`,
1190
+ state: formatStatusGlyph(task.status, color),
1191
+ statePlain: stripAnsi(formatStatusGlyph(task.status, false)),
1192
+ title: truncateText(task.title, 120),
1193
+ path: task.pathTitles && task.pathTitles.length > 1 ? task.pathTitles.join(" > ") : null,
1194
+ priority: task.priority ? formatPriority(task.priority, color) : dim("-", color),
1195
+ priorityPlain: task.priority ? task.priority === "mid" ? "medium" : task.priority : "-",
1196
+ due: task.deadline ? formatDateValue(task.deadline) : dim("-", color),
1197
+ duePlain: task.deadline ? formatDateValue(task.deadline) : "-",
1198
+ note: task.hasNote ? colorize("note", "yellow", color) : dim("-", color),
1199
+ notePlain: task.hasNote ? "note" : "-",
1200
+ children: (task.childrenCount ?? 0) > 0 ? String(task.childrenCount) : dim("-", color),
1201
+ childrenPlain: (task.childrenCount ?? 0) > 0 ? String(task.childrenCount) : "-",
1202
+ flags: formatTaskFlags(task, color) || dim("-", color),
1203
+ flagsPlain: stripAnsi(formatTaskFlags(task, false)) || "-"
1204
+ }));
1205
+ const taskWidth = Math.max("Task".length, ...rows.map((row) => row.taskPlain.length));
1206
+ const stateWidth = Math.max("State".length, ...rows.map((row) => row.statePlain.length));
1207
+ const titleWidth = Math.min(
1208
+ 40,
1209
+ Math.max("Title".length, 18, ...rows.map((row) => getDisplayWidth(row.title)))
1210
+ );
1211
+ const priorityWidth = Math.max(
1212
+ "Priority".length,
1213
+ ...rows.map((row) => row.priorityPlain.length)
1214
+ );
1215
+ const dueWidth = Math.max("Due".length, ...rows.map((row) => row.duePlain.length));
1216
+ const noteWidth = Math.max("Note".length, ...rows.map((row) => row.notePlain.length));
1217
+ const childrenWidth = Math.max(
1218
+ "Children".length,
1219
+ ...rows.map((row) => row.childrenPlain.length)
1220
+ );
1221
+ const header = [
1222
+ padCell("Task", taskWidth),
1223
+ padCell("State", stateWidth),
1224
+ padCell("Title", titleWidth),
1225
+ padCell("Children", childrenWidth),
1226
+ padCell("Priority", priorityWidth),
1227
+ padCell("Due", dueWidth),
1228
+ padCell("Note", noteWidth),
1229
+ "Flags"
1230
+ ].join(" ");
1231
+ const separator = [
1232
+ "-".repeat(taskWidth),
1233
+ "-".repeat(stateWidth),
1234
+ "-".repeat(titleWidth),
1235
+ "-".repeat(childrenWidth),
1236
+ "-".repeat(priorityWidth),
1237
+ "-".repeat(dueWidth),
1238
+ "-".repeat(noteWidth),
1239
+ "-----"
1240
+ ].join(" ");
1241
+ const body = rows.map((row) => ({
1242
+ main: [
1243
+ padCell(row.task, taskWidth),
1244
+ padCell(row.state, stateWidth),
1245
+ padCell(truncateText(row.title, titleWidth), titleWidth),
1246
+ padCell(row.children, childrenWidth),
1247
+ padCell(row.priority, priorityWidth),
1248
+ padCell(row.due, dueWidth),
1249
+ padCell(row.note, noteWidth),
1250
+ row.flags
1251
+ ].join(" "),
1252
+ path: showPath && row.path ? `${" ".repeat(taskWidth + 2 + stateWidth + 2)}${dim(
1253
+ truncateDisplayText(
1254
+ row.path,
1255
+ Math.max(
1256
+ 20,
1257
+ (process.stdout.columns ?? 100) - (taskWidth + 2 + stateWidth + 2)
1258
+ )
1259
+ ),
1260
+ color
1261
+ )}` : null
1262
+ }));
1263
+ const lines = [
1264
+ header,
1265
+ separator,
1266
+ ...body.flatMap((row) => row.path ? [row.main, row.path] : [row.main])
1267
+ ];
1268
+ lines.push("");
1269
+ lines.push(dim(`Showing ${items.length} tasks (limit ${limit}).`, color));
1270
+ if (value.nextCursor) {
1271
+ lines.push(dim(`More tasks available after #${value.nextCursor.id}.`, color));
1272
+ const nextPageCommand = value.meta?.view === "search" ? [
1273
+ "pnpm cli task search",
1274
+ quoteCliArg(value.meta.query ?? ""),
1275
+ value.meta.parent ? `--parent ${quoteCliArg(value.meta.parent)}` : null,
1276
+ value.meta.scope ? `--scope ${quoteCliArg(value.meta.scope)}` : null,
1277
+ value.nextCursor.score !== void 0 ? `--cursor-score ${value.nextCursor.score}` : null,
1278
+ `--cursor-id ${value.nextCursor.id}`,
1279
+ value.meta.limit ? `--limit ${value.meta.limit}` : null
1280
+ ].filter(Boolean).join(" ") : [
1281
+ "pnpm cli task list",
1282
+ value.meta?.parent ? `--parent ${quoteCliArg(value.meta.parent)}` : null,
1283
+ value.meta?.scope ? `--scope ${quoteCliArg(value.meta.scope)}` : null,
1284
+ `--cursor ${value.nextCursor.id}`,
1285
+ value.meta?.limit ? `--limit ${value.meta.limit}` : null
1286
+ ].filter(Boolean).join(" ");
1287
+ lines.push(dim(`Next page: ${nextPageCommand}`, color));
1288
+ }
1289
+ return lines.join("\n");
1290
+ }
1291
+ function renderTaskDetail(task, color) {
1292
+ const lines = [
1293
+ `${colorize(`#${task.id}`, "cyan", color)} ${task.title}`,
1294
+ `Status: ${formatStatusGlyph(task.status, color)} ${formatStatus(task.status, color)}`
1295
+ ];
1296
+ if (task.priority) {
1297
+ lines.push(`Priority: ${formatPriority(task.priority, color)}`);
1298
+ }
1299
+ if (task.deadline) {
1300
+ lines.push(`Deadline: ${formatDateValue(task.deadline)}`);
1301
+ }
1302
+ if (task.expectedTimeTaken !== null && task.expectedTimeTaken !== void 0) {
1303
+ lines.push(`Expected: ${formatMinutes(task.expectedTimeTaken)}`);
1304
+ }
1305
+ if (task.actualTimeTaken !== null && task.actualTimeTaken !== void 0) {
1306
+ lines.push(`Actual: ${formatMinutes(task.actualTimeTaken)}`);
1307
+ }
1308
+ if (task.parentTitle ?? task.parentId) {
1309
+ lines.push(
1310
+ `Parent: ${task.parentTitle ?? (task.parentId ? `#${task.parentId}` : "-")}`
1311
+ );
1312
+ }
1313
+ if ((task.childrenCount ?? 0) > 0) {
1314
+ lines.push(`Children: ${task.childrenCount ?? 0}`);
1315
+ }
1316
+ if (task.archivedAt) {
1317
+ lines.push("Archived: yes");
1318
+ }
1319
+ return lines.join("\n");
1320
+ }
1321
+ function renderTaskDetailResponse(result, color) {
1322
+ const task = {
1323
+ ...result.task,
1324
+ parentTitle: result.task.parentTitle ?? (result.taskParents && result.taskParents.length > 0 ? result.taskParents.map((parent) => parent.title).join(" > ") : result.task.parentTitle)
1325
+ };
1326
+ const sections = [renderTaskDetail(task, color)];
1327
+ if (result.taskParents && result.taskParents.length > 1) {
1328
+ sections.push(
1329
+ ["Parents", ...result.taskParents.map((task2) => `- ${formatTaskLine(task2, color)}`)].join("\n")
1330
+ );
1331
+ }
1332
+ if (result.taskChildren && result.taskChildren.length > 0) {
1333
+ sections.push(
1334
+ ["Children", ...result.taskChildren.map((task2) => `- ${formatTaskLine(task2, color)}`)].join("\n")
1335
+ );
1336
+ }
1337
+ if (result.taskAccessType) {
1338
+ sections.push(`Access: ${result.taskAccessType}`);
1339
+ }
1340
+ if (result.note) {
1341
+ sections.push(["Note", renderMarkdownNote(result.note.content, color)].join("\n"));
1342
+ }
1343
+ return sections.join("\n\n");
1344
+ }
1345
+ function renderTreeNode(task, color, prefix = "", isLast = true, level = 0) {
1346
+ const connector = level === 0 ? "" : isLast ? "\u2514\u2500 " : "\u251C\u2500 ";
1347
+ const nextPrefix = level === 0 ? "" : `${prefix}${isLast ? " " : "\u2502 "}`;
1348
+ const lines = [`${prefix}${connector}${formatTaskLine(task, color)}`];
1349
+ const children = task.children ?? [];
1350
+ children.forEach((child, index) => {
1351
+ lines.push(
1352
+ ...renderTreeNode(
1353
+ child,
1354
+ color,
1355
+ nextPrefix,
1356
+ index === children.length - 1,
1357
+ level + 1
1358
+ )
1359
+ );
1360
+ });
1361
+ return lines;
1362
+ }
1363
+ function renderTaskTreeResponse(value, color) {
1364
+ const lines = [];
1365
+ if (value.meta?.isTruncated && value.meta.defaultDepthApplied !== void 0) {
1366
+ lines.push(
1367
+ dim(
1368
+ `Showing root tree to depth ${value.meta.defaultDepthApplied}. Use --depth <n> or --full for more.`,
1369
+ color
1370
+ )
1371
+ );
1372
+ lines.push("");
1373
+ }
1374
+ lines.push(...renderTreeNode(value.tree, color));
1375
+ return lines.join("\n");
1376
+ }
1377
+ function renderTaskSummary(value, color) {
1378
+ const { task, directChildren, descendants, healthSignals } = value;
1379
+ const lines = [
1380
+ `${colorize(`#${task.id}`, "cyan", color)} ${task.title} summary`,
1381
+ `Status: ${formatStatusGlyph(task.status, color)} ${formatStatus(task.status, color)}`,
1382
+ `Priority: ${formatPriority(task.priority, color)}`,
1383
+ `Due: ${task.deadline ? formatDateValue(task.deadline) : dim("-", color)}`,
1384
+ `Note: ${task.hasNote ? colorize("note", "yellow", color) : dim("-", color)}`,
1385
+ "",
1386
+ `Direct children: ${directChildren.total} total (${directChildren.active} active, ${directChildren.archived} archived)`,
1387
+ `Descendants: ${descendants.total} total (${descendants.active} active, ${descendants.archived} archived)`,
1388
+ `Status split: ${descendants.statuses.notStarted} not started, ${descendants.statuses.inProgress} in progress, ${descendants.statuses.completed} completed`,
1389
+ `Priority split: ${descendants.priorities.high} high, ${descendants.priorities.mid} medium, ${descendants.priorities.low} low, ${descendants.priorities.none} none`,
1390
+ `Notes in branch: ${value.notesInBranchCount}`,
1391
+ `Due (active descendants): ${descendants.due.overdue} overdue, ${descendants.due.today} due today, ${descendants.due.thisWeek} due this week`,
1392
+ "",
1393
+ "Health signals",
1394
+ ...healthSignals.length > 0 ? healthSignals.map((signal) => `- ${signal}`) : ["- No immediate health signals"]
1395
+ ];
1396
+ return lines.join("\n");
1397
+ }
1398
+ function renderPlanningMetadataGaps(value, color) {
1399
+ const lines = [
1400
+ `${colorize(`#${value.task.id}`, "cyan", color)} ${value.task.title} planning metadata gaps`
1401
+ ];
1402
+ if (value.items.length === 0) {
1403
+ lines.push(dim("No planning metadata gaps found.", color));
1404
+ return lines.join("\n");
1405
+ }
1406
+ lines.push(
1407
+ ...value.items.map(
1408
+ (item) => `${colorize(`#${item.id}`, "cyan", color)} ${item.title}
1409
+ ${dim(`Missing: ${item.missing.join(", ")}`, color)}`
1410
+ )
1411
+ );
1412
+ return lines.join("\n");
1413
+ }
1414
+ function renderNextActions(value, color) {
1415
+ const lines = [
1416
+ `${colorize(`#${value.task.id}`, "cyan", color)} ${value.task.title} likely next actions`
1417
+ ];
1418
+ if (value.items.length === 0) {
1419
+ lines.push(dim("No next-action candidates found.", color));
1420
+ return lines.join("\n");
1421
+ }
1422
+ lines.push(
1423
+ ...value.items.map(
1424
+ (item) => `${colorize(`#${item.id}`, "cyan", color)} ${item.title}
1425
+ ${dim(`Why: ${item.reasons.join(", ")}`, color)}`
1426
+ )
1427
+ );
1428
+ return lines.join("\n");
1429
+ }
1430
+ function renderBranchFocusSignals(value, color) {
1431
+ const lines = [
1432
+ `${colorize(`#${value.task.id}`, "cyan", color)} ${value.task.title} branch focus signals`
1433
+ ];
1434
+ if (value.items.length === 0) {
1435
+ lines.push(dim("No focus branches found.", color));
1436
+ return lines.join("\n");
1437
+ }
1438
+ lines.push(
1439
+ ...value.items.map(
1440
+ (item) => `${colorize(`#${item.id}`, "cyan", color)} ${item.title}
1441
+ ${dim(
1442
+ `Signals: ${item.signals.join(", ")}`,
1443
+ color
1444
+ )}
1445
+ ${dim(
1446
+ `Missing planning metadata: ${item.missingMetadataCount}`,
1447
+ color
1448
+ )}
1449
+ ${dim(
1450
+ `Descendants: ${item.descendantCount} total (${item.activeDescendantCount} active)`,
1451
+ color
1452
+ )}`
1453
+ )
1454
+ );
1455
+ return lines.join("\n");
1456
+ }
1457
+ function renderDependencies(dependencies, color) {
1458
+ const section = (label, items) => {
1459
+ if (items.length === 0) return `${label}
1460
+ ${dim("None.", color)}`;
1461
+ return [
1462
+ label,
1463
+ ...items.map((item) => `- ${formatTaskLine(item, color)}`)
1464
+ ].join("\n");
1465
+ };
1466
+ return [
1467
+ section("Blockers", dependencies.blockers),
1468
+ section("Dependents", dependencies.dependents)
1469
+ ].join("\n\n");
1470
+ }
1471
+ function renderNotes(notes, color) {
1472
+ if (notes.length === 0) return "No note found.";
1473
+ return notes.map((note) => {
1474
+ const header = note.taskTitle ? `Note for ${colorize(`#${note.taskId}`, "cyan", color)} ${note.taskTitle}` : `Note for ${colorize(`#${note.taskId}`, "cyan", color)}`;
1475
+ return `${header}
1476
+
1477
+ ${renderMarkdownNote(note.content, color)}`;
1478
+ }).join("\n\n");
1479
+ }
1480
+ function renderDeleteMany(result, color) {
1481
+ const lines = [
1482
+ `${colorize("Deleted", "green", color)} ${result.tasksDeleted} task${result.tasksDeleted === 1 ? "" : "s"}.`,
1483
+ `Task IDs: ${result.taskIds.join(", ")}`
1484
+ ];
1485
+ if (result.affectedDependentIds && result.affectedDependentIds.length > 0) {
1486
+ lines.push(`Affected dependents: ${result.affectedDependentIds.join(", ")}`);
1487
+ }
1488
+ return lines.join("\n");
1489
+ }
1490
+ function renderUpdateMany(result, color) {
1491
+ return [
1492
+ `${colorize("Updated", "green", color)} ${result.tasks.length} task${result.tasks.length === 1 ? "" : "s"}.`,
1493
+ ...result.tasks.map((task) => formatTaskLine(task, color))
1494
+ ].join("\n");
1495
+ }
1496
+ function renderCleanupPreview(result, color) {
1497
+ const formatPreviewChangeValue = (field, value) => {
1498
+ if (value === null) return "-";
1499
+ if (field === "deadline") {
1500
+ return typeof value === "string" ? formatDateValue(value) : "-";
1501
+ }
1502
+ if (field === "expectedTimeTaken" || field === "actualTimeTaken") {
1503
+ return typeof value === "number" ? formatMinutes(value) : String(value);
1504
+ }
1505
+ return String(value);
1506
+ };
1507
+ const formatPreviewField = (field) => {
1508
+ switch (field) {
1509
+ case "deadline":
1510
+ return "due";
1511
+ case "expectedTimeTaken":
1512
+ return "expected";
1513
+ case "actualTimeTaken":
1514
+ return "actual";
1515
+ default:
1516
+ return field;
1517
+ }
1518
+ };
1519
+ const lines = [
1520
+ "Cleanup preview",
1521
+ dim(
1522
+ `${result.summary.taskCount} tasks, ${result.summary.actionCount} actions`,
1523
+ color
1524
+ ),
1525
+ "",
1526
+ ...result.tasks.map((task) => {
1527
+ const pathLine = task.destinationParentTitle && task.destinationParentTitle !== task.currentParentTitle ? ` ${dim(
1528
+ `${task.currentParentTitle ?? "Root tasks"} -> ${task.destinationParentTitle}`,
1529
+ color
1530
+ )}` : task.currentParentTitle ? ` ${dim(task.currentParentTitle, color)}` : "";
1531
+ const actionLabel = task.actions.length > 0 ? task.actions.join(", ") : "no-op";
1532
+ const changeLines = task.changes?.map(
1533
+ (change) => ` ${dim(
1534
+ `${formatPreviewField(change.field)}: ${formatPreviewChangeValue(change.field, change.from)} -> ${formatPreviewChangeValue(change.field, change.to)}`,
1535
+ color
1536
+ )}`
1537
+ ) ?? [];
1538
+ return [
1539
+ `${colorize(`#${task.id}`, "cyan", color)} ${task.title} ${dim("\xB7", color)} ${actionLabel}`,
1540
+ pathLine,
1541
+ ...changeLines
1542
+ ].filter(Boolean).join("\n");
1543
+ })
1544
+ ];
1545
+ if (result.wrappersToEmpty.length > 0) {
1546
+ lines.push("");
1547
+ lines.push("Wrappers left empty");
1548
+ lines.push(
1549
+ ...result.wrappersToEmpty.map(
1550
+ (wrapper) => `- ${colorize(`#${wrapper.id}`, "cyan", color)} ${wrapper.title}`
1551
+ )
1552
+ );
1553
+ }
1554
+ return lines.join("\n");
1555
+ }
1556
+ function renderCleanupPlanPreview(result, color) {
1557
+ const baseLines = renderCleanupPreview(result, color).split("\n");
1558
+ const workflowLabel = getCleanupWorkflowLabel(result);
1559
+ const heading = workflowLabel === "relocate-and-collapse" ? "Relocate-and-collapse preview" : "Cleanup plan preview";
1560
+ return [
1561
+ heading,
1562
+ dim(
1563
+ `${result.summary.operationCount} operation${result.summary.operationCount === 1 ? "" : "s"}, ${result.summary.taskCount} task${result.summary.taskCount === 1 ? "" : "s"}, ${result.summary.actionCount} action${result.summary.actionCount === 1 ? "" : "s"}`,
1564
+ color
1565
+ ),
1566
+ "",
1567
+ "Planned operations",
1568
+ ...result.operations.map((operation) => {
1569
+ if (operation.type === "move") {
1570
+ return `- move ${operation.taskIds.length} task${operation.taskIds.length === 1 ? "" : "s"} to ${operation.toParentId === null ? "root" : `#${operation.toParentId}`}`;
1571
+ }
1572
+ if (operation.type === "update") {
1573
+ return `- update ${operation.taskIds.length} task${operation.taskIds.length === 1 ? "" : "s"} (${(operation.changedFields ?? []).join(", ")})`;
1574
+ }
1575
+ return `- ${operation.type} ${operation.taskIds.length} task${operation.taskIds.length === 1 ? "" : "s"}`;
1576
+ }),
1577
+ "",
1578
+ ...baseLines.slice(2)
1579
+ ].join("\n");
1580
+ }
1581
+ function renderCleanupApply(result, color) {
1582
+ const workflowLabel = getCleanupWorkflowLabel(result);
1583
+ const lines = [
1584
+ workflowLabel === "relocate-and-collapse" ? `${colorize("Applied", "green", color)} relocate-and-collapse workflow` : `${colorize("Applied", "green", color)} cleanup plan`,
1585
+ dim(
1586
+ `${result.operationCount} operation${result.operationCount === 1 ? "" : "s"}, ${result.affectedTaskIds.length} affected task${result.affectedTaskIds.length === 1 ? "" : "s"}`,
1587
+ color
1588
+ ),
1589
+ "",
1590
+ ...result.operations.map((operation) => {
1591
+ if (operation.type === "move") {
1592
+ return `- move ${operation.taskIds.length} task${operation.taskIds.length === 1 ? "" : "s"} to ${operation.toParentId === null ? "root" : `#${operation.toParentId ?? "?"}`}`;
1593
+ }
1594
+ if (operation.type === "update") {
1595
+ return `- update ${operation.taskIds.length} task${operation.taskIds.length === 1 ? "" : "s"} (${operation.changedFields?.join(", ") ?? "fields"})`;
1596
+ }
1597
+ return `- ${operation.type} ${operation.taskIds.length} task${operation.taskIds.length === 1 ? "" : "s"}`;
1598
+ }),
1599
+ "",
1600
+ `Affected: ${result.affectedTaskIds.map((taskId) => colorize(`#${taskId}`, "cyan", color)).join(", ")}`
1601
+ ];
1602
+ return lines.join("\n");
1603
+ }
1604
+ function renderAuthStatus(result, color) {
1605
+ const signedInAs = result.user.username ?? result.user.primaryEmail ?? result.user.userId;
1606
+ return [
1607
+ `Signed in as: ${signedInAs}`,
1608
+ `User ID: ${result.user.userId}`,
1609
+ `Primary email: ${result.user.primaryEmail ?? "-"}`,
1610
+ `Device: ${result.token.label}`,
1611
+ `Scope: ${result.token.scope}`,
1612
+ `Token ID: ${result.token.id}`,
1613
+ `Issued: ${formatDateTimeValue(result.token.createdAt)}`,
1614
+ `Expires: ${formatDateTimeValue(result.token.expiresAt)}`,
1615
+ `Expires in: ${colorize(formatRelativeTimeUntil(result.token.expiresAt), "yellow", color)}`,
1616
+ `Last used: ${formatDateTimeValue(result.token.lastUsedAt)}`
1617
+ ].join("\n");
1618
+ }
1619
+ function formatHumanOutput(value, options = {}) {
1620
+ const color = options.color ?? Boolean(process.stdout.isTTY);
1621
+ if (Array.isArray(value) && value.length === 0) {
1622
+ return "No results.";
1623
+ }
1624
+ if (isPlanningMetadataGapsLike(value)) {
1625
+ return renderPlanningMetadataGaps(value, color);
1626
+ }
1627
+ if (isNextActionsLike(value)) {
1628
+ return renderNextActions(value, color);
1629
+ }
1630
+ if (isBranchFocusSignalsLike(value)) {
1631
+ return renderBranchFocusSignals(value, color);
1632
+ }
1633
+ if (isTaskCollection(value)) {
1634
+ return renderTaskList(value, color);
1635
+ }
1636
+ if (isTaskTreeResponseLike(value)) {
1637
+ return renderTaskTreeResponse(value, color);
1638
+ }
1639
+ if (isTaskSummaryLike(value)) {
1640
+ return renderTaskSummary(value, color);
1641
+ }
1642
+ if (isTaskDetailLike(value)) {
1643
+ return renderTaskDetailResponse(value, color);
1644
+ }
1645
+ if (isAuthStatusLike(value)) {
1646
+ return renderAuthStatus(value, color);
1647
+ }
1648
+ if (isDependencyCollection(value)) {
1649
+ return renderDependencies(value, color);
1650
+ }
1651
+ if (isDeleteManyLike(value)) {
1652
+ return renderDeleteMany(value, color);
1653
+ }
1654
+ if (isCleanupApplyLike(value)) {
1655
+ return renderCleanupApply(value, color);
1656
+ }
1657
+ if (isCleanupPlanPreviewLike(value)) {
1658
+ return renderCleanupPlanPreview(value, color);
1659
+ }
1660
+ if (isCleanupPreviewLike(value)) {
1661
+ return renderCleanupPreview(value, color);
1662
+ }
1663
+ if (isUpdateManyLike(value)) {
1664
+ return renderUpdateMany(value, color);
1665
+ }
1666
+ if (Array.isArray(value)) {
1667
+ if (value.every(isTaskLike)) {
1668
+ return renderTaskList({ items: value }, color);
1669
+ }
1670
+ if (value.every(isNoteLike)) {
1671
+ return renderNotes(value, color);
1672
+ }
1673
+ }
1674
+ if (isTaskLike(value)) {
1675
+ if (Array.isArray(value.children)) {
1676
+ return renderTreeNode(value, color).join("\n");
1677
+ }
1678
+ return renderTaskDetail(value, color);
1679
+ }
1680
+ if (isNoteLike(value)) {
1681
+ return renderNotes([value], color);
1682
+ }
1683
+ return JSON.stringify(value, null, 2);
1684
+ }
1685
+ function printJson(value) {
1686
+ process.stdout.write(`${JSON.stringify(value, null, 2)}
1687
+ `);
1688
+ }
1689
+ function printTable(value) {
1690
+ process.stdout.write(`${formatHumanOutput(value)}
1691
+ `);
1692
+ }
1693
+ async function confirmAction(message, deps = {}) {
1694
+ if (deps.isTty === false) {
1695
+ return false;
1696
+ }
1697
+ if (!deps.readLine) {
1698
+ return false;
1699
+ }
1700
+ const answer = await deps.readLine(`${message} [y/N] `);
1701
+ return answer.trim().toLowerCase() === "y";
1702
+ }
1703
+
1704
+ // src/index.ts
1705
+ var taskStatusChoices = [
1706
+ "not started",
1707
+ "in progress",
1708
+ "completed"
1709
+ ];
1710
+ var taskPriorityChoices = ["low", "mid", "medium", "high"];
1711
+ function normalizePriority(priority) {
1712
+ if (!priority) return void 0;
1713
+ if (priority === "medium") return "mid";
1714
+ if (priority === "low" || priority === "mid" || priority === "high") {
1715
+ return priority;
1716
+ }
1717
+ throw new Error(`Unsupported priority: ${priority}`);
1718
+ }
1719
+ function normalizeStatus(status) {
1720
+ if (!status) return void 0;
1721
+ if (status === "not started" || status === "in progress" || status === "completed") {
1722
+ return status;
1723
+ }
1724
+ throw new Error(`Unsupported status: ${status}`);
1725
+ }
1726
+ function normalizeArchivedMode(archived) {
1727
+ if (!archived) return void 0;
1728
+ if (archived === "active" || archived === "archived" || archived === "all") {
1729
+ return archived;
1730
+ }
1731
+ throw new Error(`Unsupported archived mode: ${archived}`);
1732
+ }
1733
+ function normalizeFilterMode(value) {
1734
+ if (!value) return void 0;
1735
+ if (value === "show" || value === "hide" || value === "only") {
1736
+ return value;
1737
+ }
1738
+ throw new Error(`Unsupported filter mode: ${value}`);
1739
+ }
1740
+ function parseIntegerOption(value, label, minimum = 0, maximum) {
1741
+ if (!value) return void 0;
1742
+ const parsed = Number(value);
1743
+ if (!Number.isInteger(parsed) || parsed < minimum) {
1744
+ throw new Error(`${label} must be an integer >= ${minimum}`);
1745
+ }
1746
+ if (maximum !== void 0 && parsed > maximum) {
1747
+ throw new Error(`${label} must be an integer between ${minimum} and ${maximum}`);
1748
+ }
1749
+ return parsed;
1750
+ }
1751
+ function parseNumberOption(value, label) {
1752
+ if (!value) return void 0;
1753
+ const parsed = Number(value);
1754
+ if (!Number.isFinite(parsed)) {
1755
+ throw new Error(`${label} must be a valid number`);
1756
+ }
1757
+ return parsed;
1758
+ }
1759
+ function parseDateOption(value, boundary) {
1760
+ if (!value) return void 0;
1761
+ const normalized = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}${boundary === "start" ? "T00:00:00.000Z" : "T23:59:59.999Z"}` : value;
1762
+ const parsed = new Date(normalized);
1763
+ if (Number.isNaN(parsed.getTime())) {
1764
+ throw new Error(`Invalid date: ${value}`);
1765
+ }
1766
+ return parsed;
1767
+ }
1768
+ function assertTaskId(ref) {
1769
+ const taskId = Number(ref);
1770
+ if (!Number.isInteger(taskId) || taskId <= 0) {
1771
+ throw new Error(`Task reference must be a numeric id: ${ref}`);
1772
+ }
1773
+ return taskId;
1774
+ }
1775
+ function resolveTaskRefFromSearchMatches(ref, matches) {
1776
+ const normalizedRef = ref.trim().toLocaleLowerCase();
1777
+ const exactMatches = matches.filter(
1778
+ (task) => task.title.trim().toLocaleLowerCase() === normalizedRef
1779
+ );
1780
+ if (exactMatches.length === 1) {
1781
+ return exactMatches[0].id;
1782
+ }
1783
+ if (exactMatches.length > 1) {
1784
+ const formattedMatches = exactMatches.map((task) => {
1785
+ const path3 = task.pathTitles?.join(" > ") ?? (task.parentTitle ? `${task.parentTitle} > ${task.title}` : task.title);
1786
+ return `- #${task.id} ${path3}`;
1787
+ }).join("\n");
1788
+ throw new Error(`Task reference is ambiguous: ${ref}
1789
+ ${formattedMatches}`);
1790
+ }
1791
+ if (matches.length === 1) {
1792
+ return matches[0].id;
1793
+ }
1794
+ throw new Error(`Task not found: ${ref}`);
1795
+ }
1796
+ async function resolveTaskId(api, ref) {
1797
+ if (/^\d+$/.test(ref)) {
1798
+ return assertTaskId(ref);
1799
+ }
1800
+ const result = await api.searchTasks({
1801
+ query: ref,
1802
+ limit: 10,
1803
+ archived: "all"
1804
+ });
1805
+ const matches = result.items ?? [];
1806
+ return resolveTaskRefFromSearchMatches(ref, matches);
1807
+ }
1808
+ function assertExclusiveHierarchyOptions(parent, scope) {
1809
+ if (parent && scope) {
1810
+ throw new Error("Use either --parent or --scope, not both");
1811
+ }
1812
+ }
1813
+ async function withCliApi(callback) {
1814
+ const api = await createCliApi();
1815
+ return callback(api);
1816
+ }
1817
+ async function promptLine(prompt) {
1818
+ const readline = createInterface({
1819
+ input: process.stdin,
1820
+ output: process.stdout
1821
+ });
1822
+ try {
1823
+ return await readline.question(prompt);
1824
+ } finally {
1825
+ readline.close();
1826
+ }
1827
+ }
1828
+ function buildCli() {
1829
+ const program = new Command();
1830
+ program.name("dypt");
1831
+ const addGroupHelpAction = (command) => {
1832
+ command.action(() => {
1833
+ command.outputHelp();
1834
+ });
1835
+ return command;
1836
+ };
1837
+ const auth = addGroupHelpAction(
1838
+ program.command("auth").description("Authentication commands")
1839
+ );
1840
+ auth.command("login").description("Start a device-code login flow").option("-l, --label <label>", "label for this device").action(async (options) => {
1841
+ await runLogin(
1842
+ {
1843
+ label: options.label ?? getDefaultDeviceLabel()
1844
+ },
1845
+ createDefaultLoginDeps()
1846
+ );
1847
+ });
1848
+ auth.command("status").description("Show the current CLI authentication status").option("--json", "print JSON output").action(async (options) => {
1849
+ await runStatus(
1850
+ {
1851
+ json: Boolean(options.json)
1852
+ },
1853
+ {
1854
+ getStatus: () => withCliApi((api) => api.getAuthStatus()),
1855
+ printJson,
1856
+ printTable
1857
+ }
1858
+ );
1859
+ });
1860
+ auth.command("logout").description("Remove the local CLI token").action(async () => {
1861
+ await runLogout(createDefaultLogoutDeps());
1862
+ });
1863
+ const task = addGroupHelpAction(
1864
+ program.command("task").description("Task commands")
1865
+ );
1866
+ task.command("get").argument("<ref>").option("--json", "print JSON output").action(async (ref, options) => {
1867
+ await runTaskGet(
1868
+ {
1869
+ ref,
1870
+ json: Boolean(options.json)
1871
+ },
1872
+ {
1873
+ getTask: (taskRef) => withCliApi(
1874
+ async (api) => api.getTask({ taskId: await resolveTaskId(api, taskRef) })
1875
+ ),
1876
+ printJson,
1877
+ printTable
1878
+ }
1879
+ );
1880
+ });
1881
+ task.command("summary").description("Show branch summary counts and health signals").argument("<ref>").option("--json", "print JSON output").addHelpText(
1882
+ "after",
1883
+ [
1884
+ "",
1885
+ "Examples:",
1886
+ " pnpm cli task summary CLI",
1887
+ " pnpm cli task summary 70867 --json"
1888
+ ].join("\n")
1889
+ ).action(async (ref, options) => {
1890
+ await runTaskSummary(
1891
+ {
1892
+ ref,
1893
+ json: Boolean(options.json)
1894
+ },
1895
+ {
1896
+ getTaskSummary: (taskRef) => withCliApi(
1897
+ async (api) => api.getTaskSummary({
1898
+ taskId: await resolveTaskId(api, taskRef)
1899
+ })
1900
+ ),
1901
+ printJson,
1902
+ printTable
1903
+ }
1904
+ );
1905
+ });
1906
+ task.command("list").option("--archived <mode>", "active, archived, or all").addOption(
1907
+ new Option(
1908
+ "--status <status>",
1909
+ `task status (${taskStatusChoices.join("|")})`
1910
+ ).choices([...taskStatusChoices])
1911
+ ).addOption(
1912
+ new Option(
1913
+ "--priority <priority>",
1914
+ `task priority (${taskPriorityChoices.join("|")})`
1915
+ ).choices([...taskPriorityChoices])
1916
+ ).option("--leaves", "only show leaf tasks").option("--blocked <mode>", "show, hide, or only blocked tasks").option("--blocking <mode>", "show, hide, or only blocking tasks").option("--title-contains <text>", "filter titles by substring").option("--deadline-from <iso>", "inclusive deadline start").option("--deadline-to <iso>", "inclusive deadline end").option("--created-from <iso>", "inclusive created-at start").option("--created-to <iso>", "inclusive created-at end").option("--expected-time-from <minutes>", "minimum expected time").option("--expected-time-to <minutes>", "maximum expected time").option("--actual-time-from <minutes>", "minimum actual time").option("--actual-time-to <minutes>", "maximum actual time").option("--parent <ref>", "only include direct children of the given task").option("--scope <ref>", "only include descendants of the given task").option("--show-path", "show task path context in list output").option("--limit <n>", "page size (1-100, default: 50)").option("--cursor <id>", "cursor task id for pagination").option("--json", "print JSON output").addHelpText(
1917
+ "after",
1918
+ [
1919
+ "",
1920
+ "Examples:",
1921
+ " pnpm cli task list --limit 20",
1922
+ " pnpm cli task list --parent Work",
1923
+ " pnpm cli task list --scope Work --show-path",
1924
+ " pnpm cli task list --show-path --title-contains dypt",
1925
+ " pnpm cli task list --cursor 119"
1926
+ ].join("\n")
1927
+ ).action(async (options) => {
1928
+ assertExclusiveHierarchyOptions(options.parent, options.scope);
1929
+ await runTaskList(
1930
+ {
1931
+ archived: options.archived,
1932
+ status: options.status,
1933
+ priority: options.priority,
1934
+ leaves: Boolean(options.leaves),
1935
+ blocked: options.blocked,
1936
+ blocking: options.blocking,
1937
+ titleContains: options.titleContains,
1938
+ deadlineFrom: options.deadlineFrom,
1939
+ deadlineTo: options.deadlineTo,
1940
+ createdFrom: options.createdFrom,
1941
+ createdTo: options.createdTo,
1942
+ expectedTimeFrom: options.expectedTimeFrom,
1943
+ expectedTimeTo: options.expectedTimeTo,
1944
+ actualTimeFrom: options.actualTimeFrom,
1945
+ actualTimeTo: options.actualTimeTo,
1946
+ parent: options.parent,
1947
+ scope: options.scope,
1948
+ showPath: Boolean(options.showPath),
1949
+ limit: options.limit,
1950
+ cursor: options.cursor,
1951
+ json: Boolean(options.json)
1952
+ },
1953
+ {
1954
+ listTasks: (input) => withCliApi(async (api) => {
1955
+ const parentTaskId = input.parent ? await resolveTaskId(api, input.parent) : void 0;
1956
+ const scopeTaskId = input.scope ? await resolveTaskId(api, input.scope) : void 0;
1957
+ return api.listTasks({
1958
+ archived: normalizeArchivedMode(input.archived),
1959
+ parentTaskId,
1960
+ scopeTaskId,
1961
+ status: normalizeStatus(input.status),
1962
+ priority: normalizePriority(input.priority),
1963
+ leaves: input.leaves,
1964
+ blocked: normalizeFilterMode(input.blocked),
1965
+ blocking: normalizeFilterMode(input.blocking),
1966
+ titleContains: input.titleContains,
1967
+ deadlineFrom: parseDateOption(input.deadlineFrom, "start"),
1968
+ deadlineTo: parseDateOption(input.deadlineTo, "end"),
1969
+ createdFrom: parseDateOption(input.createdFrom, "start"),
1970
+ createdTo: parseDateOption(input.createdTo, "end"),
1971
+ expectedTimeFrom: parseIntegerOption(
1972
+ input.expectedTimeFrom,
1973
+ "expected-time-from",
1974
+ 0
1975
+ ),
1976
+ expectedTimeTo: parseIntegerOption(
1977
+ input.expectedTimeTo,
1978
+ "expected-time-to",
1979
+ 0
1980
+ ),
1981
+ actualTimeFrom: parseIntegerOption(
1982
+ input.actualTimeFrom,
1983
+ "actual-time-from",
1984
+ 0
1985
+ ),
1986
+ actualTimeTo: parseIntegerOption(
1987
+ input.actualTimeTo,
1988
+ "actual-time-to",
1989
+ 0
1990
+ ),
1991
+ showPath: input.showPath,
1992
+ limit: parseIntegerOption(input.limit, "limit", 1, 100),
1993
+ cursor: input.cursor ? {
1994
+ id: parseIntegerOption(input.cursor, "cursor", 1)
1995
+ } : void 0
1996
+ });
1997
+ }),
1998
+ printJson,
1999
+ printTable
2000
+ }
2001
+ );
2002
+ });
2003
+ task.command("search").argument("<query>").option("--parent <ref>", "only search direct children of the given task").option("--scope <ref>", "only search descendants of the given task").option("--limit <n>", "page size (1-100, default: 20)").option("--cursor-score <score>", "pagination cursor score").option("--cursor-id <id>", "pagination cursor task id").option("--json", "print JSON output").addHelpText(
2004
+ "after",
2005
+ [
2006
+ "",
2007
+ "Examples:",
2008
+ " pnpm cli task search dypt",
2009
+ " pnpm cli task search dypt --parent Work",
2010
+ " pnpm cli task search dypt --scope Work",
2011
+ " pnpm cli task search dypt --limit 8",
2012
+ " pnpm cli task search dypt --cursor-score 1 --cursor-id 45877 --limit 8"
2013
+ ].join("\n")
2014
+ ).action(async (query, options) => {
2015
+ assertExclusiveHierarchyOptions(options.parent, options.scope);
2016
+ if (options.cursorScore && !options.cursorId || options.cursorId && !options.cursorScore) {
2017
+ throw new Error(
2018
+ "Both --cursor-score and --cursor-id are required together"
2019
+ );
2020
+ }
2021
+ await runTaskSearch(
2022
+ {
2023
+ query,
2024
+ parent: options.parent,
2025
+ scope: options.scope,
2026
+ limit: options.limit,
2027
+ cursorScore: options.cursorScore,
2028
+ cursorId: options.cursorId,
2029
+ json: Boolean(options.json)
2030
+ },
2031
+ {
2032
+ searchTasks: (input) => withCliApi(async (api) => {
2033
+ const parentTaskId = input.parent ? await resolveTaskId(api, input.parent) : void 0;
2034
+ const scopeTaskId = input.scope ? await resolveTaskId(api, input.scope) : void 0;
2035
+ return api.searchTasks({
2036
+ query: input.query,
2037
+ parentTaskId,
2038
+ scopeTaskId,
2039
+ limit: parseIntegerOption(input.limit, "limit", 1, 100),
2040
+ cursor: input.cursorScore || input.cursorId ? {
2041
+ score: parseNumberOption(
2042
+ input.cursorScore,
2043
+ "cursor-score"
2044
+ ),
2045
+ id: parseIntegerOption(
2046
+ input.cursorId,
2047
+ "cursor-id",
2048
+ 1
2049
+ )
2050
+ } : void 0
2051
+ });
2052
+ }),
2053
+ printJson,
2054
+ printTable
2055
+ }
2056
+ );
2057
+ });
2058
+ task.command("tree").description(
2059
+ "Show a task subtree; omit ref for root tasks (defaults to depth 2)"
2060
+ ).argument("[ref]", "task id or title; omit for root tasks").option("--json", "print JSON output").option("--depth <depth>", "limit subtree depth").option("--full", "show the full subtree without a default depth limit").action(
2061
+ async (ref, options) => {
2062
+ await runTaskTree(
2063
+ {
2064
+ ref,
2065
+ json: Boolean(options.json),
2066
+ depth: options.depth ? Number(options.depth) : void 0,
2067
+ full: Boolean(options.full)
2068
+ },
2069
+ {
2070
+ getTaskTree: (taskRef, depth) => withCliApi(
2071
+ async (api) => api.getTaskTree({
2072
+ taskId: taskRef === void 0 ? void 0 : await resolveTaskId(api, taskRef),
2073
+ depth
2074
+ })
2075
+ ),
2076
+ printJson,
2077
+ printTable
2078
+ }
2079
+ );
2080
+ }
2081
+ );
2082
+ const plan = addGroupHelpAction(
2083
+ task.command("plan").description("Planning and prioritisation helper commands")
2084
+ );
2085
+ plan.command("metadata").description("Show tasks in a branch missing planning metadata").argument("<ref>").option("--priority", "only surface missing priority").option("--deadline", "only surface missing deadline").option("--expected-time", "only surface missing expected time").option("--leaves-only", "only include leaf tasks").option("--limit <n>", "maximum tasks to return (1-100, default: 20)").option("--json", "print JSON output").action(
2086
+ async (ref, options) => {
2087
+ await runTaskPlanMetadata(
2088
+ {
2089
+ ref,
2090
+ json: Boolean(options.json),
2091
+ priority: Boolean(options.priority),
2092
+ deadline: Boolean(options.deadline),
2093
+ expectedTime: Boolean(options.expectedTime),
2094
+ leavesOnly: Boolean(options.leavesOnly),
2095
+ limit: options.limit
2096
+ },
2097
+ {
2098
+ listPlanningMetadataGaps: (input) => withCliApi(
2099
+ async (api) => api.getPlanningMetadataGaps({
2100
+ taskId: await resolveTaskId(api, input.ref),
2101
+ missingPriority: input.priority || void 0,
2102
+ missingDeadline: input.deadline || void 0,
2103
+ missingExpectedTime: input.expectedTime || void 0,
2104
+ leavesOnly: input.leavesOnly || void 0,
2105
+ limit: parseIntegerOption(input.limit, "limit", 1, 100)
2106
+ })
2107
+ ),
2108
+ printJson,
2109
+ printTable
2110
+ }
2111
+ );
2112
+ }
2113
+ );
2114
+ plan.command("next-actions").description("Show likely next-action candidates in a branch").argument("<ref>").option("--limit <n>", "maximum tasks to return (1-100, default: 10)").option("--json", "print JSON output").action(
2115
+ async (ref, options) => {
2116
+ await runTaskPlanNextActions(
2117
+ {
2118
+ ref,
2119
+ json: Boolean(options.json),
2120
+ limit: options.limit
2121
+ },
2122
+ {
2123
+ listNextActions: (input) => withCliApi(
2124
+ async (api) => api.getBranchNextActions({
2125
+ taskId: await resolveTaskId(api, input.ref),
2126
+ limit: parseIntegerOption(input.limit, "limit", 1, 100)
2127
+ })
2128
+ ),
2129
+ printJson,
2130
+ printTable
2131
+ }
2132
+ );
2133
+ }
2134
+ );
2135
+ plan.command("focus").description("Show child branches with near-term focus signals").argument("<ref>").option("--limit <n>", "maximum branches to return (1-100, default: 10)").option("--json", "print JSON output").action(
2136
+ async (ref, options) => {
2137
+ await runTaskPlanFocus(
2138
+ {
2139
+ ref,
2140
+ json: Boolean(options.json),
2141
+ limit: options.limit
2142
+ },
2143
+ {
2144
+ listFocusBranches: (input) => withCliApi(
2145
+ async (api) => api.getBranchFocusSignals({
2146
+ taskId: await resolveTaskId(api, input.ref),
2147
+ limit: parseIntegerOption(input.limit, "limit", 1, 100)
2148
+ })
2149
+ ),
2150
+ printJson,
2151
+ printTable
2152
+ }
2153
+ );
2154
+ }
2155
+ );
2156
+ const addTaskNoteCommands = (parent) => {
2157
+ parent.command("get").argument("<taskRef>").option("--json", "print JSON output").action(async (taskRef, options) => {
2158
+ await runNoteGet(
2159
+ {
2160
+ taskRef,
2161
+ json: Boolean(options.json)
2162
+ },
2163
+ {
2164
+ getNote: (ref) => withCliApi(
2165
+ async (api) => api.getNote({
2166
+ taskId: await resolveTaskId(api, ref)
2167
+ })
2168
+ ),
2169
+ printJson,
2170
+ printTable
2171
+ }
2172
+ );
2173
+ });
2174
+ parent.command("set").argument("<taskRef>").argument("<content>").option("--json", "print JSON output").action(
2175
+ async (taskRef, content, options) => {
2176
+ await runNoteSet(
2177
+ {
2178
+ taskRef,
2179
+ content,
2180
+ json: Boolean(options.json)
2181
+ },
2182
+ {
2183
+ setNote: (ref, noteContent) => withCliApi(
2184
+ async (api) => api.setNote({
2185
+ taskId: await resolveTaskId(api, ref),
2186
+ content: noteContent
2187
+ })
2188
+ ),
2189
+ printJson,
2190
+ printTable
2191
+ }
2192
+ );
2193
+ }
2194
+ );
2195
+ parent.command("search").argument("<query>").option("--json", "print JSON output").action(async (query, options) => {
2196
+ await runNoteSearch(
2197
+ {
2198
+ query,
2199
+ json: Boolean(options.json)
2200
+ },
2201
+ {
2202
+ searchNotes: (searchQuery) => withCliApi((api) => api.searchNotes({ query: searchQuery })),
2203
+ printJson,
2204
+ printTable
2205
+ }
2206
+ );
2207
+ });
2208
+ };
2209
+ addGroupHelpAction(
2210
+ task.command("note").description("Task note commands")
2211
+ );
2212
+ const taskNote = task.commands.find((command) => command.name() === "note");
2213
+ if (taskNote) {
2214
+ addTaskNoteCommands(taskNote);
2215
+ }
2216
+ task.command("create").argument("<title>").option("--parent <taskId>", "parent task id").option("--json", "print JSON output").action(
2217
+ async (title, options) => {
2218
+ await runTaskCreate(
2219
+ {
2220
+ title,
2221
+ parentId: options.parent,
2222
+ json: Boolean(options.json)
2223
+ },
2224
+ {
2225
+ createTask: (input) => withCliApi((api) => api.createTask(input)),
2226
+ printJson,
2227
+ printTable
2228
+ }
2229
+ );
2230
+ }
2231
+ );
2232
+ task.command("delete").argument("<ref>").option("--yes", "skip confirmation").action(async (ref, options) => {
2233
+ await runTaskDelete(
2234
+ {
2235
+ ref,
2236
+ yes: Boolean(options.yes)
2237
+ },
2238
+ {
2239
+ isTty: Boolean(process.stdout.isTTY),
2240
+ confirm: (message) => confirmAction(message, {
2241
+ isTty: Boolean(process.stdout.isTTY),
2242
+ readLine: promptLine
2243
+ }),
2244
+ removeTask: (taskRef) => withCliApi(
2245
+ async (api) => api.deleteTasks({
2246
+ taskIds: [await resolveTaskId(api, taskRef)]
2247
+ })
2248
+ )
2249
+ }
2250
+ );
2251
+ });
2252
+ task.command("delete-many").argument("<refs...>").option("--yes", "skip confirmation").option("--json", "print JSON output").action(async (refs, options) => {
2253
+ await runTaskDeleteMany(
2254
+ {
2255
+ refs,
2256
+ yes: Boolean(options.yes),
2257
+ json: Boolean(options.json)
2258
+ },
2259
+ {
2260
+ isTty: Boolean(process.stdout.isTTY),
2261
+ confirm: (message) => confirmAction(message, {
2262
+ isTty: Boolean(process.stdout.isTTY),
2263
+ readLine: promptLine
2264
+ }),
2265
+ deleteTasks: (taskRefs) => withCliApi(async (api) => {
2266
+ const taskIds = await Promise.all(
2267
+ taskRefs.map((ref) => resolveTaskId(api, ref))
2268
+ );
2269
+ return api.deleteTasks({ taskIds });
2270
+ }),
2271
+ printJson,
2272
+ printTable
2273
+ }
2274
+ );
2275
+ });
2276
+ task.command("update").argument("<ref>").option("--title <title>", "new title").addOption(
2277
+ new Option(
2278
+ "--status <status>",
2279
+ `new status (${taskStatusChoices.join("|")})`
2280
+ ).choices([...taskStatusChoices])
2281
+ ).addOption(
2282
+ new Option(
2283
+ "--priority <priority>",
2284
+ `new priority (${taskPriorityChoices.join("|")})`
2285
+ ).choices([...taskPriorityChoices])
2286
+ ).option("--deadline <deadline>", "ISO deadline").option("--expected-time <minutes>", "expected minutes").option("--actual-time <minutes>", "actual minutes").option("--json", "print JSON output").action(
2287
+ async (ref, options) => {
2288
+ await runTaskUpdate(
2289
+ {
2290
+ ref,
2291
+ title: options.title,
2292
+ status: options.status,
2293
+ priority: options.priority,
2294
+ deadline: options.deadline,
2295
+ expectedTimeTaken: options.expectedTime,
2296
+ actualTimeTaken: options.actualTime,
2297
+ json: Boolean(options.json)
2298
+ },
2299
+ {
2300
+ updateTask: (input) => withCliApi(
2301
+ async (api) => api.updateTask({
2302
+ taskId: await resolveTaskId(api, String(input.ref)),
2303
+ title: input.title,
2304
+ status: normalizeStatus(input.status),
2305
+ priority: normalizePriority(input.priority),
2306
+ deadline: input.deadline ? new Date(String(input.deadline)) : void 0,
2307
+ expectedTimeTaken: input.expectedTimeTaken ? Number(input.expectedTimeTaken) : void 0,
2308
+ actualTimeTaken: input.actualTimeTaken ? Number(input.actualTimeTaken) : void 0
2309
+ })
2310
+ ),
2311
+ printJson,
2312
+ printTable
2313
+ }
2314
+ );
2315
+ }
2316
+ );
2317
+ task.command("archive").argument("<ref>").option("--undo", "unarchive the task instead").option("--json", "print JSON output").action(
2318
+ async (ref, options) => {
2319
+ await runTaskArchive(
2320
+ {
2321
+ ref,
2322
+ undo: options.undo,
2323
+ json: Boolean(options.json)
2324
+ },
2325
+ {
2326
+ updateTask: (input) => withCliApi(
2327
+ async (api) => input.archivedAt === null ? api.unarchiveTask({
2328
+ taskId: await resolveTaskId(api, String(input.ref))
2329
+ }) : api.archiveTask({
2330
+ taskId: await resolveTaskId(api, String(input.ref))
2331
+ })
2332
+ ),
2333
+ printJson,
2334
+ printTable
2335
+ }
2336
+ );
2337
+ }
2338
+ );
2339
+ task.command("update-many").argument("<refs...>").addOption(
2340
+ new Option(
2341
+ "--status <status>",
2342
+ `new status (${taskStatusChoices.join("|")})`
2343
+ ).choices([...taskStatusChoices])
2344
+ ).addOption(
2345
+ new Option(
2346
+ "--priority <priority>",
2347
+ `new priority (${taskPriorityChoices.join("|")})`
2348
+ ).choices([...taskPriorityChoices])
2349
+ ).option("--deadline <deadline>", "ISO deadline").option("--expected-time <minutes>", "expected minutes").option("--actual-time <minutes>", "actual minutes").option("--archive", "archive the tasks").option("--unarchive", "unarchive the tasks").option("--parent <ref>", 'move tasks under the given parent or "root"').option("--preview", "preview the bulk update without mutating").option("--json", "print JSON output").action(
2350
+ async (refs, options) => {
2351
+ await runTaskUpdateMany(
2352
+ {
2353
+ refs,
2354
+ status: options.status,
2355
+ priority: options.priority,
2356
+ deadline: options.deadline,
2357
+ expectedTimeTaken: options.expectedTime,
2358
+ actualTimeTaken: options.actualTime,
2359
+ archivedAt: options.archive ? /* @__PURE__ */ new Date() : options.unarchive ? null : void 0,
2360
+ parentRef: options.parent,
2361
+ preview: Boolean(options.preview),
2362
+ json: Boolean(options.json)
2363
+ },
2364
+ {
2365
+ updateManyTasks: (input) => withCliApi(async (api) => {
2366
+ const taskIds = await Promise.all(
2367
+ input.refs.map((ref) => resolveTaskId(api, ref))
2368
+ );
2369
+ const normalizedParentRef = input.parentRef?.toLowerCase() === "root" ? null : input.parentRef;
2370
+ return api.updateManyTasks({
2371
+ taskIds,
2372
+ status: normalizeStatus(input.status),
2373
+ priority: normalizePriority(input.priority),
2374
+ deadline: input.deadline ? new Date(String(input.deadline)) : void 0,
2375
+ expectedTimeTaken: input.expectedTimeTaken ? Number(input.expectedTimeTaken) : void 0,
2376
+ actualTimeTaken: input.actualTimeTaken ? Number(input.actualTimeTaken) : void 0,
2377
+ archivedAt: input.archivedAt,
2378
+ parentId: normalizedParentRef === void 0 ? void 0 : normalizedParentRef === null ? null : await resolveTaskId(api, normalizedParentRef)
2379
+ });
2380
+ }),
2381
+ previewManyTasks: (input) => withCliApi(async (api) => {
2382
+ const taskIds = await Promise.all(
2383
+ input.refs.map((ref) => resolveTaskId(api, ref))
2384
+ );
2385
+ const normalizedParentRef = input.parentRef?.toLowerCase() === "root" ? null : input.parentRef;
2386
+ return api.previewManyTasks({
2387
+ taskIds,
2388
+ status: normalizeStatus(input.status),
2389
+ priority: normalizePriority(input.priority),
2390
+ deadline: input.deadline ? new Date(String(input.deadline)) : void 0,
2391
+ expectedTimeTaken: input.expectedTimeTaken ? Number(input.expectedTimeTaken) : void 0,
2392
+ actualTimeTaken: input.actualTimeTaken ? Number(input.actualTimeTaken) : void 0,
2393
+ archivedAt: input.archivedAt,
2394
+ parentId: normalizedParentRef === void 0 ? void 0 : normalizedParentRef === null ? null : await resolveTaskId(api, normalizedParentRef)
2395
+ });
2396
+ }),
2397
+ printJson,
2398
+ printTable
2399
+ }
2400
+ );
2401
+ }
2402
+ );
2403
+ const cleanup = addGroupHelpAction(
2404
+ task.command("cleanup").description("Cleanup plan commands")
2405
+ );
2406
+ cleanup.command("relocate-and-collapse").description("Move surviving direct children out of a wrapper and collapse it if emptied").requiredOption("--wrapper <ref>", "wrapper task to clean up").requiredOption("--tasks <refs...>", "surviving direct child tasks to move").requiredOption("--to <ref>", 'destination parent task or "root"').option("--preview", "preview the workflow without mutating (default)").option("--yes", "apply the workflow immediately").option("--json", "print JSON output").addHelpText(
2407
+ "after",
2408
+ [
2409
+ "",
2410
+ "Examples:",
2411
+ ' pnpm cli task cleanup relocate-and-collapse --wrapper "Old wrapper" --tasks 42 43 --to "Canonical branch"',
2412
+ " pnpm cli task cleanup relocate-and-collapse --wrapper 100 --tasks 101 --to root --yes --json"
2413
+ ].join("\n")
2414
+ ).action(
2415
+ async (options) => {
2416
+ await withCliApi(
2417
+ async (api) => runTaskCleanupRelocateCollapse(
2418
+ {
2419
+ wrapper: options.wrapper,
2420
+ tasks: options.tasks,
2421
+ to: options.to,
2422
+ preview: Boolean(options.preview),
2423
+ yes: Boolean(options.yes),
2424
+ json: Boolean(options.json)
2425
+ },
2426
+ {
2427
+ resolveTaskRef: (ref) => resolveTaskId(api, ref),
2428
+ listActiveDirectChildren: ({ wrapperId, cursor }) => api.listTasks({
2429
+ parentTaskId: wrapperId,
2430
+ archived: "active",
2431
+ limit: 100,
2432
+ cursor
2433
+ }),
2434
+ previewCleanupPlan: (input) => api.previewCleanupPlan(input),
2435
+ applyCleanupPlan: (input) => api.applyCleanupPlan(input),
2436
+ printJson,
2437
+ printTable
2438
+ }
2439
+ )
2440
+ );
2441
+ }
2442
+ );
2443
+ cleanup.command("preview").option("--plan <json>", "inline cleanup plan JSON").option("--plan-file <path>", "path to a cleanup plan JSON file").option("--json", "print JSON output").addHelpText(
2444
+ "after",
2445
+ [
2446
+ "",
2447
+ "Examples:",
2448
+ ` pnpm cli task cleanup preview --plan '{"operations":[{"type":"archive","taskIds":[42]}]}'`,
2449
+ " pnpm cli task cleanup preview --plan-file /tmp/cleanup-plan.json --json"
2450
+ ].join("\n")
2451
+ ).action(
2452
+ async (options) => {
2453
+ await runTaskCleanupPreview(
2454
+ {
2455
+ plan: options.plan,
2456
+ planFile: options.planFile,
2457
+ json: Boolean(options.json)
2458
+ },
2459
+ {
2460
+ previewCleanupPlan: (input) => withCliApi((api) => api.previewCleanupPlan(input)),
2461
+ printJson,
2462
+ printTable
2463
+ }
2464
+ );
2465
+ }
2466
+ );
2467
+ cleanup.command("apply").option("--plan <json>", "inline cleanup plan JSON").option("--plan-file <path>", "path to a cleanup plan JSON file").option("--yes", "skip confirmation").option("--json", "print JSON output").addHelpText(
2468
+ "after",
2469
+ [
2470
+ "",
2471
+ "Examples:",
2472
+ ` pnpm cli task cleanup apply --plan '{"operations":[{"type":"archive","taskIds":[42]}]}' --yes`,
2473
+ " pnpm cli task cleanup apply --plan-file /tmp/cleanup-plan.json --json --yes"
2474
+ ].join("\n")
2475
+ ).action(
2476
+ async (options) => {
2477
+ await runTaskCleanupApply(
2478
+ {
2479
+ plan: options.plan,
2480
+ planFile: options.planFile,
2481
+ yes: Boolean(options.yes),
2482
+ json: Boolean(options.json)
2483
+ },
2484
+ {
2485
+ isTty: Boolean(process.stdout.isTTY),
2486
+ confirm: (message) => confirmAction(message, {
2487
+ isTty: Boolean(process.stdout.isTTY),
2488
+ readLine: promptLine
2489
+ }),
2490
+ applyCleanupPlan: (input) => withCliApi((api) => api.applyCleanupPlan(input)),
2491
+ printJson,
2492
+ printTable
2493
+ }
2494
+ );
2495
+ }
2496
+ );
2497
+ const dep = addGroupHelpAction(
2498
+ program.command("dep").description("Dependency commands")
2499
+ );
2500
+ dep.command("add").argument("<taskRef>").argument("<blockedByRef>").option("--json", "print JSON output").action(
2501
+ async (taskRef, blockedByRef, options) => {
2502
+ await runDependencyAdd(
2503
+ {
2504
+ taskRef,
2505
+ blockedByRef,
2506
+ json: Boolean(options.json)
2507
+ },
2508
+ {
2509
+ addDependency: (task2, blocker) => withCliApi(
2510
+ async (api) => api.addDependency({
2511
+ taskId: await resolveTaskId(api, task2),
2512
+ blockedByTaskId: await resolveTaskId(api, blocker)
2513
+ })
2514
+ ),
2515
+ printJson,
2516
+ printTable
2517
+ }
2518
+ );
2519
+ }
2520
+ );
2521
+ dep.command("remove").argument("<taskRef>").argument("<blockedByRef>").option("--json", "print JSON output").action(
2522
+ async (taskRef, blockedByRef, options) => {
2523
+ await runDependencyRemove(
2524
+ {
2525
+ taskRef,
2526
+ blockedByRef,
2527
+ json: Boolean(options.json)
2528
+ },
2529
+ {
2530
+ removeDependency: (task2, blocker) => withCliApi(
2531
+ async (api) => api.removeDependency({
2532
+ taskId: await resolveTaskId(api, task2),
2533
+ blockedByTaskId: await resolveTaskId(api, blocker)
2534
+ })
2535
+ ),
2536
+ printJson,
2537
+ printTable
2538
+ }
2539
+ );
2540
+ }
2541
+ );
2542
+ dep.command("list").argument("<taskRef>").option("--json", "print JSON output").action(async (taskRef, options) => {
2543
+ await runDependencyList(
2544
+ {
2545
+ taskRef,
2546
+ json: Boolean(options.json)
2547
+ },
2548
+ {
2549
+ listDependencies: (ref) => withCliApi(
2550
+ async (api) => api.listDependencies({
2551
+ taskId: await resolveTaskId(api, ref)
2552
+ })
2553
+ ),
2554
+ printJson,
2555
+ printTable
2556
+ }
2557
+ );
2558
+ });
2559
+ const note = addGroupHelpAction(
2560
+ program.command("note").description("Note commands")
2561
+ );
2562
+ addTaskNoteCommands(note);
2563
+ return program;
2564
+ }
2565
+ function isTopLevelHelpRequest(argv) {
2566
+ const args = argv.slice(2);
2567
+ if (args.length === 0) return true;
2568
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
2569
+ return true;
2570
+ }
2571
+ if (args.length === 1 && args[0] === "help") {
2572
+ return true;
2573
+ }
2574
+ return false;
2575
+ }
2576
+ async function runCli(argv) {
2577
+ const cli = buildCli();
2578
+ if (isTopLevelHelpRequest(argv)) {
2579
+ process.stdout.write(getCliBanner());
2580
+ cli.outputHelp();
2581
+ return 0;
2582
+ }
2583
+ await cli.parseAsync(argv);
2584
+ return 0;
2585
+ }
2586
+ function formatCliError(error) {
2587
+ if (error instanceof Error) {
2588
+ return error.message;
2589
+ }
2590
+ return String(error);
2591
+ }
2592
+ function isCliEntrypoint(invokedPath, moduleUrl) {
2593
+ if (!invokedPath) {
2594
+ return false;
2595
+ }
2596
+ try {
2597
+ const invokedRealPath = pathToFileURL(realpathSync(invokedPath)).href;
2598
+ const moduleRealPath = pathToFileURL(
2599
+ realpathSync(fileURLToPath(moduleUrl))
2600
+ ).href;
2601
+ return invokedRealPath === moduleRealPath;
2602
+ } catch {
2603
+ return pathToFileURL(invokedPath).href === moduleUrl;
2604
+ }
2605
+ }
2606
+ if (isCliEntrypoint(process.argv[1], import.meta.url)) {
2607
+ void runCli(process.argv).then((exitCode) => {
2608
+ process.exitCode = exitCode;
2609
+ }).catch((error) => {
2610
+ process.stderr.write(`${formatCliError(error)}
2611
+ `);
2612
+ process.exitCode = 1;
2613
+ });
2614
+ }
2615
+ export {
2616
+ buildCli,
2617
+ isCliEntrypoint,
2618
+ resolveTaskRefFromSearchMatches,
2619
+ runCli
2620
+ };
2621
+ //# sourceMappingURL=index.js.map