soltask 0.0.0-stage → 0.1.1

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/domain.js ADDED
@@ -0,0 +1,747 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { CliError, EXIT_RUNTIME, EXIT_VALIDATION } from "./errors.js";
3
+ export const COLUMNS = [
4
+ { id: "backlog", name: "Backlog", icon: "i-archive", hint: "Drafts nobody has sent to an agent yet." },
5
+ { id: "queued", name: "Queued", icon: "i-clock", hint: "Sent to the agent; its first answer has not come." },
6
+ { id: "working", name: "Agents working", icon: "i-bot", hint: "Agents are taking turns in the thread." },
7
+ { id: "needs", name: "Needs you", icon: "i-hand", hint: "A card, a question, or a decision is waiting on a person." },
8
+ { id: "shipping", name: "Shipping", icon: "i-merge", hint: "Approved: a machine merges, plans, and applies." },
9
+ { id: "done", name: "Done", icon: "i-ok", hint: "Saved, deployed, answered, or decided." },
10
+ ];
11
+ export const OPEN_COLUMNS = ["queued", "working", "needs", "shipping"];
12
+ export const PRIORITIES = ["low", "normal", "high", "urgent"];
13
+ export const TEMPLATES = {
14
+ brainstorm: {
15
+ id: "brainstorm",
16
+ name: "Brainstorm",
17
+ icon: "i-bulb",
18
+ channel: "brainstorm",
19
+ entry: "brainstorm-lead",
20
+ budget: 120,
21
+ blurb: "Brainstorm Lead's team frames the idea, debates it, and writes a brief. You decide whether to keep it.",
22
+ approver: "You, the requester: the thread's first author is the only person Machine Agent counts.",
23
+ outcome: "Machine Agent saves the session in docs/brainstorms/ through a merge request it opens and merges. Nothing deploys.",
24
+ stages: [
25
+ ["sent", "Sent", "queued"],
26
+ ["frame", "Frame", "working"],
27
+ ["r1", "Round 1", "working"],
28
+ ["r2", "Debate", "working"],
29
+ ["r3", "Challenge", "working"],
30
+ ["brief", "Brief", "working"],
31
+ ["card", "Save card", "needs"],
32
+ ["saving", "Saving", "shipping"],
33
+ ["saved", "Saved", "done"],
34
+ ],
35
+ on: {
36
+ frame: "frame",
37
+ r1: "r1",
38
+ r2: "r2",
39
+ r3: "r3",
40
+ stop: "brief",
41
+ brief: "brief",
42
+ card: "card",
43
+ saving: "saving",
44
+ saved: "saved",
45
+ reject: "brief",
46
+ revise: "brief",
47
+ },
48
+ stall: { stages: ["frame", "r1", "r2", "r3"], minutes: 20, nudge: "brainstorm-lead", nudgeName: "Brainstorm Lead" },
49
+ },
50
+ agent: {
51
+ id: "agent",
52
+ name: "Request an agent",
53
+ icon: "i-rocket",
54
+ channel: "general",
55
+ entry: "agent-lead",
56
+ blurb: "Agent Lead has it built and reviewed, you say publish, an owner or admin approves Infra Gate's card, and it deploys.",
57
+ approver: "An owner or admin of the channel approves Infra Gate's card; HIGH risk means read the diff first.",
58
+ outcome: "Infra Gate merges the approved commit, waits for plan, and applies infrastructure changes.",
59
+ stages: [
60
+ ["sent", "Sent", "queued"],
61
+ ["scope", "Scope", "working"],
62
+ ["build", "Build", "working"],
63
+ ["review", "Review", "working"],
64
+ ["describe", "Your go", "working"],
65
+ ["publish", "Publish", "working"],
66
+ ["card", "Approval card", "needs"],
67
+ ["merge", "Merge + plan", "shipping"],
68
+ ["apply", "Apply", "shipping"],
69
+ ["deployed", "Deployed", "done"],
70
+ ],
71
+ on: {
72
+ ask: "scope",
73
+ person: null,
74
+ mr: "build",
75
+ "review-asked": "review",
76
+ "review-pass": "review",
77
+ "review-blocked": "build",
78
+ describe: "describe",
79
+ publish: "publish",
80
+ "publish-request": "publish",
81
+ card: "card",
82
+ counted: "merge",
83
+ merged: "merge",
84
+ applying: "apply",
85
+ deployed: "deployed",
86
+ rework: "build",
87
+ "card-rejected": "build",
88
+ },
89
+ },
90
+ bug: {
91
+ id: "bug",
92
+ name: "Report a bug",
93
+ icon: "i-bug",
94
+ channel: "bug-hunt",
95
+ entry: "repro-agent",
96
+ blurb: "Repro Agent reproduces it in a browser; Hackathon Agent drafts one bug-fix run; people approve the run.",
97
+ approver: "The people on the run's approval card (owners and admins of the channel).",
98
+ outcome: "The fix team builds it in #bug-fix and reports back once verified live.",
99
+ stages: [
100
+ ["sent", "Sent", "queued"],
101
+ ["repro", "Reproduce", "working"],
102
+ ["draft", "Draft the run", "working"],
103
+ ["card", "Run card", "needs"],
104
+ ["fix", "Fix in #bug-fix", "working"],
105
+ ["verified", "Verified live", "done"],
106
+ ],
107
+ on: { reproduced: "draft", mr: "draft", card: "card", merged: "fix", verified: "verified", "not-reproduced": "repro" },
108
+ },
109
+ canon: {
110
+ id: "canon",
111
+ name: "Canon rule",
112
+ icon: "i-scroll",
113
+ channel: "canon",
114
+ entry: "canon-lead",
115
+ blurb: "Canon Lead researches it, BA or Tech Agent drafts it, reviewers check every head, and people ratify it.",
116
+ approver: "The proposer approves; a HIGH change needs a second person.",
117
+ outcome: "Machine Agent merges the ratified head; its publisher lane publishes the document.",
118
+ stages: [
119
+ ["sent", "Sent", "queued"],
120
+ ["frame", "Frame", "working"],
121
+ ["rounds", "Rounds", "working"],
122
+ ["draft", "Draft MR", "working"],
123
+ ["reviews", "Reviews", "working"],
124
+ ["card", "Ratify card", "needs"],
125
+ ["merge", "Merge", "shipping"],
126
+ ["published", "Published", "done"],
127
+ ],
128
+ on: {
129
+ frame: "frame",
130
+ r1: "rounds",
131
+ r2: "rounds",
132
+ "canon-brief": "rounds",
133
+ mr: "draft",
134
+ draft: "draft",
135
+ "review-pass": "reviews",
136
+ "review-blocked": "draft",
137
+ card: "card",
138
+ merged: "merge",
139
+ published: "published",
140
+ },
141
+ },
142
+ hackathons: {
143
+ id: "hackathons",
144
+ name: "Hackathons",
145
+ icon: "i-rocket",
146
+ channel: "hackathons",
147
+ entry: "hackathon-lead",
148
+ blurb: "Hackathon Lead researches the run and hands the preview to the BA or Tech Agent named in the request.",
149
+ approver: "The people on the run's approval card.",
150
+ outcome: "Machine Agent hands an approved run to #implementation.",
151
+ stages: [
152
+ ["sent", "Sent", "queued"],
153
+ ["research", "Research", "working"],
154
+ ["draft", "Draft and review", "working"],
155
+ ["card", "Run card", "needs"],
156
+ ["merge", "Freeze and merge", "shipping"],
157
+ ["handoff", "Handed off", "done"],
158
+ ],
159
+ on: {
160
+ frame: "research",
161
+ r1: "research",
162
+ r2: "research",
163
+ draft: "draft",
164
+ mr: "draft",
165
+ card: "card",
166
+ merged: "merge",
167
+ handed: "handoff",
168
+ "card-rejected": "draft",
169
+ },
170
+ },
171
+ plan: {
172
+ id: "plan",
173
+ name: "Rollout plan",
174
+ icon: "i-map",
175
+ channel: "plan",
176
+ entry: "plan-agent",
177
+ blurb: "Plan Agent drafts steps from the repository and maintains #plan's roadmap canvas. People act on the steps.",
178
+ approver: "Nobody approves a plan; a blocked step needs the person it names.",
179
+ outcome: "The plan's bar turns green on the canvas and stays for 7 days.",
180
+ stages: [
181
+ ["sent", "Sent", "queued"],
182
+ ["drafted", "Drafted", "working"],
183
+ ["now", "In progress", "working"],
184
+ ["done", "Done", "done"],
185
+ ],
186
+ on: { "plan-todo": "drafted", "plan-now": "now", "plan-blocked": "now", "plan-done": "done" },
187
+ },
188
+ discovery: {
189
+ id: "discovery",
190
+ name: "Discovery cycle",
191
+ icon: "i-compass",
192
+ channel: "discovery",
193
+ entry: "discovery-lead",
194
+ budget: 48,
195
+ blurb: "Every four hours Discovery Lead opens a cycle that ends in one sourced proposal for a person to decide on.",
196
+ approver: "Any person in the channel: reply accepted, rejected, or done with a reason.",
197
+ outcome: "The decision becomes the proposal's status; Discovery Critic holds rejected ideas to new evidence.",
198
+ stages: [
199
+ ["cycle", "Cycle", "working"],
200
+ ["scan", "Scan + audit", "working"],
201
+ ["shortlist", "Shortlist", "working"],
202
+ ["debate", "Debate", "working"],
203
+ ["draft", "Draft", "working"],
204
+ ["proposal", "Proposal", "needs"],
205
+ ["decided", "Decided", "done"],
206
+ ],
207
+ on: { cycle: "cycle", scan: "scan", shortlist: "shortlist", stake: "debate", draft: "draft", proposal: "proposal", decide: "decided" },
208
+ },
209
+ ask: {
210
+ id: "ask",
211
+ name: "Ask an agent",
212
+ icon: "i-msg",
213
+ channel: null,
214
+ entry: null,
215
+ blurb: "A direct question to one agent: Monitor Agent about an incident, Infra Operator about a pipeline, or Canon Agent about rules.",
216
+ approver: "Nobody: the answer is the result.",
217
+ outcome: "Done when the agent has answered and stays quiet for 15 minutes, or when you mark it answered.",
218
+ stages: [
219
+ ["sent", "Sent", "queued"],
220
+ ["answering", "Answering", "working"],
221
+ ["answered", "Answered", "done"],
222
+ ],
223
+ on: { agent: "answering", ask: "answering", resolved: "answered" },
224
+ quiet: { from: "answering", to: "answered", hours: 0.25 },
225
+ },
226
+ requirement: {
227
+ id: "requirement",
228
+ name: "Requirement",
229
+ icon: "i-file",
230
+ channel: "requirements",
231
+ entry: "requirement-lead",
232
+ blurb: "Requirement Lead and its critics shape a feature request; the requester approves the gate card before handoff.",
233
+ approver: "The requester.",
234
+ outcome: "An approved requirement is handed to #canon.",
235
+ stages: [
236
+ ["sent", "Sent", "queued"],
237
+ ["shape", "Shape", "working"],
238
+ ["card", "Requirement card", "needs"],
239
+ ["handoff", "Hand-off", "shipping"],
240
+ ["canon", "In #canon", "done"],
241
+ ],
242
+ on: { agent: "shape", card: "card", handed: "canon" },
243
+ },
244
+ fixrun: {
245
+ id: "fixrun",
246
+ name: "Fix run",
247
+ icon: "i-merge",
248
+ channel: "bug-fix",
249
+ entry: "lead-agent",
250
+ blurb: "Lead Agent coordinates Architect, Coder, and QA Agents on one bug-fix run; merges require level-based approvals.",
251
+ approver: "MEDIUM needs one owner or admin; HIGH needs two different people.",
252
+ outcome: "The fix lane merges, reports back, and the reporter hears the result.",
253
+ stages: [
254
+ ["sent", "Started", "working"],
255
+ ["design", "Design", "working"],
256
+ ["code", "Code", "working"],
257
+ ["qa", "QA", "working"],
258
+ ["card", "Merge review", "needs"],
259
+ ["merge", "Merge", "shipping"],
260
+ ["done", "Done", "done"],
261
+ ],
262
+ on: { agent: null, design: "design", mr: "code", "qa-pass": "qa", card: "card", merged: "merge", verified: "done" },
263
+ },
264
+ };
265
+ export const PUBLIC_TEMPLATES = ["brainstorm", "agent", "bug", "plan", "canon", "hackathons", "ask"];
266
+ export const TASK_KINDS = {
267
+ brainstorm: { id: "brainstorm", name: "Brainstorm", icon: "i-bulb", channel: "brainstorm", entry: "brainstorm-lead" },
268
+ canon: { id: "canon", name: "Canon", icon: "i-scroll", channel: "canon", entry: "canon-lead" },
269
+ hackathons: { id: "hackathons", name: "Hackathons", icon: "i-rocket", channel: "hackathons", entry: "hackathon-lead" },
270
+ implementation: { id: "implementation", name: "Implementation", icon: "i-merge", channel: "implementation", entry: "lead-agent" },
271
+ bug: { id: "bug", name: "Bug Hunt", icon: "i-bug", channel: "bug-hunt", entry: "repro-agent" },
272
+ ask: { id: "ask", name: "Ask an agent", icon: "i-msg", channel: null, entry: null },
273
+ };
274
+ export const REASONS = {
275
+ approve: { label: "Approve", icon: "i-check", verb: "Review" },
276
+ answer: { label: "Answer", icon: "i-reply", verb: "Answer" },
277
+ publish: { label: "Say publish", icon: "i-rocket", verb: "Review" },
278
+ decide: { label: "Decide", icon: "i-compass", verb: "Decide" },
279
+ nudge: { label: "Nudge", icon: "i-hand", verb: "Nudge" },
280
+ retry: { label: "Retry", icon: "i-refresh", verb: "Retry" },
281
+ unblock: { label: "Unblock", icon: "i-alert", verb: "Open" },
282
+ };
283
+ const IN_THREAD_ONLY = /\bin the thread\b|\bto the thread\b|\ban answer to a question\b/i;
284
+ /** True when a channel's `people:` rule allows a person to open a new task thread with that agent. */
285
+ export function canStart(rule) {
286
+ return !IN_THREAD_ONLY.test(rule);
287
+ }
288
+ const BY_ENTRY = {
289
+ "brainstorm-lead": "brainstorm",
290
+ "agent-lead": "agent",
291
+ "plan-agent": "plan",
292
+ "repro-agent": "bug",
293
+ };
294
+ const CANON_ENTRIES = new Set(["canon-lead", "ba-agent", "tech-agent"]);
295
+ /** Infers the workflow template for an entry agent in a channel slug. */
296
+ export function templateOf(entry, slug) {
297
+ if (slug === "canon" && CANON_ENTRIES.has(entry)) {
298
+ return "canon";
299
+ }
300
+ if (slug === "hackathons" && entry === "hackathon-lead") {
301
+ return "hackathons";
302
+ }
303
+ return BY_ENTRY[entry] ?? "ask";
304
+ }
305
+ export const HACKATHON_DRAFTER_HINT = "Mention one drafter in your message, @BA Agent or @Tech Agent.";
306
+ /** Named drafter IDs mentioned in a hackathon request (`@BA Agent` -> `ba-agent`, `@Tech Agent` -> `tech-agent`). */
307
+ export function hackathonDrafters(message) {
308
+ const matches = message.matchAll(/(?<![\p{L}\p{N}_@])@(BA|Tech) Agent(?![\p{L}\p{N}_-])/gu);
309
+ return [...new Set(Array.from(matches, (match) => (match[1] === "BA" ? "ba-agent" : "tech-agent")))];
310
+ }
311
+ /** Summarizes an agent's live operational state from presence, active tasks, and agent kind. */
312
+ export function agentStatus(agent) {
313
+ if (agent.presence === "offline") {
314
+ return { kind: "down", label: "Down" };
315
+ }
316
+ if (agent.tasks.length > 0) {
317
+ return { kind: "working", label: "Working" };
318
+ }
319
+ if (agent.presence === "online") {
320
+ return { kind: "idle", label: "Idle" };
321
+ }
322
+ if (agent.presence === "away") {
323
+ return { kind: "away", label: "Away" };
324
+ }
325
+ return { kind: "key", label: agent.kind === "machine" ? "Machine" : "Key" };
326
+ }
327
+ /** Splits stored draft markdown into first-line title and trimmed body. */
328
+ export function splitDraftBody(text = "") {
329
+ const normalized = text.replace(/\r\n?/g, "\n");
330
+ const [title = "", ...rest] = normalized.split("\n");
331
+ return { title, body: rest.join("\n").trim() };
332
+ }
333
+ /** Generates a 16-character base64url draft ID matching `/^[\w-]{16}$/`. */
334
+ export function generateDraftId() {
335
+ return randomBytes(12).toString("base64url");
336
+ }
337
+ const HEX64 = /^[0-9a-f]{64}$/i;
338
+ const HEX_PREFIX = /^[0-9a-f]{8,63}$/i;
339
+ /**
340
+ * Resolves a task reference (`INF-8`, full 64-hex `root`, or unique >=8-char hex prefix) against a task list.
341
+ */
342
+ export function resolveTaskRef(ref, tasks) {
343
+ const trimmed = ref.trim();
344
+ if (trimmed === "") {
345
+ throw new CliError("Task reference cannot be empty.", { exitCode: EXIT_VALIDATION });
346
+ }
347
+ const lower = trimmed.toLowerCase();
348
+ const byKey = tasks.filter((task) => task.key.toLowerCase() === lower);
349
+ if (byKey.length === 1) {
350
+ const match = byKey[0];
351
+ if (match !== undefined) {
352
+ return match;
353
+ }
354
+ }
355
+ if (byKey.length > 1) {
356
+ const candidates = byKey.map((task) => `${task.community}:${task.key} (${task.root.slice(0, 8)})`).join(", ");
357
+ throw new CliError(`Ambiguous task reference '${trimmed}'; matches: ${candidates}. Specify --community or a full root ID.`, {
358
+ exitCode: EXIT_VALIDATION,
359
+ payload: { ok: false, error: "ambiguous_task_ref", message: `Ambiguous task reference '${trimmed}'.` },
360
+ });
361
+ }
362
+ if (HEX64.test(trimmed)) {
363
+ const byRoot = tasks.filter((task) => task.root.toLowerCase() === lower);
364
+ if (byRoot.length === 1) {
365
+ const match = byRoot[0];
366
+ if (match !== undefined) {
367
+ return match;
368
+ }
369
+ }
370
+ if (byRoot.length > 1) {
371
+ const candidates = byRoot.map((task) => `${task.community}:${task.key}`).join(", ");
372
+ throw new CliError(`Ambiguous task root '${trimmed}'; matches: ${candidates}. Specify --community.`, {
373
+ exitCode: EXIT_VALIDATION,
374
+ payload: { ok: false, error: "ambiguous_task_ref", message: `Ambiguous task root '${trimmed}'.` },
375
+ });
376
+ }
377
+ }
378
+ else if (HEX_PREFIX.test(trimmed)) {
379
+ const byPrefix = tasks.filter((task) => task.root.toLowerCase().startsWith(lower));
380
+ if (byPrefix.length === 1) {
381
+ const match = byPrefix[0];
382
+ if (match !== undefined) {
383
+ return match;
384
+ }
385
+ }
386
+ if (byPrefix.length > 1) {
387
+ const candidates = byPrefix.map((task) => `${task.key} (${task.root.slice(0, 12)})`).join(", ");
388
+ throw new CliError(`Ambiguous task prefix '${trimmed}'; matches: ${candidates}. Provide more hex characters.`, {
389
+ exitCode: EXIT_VALIDATION,
390
+ payload: { ok: false, error: "ambiguous_task_ref", message: `Ambiguous task prefix '${trimmed}'.` },
391
+ });
392
+ }
393
+ }
394
+ throw new CliError(`Task not found: ${trimmed}`, {
395
+ exitCode: EXIT_RUNTIME,
396
+ payload: { ok: false, error: "not_found", status: 404, message: `Task not found: ${trimmed}` },
397
+ });
398
+ }
399
+ /** Resolves a channel by UUID or slug (with or without leading `#`). */
400
+ export function resolveChannel(selector, channels) {
401
+ const trimmed = selector.trim();
402
+ if (trimmed === "") {
403
+ throw new CliError("Channel selector cannot be empty.", { exitCode: EXIT_VALIDATION });
404
+ }
405
+ const byId = channels.find((channel) => channel.id === trimmed);
406
+ if (byId !== undefined) {
407
+ return byId;
408
+ }
409
+ const slug = trimmed.replace(/^#/, "").toLowerCase();
410
+ const bySlug = channels.filter((channel) => channel.slug.toLowerCase() === slug);
411
+ if (bySlug.length === 1) {
412
+ const match = bySlug[0];
413
+ if (match !== undefined) {
414
+ return match;
415
+ }
416
+ }
417
+ if (bySlug.length > 1) {
418
+ const ids = bySlug.map((channel) => channel.id).join(", ");
419
+ throw new CliError(`Ambiguous channel '#${slug}'; pass channel ID (${ids}).`, {
420
+ exitCode: EXIT_VALIDATION,
421
+ payload: { ok: false, error: "ambiguous_channel", message: `Ambiguous channel '#${slug}'.` },
422
+ });
423
+ }
424
+ throw new CliError(`Channel not found: ${trimmed}`, {
425
+ exitCode: EXIT_RUNTIME,
426
+ payload: { ok: false, error: "not_found", status: 404, message: `Channel not found: ${trimmed}` },
427
+ });
428
+ }
429
+ /** Resolves an agent by ID, display name (case-insensitive, optional leading `@`), or 64-hex pubkey. */
430
+ export function resolveAgent(selector, agents) {
431
+ const trimmed = selector.trim();
432
+ if (trimmed === "") {
433
+ throw new CliError("Agent selector cannot be empty.", { exitCode: EXIT_VALIDATION });
434
+ }
435
+ const lower = trimmed.toLowerCase();
436
+ const withoutAt = lower.replace(/^@/, "");
437
+ const byId = agents.filter((agent) => agent.id.toLowerCase() === withoutAt);
438
+ if (byId.length === 1) {
439
+ const match = byId[0];
440
+ if (match !== undefined) {
441
+ return match;
442
+ }
443
+ }
444
+ if (byId.length > 1) {
445
+ throw new CliError(`Ambiguous agent ID '${trimmed}'.`, { exitCode: EXIT_VALIDATION });
446
+ }
447
+ const byName = agents.filter((agent) => agent.name.toLowerCase() === withoutAt);
448
+ if (byName.length === 1) {
449
+ const match = byName[0];
450
+ if (match !== undefined) {
451
+ return match;
452
+ }
453
+ }
454
+ if (byName.length > 1) {
455
+ const ids = byName.map((agent) => agent.id).join(", ");
456
+ throw new CliError(`Ambiguous agent name '${trimmed}'; matches: ${ids}.`, { exitCode: EXIT_VALIDATION });
457
+ }
458
+ if (HEX64.test(trimmed)) {
459
+ const byPubkey = agents.filter((agent) => agent.pubkey?.toLowerCase() === lower);
460
+ if (byPubkey.length === 1) {
461
+ const match = byPubkey[0];
462
+ if (match !== undefined) {
463
+ return match;
464
+ }
465
+ }
466
+ if (byPubkey.length > 1) {
467
+ throw new CliError(`Ambiguous agent pubkey '${trimmed}'.`, { exitCode: EXIT_VALIDATION });
468
+ }
469
+ }
470
+ throw new CliError(`Agent not found: ${trimmed}`, {
471
+ exitCode: EXIT_RUNTIME,
472
+ payload: { ok: false, error: "not_found", status: 404, message: `Agent not found: ${trimmed}` },
473
+ });
474
+ }
475
+ /** Builds a `NameResolver` from a community's agents and people lists. */
476
+ export function createNameResolver(agents, people = [], community) {
477
+ const byKey = new Map();
478
+ const pubkeyById = new Map();
479
+ for (const person of people) {
480
+ byKey.set(person.pubkey.toLowerCase(), person.name);
481
+ }
482
+ for (const agent of agents) {
483
+ byKey.set(agent.id.toLowerCase(), agent.name);
484
+ if (agent.pubkey !== null) {
485
+ byKey.set(agent.pubkey.toLowerCase(), agent.name);
486
+ pubkeyById.set(agent.id.toLowerCase(), agent.pubkey);
487
+ pubkeyById.set(agent.pubkey.toLowerCase(), agent.pubkey);
488
+ }
489
+ }
490
+ return {
491
+ name(idOrPubkey) {
492
+ const found = byKey.get(idOrPubkey.toLowerCase());
493
+ if (found !== undefined) {
494
+ return found;
495
+ }
496
+ if (HEX64.test(idOrPubkey)) {
497
+ return idOrPubkey.slice(0, 8);
498
+ }
499
+ return idOrPubkey
500
+ .replaceAll("-", " ")
501
+ .replace(/\b\w/g, (ch) => ch.toUpperCase());
502
+ },
503
+ pubkeyOf(targetCommunity, idOrPubkey) {
504
+ if (community !== undefined && targetCommunity !== community) {
505
+ return undefined;
506
+ }
507
+ const found = pubkeyById.get(idOrPubkey.toLowerCase());
508
+ if (found !== undefined) {
509
+ return found;
510
+ }
511
+ return HEX64.test(idOrPubkey) ? idOrPubkey.toLowerCase() : undefined;
512
+ },
513
+ };
514
+ }
515
+ const NO_MENTION_ACTIONS = new Set(["approve", "reject", "accepted", "rejected", "done"]);
516
+ /**
517
+ * Composes the exact message or gate payload for a task action, mirroring the board UI's confirmation composer.
518
+ */
519
+ export function composeActionPost(kind, task, reason, names, text = "") {
520
+ const agent = names.name(reason.by);
521
+ const card = `${agent}'s card`;
522
+ const typed = text.trim();
523
+ const recipientPubkey = names.pubkeyOf(task.community, reason.by);
524
+ const mentions = recipientPubkey === undefined ? [] : [recipientPubkey];
525
+ const unavailable = !NO_MENTION_ACTIONS.has(kind) && recipientPubkey === undefined ? `${agent} has no profile on the relay yet.` : undefined;
526
+ let composed;
527
+ switch (kind) {
528
+ case "approve":
529
+ composed = {
530
+ kind,
531
+ endpoint: "approve",
532
+ text: "approve",
533
+ to: card,
534
+ needsText: false,
535
+ mentions: [],
536
+ cardId: reason.cardId ?? "",
537
+ };
538
+ break;
539
+ case "reject":
540
+ composed = {
541
+ kind,
542
+ endpoint: "reject",
543
+ text: `reject: ${typed === "" ? "<what must change>" : typed}`,
544
+ to: card,
545
+ needsText: true,
546
+ mentions: [],
547
+ cardId: reason.cardId ?? "",
548
+ };
549
+ break;
550
+ case "reply":
551
+ case "change":
552
+ case "unblocked": {
553
+ const placeholder = kind === "reply" ? "<your answer>" : kind === "change" ? "<the change>" : "<what you did>";
554
+ composed = {
555
+ kind,
556
+ endpoint: "messages",
557
+ text: `@${agent} ${typed === "" ? placeholder : typed}`,
558
+ to: "the thread",
559
+ needsText: true,
560
+ mentions,
561
+ };
562
+ break;
563
+ }
564
+ case "publish":
565
+ composed = {
566
+ kind,
567
+ endpoint: "messages",
568
+ text: `@${agent} publish`,
569
+ to: "the thread",
570
+ needsText: false,
571
+ mentions,
572
+ };
573
+ break;
574
+ case "nudge": {
575
+ const blockedName = reason.blocked !== undefined && reason.until !== undefined ? names.name(reason.blocked) : null;
576
+ const bodyText = blockedName !== null && reason.until !== undefined
577
+ ? `@${agent} ${blockedName} cannot answer before ${new Date(reason.until * 1000).toUTCString().slice(5, 22)} UTC (its quota is used up): please go on without it.`
578
+ : `@${agent} the round has gone quiet: please go on.`;
579
+ composed = {
580
+ kind,
581
+ endpoint: "messages",
582
+ text: bodyText,
583
+ to: "the thread",
584
+ needsText: false,
585
+ mentions,
586
+ };
587
+ break;
588
+ }
589
+ case "retry":
590
+ composed = {
591
+ kind,
592
+ endpoint: "messages",
593
+ text: `@${agent} please retry your last turn.`,
594
+ to: "the thread",
595
+ needsText: false,
596
+ mentions,
597
+ };
598
+ break;
599
+ case "accepted":
600
+ case "rejected":
601
+ case "done":
602
+ composed = {
603
+ kind,
604
+ endpoint: "messages",
605
+ text: `${kind}: ${typed === "" ? "<a reason>" : typed}`,
606
+ to: "the proposal",
607
+ needsText: true,
608
+ mentions: [],
609
+ };
610
+ break;
611
+ }
612
+ return unavailable === undefined ? composed : { ...composed, unavailable };
613
+ }
614
+ function titleCaseId(id) {
615
+ return id.replaceAll("-", " ").replace(/\b\w/g, (ch) => ch.toUpperCase());
616
+ }
617
+ /**
618
+ * Validates and previews a new task submission before sending, mirroring the board composer's preflight rules.
619
+ */
620
+ export function preflightNewTask(input) {
621
+ const blockers = [];
622
+ const warnings = [];
623
+ const additionalMentions = [];
624
+ const cleanTitle = input.title.trim();
625
+ const cleanBody = (input.body ?? "").trim();
626
+ if (cleanTitle === "") {
627
+ blockers.push("Title is required.");
628
+ }
629
+ const delivery = input.delivery;
630
+ const workflow = input.kind !== undefined ? TASK_KINDS[input.kind] : undefined;
631
+ let resolvedChannel = null;
632
+ if (delivery !== undefined) {
633
+ resolvedChannel = input.channels.find((ch) => ch.id === delivery.channel) ?? null;
634
+ if (resolvedChannel === null) {
635
+ blockers.push(`Original delivery channel '${delivery.channel}' is unavailable in ${input.community}.`);
636
+ }
637
+ }
638
+ else if (workflow !== undefined && workflow.channel !== null) {
639
+ resolvedChannel = input.channels.find((ch) => ch.slug === workflow.channel) ?? null;
640
+ if (resolvedChannel === null) {
641
+ blockers.push(`Channel #${workflow.channel} is unavailable in ${input.community}.`);
642
+ }
643
+ }
644
+ else if (input.channel !== undefined && input.channel.trim() !== "") {
645
+ const trimmed = input.channel.trim();
646
+ const slug = trimmed.replace(/^#/, "").toLowerCase();
647
+ resolvedChannel = input.channels.find((ch) => ch.id === trimmed || ch.slug.toLowerCase() === slug) ?? null;
648
+ if (resolvedChannel === null) {
649
+ blockers.push(`Channel '${trimmed}' is unavailable in ${input.community}.`);
650
+ }
651
+ }
652
+ else {
653
+ blockers.push("Choose a task kind or channel.");
654
+ }
655
+ let entryId;
656
+ let entryRule;
657
+ if (resolvedChannel !== null) {
658
+ const peopleEntries = Object.entries(resolvedChannel.people);
659
+ const eligible = peopleEntries.filter(([, rule]) => canStart(rule));
660
+ if (delivery !== undefined) {
661
+ entryId = delivery.entry;
662
+ entryRule = resolvedChannel.people[entryId];
663
+ }
664
+ else if (workflow !== undefined && workflow.entry !== null) {
665
+ entryId = workflow.entry;
666
+ entryRule = resolvedChannel.people[entryId];
667
+ }
668
+ else if (input.entry !== undefined && input.entry.trim() !== "") {
669
+ const wanted = input.entry.trim().replace(/^@/, "").toLowerCase();
670
+ const matchedAgent = input.agents.find((a) => a.id.toLowerCase() === wanted || a.name.toLowerCase() === wanted);
671
+ const targetId = matchedAgent?.id ?? wanted;
672
+ const found = peopleEntries.find(([id]) => id.toLowerCase() === targetId.toLowerCase());
673
+ entryId = found?.[0] ?? targetId;
674
+ entryRule = found?.[1];
675
+ }
676
+ else if (eligible.length === 1) {
677
+ const only = eligible[0];
678
+ entryId = only?.[0];
679
+ entryRule = only?.[1];
680
+ }
681
+ else {
682
+ blockers.push(`Choose an entry agent for #${resolvedChannel.slug}.`);
683
+ }
684
+ }
685
+ const matchedAgent = entryId === undefined ? undefined : input.agents.find((a) => a.id === entryId);
686
+ const entryName = matchedAgent?.name ?? (entryId === undefined ? undefined : titleCaseId(entryId));
687
+ const resolvedEntry = entryId !== undefined && entryName !== undefined && entryRule !== undefined
688
+ ? { id: entryId, name: entryName, rule: entryRule, pubkey: matchedAgent?.pubkey ?? null }
689
+ : null;
690
+ const isImplementation = input.kind === "implementation" && delivery === undefined;
691
+ if (isImplementation) {
692
+ blockers.push("Implementation tasks are started by handoff from an approved hackathon run.");
693
+ }
694
+ const template = resolvedChannel !== null && resolvedEntry !== null ? TEMPLATES[templateOf(resolvedEntry.id, resolvedChannel.slug)] : null;
695
+ const message = `${cleanTitle === "" ? "<the title>" : cleanTitle}${cleanBody !== "" ? `\n\n${cleanBody}` : ""}`;
696
+ const previewText = isImplementation
697
+ ? "Waiting for an approved hackathon"
698
+ : `@${entryName ?? "..."} ${message}`;
699
+ if (resolvedChannel !== null && entryId !== undefined && entryRule === undefined) {
700
+ blockers.push(`${entryName ?? entryId} is not configured in #${resolvedChannel.slug}.`);
701
+ }
702
+ if (resolvedChannel !== null && resolvedEntry !== null) {
703
+ if (!canStart(resolvedEntry.rule)) {
704
+ blockers.push(`${resolvedEntry.name} takes replies in an existing thread.`);
705
+ }
706
+ else if (delivery === undefined && !isImplementation) {
707
+ if (matchedAgent?.pubkey === null || matchedAgent?.pubkey === undefined) {
708
+ blockers.push(`${resolvedEntry.name} has no profile on the relay yet.`);
709
+ }
710
+ else if (matchedAgent.presence === "offline") {
711
+ blockers.push(`${matchedAgent.name} is down. Send it once the agent is back.`);
712
+ }
713
+ else if (template?.id === "hackathons") {
714
+ const [drafter, second] = hackathonDrafters(message);
715
+ if (drafter === undefined || second !== undefined) {
716
+ blockers.push(HACKATHON_DRAFTER_HINT);
717
+ }
718
+ else {
719
+ const drafterAgent = input.agents.find((a) => a.id === drafter && a.pubkey !== null);
720
+ if (!Object.hasOwn(resolvedChannel.people, drafter) || drafterAgent?.pubkey === undefined || drafterAgent.pubkey === null) {
721
+ blockers.push("The named drafter is unavailable in #hackathons.");
722
+ }
723
+ else {
724
+ additionalMentions.push(drafterAgent.pubkey);
725
+ }
726
+ }
727
+ }
728
+ const applying = (input.tasks ?? []).find((task) => task.stage === "apply" && task.col === "shipping");
729
+ if (applying !== undefined) {
730
+ warnings.push(`An apply of ${input.community} is running (${applying.key}). The agent may miss this mention.`);
731
+ }
732
+ else if (matchedAgent?.presence === "unknown") {
733
+ warnings.push(`${matchedAgent.name} has no recent presence. Check the relay if you need a live response.`);
734
+ }
735
+ }
736
+ }
737
+ return {
738
+ ok: blockers.length === 0,
739
+ blockers,
740
+ warnings,
741
+ previewText,
742
+ channel: resolvedChannel,
743
+ entry: resolvedEntry,
744
+ template,
745
+ additionalMentions,
746
+ };
747
+ }