soltask 0.0.0-stage → 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.
@@ -0,0 +1,736 @@
1
+ import { resolve } from "node:path";
2
+ import { HACKATHON_DRAFTER_HINT, PRIORITIES, TASK_KINDS, generateDraftId, hackathonDrafters, preflightNewTask, splitDraftBody, } from "../domain.js";
3
+ import { CliError, EXIT_CONFLICT, EXIT_OK, EXIT_RUNTIME, EXIT_VALIDATION } from "../errors.js";
4
+ import { readUtf8File } from "../fsutil.js";
5
+ import { displayText, emitJson, errOut, formatTable, formatTimestamp, out } from "../output.js";
6
+ import { nonEmptyString, splitCsvList, stripControls } from "../util.js";
7
+ import { PROGRAM } from "../version.js";
8
+ export const MAX_DRAFT_BYTES = 65_536;
9
+ export const MAX_TITLE_CHARS = 200;
10
+ export const MAX_BODY_CHARS = 60_000;
11
+ export const DRAFT_ID_RE = /^[\w-]{16}$/;
12
+ export const MAX_LABELS = 10;
13
+ export const MAX_LABEL_LEN = 40;
14
+ const OFFLINE_BLOCKER_SUFFIX = " is down. Send it once the agent is back.";
15
+ async function readStdinText(stream, maxBytes = MAX_DRAFT_BYTES) {
16
+ const chunks = [];
17
+ let total = 0;
18
+ for await (const chunk of stream) {
19
+ const buf = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : Buffer.from(chunk);
20
+ total += buf.byteLength;
21
+ if (total > maxBytes) {
22
+ throw new CliError(`Stdin input exceeds the ${maxBytes}-byte limit.`, { exitCode: EXIT_VALIDATION });
23
+ }
24
+ chunks.push(buf);
25
+ }
26
+ try {
27
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)).replace(/\r\n?/g, "\n");
28
+ }
29
+ catch {
30
+ throw new CliError("Stdin input is not valid UTF-8.", { exitCode: EXIT_VALIDATION });
31
+ }
32
+ }
33
+ async function readBodyInput(ctx) {
34
+ const rawBody = ctx.opt("body");
35
+ const bodyFile = ctx.opt("body-file");
36
+ const bodyStdin = ctx.flag("body-stdin");
37
+ const count = (rawBody !== undefined ? 1 : 0) + (bodyFile !== undefined ? 1 : 0) + (bodyStdin ? 1 : 0);
38
+ if (count > 1) {
39
+ throw new CliError("Pass only one of --body, --body-file, or --body-stdin.", { exitCode: EXIT_VALIDATION });
40
+ }
41
+ if (rawBody !== undefined) {
42
+ return { provided: true, text: rawBody.replace(/\r\n?/g, "\n") };
43
+ }
44
+ if (bodyFile !== undefined) {
45
+ const trimmedPath = bodyFile.trim();
46
+ if (trimmedPath === "") {
47
+ throw new CliError("--body-file requires a file path.", { exitCode: EXIT_VALIDATION });
48
+ }
49
+ return { provided: true, text: readUtf8File(resolve(ctx.io.cwd, trimmedPath), MAX_DRAFT_BYTES) };
50
+ }
51
+ if (bodyStdin) {
52
+ return { provided: true, text: await readStdinText(ctx.io.stdin, MAX_DRAFT_BYTES) };
53
+ }
54
+ return { provided: false, text: "" };
55
+ }
56
+ async function fetchDrafts(client) {
57
+ const res = await client.request("GET", "/api/drafts");
58
+ if (!Array.isArray(res.body.drafts)) {
59
+ throw new CliError('Unexpected /api/drafts response: "drafts" is missing.', { exitCode: EXIT_RUNTIME });
60
+ }
61
+ return res.body.drafts;
62
+ }
63
+ function resolveDraftId(ref, drafts) {
64
+ const trimmed = ref.trim();
65
+ if (trimmed === "") {
66
+ throw new CliError("Draft ID cannot be empty.", { exitCode: EXIT_VALIDATION });
67
+ }
68
+ const exact = drafts.find((draft) => draft.id === trimmed);
69
+ if (exact !== undefined) {
70
+ return exact;
71
+ }
72
+ if (trimmed.length >= 6) {
73
+ const matches = drafts.filter((draft) => draft.id.startsWith(trimmed));
74
+ if (matches.length === 1) {
75
+ const only = matches[0];
76
+ if (only !== undefined) {
77
+ return only;
78
+ }
79
+ }
80
+ if (matches.length > 1) {
81
+ const ids = matches.map((draft) => draft.id).join(", ");
82
+ throw new CliError(`Ambiguous draft ID prefix '${trimmed}'; matches: ${ids}.`, {
83
+ exitCode: EXIT_VALIDATION,
84
+ payload: { ok: false, error: "ambiguous_draft_id", message: `Ambiguous draft ID prefix '${trimmed}'.` },
85
+ });
86
+ }
87
+ }
88
+ throw new CliError(`Draft not found: ${trimmed}`, {
89
+ exitCode: EXIT_RUNTIME,
90
+ payload: { ok: false, error: "not_found", status: 404, message: `Draft not found: ${trimmed}` },
91
+ });
92
+ }
93
+ async function resolveTargetCommunity(ctx) {
94
+ const configured = ctx.community();
95
+ if (configured !== undefined) {
96
+ return configured;
97
+ }
98
+ const communities = await ctx.client().communities();
99
+ if (communities.length === 1) {
100
+ const only = communities[0];
101
+ if (only !== undefined) {
102
+ return only.id;
103
+ }
104
+ }
105
+ if (communities.length === 0) {
106
+ throw new CliError("No communities are configured on the server. Specify --community ID.", {
107
+ exitCode: EXIT_VALIDATION,
108
+ });
109
+ }
110
+ const available = communities.map((community) => community.id).join(", ");
111
+ throw new CliError(`Multiple communities available (${available}). Specify --community ID or set SOLTASK_COMMUNITY.`, {
112
+ exitCode: EXIT_VALIDATION,
113
+ });
114
+ }
115
+ function validateDraftSize(text) {
116
+ if (text === "") {
117
+ throw new CliError("Draft content cannot be empty.", { exitCode: EXIT_VALIDATION });
118
+ }
119
+ if (Buffer.byteLength(text, "utf8") > MAX_DRAFT_BYTES) {
120
+ throw new CliError(`Draft content exceeds the ${MAX_DRAFT_BYTES}-byte limit.`, { exitCode: EXIT_VALIDATION });
121
+ }
122
+ }
123
+ function validateLabels(labels) {
124
+ if (labels.length > MAX_LABELS) {
125
+ throw new CliError(`At most ${MAX_LABELS} labels are allowed (got ${labels.length}).`, {
126
+ exitCode: EXIT_VALIDATION,
127
+ });
128
+ }
129
+ for (const label of labels) {
130
+ if (label.length === 0 || label.length > MAX_LABEL_LEN) {
131
+ throw new CliError(`Each label must be 1..${MAX_LABEL_LEN} characters (got '${label}').`, {
132
+ exitCode: EXIT_VALIDATION,
133
+ });
134
+ }
135
+ }
136
+ }
137
+ function validateTaskTextLimits(title, body) {
138
+ if (title.length > MAX_TITLE_CHARS) {
139
+ throw new CliError(`Draft title exceeds the ${MAX_TITLE_CHARS}-character limit (got ${title.length}).`, {
140
+ exitCode: EXIT_VALIDATION,
141
+ });
142
+ }
143
+ if (body.length > MAX_BODY_CHARS) {
144
+ throw new CliError(`Draft body exceeds the ${MAX_BODY_CHARS}-character limit (got ${body.length}).`, {
145
+ exitCode: EXIT_VALIDATION,
146
+ });
147
+ }
148
+ }
149
+ function isOfflineBlocker(blocker) {
150
+ return blocker.endsWith(OFFLINE_BLOCKER_SUFFIX);
151
+ }
152
+ /** `draft list`: lists backlog drafts with optional community and text filters. */
153
+ export async function cmdDraftList(ctx) {
154
+ const drafts = await fetchDrafts(ctx.client());
155
+ const showAll = ctx.flag("all");
156
+ const targetCommunity = showAll ? undefined : ctx.community();
157
+ const query = nonEmptyString(ctx.opt("q"))?.toLowerCase();
158
+ const filtered = drafts.filter((draft) => {
159
+ if (targetCommunity !== undefined && draft.community !== targetCommunity) {
160
+ return false;
161
+ }
162
+ if (query !== undefined) {
163
+ const haystacks = [draft.id, draft.community, draft.body];
164
+ if (!haystacks.some((value) => value.toLowerCase().includes(query))) {
165
+ return false;
166
+ }
167
+ }
168
+ return true;
169
+ });
170
+ const enriched = filtered.map((draft) => {
171
+ const { title } = splitDraftBody(draft.body);
172
+ return { ...draft, title };
173
+ });
174
+ if (ctx.global.json) {
175
+ emitJson({ drafts: enriched, total: enriched.length });
176
+ return EXIT_OK;
177
+ }
178
+ if (enriched.length === 0) {
179
+ out("No drafts found.");
180
+ return EXIT_OK;
181
+ }
182
+ out(formatTable(["ID", "COMMUNITY", "STATUS", "TITLE", "UPDATED"], enriched.map((draft) => [
183
+ draft.id,
184
+ draft.community,
185
+ draft.delivery !== undefined ? "pending delivery" : "draft",
186
+ draft.title,
187
+ formatTimestamp(draft.updatedAt),
188
+ ])));
189
+ return EXIT_OK;
190
+ }
191
+ /** `draft show <DRAFT_ID>`: displays metadata and sanitized body for a single draft. */
192
+ export async function cmdDraftShow(ctx) {
193
+ const ref = ctx.positionals[0] ?? "";
194
+ const drafts = await fetchDrafts(ctx.client());
195
+ const draft = resolveDraftId(ref, drafts);
196
+ const { title, body } = splitDraftBody(draft.body);
197
+ if (ctx.global.json) {
198
+ emitJson({ draft, title, body });
199
+ return EXIT_OK;
200
+ }
201
+ out(`ID: ${displayText(draft.id)}`);
202
+ out(`Community: ${displayText(draft.community)}`);
203
+ out(`Status: ${draft.delivery !== undefined ? "pending delivery" : "draft"}`);
204
+ if (draft.delivery !== undefined) {
205
+ out(`Delivery: channel=${displayText(draft.delivery.channel)}, entry=${displayText(draft.delivery.entry)}`);
206
+ }
207
+ out(`Created: ${formatTimestamp(draft.createdAt)}`);
208
+ out(`Updated: ${formatTimestamp(draft.updatedAt)}`);
209
+ out(`Title: ${displayText(title)}`);
210
+ if (body !== "") {
211
+ out("");
212
+ out(stripControls(body));
213
+ }
214
+ return EXIT_OK;
215
+ }
216
+ /** `draft create`: creates a new backlog draft in the target community. */
217
+ export async function cmdDraftCreate(ctx) {
218
+ const rawTitle = ctx.opt("title");
219
+ const explicitId = ctx.opt("id");
220
+ if (explicitId !== undefined && !DRAFT_ID_RE.test(explicitId)) {
221
+ throw new CliError("--id must be a 16-character base64url draft ID.", { exitCode: EXIT_VALIDATION });
222
+ }
223
+ const bodyInput = await readBodyInput(ctx);
224
+ const cleanTitle = rawTitle?.trim() ?? "";
225
+ if (rawTitle !== undefined && cleanTitle === "") {
226
+ throw new CliError("--title cannot be empty.", { exitCode: EXIT_VALIDATION });
227
+ }
228
+ const cleanBody = bodyInput.provided ? bodyInput.text.trim() : "";
229
+ let draftBody;
230
+ if (cleanTitle !== "" && cleanBody !== "") {
231
+ draftBody = `${cleanTitle}\n\n${cleanBody}`;
232
+ }
233
+ else if (cleanTitle !== "") {
234
+ draftBody = cleanTitle;
235
+ }
236
+ else {
237
+ draftBody = cleanBody;
238
+ }
239
+ validateDraftSize(draftBody);
240
+ const { title, body } = splitDraftBody(draftBody);
241
+ const community = await resolveTargetCommunity(ctx);
242
+ if (ctx.global.dryRun) {
243
+ const previewId = explicitId ?? generateDraftId();
244
+ const plan = {
245
+ ok: true,
246
+ dry_run: true,
247
+ action: "draft.create",
248
+ community,
249
+ id: previewId,
250
+ title,
251
+ body,
252
+ };
253
+ if (ctx.global.json) {
254
+ emitJson(plan);
255
+ }
256
+ else {
257
+ out(`Dry run: would create draft ${displayText(previewId)} in ${displayText(community)}: ${displayText(title)}`);
258
+ }
259
+ return EXIT_OK;
260
+ }
261
+ const payload = {
262
+ community,
263
+ body: draftBody,
264
+ ...(explicitId === undefined ? {} : { id: explicitId }),
265
+ };
266
+ const res = await ctx.client().request("POST", "/api/drafts", { jsonBody: payload });
267
+ const createdId = nonEmptyString(res.body.id) ?? explicitId;
268
+ if (createdId === undefined) {
269
+ throw new CliError('Unexpected POST /api/drafts response: "id" is missing.', { exitCode: EXIT_RUNTIME });
270
+ }
271
+ if (ctx.global.json) {
272
+ emitJson({ ok: true, id: createdId, community, title });
273
+ }
274
+ else {
275
+ out(`Created draft ${displayText(createdId)} in ${displayText(community)}: ${displayText(title)}`);
276
+ }
277
+ return EXIT_OK;
278
+ }
279
+ /** `draft update <DRAFT_ID>`: updates an existing backlog draft's title and/or body. */
280
+ export async function cmdDraftUpdate(ctx) {
281
+ const ref = ctx.positionals[0] ?? "";
282
+ const rawTitle = ctx.opt("title");
283
+ const replace = ctx.flag("replace");
284
+ const bodyInput = await readBodyInput(ctx);
285
+ if (rawTitle === undefined && !bodyInput.provided) {
286
+ throw new CliError("Provide at least one of --title, --body, --body-file, or --body-stdin.", {
287
+ exitCode: EXIT_VALIDATION,
288
+ });
289
+ }
290
+ if (replace && rawTitle !== undefined) {
291
+ throw new CliError("Cannot combine --replace with --title.", { exitCode: EXIT_VALIDATION });
292
+ }
293
+ if (replace && !bodyInput.provided) {
294
+ throw new CliError("--replace requires one of --body, --body-file, or --body-stdin.", {
295
+ exitCode: EXIT_VALIDATION,
296
+ });
297
+ }
298
+ if (rawTitle?.trim() === "") {
299
+ throw new CliError("--title cannot be empty.", { exitCode: EXIT_VALIDATION });
300
+ }
301
+ const client = ctx.client();
302
+ const drafts = await fetchDrafts(client);
303
+ const existing = resolveDraftId(ref, drafts);
304
+ if (existing.delivery !== undefined) {
305
+ const message = `Draft '${existing.id}' is waiting for delivery confirmation and cannot be edited. Use '${PROGRAM} draft retry ${existing.id}'.`;
306
+ throw new CliError(message, {
307
+ exitCode: EXIT_CONFLICT,
308
+ payload: { ok: false, error: "draft_pending_delivery", message },
309
+ });
310
+ }
311
+ let updatedBody;
312
+ if (replace) {
313
+ updatedBody = bodyInput.text.trim();
314
+ }
315
+ else {
316
+ const parts = splitDraftBody(existing.body);
317
+ const nextTitle = rawTitle !== undefined ? rawTitle.trim() : parts.title.trim();
318
+ const nextBody = bodyInput.provided ? bodyInput.text.trim() : parts.body;
319
+ if (nextTitle === "") {
320
+ throw new CliError("Draft title cannot be empty.", { exitCode: EXIT_VALIDATION });
321
+ }
322
+ updatedBody = nextBody !== "" ? `${nextTitle}\n\n${nextBody}` : nextTitle;
323
+ }
324
+ validateDraftSize(updatedBody);
325
+ const { title: newTitle, body: newBody } = splitDraftBody(updatedBody);
326
+ if (ctx.global.dryRun) {
327
+ const plan = {
328
+ ok: true,
329
+ dry_run: true,
330
+ action: "draft.update",
331
+ id: existing.id,
332
+ community: existing.community,
333
+ title: newTitle,
334
+ body: newBody,
335
+ };
336
+ if (ctx.global.json) {
337
+ emitJson(plan);
338
+ }
339
+ else {
340
+ out(`Dry run: would update draft ${displayText(existing.id)} in ${displayText(existing.community)}: ${displayText(newTitle)}`);
341
+ }
342
+ return EXIT_OK;
343
+ }
344
+ await client.request("PUT", `/api/drafts/${encodeURIComponent(existing.id)}`, {
345
+ jsonBody: { body: updatedBody },
346
+ });
347
+ if (ctx.global.json) {
348
+ emitJson({ ok: true, id: existing.id, community: existing.community, title: newTitle });
349
+ }
350
+ else {
351
+ out(`Updated draft ${displayText(existing.id)}: ${displayText(newTitle)}`);
352
+ }
353
+ return EXIT_OK;
354
+ }
355
+ /** `draft delete <DRAFT_ID>`: deletes a backlog draft directly without prompting. */
356
+ export async function cmdDraftDelete(ctx) {
357
+ const ref = ctx.positionals[0] ?? "";
358
+ const client = ctx.client();
359
+ const drafts = await fetchDrafts(client);
360
+ const existing = resolveDraftId(ref, drafts);
361
+ if (existing.delivery !== undefined) {
362
+ const message = `Draft '${existing.id}' is waiting for delivery confirmation and cannot be deleted. Use '${PROGRAM} draft retry ${existing.id}'.`;
363
+ throw new CliError(message, {
364
+ exitCode: EXIT_CONFLICT,
365
+ payload: { ok: false, error: "draft_pending_delivery", message },
366
+ });
367
+ }
368
+ if (ctx.global.dryRun) {
369
+ const plan = {
370
+ ok: true,
371
+ dry_run: true,
372
+ action: "draft.delete",
373
+ id: existing.id,
374
+ community: existing.community,
375
+ };
376
+ if (ctx.global.json) {
377
+ emitJson(plan);
378
+ }
379
+ else {
380
+ out(`Dry run: would delete draft ${displayText(existing.id)} in ${displayText(existing.community)}.`);
381
+ }
382
+ return EXIT_OK;
383
+ }
384
+ await client.request("DELETE", `/api/drafts/${encodeURIComponent(existing.id)}`);
385
+ if (ctx.global.json) {
386
+ emitJson({ ok: true, deleted: true, id: existing.id, community: existing.community });
387
+ }
388
+ else {
389
+ out(`Deleted draft ${displayText(existing.id)}.`);
390
+ }
391
+ return EXIT_OK;
392
+ }
393
+ /** `draft send <DRAFT_ID>`: preflights and sends a draft as a new task, applying optional priority and labels. */
394
+ export async function cmdDraftSend(ctx) {
395
+ const ref = ctx.positionals[0] ?? "";
396
+ const kind = ctx.opt("kind");
397
+ const channelSelector = ctx.opt("channel");
398
+ const entrySelector = ctx.opt("entry");
399
+ const priority = ctx.opt("priority");
400
+ const labels = splitCsvList([...ctx.optList("labels"), ...ctx.optList("label")]);
401
+ const force = ctx.flag("force");
402
+ validateLabels(labels);
403
+ const client = ctx.client();
404
+ const drafts = await fetchDrafts(client);
405
+ const draft = resolveDraftId(ref, drafts);
406
+ const { title, body } = splitDraftBody(draft.body);
407
+ const cleanTitle = title.trim();
408
+ const cleanBody = body.trim();
409
+ validateTaskTextLimits(cleanTitle, cleanBody);
410
+ const communities = ctx.global.waitLive
411
+ ? (await client.waitUntilLive([draft.community])).communities
412
+ : await client.communities();
413
+ const communityView = communities.find((community) => community.id === draft.community);
414
+ const channels = communityView?.channels ?? [];
415
+ const [agentsRes, tasksRes] = await Promise.all([
416
+ client.request("GET", "/api/agents", { query: { community: draft.community } }),
417
+ client.request("GET", "/api/tasks", { query: { community: draft.community } }),
418
+ ]);
419
+ const preflight = preflightNewTask({
420
+ community: draft.community,
421
+ title: cleanTitle,
422
+ body: cleanBody,
423
+ ...(kind === undefined ? {} : { kind }),
424
+ ...(channelSelector === undefined ? {} : { channel: channelSelector }),
425
+ ...(entrySelector === undefined ? {} : { entry: entrySelector }),
426
+ channels,
427
+ agents: agentsRes.body.agents,
428
+ tasks: tasksRes.body.tasks,
429
+ ...(draft.delivery === undefined ? {} : { delivery: draft.delivery }),
430
+ });
431
+ const warnings = [...preflight.warnings];
432
+ let effectiveBlockers;
433
+ if (force) {
434
+ let bypassedOffline = false;
435
+ effectiveBlockers = [];
436
+ for (const blocker of preflight.blockers) {
437
+ if (isOfflineBlocker(blocker)) {
438
+ bypassedOffline = true;
439
+ warnings.push(`${blocker} (bypassed with --force)`);
440
+ }
441
+ else {
442
+ effectiveBlockers.push(blocker);
443
+ }
444
+ }
445
+ // Preflight skips the hackathon drafter check when the entry agent is offline; re-run that structural check under --force.
446
+ if (bypassedOffline &&
447
+ draft.delivery === undefined &&
448
+ kind !== "implementation" &&
449
+ preflight.template?.id === "hackathons" &&
450
+ preflight.channel !== null) {
451
+ const message = cleanBody !== "" ? `${cleanTitle}\n\n${cleanBody}` : cleanTitle;
452
+ const [drafter, second] = hackathonDrafters(message);
453
+ if (drafter === undefined || second !== undefined) {
454
+ effectiveBlockers.push(HACKATHON_DRAFTER_HINT);
455
+ }
456
+ else {
457
+ const drafterAgent = agentsRes.body.agents.find((agent) => agent.id === drafter && agent.pubkey !== null);
458
+ if (!Object.hasOwn(preflight.channel.people, drafter) || drafterAgent === undefined) {
459
+ effectiveBlockers.push("The named drafter is unavailable in #hackathons.");
460
+ }
461
+ }
462
+ }
463
+ }
464
+ else {
465
+ effectiveBlockers = [...preflight.blockers];
466
+ }
467
+ if (!ctx.global.json) {
468
+ for (const warning of warnings) {
469
+ errOut(`Warning: ${displayText(warning)}`);
470
+ }
471
+ }
472
+ const effectivePriority = priority ?? "normal";
473
+ const shouldSetMeta = effectivePriority !== "normal" || labels.length > 0;
474
+ const taskPayload = {
475
+ community: draft.community,
476
+ channel: preflight.channel?.id ?? null,
477
+ entry: preflight.entry?.id ?? null,
478
+ title: cleanTitle,
479
+ body: cleanBody,
480
+ draftId: draft.id,
481
+ ...(kind !== undefined && draft.delivery === undefined ? { kind } : {}),
482
+ };
483
+ const metaPayload = shouldSetMeta
484
+ ? { priority: effectivePriority, labels }
485
+ : null;
486
+ if (ctx.global.dryRun) {
487
+ const dryDoc = {
488
+ ok: effectiveBlockers.length === 0,
489
+ dry_run: true,
490
+ draft_id: draft.id,
491
+ community: draft.community,
492
+ channel: preflight.channel === null ? null : { id: preflight.channel.id, slug: preflight.channel.slug },
493
+ entry: preflight.entry === null ? null : { id: preflight.entry.id, name: preflight.entry.name },
494
+ template: preflight.template?.id ?? null,
495
+ preview_text: preflight.previewText,
496
+ blockers: effectiveBlockers,
497
+ warnings,
498
+ payload: taskPayload,
499
+ meta: metaPayload,
500
+ };
501
+ if (ctx.global.json) {
502
+ emitJson(dryDoc);
503
+ }
504
+ else {
505
+ out(`Dry run: draft ${displayText(draft.id)} in ${displayText(draft.community)}`);
506
+ if (preflight.channel !== null) {
507
+ out(`Channel: #${displayText(preflight.channel.slug)} (${displayText(preflight.channel.id)})`);
508
+ }
509
+ if (preflight.entry !== null) {
510
+ out(`Entry: @${displayText(preflight.entry.name)} (${displayText(preflight.entry.id)})`);
511
+ }
512
+ if (preflight.template !== null) {
513
+ out(`Template: ${displayText(preflight.template.id)}`);
514
+ }
515
+ out(`Preview: ${stripControls(preflight.previewText)}`);
516
+ if (metaPayload !== null) {
517
+ const labelText = labels.length > 0 ? labels.map(displayText).join(", ") : "(none)";
518
+ out(`Meta: priority=${displayText(effectivePriority)}, labels=${labelText}`);
519
+ }
520
+ if (effectiveBlockers.length > 0) {
521
+ out("Blockers:");
522
+ for (const blocker of effectiveBlockers) {
523
+ out(` - ${displayText(blocker)}`);
524
+ }
525
+ }
526
+ }
527
+ return effectiveBlockers.length === 0 ? EXIT_OK : EXIT_VALIDATION;
528
+ }
529
+ if (effectiveBlockers.length > 0 || preflight.channel === null || preflight.entry === null) {
530
+ const reasons = effectiveBlockers.length > 0 ? effectiveBlockers : ["Unable to resolve channel or entry agent."];
531
+ const message = `Cannot send draft '${draft.id}': ${reasons.join(" ")}`;
532
+ throw new CliError(message, {
533
+ exitCode: EXIT_VALIDATION,
534
+ payload: {
535
+ ok: false,
536
+ error: "preflight_blocked",
537
+ message,
538
+ blockers: reasons,
539
+ warnings,
540
+ },
541
+ });
542
+ }
543
+ const createdRes = await client.request("POST", "/api/tasks", { jsonBody: taskPayload });
544
+ const key = nonEmptyString(createdRes.body.key);
545
+ const root = nonEmptyString(createdRes.body.root);
546
+ if (key === undefined || root === undefined) {
547
+ throw new CliError('Unexpected POST /api/tasks response: "key" or "root" is missing.', {
548
+ exitCode: EXIT_RUNTIME,
549
+ });
550
+ }
551
+ if (shouldSetMeta) {
552
+ await client.request("PUT", `/api/tasks/${encodeURIComponent(draft.community)}/${encodeURIComponent(root)}/meta`, { jsonBody: { priority: effectivePriority, labels } });
553
+ }
554
+ if (ctx.global.json) {
555
+ emitJson({
556
+ ok: true,
557
+ draft_id: draft.id,
558
+ key,
559
+ root,
560
+ community: draft.community,
561
+ channel: preflight.channel.slug,
562
+ entry: preflight.entry.id,
563
+ template: preflight.template?.id ?? null,
564
+ priority: effectivePriority,
565
+ labels,
566
+ warnings,
567
+ });
568
+ }
569
+ else {
570
+ out(`Sent draft ${displayText(draft.id)} as ${displayText(key)} (${displayText(root)}) ` +
571
+ `in ${displayText(draft.community)} #${displayText(preflight.channel.slug)} -> @${displayText(preflight.entry.name)}`);
572
+ }
573
+ return EXIT_OK;
574
+ }
575
+ /** `draft retry <DRAFT_ID>`: retries sending a draft that is waiting for delivery confirmation. */
576
+ export async function cmdDraftRetry(ctx) {
577
+ const ref = ctx.positionals[0] ?? "";
578
+ const client = ctx.client();
579
+ const drafts = await fetchDrafts(client);
580
+ const draft = resolveDraftId(ref, drafts);
581
+ if (draft.delivery === undefined) {
582
+ const message = `Draft '${draft.id}' is not waiting for delivery confirmation. Use '${PROGRAM} draft send ${draft.id}' instead.`;
583
+ throw new CliError(message, {
584
+ exitCode: EXIT_CONFLICT,
585
+ payload: { ok: false, error: "not_pending_delivery", message },
586
+ });
587
+ }
588
+ const { title, body } = splitDraftBody(draft.body);
589
+ const cleanTitle = title.trim();
590
+ const cleanBody = body.trim();
591
+ if (cleanTitle === "") {
592
+ throw new CliError("Draft title cannot be empty.", { exitCode: EXIT_VALIDATION });
593
+ }
594
+ validateTaskTextLimits(cleanTitle, cleanBody);
595
+ if (ctx.global.dryRun) {
596
+ const plan = {
597
+ ok: true,
598
+ dry_run: true,
599
+ action: "draft.retry",
600
+ draft_id: draft.id,
601
+ community: draft.community,
602
+ delivery: draft.delivery,
603
+ title: cleanTitle,
604
+ body: cleanBody,
605
+ };
606
+ if (ctx.global.json) {
607
+ emitJson(plan);
608
+ }
609
+ else {
610
+ out(`Dry run: would retry draft ${displayText(draft.id)} in ${displayText(draft.community)} ` +
611
+ `(channel=${displayText(draft.delivery.channel)}, entry=${displayText(draft.delivery.entry)}): ${displayText(cleanTitle)}`);
612
+ }
613
+ return EXIT_OK;
614
+ }
615
+ const createdRes = await client.request("POST", "/api/tasks", {
616
+ jsonBody: {
617
+ community: draft.community,
618
+ channel: draft.delivery.channel,
619
+ entry: draft.delivery.entry,
620
+ title: cleanTitle,
621
+ body: cleanBody,
622
+ draftId: draft.id,
623
+ },
624
+ });
625
+ const key = nonEmptyString(createdRes.body.key);
626
+ const root = nonEmptyString(createdRes.body.root);
627
+ if (key === undefined || root === undefined) {
628
+ throw new CliError('Unexpected POST /api/tasks response: "key" or "root" is missing.', {
629
+ exitCode: EXIT_RUNTIME,
630
+ });
631
+ }
632
+ if (ctx.global.json) {
633
+ emitJson({
634
+ ok: true,
635
+ draft_id: draft.id,
636
+ key,
637
+ root,
638
+ community: draft.community,
639
+ delivery: draft.delivery,
640
+ });
641
+ }
642
+ else {
643
+ out(`Retried draft ${displayText(draft.id)} -> ${displayText(key)} (${displayText(root)}) in ${displayText(draft.community)}`);
644
+ }
645
+ return EXIT_OK;
646
+ }
647
+ const DRAFT_LIST_OPTIONS = {
648
+ q: { type: "string", placeholder: "TEXT", description: "Filter by substring in draft ID, community, or body" },
649
+ all: { type: "boolean", description: "List drafts across all communities even when a default community is configured" },
650
+ };
651
+ const DRAFT_CREATE_OPTIONS = {
652
+ title: { type: "string", placeholder: "TEXT", description: "Draft title (first line)" },
653
+ body: { type: "string", placeholder: "TEXT", description: "Draft body text (or full markdown when --title is omitted)" },
654
+ "body-file": { type: "string", placeholder: "PATH", description: "Read draft body text from a UTF-8 file" },
655
+ "body-stdin": { type: "boolean", description: "Read draft body text from stdin" },
656
+ id: { type: "string", placeholder: "ID", description: "Explicit 16-character base64url draft ID" },
657
+ };
658
+ const DRAFT_UPDATE_OPTIONS = {
659
+ title: { type: "string", placeholder: "TEXT", description: "Update draft title (first line)" },
660
+ body: { type: "string", placeholder: "TEXT", description: "Update draft body text (or full markdown with --replace)" },
661
+ "body-file": { type: "string", placeholder: "PATH", description: "Read replacement text from a UTF-8 file" },
662
+ "body-stdin": { type: "boolean", description: "Read replacement text from stdin" },
663
+ replace: { type: "boolean", description: "Replace the entire draft markdown verbatim from the body source" },
664
+ };
665
+ const DRAFT_SEND_OPTIONS = {
666
+ kind: { type: "string", placeholder: "KIND", choices: Object.keys(TASK_KINDS), description: "Task workflow kind" },
667
+ channel: { type: "string", placeholder: "SELECTOR", description: "Target channel slug or ID" },
668
+ entry: { type: "string", placeholder: "AGENT", description: "Entry agent ID or display name" },
669
+ priority: { type: "string", placeholder: "LEVEL", choices: PRIORITIES, description: "Initial task priority" },
670
+ labels: { type: "string", placeholder: "CSV", multiple: true, description: "Comma-separated labels to apply after creation" },
671
+ label: { type: "string", placeholder: "LABEL", multiple: true, description: "Label to apply after creation (repeatable)" },
672
+ force: { type: "boolean", description: "Bypass soft preflight blockers such as an offline entry agent" },
673
+ };
674
+ const draftSubcommands = [
675
+ {
676
+ name: "list",
677
+ summary: "List backlog drafts",
678
+ usage: "draft list [--q TEXT] [--all]",
679
+ options: DRAFT_LIST_OPTIONS,
680
+ positionals: { min: 0, max: 0 },
681
+ handler: cmdDraftList,
682
+ },
683
+ {
684
+ name: "show",
685
+ summary: "Show one backlog draft",
686
+ usage: "draft show <DRAFT_ID>",
687
+ positionals: { min: 1, max: 1 },
688
+ handler: cmdDraftShow,
689
+ },
690
+ {
691
+ name: "create",
692
+ summary: "Create a new backlog draft",
693
+ usage: "draft create [--title TEXT] [--body TEXT | --body-file PATH | --body-stdin] [--id ID]",
694
+ options: DRAFT_CREATE_OPTIONS,
695
+ positionals: { min: 0, max: 0 },
696
+ handler: cmdDraftCreate,
697
+ },
698
+ {
699
+ name: "update",
700
+ summary: "Update an existing backlog draft",
701
+ usage: "draft update <DRAFT_ID> [--title TEXT] [--body TEXT | --body-file PATH | --body-stdin] [--replace]",
702
+ options: DRAFT_UPDATE_OPTIONS,
703
+ positionals: { min: 1, max: 1 },
704
+ handler: cmdDraftUpdate,
705
+ },
706
+ {
707
+ name: "delete",
708
+ summary: "Delete a backlog draft",
709
+ usage: "draft delete <DRAFT_ID>",
710
+ positionals: { min: 1, max: 1 },
711
+ handler: cmdDraftDelete,
712
+ },
713
+ {
714
+ name: "send",
715
+ summary: "Preflight and send a backlog draft as a new task",
716
+ usage: "draft send <DRAFT_ID> [--kind K] [--channel C] [--entry A] [--priority P] [--labels L] [--label L] [--force]",
717
+ options: DRAFT_SEND_OPTIONS,
718
+ positionals: { min: 1, max: 1 },
719
+ handler: cmdDraftSend,
720
+ },
721
+ {
722
+ name: "retry",
723
+ summary: "Retry sending a draft that is waiting for delivery confirmation",
724
+ usage: "draft retry <DRAFT_ID>",
725
+ positionals: { min: 1, max: 1 },
726
+ handler: cmdDraftRetry,
727
+ },
728
+ ];
729
+ export const draftCommands = [
730
+ {
731
+ name: "draft",
732
+ summary: "Manage backlog drafts (list, show, create, update, delete, send, retry)",
733
+ usage: "draft <list|show|create|update|delete|send|retry>",
734
+ subcommands: draftSubcommands,
735
+ },
736
+ ];