@staix/agent-hub 0.46.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +12 -6
  3. package/docs/adding-an-ai-tool.md +20 -4
  4. package/docs/agent-notes/adapters.md +3 -3
  5. package/docs/agent-notes/benchmarks.md +7 -1
  6. package/docs/agent-notes/daemon.md +5 -4
  7. package/docs/agent-notes/tasks.md +4 -2
  8. package/docs/agent-notes/tests.md +3 -0
  9. package/docs/contracts/companion-cli-v1.json +3 -0
  10. package/docs/data-policy.md +9 -0
  11. package/docs/design/adapters.md +14 -0
  12. package/docs/design/cli-output-inventory.md +362 -0
  13. package/docs/design/cli-output.md +42 -1
  14. package/docs/design/execution-reference.md +5 -2
  15. package/docs/design/guidance-probes.md +14 -2
  16. package/docs/design/refusal-inventory.md +26 -0
  17. package/docs/design/roadmap.md +4 -0
  18. package/docs/design/task-board.md +17 -1
  19. package/docs/dogfood.md +27 -11
  20. package/docs/events.md +9 -0
  21. package/docs/friction.md +46 -0
  22. package/docs/memory.md +35 -3
  23. package/docs/operations.md +95 -16
  24. package/docs/profiles.md +1 -0
  25. package/docs/quickstart.md +14 -2
  26. package/docs/roles.md +6 -0
  27. package/docs/sdlc.md +44 -1
  28. package/docs/security.md +29 -12
  29. package/docs/specs/2026-09-19-agent-hub-design.md +17 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +7 -1
  31. package/docs/verification/2026-11-25-agy-1.5.16.md +31 -0
  32. package/docs/verification/2026-11-25-claude-implementer-2.1.332.md +47 -0
  33. package/docs/verification/2026-11-25-codex-0172-reviewer-isolation.md +47 -0
  34. package/docs/verification/2026-11-25-kimi-272-reviewer-compat.md +38 -0
  35. package/docs/verification/2026-11-25-kimi-tui-272.md +14 -0
  36. package/docs/verification/2026-11-25-pi-160-compat.md +40 -0
  37. package/docs/verification/2026-11-26-0.47.0.md +43 -0
  38. package/docs/verification/2026-11-26-0.48.0.md +45 -0
  39. package/docs/verification/2026-11-26-codex-0172-reviewer-tool-call.md +29 -0
  40. package/docs/verification/dogfood/2026-11-24.md +2829 -0
  41. package/docs/verification/pi-160-model-free.ts +57 -0
  42. package/docs/verification/pi-160-native.mjs +21 -0
  43. package/docs/verified.json +44 -32
  44. package/package.json +2 -2
  45. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  46. package/plugins/agent-hub/kimi-hook.js +598 -131
  47. package/plugins/agent-hub/server.js +687 -143
  48. package/src/adapters/acp.ts +5 -0
  49. package/src/adapters/channel-peer.ts +7 -0
  50. package/src/adapters/claude-print-child.ts +27 -5
  51. package/src/adapters/codex-appserver.ts +9 -0
  52. package/src/adapters/compat.ts +12 -11
  53. package/src/adapters/configured-acp.ts +45 -2
  54. package/src/adapters/configured-print.ts +163 -0
  55. package/src/adapters/conformance/index.ts +1 -0
  56. package/src/adapters/conformance/print.ts +57 -0
  57. package/src/adapters/definitions/native-activity.ts +57 -0
  58. package/src/adapters/definitions/native-factories.ts +4 -2
  59. package/src/adapters/jcode.ts +10 -2
  60. package/src/adapters/local-probe.ts +59 -14
  61. package/src/adapters/local-worker.ts +20 -6
  62. package/src/adapters/registry-types.ts +5 -3
  63. package/src/adapters/role-eligibility.ts +5 -0
  64. package/src/cli/bench.ts +2 -1
  65. package/src/cli/broker.ts +2 -1
  66. package/src/cli/capabilities-output.ts +10 -14
  67. package/src/cli/configured-acp-entry.ts +10 -2
  68. package/src/cli/console-state.ts +25 -5
  69. package/src/cli/error-format.ts +2 -0
  70. package/src/cli/guidance.ts +1 -1
  71. package/src/cli/handoff-output.ts +20 -17
  72. package/src/cli/help.ts +79 -41
  73. package/src/cli/init-settings.ts +15 -0
  74. package/src/cli/intake-output.ts +13 -13
  75. package/src/cli/launch.ts +3 -2
  76. package/src/cli/learn-output.ts +40 -21
  77. package/src/cli/main.ts +150 -79
  78. package/src/cli/memory.ts +47 -2
  79. package/src/cli/output.ts +54 -31
  80. package/src/cli/roadmap.ts +2 -2
  81. package/src/cli/room-output.ts +71 -0
  82. package/src/cli/room.ts +19 -33
  83. package/src/cli/schedule-output.ts +20 -19
  84. package/src/cli/sdlc-output.ts +188 -170
  85. package/src/cli/source-output.ts +17 -14
  86. package/src/cli/specs.ts +13 -13
  87. package/src/cli/study-output.ts +66 -69
  88. package/src/cli/task-output.ts +106 -158
  89. package/src/cli/terminal-recovery.ts +2 -1
  90. package/src/cli/upgrade-runtime.ts +2 -1
  91. package/src/cli/warn-line.ts +18 -0
  92. package/src/cli/worktrees-output.ts +25 -23
  93. package/src/hub/audit-source.ts +45 -0
  94. package/src/hub/board.ts +141 -5
  95. package/src/hub/bus.ts +13 -2
  96. package/src/hub/config-apply.ts +14 -1
  97. package/src/hub/config-trust.ts +1 -0
  98. package/src/hub/control-client.ts +1 -1
  99. package/src/hub/daemon.ts +390 -47
  100. package/src/hub/guidance-probe-store.ts +51 -10
  101. package/src/hub/guidance-probes.ts +25 -7
  102. package/src/hub/handoff.ts +5 -1
  103. package/src/hub/hub-tools.ts +23 -5
  104. package/src/hub/instance-config.ts +3 -3
  105. package/src/hub/learn-followup.ts +103 -0
  106. package/src/hub/learning.ts +63 -1
  107. package/src/hub/manager.ts +15 -1
  108. package/src/hub/memory-policy.ts +2 -1
  109. package/src/hub/memory-review.ts +217 -0
  110. package/src/hub/peer-activity.ts +37 -0
  111. package/src/hub/peers.ts +3 -0
  112. package/src/hub/project-move.ts +258 -0
  113. package/src/hub/registry.ts +16 -5
  114. package/src/hub/restart.ts +7 -0
  115. package/src/hub/review-brief.ts +8 -4
  116. package/src/hub/review-checkout.ts +26 -0
  117. package/src/hub/review-findings.ts +6 -3
  118. package/src/hub/risk-tier.ts +129 -0
  119. package/src/hub/roadmap-check.ts +1 -0
  120. package/src/hub/routing.ts +3 -1
  121. package/src/hub/sdlc-merge.ts +9 -0
  122. package/src/hub/sdlc-metrics.ts +24 -1
  123. package/src/hub/sdlc-queue.ts +1 -1
  124. package/src/hub/sdlc.ts +15 -6
  125. package/src/hub/settings.ts +2 -0
  126. package/src/hub/spec-readback.ts +136 -0
  127. package/src/hub/specs.ts +1 -1
  128. package/src/hub/task-list-page.ts +1 -1
  129. package/src/hub/tasks.ts +586 -80
  130. package/src/hub/ui.ts +4 -2
  131. package/src/local/probe-types.ts +1 -0
  132. package/src/local/probe-workspace.ts +49 -0
  133. package/src/omniroute/client.ts +19 -3
  134. package/src/ui/guidance-panel.ts +2 -2
  135. package/src/ui/guidance-view.ts +4 -2
  136. package/src/ui/index.html +26 -2
  137. package/src/ui/overview-model.ts +138 -0
  138. package/src/ui/plugin.ts +30 -4
  139. package/templates/roles/ops/project-manager.md +1 -1
package/src/cli/memory.ts CHANGED
@@ -6,7 +6,8 @@ import { join } from "node:path";
6
6
  import { CodeFacts } from "../hub/code-facts.ts";
7
7
  import { HUB_DB_BUSY_TIMEOUT_MS } from "../hub/db-timeout.ts";
8
8
  import { hubGitEnv, hubGitSync } from "../hub/git.ts";
9
- import { stateDirFor } from "../hub/control-client.ts";
9
+ import { stateDirFor, ControlClient } from "../hub/control-client.ts";
10
+ import { scheduleWhen } from "../hub/schedules.ts";
10
11
  import { isDenied } from "../local/deny.ts";
11
12
  import { foldSegment } from "../hub/permission-mode.ts";
12
13
  import { matchesPolicyLexically } from "../hub/path-policy.ts";
@@ -28,7 +29,7 @@ import { bindProfileMemory, memoryProjectFor, memoryProjectForStore, openProfile
28
29
  import { createMemorySyncPolicy, inspectDeclinedMemoryRows, projectMemorySyncText } from "../hub/memory-sync-policy.ts";
29
30
 
30
31
  export const GOAL_USAGE = goalUsage(AHUB_NAMES.goal);
31
- export const MEMORY_USAGE = `${memoryUsage(AHUB_NAMES.memory)} | decay [--days N] [--json] | declined [--json] | profile-check [--json]`;
32
+ export const MEMORY_USAGE = `${memoryUsage(AHUB_NAMES.memory)} | decay [--days N] [--json] | declined [--json] | profile-check [--json] | review on|off|status [--json]`;
32
33
 
33
34
  const fail = (message: string): never => { throw new Error(message); };
34
35
  /** The project's config, or none when there is no valid one (reading memory needs none). */
@@ -136,9 +137,53 @@ export async function memoryCommand(args: string[], cwd: string, opts: { store?:
136
137
  return memoryCommandBody(args, cwd, opts, person);
137
138
  }
138
139
 
140
+ /**
141
+ * #1329 part 1: `ahub memory review on|off|status`. The switch, its caps and the open card's cancellation are the daemon's
142
+ * (`memory_review`), so this only carries the answer: the config write, the pause that stops the timer at once and the
143
+ * `Tasks.cancel` of the card a run left open all happen in one op, in that order, where the schedule and the board are.
144
+ */
145
+ async function memoryReviewCommand(args: string[], cwd: string, person: boolean): Promise<string> {
146
+ const json = args.includes("--json");
147
+ const rest = args.filter(arg => arg !== "--json");
148
+ const action = rest[1];
149
+ if (rest.length !== 2 || (action !== "on" && action !== "off" && action !== "status")) fail("usage: ahub memory review on|off|status [--json]");
150
+ // The switch is machine-local and a person's: an agent shell must not turn it on, and it must not read as the console either.
151
+ if (!person) fail(`memory review ${action} is the person's switch on the machine-local memory.review config; run it in the person's terminal or the console`);
152
+ const hub = await ControlClient.connect(stateDirFor(cwd), { role: "console", projectRoot: cwd }, 5_000);
153
+ try {
154
+ const res = await hub.request({ t: "task", op: "memory_review", args: { action } }, 30_000);
155
+ if (!res.ok) fail(res.error);
156
+ if (json) return res.text;
157
+ const data = JSON.parse(res.text) as {
158
+ action: string; enabled?: boolean; cancelled?: number; error?: string;
159
+ review?: { every?: string; max_notes?: number; projects?: string[]; max_tokens_run?: number; max_tokens_week?: number };
160
+ schedule?: { state: string; next: number; last?: number; task?: number; error?: string; zone?: string };
161
+ /** #1329 part 2: the counted spend of the last card (`run`) and of this week's reviews, present while a card is open. */
162
+ spend?: { run: number; week: number };
163
+ task?: number;
164
+ };
165
+ const review = data.review ?? {}, lines = [`memory review: ${data.enabled ? "on" : "off"}`];
166
+ if (data.cancelled !== undefined) lines.push(`cancelled the open review task #${data.cancelled}`);
167
+ if (data.error) lines.push(`not changed: ${data.error}`);
168
+ if (review.every !== undefined) lines.push(`period: every ${review.every}`);
169
+ lines.push(`caps: ${review.max_tokens_run ?? "unset"} per run, ${review.max_tokens_week ?? "unset"} per week`);
170
+ if (review.max_notes !== undefined) lines.push(`notes per run: at most ${review.max_notes}`);
171
+ if (review.projects?.length) lines.push(`projects: ${review.projects.join(", ")}`);
172
+ const schedule = data.schedule;
173
+ lines.push(schedule
174
+ ? `schedule: ${schedule.state}, next ${scheduleWhen(schedule, schedule.next)}${schedule.task !== undefined ? `, last task #${schedule.task}` : ""}${schedule.error ? `, last error: ${schedule.error}` : ""}`
175
+ : "schedule: not running here (the switch is off, or this project is not one it selects)");
176
+ // #1329 part 2: the spend is the hub's own counted tokens, so an open card reports it; with no card there is nothing spent.
177
+ lines.push(data.spend ? `spend: ${data.spend.run} of ${review.max_tokens_run ?? "unset"} this run, ${data.spend.week} of ${review.max_tokens_week ?? "unset"} this week (task #${data.task})`
178
+ : `spend: nothing counted for an open review card (${review.max_tokens_run ?? "unset"} per run, ${review.max_tokens_week ?? "unset"} per week)`);
179
+ return lines.join("\n");
180
+ } finally { hub.close(); }
181
+ }
182
+
139
183
  async function memoryCommandBody(args: string[], cwd: string, opts: { store?: MemoryStore; sync?: Omit<SyncOptions, "remote">; now?: () => number }, person: boolean): Promise<string> {
140
184
  const privatePaths = (): string[] => { try { return loadConfig(cwd).pii?.paths ?? []; } catch (e) { return fail(`the project's config does not load (${(e as Error).message}); fix it before reading hub memory`); } };
141
185
  const rest = args.filter(arg => arg !== "--json");
186
+ if (rest[0] === "review") return memoryReviewCommand(args, cwd, person);
142
187
  if (rest[0] === "decay") {
143
188
  let days = 90;
144
189
  if (rest.length !== 1) {
package/src/cli/output.ts CHANGED
@@ -265,10 +265,13 @@ function contextText(p: any, now: number): string {
265
265
  if (!c) return "unknown";
266
266
  return `${c.used === null || c.used === undefined ? "unknown" : `${Math.round(c.used * 100)}%`}${c.freshness === "stale" ? " stale" : ""}${typeof c.measuredAt === "number" ? ` ${relative(c.measuredAt, now)}` : ""}${c.source ? ` ${c.source}` : ""}`;
267
267
  }
268
- export function renderStatus(data: StatusOutput, columns?: number, now = Date.now(), full = false): Span[][] {
268
+ export function renderStatus(data: StatusOutput, columns?: number, now = Date.now(), full = false, ascii = false): Span[][] {
269
269
  if (data.roleInfo) data = { ...data, peers: Object.fromEntries(Object.entries(data.peers).map(([peer, value]) => [peer, { ...value, ...data.roleInfo?.[peer] }])) };
270
- const out = lines(`agent-hub${data.version ? ` ${data.version}` : ""} pid ${data.pid ?? "unknown"} control 127.0.0.1:${data.controlPort ?? "unknown"}`, columns, "info");
271
- if (data.cwd) out.push(...lines(data.cwd, columns));
270
+ // #1654 T3: the shared header, then a section mark per group. Every detail line below keeps its text, so a search for one still finds it.
271
+ const out: Span[][] = new LayoutReport(columns, ascii).titled("ahub", "Status", [`agent-hub${data.version ? ` ${data.version}` : ""}`, `pid ${data.pid ?? "unknown"}`, `127.0.0.1:${data.controlPort ?? "unknown"}`].filter(Boolean).join(" ")).lines();
272
+ const mark = (name: string, count?: string) => { out.push(...(out.length && out.at(-1)!.length ? [[]] : []), ...new LayoutReport(columns, ascii).section(name, count).lines()); };
273
+ const hubStart = out.length; // the Hub section opens here only if a row below lands in it
274
+ if (data.cwd) out.push(...detail("project", data.cwd, columns));
272
275
  if (data.runtimeModelsUnavailable === true) out.push(...lines("Runtime models unavailable: could not read a bounded model catalog; run ahub model list for the cause. For a known peer, use ahub model set <peer> <model> or ahub model clear <peer>; repair storage or reduce the retained peer catalog as indicated before listing again.", columns, "attention"));
273
276
  else if (Array.isArray(data.runtimeModels)) out.push(...renderRuntimeModels(data.runtimeModels.map(projectModelStatus).filter((row): row is RuntimeModelStatus => row !== null), columns));
274
277
  const timing = data.controlWriteTiming;
@@ -389,6 +392,7 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
389
392
  if (p.ownerIsolationNote) out.push(...detail("owner isolation", p.ownerIsolationNote, columns, "attention"));
390
393
  if (p.permissionNote) out.push(...detail("permission", p.permissionNote, columns, "muted"));
391
394
  if (typeof p.statusNotice?.message === "string" && p.statusNotice.message) out.push(...detail("status notice", p.statusNotice.message, columns, "attention"));
395
+ if (typeof p.detached?.cause === "string" && p.detached.cause) out.push(...detail("detached", `${p.detached.cause}${typeof p.detached.command === "string" && p.detached.command ? `; relaunch it with ${p.detached.command}` : ""}`, columns, "attention"));
392
396
  if (p.requestedModel && p.servedBy && p.requestedModel !== p.servedBy) out.push(...detail("requested model", p.requestedModel, columns));
393
397
  if (p.reviewScope === "code" || p.reviewScope === "full") out.push(...detail("review scope", p.reviewScope === "code" ? "code only (cannot run tests or read CI; the merger gates on exact-head CI)" : "full", columns, "muted")); // #852
394
398
  if (typeof p.modelSource === "string" && p.modelSource) out.push(...detail("model source", flat(p.modelSource), columns, "muted")); // an extra Jcode instance (#685): names only, never a URL or token
@@ -396,16 +400,19 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
396
400
  if (typeof p.oldestQueuedAt === "number") out.push(...detail(`${id} oldest queued`, relative(p.oldestQueuedAt, now), columns, "muted"));
397
401
  return out;
398
402
  });
399
- if (peerRows.length) out.push([], ...rows(head, peerRows, columns, peerDetails));
403
+ if (out.length > hubStart) out.splice(hubStart, 0, [], ...new LayoutReport(columns, ascii).section("Hub").lines());
404
+ mark("Peers", peerRows.length ? String(peerRows.length) : undefined);
405
+ if (peerRows.length) out.push(...rows(head, peerRows, columns, peerDetails));
400
406
  else out.push(...lines("no peers attached yet (ahub claude | ahub codex | ahub kimi)", columns));
401
407
  if (settling) out.push([], ...lines("settling: the adapter has not confirmed these deliveries yet (Claude: reply or hub_delivery_done). Task state is independent.", columns, "muted"));
402
408
  if (data.taskWip) for (const [peer, value] of Object.entries(data.taskWip)) out.push(...detail(`${peer} planner WIP`, `${value.wip}/${value.wipLimit}${wipSplit(value)}`, columns));
403
409
  if (data.models?.backends?.length) {
404
- out.push([], ...rows(["MODEL", "STATE", "ACTIVE", "REQUESTED", "ACTUAL", "PROVIDER"], data.models.backends.map(b => [span(backendLabel(b)), span(b.state ?? "unknown", stateTone(b.state ?? "")), span(b.active || "-"), span(b.requestedModel ?? "-"), span(b.actualModel ?? "-"), span(b.provider ?? "-")]), columns));
410
+ mark("Models", String(data.models.backends.length));
411
+ out.push(...rows(["MODEL", "STATE", "ACTIVE", "REQUESTED", "ACTUAL", "PROVIDER"], data.models.backends.map(b => [span(backendLabel(b)), span(b.state ?? "unknown", stateTone(b.state ?? "")), span(b.active || "-"), span(b.requestedModel ?? "-"), span(b.actualModel ?? "-"), span(b.provider ?? "-")]), columns));
405
412
  for (const b of data.models.backends) for (const [key, label] of [["coolingUntil", "cooling"], ["failingUntil", "dispatch held"]]) if (b[key!]) { const at = Date.parse(b[key!]); out.push(...detail(`${backendLabel(b)} ${label}`, `${Number.isFinite(at) ? relative(at, now) : "unknown"}${key === "coolingUntil" && typeof b.failures === "number" ? ` after ${b.failures} failures` : key === "failingUntil" ? "; no load moves until then" : ""}`, columns, "attention")); }
406
413
  }
407
414
  const counts = Object.entries(data.tasks ?? {}).map(([state, count]) => `${count} ${state}`).join(", ");
408
- if (counts) out.push([], ...lines(`TASKS ${counts} (ahub board)`, columns));
415
+ if (counts) { mark("Tasks"); out.push(...lines(`TASKS ${counts} (ahub board)`, columns)); }
409
416
  if (data.personRun?.length) out.push(...lines(`WAITING ON YOU ${data.personRun.map(id => `#${id}`).join(", ")} (person-run: no agent is offered it; ahub backlog list)`, columns, "attention"));
410
417
  return out;
411
418
  }
@@ -463,6 +470,8 @@ export function statusAttention(data: StatusOutput, now = Date.now()): Attention
463
470
  if (typeof p.reviewerUnavailable === "string" && p.reviewerUnavailable) add("fail", `${id} reviewer unavailable: ${flat(p.reviewerUnavailable)}`);
464
471
  if (p.ownerIsolationNote) add("warn", `${id} owner isolation: ${p.ownerIsolationNote}`);
465
472
  if (typeof p.statusNotice?.message === "string" && p.statusNotice.message) add("warn", `${id}: ${p.statusNotice.message}`);
473
+ // #1668: the hub refused a hub-tools hello because a server the hub did not start is serving that peer's socket; the hub already knows the launch that ends it.
474
+ if (typeof p.detached?.cause === "string" && p.detached.cause) add("warn", `${id} is detached: ${p.detached.cause}`, typeof p.detached.command === "string" ? p.detached.command : undefined);
466
475
  if (typeof p.importantWaitingSince === "number" && p.importantWaitingNote) add("warn", `${id}: ${String(p.importantWaitingNote)}`, `ahub queue list --peer ${id}`);
467
476
  const actionPolicy = data.actionPolicyInfo?.[id];
468
477
  if (actionPolicy?.note && !actionPolicy.enforceable) add("warn", `${id} action policy: ${actionPolicy.note}`);
@@ -481,7 +490,7 @@ export function statusAttention(data: StatusOutput, now = Date.now()): Attention
481
490
  */
482
491
  export function renderStatusDefault(data: StatusOutput, columns?: number, now = Date.now(), ascii = false): Span[][] {
483
492
  if (data.roleInfo) data = { ...data, peers: Object.fromEntries(Object.entries(data.peers).map(([peer, value]) => [peer, { ...value, ...data.roleInfo?.[peer] }])) };
484
- const report = new LayoutReport(columns, ascii).header("ahub", "Status", [data.version, data.pid !== undefined ? `pid ${data.pid}` : undefined, data.controlPort !== undefined ? `127.0.0.1:${data.controlPort}` : undefined].filter(Boolean).join(" "));
493
+ const report = new LayoutReport(columns, ascii).titled("ahub", "Status", [data.version, data.pid !== undefined ? `pid ${data.pid}` : undefined, data.controlPort !== undefined ? `127.0.0.1:${data.controlPort}` : undefined].filter(Boolean).join(" "));
485
494
  const attention = statusAttention(data, now);
486
495
  report.section("Attention", attention.length ? plural(attention.length, "item") : undefined);
487
496
  if (!attention.length) report.bullet("ok", "nothing needs attention");
@@ -710,30 +719,38 @@ export function renderDoctor(checks: DoctorCheck[], columns?: number, _now = Dat
710
719
  return report.lines();
711
720
  }
712
721
 
713
- export function renderProjects(projects: any[], columns?: number, _now = Date.now()): Span[][] {
722
+ /** #1654 T3: a list view is ` ahub <Name>` and one `▸` section holding its table. An empty list prints only its one-line empty state, as `ahub board` does (`test/reset.test.ts` pins `no retained deliveries`). */
723
+ function listReport(name: string, columns: number | undefined, ascii: boolean, context?: string): LayoutReport {
724
+ return new LayoutReport(columns, ascii).header("ahub", name, context);
725
+ }
726
+ export function renderProjects(projects: any[], columns?: number, _now = Date.now(), ascii = false): Span[][] {
714
727
  if (!projects.length) return lines("No registered projects. Run ahub init in a project directory.", columns);
715
- return rows(["PROJECT", "STATE", "PEERS", "TASKS", "ROOT"], projects.map(project => {
728
+ const report = listReport("Projects", columns, ascii);
729
+ return report.section("Projects", String(projects.length)).append(rows(["PROJECT", "STATE", "PEERS", "TASKS", "ROOT"], projects.map(project => {
716
730
  const tasks = Object.entries(project.status?.tasks ?? {}).map(([state, n]) => `${n} ${state}`).join(", ");
717
731
  return [span(project.id, "info"), span(project.state ?? "unknown", stateTone(project.state ?? "")),
718
732
  span(project.status ? Object.keys(project.status.peers ?? {}).length : "unknown", "number"), { ...span(tasks || "-"), items: Object.entries(project.status?.tasks ?? {}).map(([state, n]) => `${n} ${state}`) }, span(project.root)];
719
- }), columns, projects.map(project => project.error ? detail("error", project.error, columns, "failure") : []));
733
+ }), columns, projects.map(project => project.error ? detail("error", project.error, columns, "failure") : []))).lines();
720
734
  }
721
- export function renderQueue(deliveries: any[], columns?: number, now = Date.now()): Span[][] {
735
+ export function renderQueue(deliveries: any[], columns?: number, now = Date.now(), ascii = false): Span[][] {
722
736
  if (!deliveries.length) return lines("no retained deliveries", columns);
737
+ const report = listReport("Queue", columns, ascii);
723
738
  const s = initialConsoleState(); s.panel = 4;
724
739
  const data = deliveries.map(delivery => {
725
740
  const row = cells(s, { ...delivery, id: String(delivery.id) }, false, now);
726
741
  row[1] = span(row[1]!.text, peerTone(delivery.peer)); return row;
727
742
  });
728
- return rows([...TABLES[4]!], data, columns, deliveries.map(delivery => delivery.important ? detail("priority", "important", columns, "attention") : []));
743
+ const table = rows([...TABLES[4]!], data, columns, deliveries.map(delivery => delivery.important ? detail("priority", "important", columns, "attention") : []));
744
+ return report.section("Queue", String(deliveries.length)).append(table).lines();
729
745
  }
730
746
  const moment = (value: unknown, now: number) => {
731
747
  const at = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : NaN;
732
748
  return Number.isFinite(at) ? relative(at, now) : "unknown";
733
749
  };
734
- export function renderTurns(turns: any[], columns?: number, now = Date.now()): Span[][] {
750
+ export function renderTurns(turns: any[], columns?: number, now = Date.now(), ascii = false): Span[][] {
735
751
  if (!turns.length) return lines("no turns recorded (they need a git work tree and snapshots.enabled)", columns);
736
- return rows(["TURN", "PEER", "STARTED", "STATE", "FILES"], turns.map(turn => {
752
+ const report = listReport("Turns", columns, ascii);
753
+ return report.section("Turns", String(turns.length)).append(rows(["TURN", "PEER", "STARTED", "STATE", "FILES"], turns.map(turn => {
737
754
  const state = !turn.ended ? "running" : !turn.end_tree ? "no end snapshot" : "completed";
738
755
  const files = turn.changed ?? [];
739
756
  // #798 D2: a dirty submodule is listed beside the files, tagged, so a turn that edited only a submodule never reads "0 files".
@@ -741,25 +758,28 @@ export function renderTurns(turns: any[], columns?: number, now = Date.now()): S
741
758
  const shown = [...files, ...unobserved.map(path => `${path} (changed, contents unobserved)`)];
742
759
  return [span(turn.id, "info"), span(turn.peer ?? "unknown", peerTone(turn.peer)), span(moment(turn.started, now), "muted"),
743
760
  span(state, state === "running" ? "attention" : state === "no end snapshot" ? "failure" : "success"), { ...span(`${plural(files.length, "file")}${shown.length ? `: ${shown.join(", ")}` : ""}`), ...(shown.length ? { items: shown, pathItems: true, prefix: `${plural(files.length, "file")}:` } : {}) }];
744
- }), columns);
761
+ }), columns)).lines();
745
762
  }
746
- export function renderOrphans(orphans: { project: any; pids: number[] }[], columns?: number, _now = Date.now(), killing = false): Span[][] {
763
+ export function renderOrphans(orphans: { project: any; pids: number[] }[], columns?: number, _now = Date.now(), killing = false, ascii = false): Span[][] {
747
764
  if (!orphans.length) return lines("no orphaned hub registrations", columns);
748
- return [...lines("orphaned hub registrations (the project root is gone):", columns, "strong"),
749
- ...rows(["PROJECT", "STATE", "PIDS", "ROOT"], orphans.map(({ project, pids }) => [span(project.id, "info"), span(pids.length ? "live" : "no live process", pids.length ? "attention" : "muted"), span(pids.length ? pids.join(", ") : "-", "number"), span(project.root)]), columns),
750
- ...(killing ? [] : [[], ...lines("kill live orphans with ahub doctor --orphans --kill", columns)]),
751
- ...orphans.flatMap(({ project }) => detail("forget", `ahub projects remove ${project.id}`, columns))];
765
+ const report = listReport("Orphans", columns, ascii, "orphaned hub registrations (the project root is gone)");
766
+ report.section("Orphans", String(orphans.length)).append(
767
+ rows(["PROJECT", "STATE", "PIDS", "ROOT"], orphans.map(({ project, pids }) => [span(project.id, "info"), span(pids.length ? "live" : "no live process", pids.length ? "attention" : "muted"), span(pids.length ? pids.join(", ") : "-", "number"), span(project.root)]), columns));
768
+ if (!killing && orphans.some(({ pids }) => pids.length)) report.section("Next").next("ahub doctor --orphans --kill");
769
+ for (const { project } of orphans) report.next(`ahub projects remove ${project.id}`);
770
+ return report.lines();
752
771
  }
753
772
  /** `ahub doctor --orphans --kill` from the conductor's shell (#812, #899): the hub inspects and stops only its own positively identified process; the shell prints what it answered. */
754
- export function renderOrphanCleanup(result: unknown, columns?: number, _now = Date.now()): Span[][] {
773
+ export function renderOrphanCleanup(result: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
755
774
  const r = result as any;
756
775
  const stopped: number[] | undefined = Array.isArray(r?.stopped) ? r.stopped.filter((pid: unknown) => typeof pid === "number") : undefined;
757
- const out = stopped === undefined ? lines("stopped processes unknown", columns, "attention")
758
- : stopped.length ? lines(`stopped ${stopped.length} orphaned hub process${stopped.length === 1 ? "" : "es"}: ${stopped.join(", ")}`, columns, "success")
759
- : lines("no orphaned hub process to stop", columns, "muted");
760
- if (r?.self === true) out.push(...lines("this hub was itself an orphan and is stopping", columns, "attention"));
761
- if (r?.unknown === true) out.push(...lines("a candidate could not be confirmed stopped; a person can inspect it with ahub doctor --orphans", columns, "attention"));
762
- return out;
776
+ const report = listReport("Orphan cleanup", columns, ascii).section("Cleanup");
777
+ if (stopped === undefined) report.bullet("unknown", "stopped processes unknown");
778
+ else if (stopped.length) report.bullet("ok", `stopped ${stopped.length} orphaned hub process${stopped.length === 1 ? "" : "es"}: ${stopped.join(", ")}`);
779
+ else report.note("no orphaned hub process to stop");
780
+ if (r?.self === true) report.bullet("warn", "this hub was itself an orphan and is stopping");
781
+ if (r?.unknown === true) report.bullet("warn", "a candidate could not be confirmed stopped").next("ahub doctor --orphans");
782
+ return report.lines();
763
783
  }
764
784
  const TIME_FIELD = /^(?:at|ts|started|ended|created|updated|expires)$|(?:At|Until)$/;
765
785
  const ID_FIELD = /^(?:id|trace|previousId|sessionId|threadId|operationId|turnId|envelopeIds)$/;
@@ -809,12 +829,15 @@ export function renderExecutionBudgetStatus(budgets: unknown, columns?: number,
809
829
  return [...lines("Execution budget", columns, "strong"), ...(Array.isArray(budgets) && !budgets.length ? lines("No execution budgets configured.", columns) : budgets === undefined ? lines("No matching execution budget.", columns) : fields(budgets, columns, now))];
810
830
  }
811
831
  /** Retain the report's coverage and attribution sentences; add sections and aligned counters for scanning. */
812
- export function renderReport(report: Report | TaskReport, columns?: number, now = Date.now(), byTask = false): Span[][] {
813
- const out = lines(`period: ${report.from ? moment(report.from, now) : "-"} .. ${report.to ? moment(report.to, now) : "-"}`, columns, "muted");
832
+ export function renderReport(report: Report | TaskReport, columns?: number, now = Date.now(), byTask = false, ascii = false): Span[][] {
833
+ // #1654 T3: the shared header and `▸` section marks; the period line and every sentence keep their words.
834
+ const out: Span[][] = new LayoutReport(columns, ascii).header("ahub", byTask ? "Report by task" : "Report").lines();
835
+ out.push(...lines(`period: ${report.from ? moment(report.from, now) : "-"} .. ${report.to ? moment(report.to, now) : "-"}`, columns, "muted"));
836
+ const mark = (name: string) => { out.push(...new LayoutReport(columns, ascii).section(name).lines()); };
814
837
  const formatted = byTask ? formatTaskReport(report as TaskReport) : formatReport(report as Report);
815
838
  if (!byTask) {
816
839
  const r = report as Report;
817
- out.push([], ...lines("Counters", columns, "strong"), ...rows(["METRIC", "COUNT"], [
840
+ out.push([]); mark("Counters"); out.push(...rows(["METRIC", "COUNT"], [
818
841
  [span("messages"), span(r.messages.total, "number")], [span("overflow"), span(r.messages.overflow, "number")],
819
842
  [span("undeliverable"), span(r.messages.undeliverable, "number")], [span("messages per task"), span(r.messages.perTask, "number")],
820
843
  [span("overlap warnings"), span(r.overlaps.warnings, "number")], [span("task pairs"), span(r.overlaps.pairs, "number")],
@@ -828,7 +851,7 @@ export function renderReport(report: Report | TaskReport, columns?: number, now
828
851
  for (const sentence of formatted.slice(1)) {
829
852
  const name = section(sentence);
830
853
  if (name !== previous) {
831
- out.push([], ...lines(name, columns, "strong")); previous = name;
854
+ out.push([]); mark(name); previous = name;
832
855
  if (name === "Peers" && !byTask) out.push(...rows(["PEER", "TURNS", "BUSY", "TOKENS"], Object.entries((report as Report).peers).map(([peer, p]) => [span(peer, peerTone(peer)), span(p.turns ?? "unknown", "number"), span(`${p.busyMinutes}m`, "muted"), span(p.tokens || "unknown", "number")]), columns));
833
856
  if (name === "Tasks" && byTask) out.push(...rows(["TASK", "CLASS", "OUTCOME", "TURNS", "WALL"], Object.entries((report as TaskReport).tasks).map(([id, task]) => [span(`#${id}${task.pii ? " [pii]" : ""}`, "taskRef"), span(task.class ?? "unknown"), span(task.outcome ?? "unknown", stateTone(task.outcome ?? "")), span(task.turns, "number"), span(task.wallMs === null ? "unknown" : duration(task.wallMs), "muted")]), columns));
834
857
  }
@@ -1,7 +1,7 @@
1
1
  import { milestoneId, milestoneRevision, milestoneLinkRef, parseMilestoneInput, parseMilestonePatch, githubRepo, type MilestoneLinkKind } from "../hub/roadmap.ts";
2
2
  import { terminalText, wrap } from "./console-state.ts";
3
3
 
4
- const optionalFields = "[--horizon now|next|later] [--order <n>] [--target YYYY-MM-DD|none] [--parent <id>|none]";
4
+ const optionalFields = "[--horizon now|next|later] [--order <n>] [--target <date>|none] [--parent <id>|none]";
5
5
  export const ROADMAP_FORMS = {
6
6
  list: "[list] [--json]", show: "show <id> [--json]",
7
7
  new: `new --title <text> --outcome <text> ${optionalFields}`,
@@ -131,7 +131,7 @@ export function parseRoadmapArgs(argv: readonly string[]): RoadmapArgs {
131
131
  if (word.startsWith("-")) return usage("unknown roadmap option");
132
132
  operands.push(word);
133
133
  }
134
- if (json && command !== "list" && command !== "show") return usage("roadmap --json is available on list and show only");
134
+ if (json && command !== "list" && command !== "show") return usage("ahub roadmap --json works with list, show, check and export. Run ahub help roadmap for usage");
135
135
  if (command === "list") {
136
136
  if (operands.length) return usage("roadmap list takes no operands");
137
137
  return { op: "hub_roadmap_list", args: {}, json };
@@ -0,0 +1,71 @@
1
+ // Human output for `ahub room` (#1724, from #1654 item 20). Pure: validated rows in, spans out, no I/O. `--json` is the caller's branch and prints the same rows.
2
+ import { roomReceiptReasonText } from "../rooms/application.ts";
3
+ import { moment } from "./sdlc-output.ts";
4
+ import { Report, type MarkerName, type Span } from "./console-state.ts";
5
+
6
+ const list = (value: unknown): any[] => Array.isArray(value) ? value : [];
7
+ const age = (value: unknown) => typeof value === "number" ? `${value}ms` : "unknown";
8
+ const peerMarker = (state: unknown): MarkerName => state === "idle" ? "ok" : state === "busy" ? "active" : state === "paused" ? "pending" : state === "offline" ? "absent" : "unknown";
9
+ const deliveryMarker = (state: unknown): MarkerName => /^completed|^disposed/.test(String(state)) ? "ok" : state === "failed_safe" || state === "needs_review" ? "warn" : "pending";
10
+
11
+ /** `ahub room list` and `ahub room status`: one section per room; status adds the link, the outbox, refusals, remote peers and deliveries. */
12
+ export function renderRooms(rows: unknown, status: boolean, columns?: number, ascii = false): Span[][] {
13
+ const rooms = list(rows);
14
+ const out = new Report(columns, ascii).titled("ahub", status ? "Room status" : "Rooms", String(rooms.length));
15
+ if (!rooms.length) out.note("no rooms");
16
+ for (const row of rooms) {
17
+ out.section(String(row.name), String(row.state)).kv([["room", row.room], ["epoch", row.epoch], ["owner", row.owner], ["member", row.member]]);
18
+ if (status) {
19
+ const health = row.health;
20
+ if (row.state === "online" && (row.linkCause === null || row.linkCause === undefined)) out.bullet("ok", "link online");
21
+ else out.bullet("warn", `link cause ${row.linkCause ?? "unknown"}`).note(row.linkNextStep ?? "Check broker availability, then read ahub room status again.");
22
+ out.bullet("unknown", `outbox ${health?.outboxDepth ?? "unknown"}; oldest ${age(health?.oldestOutboxAgeMs)}; last receipt ${age(health?.lastReceiptAgeMs)}`);
23
+ out.bullet(health?.refused ? "warn" : "unknown", `refused: ${health?.refused ? Object.entries(health.refused).map(([reason, count]) => `${reason} ${count}`).join(", ") : "unknown"}`);
24
+ }
25
+ for (const peer of list(row.remotePeers)) {
26
+ out.bullet(peerMarker(peer.presence ?? peer.state), `peer ${peer.id}: ${peer.presence ?? peer.state}${peer.liveness === "untracked" ? "; liveness not tracked (broker without ephemeral); upgrade the broker to track liveness" : ""}`);
27
+ }
28
+ for (const delivery of list(row.deliveries)) {
29
+ if (!("id" in delivery)) out.bullet(delivery.needsReview > 0 ? "warn" : "pending", `inbound: pending ${delivery.pending}, needs_review ${delivery.needsReview}${delivery.truncated ? "; truncated" : ""}`);
30
+ else out.bullet(deliveryMarker(delivery.state), `${delivery.direction} ${delivery.id}: ${delivery.state}; application ${delivery.application}; peer ${delivery.peer}${delivery.disposition ? `; person disposition ${delivery.disposition}` : ""}${delivery.lateReceipt ? `; late receipt evidence ${delivery.lateReceipt}` : ""}${delivery.refusalReason ? `; refusal ${roomReceiptReasonText(delivery.refusalReason)}` : ""}${delivery.holdReason ? "; reason epoch rotated; inspect ahub queue show before resolving" : ""}`);
31
+ }
32
+ }
33
+ return out.lines();
34
+ }
35
+
36
+ /** `ahub room inbox [<name>]`: the person inbox metadata, never a body. */
37
+ export function renderRoomInbox(rows: unknown, now = Date.now(), columns?: number, ascii = false): Span[][] {
38
+ const items = list(rows);
39
+ const out = new Report(columns, ascii).titled("ahub", "Room inbox", String(items.length)).section("Messages", String(items.length));
40
+ if (!items.length) out.note("the inbox is empty");
41
+ for (const row of items) {
42
+ out.bullet(row.state === "unread" ? "pending" : "ok", `${row.id} ${row.name} ${row.from} ${row.state}; received ${moment(row.receivedAt, now)}; expires ${moment(row.expiresAt, now)}; ${row.bytes} bytes`);
43
+ out.note(`sender ${row.sender}`);
44
+ }
45
+ return out.lines();
46
+ }
47
+
48
+ /** `ahub room inbox done|discard|show`: the one line that says what the item became. */
49
+ export function renderRoomInboxResult(item: { id: string; state: string }, bodyUnavailable: boolean, columns?: number, ascii = false): Span[][] {
50
+ return new Report(columns, ascii).titled("ahub", "Room inbox", item.state).section("Result").bullet(bodyUnavailable ? "warn" : "ok", `Room inbox ${item.id}: ${item.state}${bodyUnavailable ? " (body unavailable)" : ""}`).lines();
51
+ }
52
+
53
+ /** The confirmation preview of a membership change: both fingerprints to compare out of band, then the deliveries an epoch change leaves behind. */
54
+ export function renderRoomPreview(action: string, preview: { owner: string; member: string; outstanding?: readonly string[] }, columns?: number, ascii = false): Span[][] {
55
+ const out = new Report(columns, ascii).titled("ahub", `Room ${action}`, "preview");
56
+ out.section("Fingerprints").kv([["Owner fingerprint", preview.owner], ["Member fingerprint", preview.member]]);
57
+ if (preview.outstanding !== undefined) {
58
+ out.section("Outstanding", String(preview.outstanding.length)).note(`Outstanding deliveries on the old epoch (${preview.outstanding.length})`);
59
+ for (const id of preview.outstanding) out.note(id, "value");
60
+ }
61
+ return out.lines();
62
+ }
63
+
64
+ /** What a confirmed membership change did: the room it named and, for an artifact, the line that introduces it (the artifact itself is printed raw so it copies exactly). */
65
+ export function renderRoomResult(action: string, result: { name?: string; disposed?: boolean; artifact?: boolean }, columns?: number, ascii = false): Span[][] {
66
+ const out = new Report(columns, ascii).titled("ahub", `Room ${action}`, "done").section("Result");
67
+ if (result.name !== undefined) out.bullet("ok", `Room: ${result.name}`);
68
+ if (result.artifact) out.bullet("ok", "Room artifact (share out of band):");
69
+ else out.bullet("ok", result.disposed ? "room resolve: disposed" : `room ${action}: complete`);
70
+ return out.lines();
71
+ }
package/src/cli/room.ts CHANGED
@@ -2,7 +2,8 @@ import { projectRoomUnavailable, projectRoomDiagnostics, type RoomStatusDiagnost
2
2
  import { decodeBase64url } from "../rooms/crypto.ts";
3
3
  import { roomReceiptReasonText, type RoomReceiptReason } from "../rooms/application.ts";
4
4
  import { frame, type Envelope } from "../hub/envelope.ts";
5
- import { terminalText } from "./console-state.ts";
5
+ import { paint, terminalText, type Span } from "./console-state.ts";
6
+ import { renderRoomInbox, renderRoomInboxResult, renderRoomPreview, renderRoomResult, renderRooms } from "./room-output.ts";
6
7
  import { ROOM_STORE_LIMITS, type RoomPersonInboxMeta, type RoomPersonInboxItem } from "../rooms/store.ts";
7
8
  /** Membership mutations and inbox forms are person-only; main.ts refuses agent/live-test calls before importing this module. */
8
9
  export const ROOM_USAGE = "usage: ahub room create <name> --broker <url> [--label <id>] | invite <name> [--accept <request>] | join <token> [--name <name>] [--label <id>] | join <name> --roster <signed-roster> | leave <name> | revoke <name> <fingerprint> | expose <name> [<peer>...] | resolve <name> --frame <digest> --action accept|discard (membership mutations and resolve require TTY y/N or --confirm <member-fingerprint-prefix>, 16..64 lowercase hex) | list [--json] | status [<name>] [--json] | inbox [<name>] [--json] | inbox show|done|discard <id>";
@@ -242,7 +243,12 @@ function inboxItem(value: unknown, expectedId: string): RoomPersonInboxItem {
242
243
  return { ...meta, body };
243
244
  }
244
245
 
245
- async function runInboxCommand(options: Extract<RoomCliCommand, { op: "inbox" }>, request: RoomRequest): Promise<void> {
246
+ /** How a human view is drawn: the terminal width, color and ASCII markers `main.ts` resolved for this process; a test passes none and reads plain lines. */
247
+ export interface RoomPresentation { columns?: number; color?: boolean; ascii?: boolean }
248
+ // ponytail: the one print loop of this module; it moves onto a shared printer when main.ts's printOutput leaves main.ts (#1724).
249
+ const show = (lines: readonly Span[][], present: RoomPresentation) => { for (const line of lines) console.log(paint(line, present.color === true)); };
250
+
251
+ async function runInboxCommand(options: Extract<RoomCliCommand, { op: "inbox" }>, request: RoomRequest, present: RoomPresentation): Promise<void> {
246
252
  if (options.action === "list") {
247
253
  const reply = record(await request({ t: "room", op: "inbox_list", input: options.input }));
248
254
  if (reply.ok !== true && reply.code === "inbox_list_limit") fail("inbox_list_limit");
@@ -252,72 +258,52 @@ async function runInboxCommand(options: Extract<RoomCliCommand, { op: "inbox" }>
252
258
  const rows = value.map(inboxMeta);
253
259
  if (new Set(rows.map(row => row.id)).size !== rows.length || options.input.name !== undefined && rows.some(row => row.name !== options.input.name)) fail("invalid_reply");
254
260
  if (options.json) return console.log(JSON.stringify(rows));
255
- console.log(`Room inbox (${rows.length})`);
256
- for (const row of rows) console.log(`${row.id} ${row.name} ${row.from} ${row.state}; received ${row.receivedAt}; expires ${row.expiresAt}; ${row.bytes} bytes\n sender ${row.sender}`);
261
+ show(renderRoomInbox(rows, Date.now(), present.columns, present.ascii), present);
257
262
  return;
258
263
  }
259
264
  const reply = success(await request({ t: "room", op: `inbox_${options.action}`, input: options.input }));
260
265
  if (options.action !== "show") {
261
266
  const item = inboxMeta(reply.item);
262
267
  if (item.id !== options.input.id || item.state === "unread") fail("invalid_reply");
263
- console.log(`Room inbox ${item.id}: ${item.state}`);
268
+ show(renderRoomInboxResult(item, false, present.columns, present.ascii), present);
264
269
  return;
265
270
  }
266
271
  const item = inboxItem(reply.item, options.input.id);
267
- if (item.body === undefined) { console.log(`Room inbox ${item.id}: ${item.state} (body unavailable)`); return; }
272
+ if (item.body === undefined) { show(renderRoomInboxResult(item, true, present.columns, present.ascii), present); return; }
268
273
  const env: Envelope = { id: item.id, trace: item.id, hop: 0, from: item.from, to: ["user"], kind: "chat", priority: "status", ts: item.receivedAt, body: terminalText(item.body) };
269
- console.log(frame(env));
274
+ console.log(frame(env)); // a hub envelope frame, the same text `ahub inbox` prints
270
275
  }
271
276
 
272
277
  /** Uses one already authenticated control connection so an ephemeral preview ticket cannot cross callers. */
273
- export async function runRoomCommand(args: readonly string[], request: RoomRequest, io: RoomConfirmationIO = confirmationIO): Promise<void> {
278
+ export async function runRoomCommand(args: readonly string[], request: RoomRequest, io: RoomConfirmationIO = confirmationIO, present: RoomPresentation = {}): Promise<void> {
274
279
  const command = parseRoomCommand(args);
275
- if (command.op === "inbox") return runInboxCommand(command, request);
280
+ if (command.op === "inbox") return runInboxCommand(command, request, present);
276
281
  if (command.op !== "mutation") {
277
282
  const result = success(await request({ t: "room", op: command.op, input: command.input })), rows = roomRows(result.rooms);
278
283
  if (args.includes("--json")) return console.log(JSON.stringify(rows));
279
- console.log(`Rooms (${rows.length})`);
280
- for (const row of rows) {
281
- console.log(`${row.name} ${row.room} epoch ${row.epoch} ${row.state}\n owner ${row.owner}\n member ${row.member}`);
282
- if (command.op === "status") {
283
- const health = row.health, age = (value: number | null | undefined) => typeof value === "number" ? `${value}ms` : "unknown";
284
- if (row.state === "online" && (row.linkCause === null || row.linkCause === undefined)) console.log(" link online");
285
- else console.log(` link cause ${row.linkCause ?? "unknown"}; next: ${row.linkNextStep ?? "Check broker availability, then read ahub room status again."}`);
286
- console.log(` outbox ${health?.outboxDepth ?? "unknown"}; oldest ${age(health?.oldestOutboxAgeMs)}; last receipt ${age(health?.lastReceiptAgeMs)}`);
287
- console.log(` refused: ${health?.refused ? Object.entries(health.refused).map(([reason, count]) => `${reason} ${count}`).join(", ") : "unknown"}`);
288
- }
289
- for (const peer of row.remotePeers ?? []) console.log(` peer ${peer.id}: ${peer.presence ?? peer.state}${peer.liveness === "untracked" ? "; liveness not tracked (broker without ephemeral); upgrade the broker to track liveness" : ""}`);
290
- for (const delivery of row.deliveries ?? []) {
291
- if (!("id" in delivery)) console.log(` inbound: pending ${delivery.pending}, needs_review ${delivery.needsReview}${delivery.truncated ? "; truncated" : ""}`);
292
- else console.log(` ${delivery.direction} ${delivery.id}: ${delivery.state}; application ${delivery.application}; peer ${delivery.peer}${delivery.disposition ? `; person disposition ${delivery.disposition}` : ""}${delivery.lateReceipt ? `; late receipt evidence ${delivery.lateReceipt}` : ""}${delivery.refusalReason ? `; refusal ${roomReceiptReasonText(delivery.refusalReason)}` : ""}${delivery.holdReason ? "; reason epoch rotated; inspect ahub queue show before resolving" : ""}`);
293
- }
294
- }
284
+ show(renderRooms(rows, command.op === "status", present.columns, present.ascii), present);
295
285
  return;
296
286
  }
297
287
  const preview = success(await request({ t: "room", op: "preview", action: command.action, input: command.input }));
298
288
  if (typeof preview.owner !== "string" || !FP.test(preview.owner) || typeof preview.member !== "string" || !FP.test(preview.member)
299
289
  || typeof preview.ticket !== "string" || !/^[A-Za-z0-9_-]{16,128}$/.test(preview.ticket)) fail("invalid_reply");
300
- console.log(`Owner fingerprint: ${preview.owner}`);
301
- console.log(`Member fingerprint: ${preview.member}`);
302
290
  if (preview.outstanding !== undefined) {
303
291
  if (!Array.isArray(preview.outstanding) || preview.outstanding.length > ROOM_STORE_LIMITS.outboxPerRoom
304
292
  || preview.outstanding.some(value => typeof value !== "string" || !UUID.test(value)) || new Set(preview.outstanding).size !== preview.outstanding.length) fail("invalid_reply");
305
- console.log(`Outstanding deliveries on the old epoch (${preview.outstanding.length}):`);
306
- for (const id of preview.outstanding) console.log(` ${id}`);
307
293
  }
294
+ show(renderRoomPreview(command.action, { owner: preview.owner, member: preview.member, ...(preview.outstanding !== undefined ? { outstanding: preview.outstanding as string[] } : {}) }, present.columns, present.ascii), present);
308
295
  const confirm = await confirmMember(preview.member, command.confirm, io);
309
296
  const result = success(await request({ t: "room", op: "execute", ticket: preview.ticket, confirm }));
310
297
  if (result.name !== undefined) {
311
298
  if (typeof result.name !== "string" || !ID.test(result.name)) fail("invalid_reply");
312
- console.log(`Room: ${result.name}`);
313
299
  }
314
300
  if (result.artifact !== undefined) {
315
301
  if (typeof result.artifact !== "string") fail("invalid_reply");
316
302
  let encoded: string;
317
303
  try { encoded = artifact(result.artifact); } catch { return fail("invalid_reply"); }
318
- console.log("Room artifact (share out of band):");
319
- console.log(encoded);
320
- } else console.log(command.action === "resolve" && result.kind === "disposed" ? "room resolve: disposed" : `room ${command.action}: complete`);
304
+ show(renderRoomResult(command.action, { ...(typeof result.name === "string" ? { name: result.name } : {}), artifact: true }, present.columns, present.ascii), present);
305
+ console.log(encoded); // raw on purpose: the artifact is copied exactly, never wrapped or painted
306
+ } else show(renderRoomResult(command.action, { ...(typeof result.name === "string" ? { name: result.name } : {}), disposed: command.action === "resolve" && result.kind === "disposed" }, present.columns, present.ascii), present);
321
307
  }
322
308
 
323
309
  /** Never echo tokens, broker URLs, daemon payloads or native diagnostics on refusal. */
@@ -1,8 +1,7 @@
1
1
  // Human output for `ahub schedule list|run|pause|resume` (#335). Pure: parsed hub JSON in, spans out, no I/O. `--json` is the caller's branch and prints the same text.
2
2
  // Titles and details are task text and never appear here: a schedule is named by its id, period, class and queue.
3
- import { blank, grid, heading, pair, s } from "./sdlc-output.ts";
4
- import { moment } from "./sdlc-output.ts";
5
- import type { Span, Tone } from "./console-state.ts";
3
+ import { grid, moment, s } from "./sdlc-output.ts";
4
+ import { Report, plural, type Span, type Tone } from "./console-state.ts";
6
5
  import { schedulePeriodText, scheduleWhen } from "../hub/schedules.ts";
7
6
 
8
7
  const list = (value: unknown): any[] => Array.isArray(value) ? value : [];
@@ -17,37 +16,39 @@ export const nextText = (row: any, now: number): string => {
17
16
  };
18
17
 
19
18
  /** `ahub schedule list`: one row per configured schedule with its next run. */
20
- export function renderScheduleList(rows: unknown, columns?: number, now = Date.now()): Span[][] {
19
+ export function renderScheduleList(rows: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
21
20
  const schedules = list(rows);
22
21
  if (!schedules.length) return [[s("no schedules configured; add them under `schedules` in .agenthub/config.local.json", "muted")]];
23
- const out: Span[][] = [...heading(`Schedules (${schedules.length})`, columns)];
24
- out.push(...grid(["ID", "SCHEDULE", "CLASS", "QUEUE", "STATE", "NEXT RUN", "LAST RUN", "TASK"], schedules.map((row: any) => [
22
+ const out = new Report(columns, ascii).titled("ahub", `Schedules (${schedules.length})`);
23
+ out.section("Configured", String(schedules.length)).append(grid(["ID", "SCHEDULE", "CLASS", "QUEUE", "STATE", "NEXT RUN", "LAST RUN", "TASK"], schedules.map((row: any) => [
25
24
  s(row.id, "issueRef"), s(row.cron !== undefined ? schedulePeriodText(row) : String(row.every)), s(row.class), s(row.queue), s(row.state, TONE[row.state]), s(nextText(row, now), TONE[row.state]),
26
25
  s(row.last ? moment(row.last, now) : "never", "muted"), s(row.task === undefined ? "-" : `#${row.task}`, "taskRef"),
27
26
  ]), columns));
28
27
  for (const row of schedules) {
29
- if (row.coalesced) out.push(blank, ...pair(row.id, `${row.coalesced} due tick${row.coalesced === 1 ? "" : "s"} skipped; one run follows when it can`, columns, 12, "muted"));
30
- if (row.error) out.push(blank, ...pair(row.id, `last run failed: ${row.error}`, columns, 12, "attention"));
28
+ if (row.coalesced) out.note(`${row.id}: ${plural(row.coalesced, "due tick")} skipped; one run follows when it can`);
29
+ if (row.error) out.bullet("warn", `${row.id}: last run failed: ${row.error}`);
31
30
  }
32
- return out;
31
+ return out.lines();
33
32
  }
34
33
 
35
34
  const RESULT: Record<string, string> = { changed: "not run: it was paused or resumed meanwhile", ran: "ran", held: "not run: the hub is held (stopping or recovering)", waiting: "not run: the task its last run made is still open", failed: "failed" };
36
35
 
37
36
  /** `ahub schedule run <id>`: what the run did. */
38
- export function renderScheduleRun(result: unknown, columns?: number): Span[][] {
37
+ export function renderScheduleRun(result: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
39
38
  const r = result as any;
40
- const out: Span[][] = [...heading(`Schedule ${r?.id ?? "?"}: ${RESULT[r?.outcome] ?? "unknown outcome"}`, columns)];
41
- if (r?.task !== undefined) out.push(...pair("task", `#${r.task}`, columns, 8, "taskRef"));
42
- if (r?.reason) out.push(...pair("because", String(r.reason), columns, 8, "attention"));
43
- if (r?.outcome === "ran") out.push(...pair("next", "its period restarts now", columns, 8, "muted"));
44
- return out;
39
+ const out = new Report(columns, ascii).titled("ahub", `Schedule ${r?.id ?? "?"}: ${RESULT[r?.outcome] ?? "unknown outcome"}`);
40
+ const rows: [string, unknown][] = [];
41
+ if (r?.task !== undefined) rows.push(["task", `#${r.task}`]);
42
+ if (r?.outcome === "ran") rows.push(["next", "its period restarts now"]);
43
+ if (rows.length) out.section("Run").kv(rows);
44
+ if (r?.reason) out.bullet("warn", `because: ${String(r.reason)}`);
45
+ return out.lines();
45
46
  }
46
47
 
47
48
  /** `ahub schedule pause|resume <id>`: the schedule as the hub now holds it. */
48
- export function renderScheduleChange(op: "pause" | "resume", rows: unknown, columns?: number, now = Date.now()): Span[][] {
49
+ export function renderScheduleChange(op: "pause" | "resume", rows: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
49
50
  const row = list(rows)[0];
50
- const out: Span[][] = [...heading(`Schedule ${row?.id ?? "?"} ${op === "pause" ? "paused" : "resumed"}`, columns)];
51
- if (row) out.push(...pair("state", row.state, columns, 8, TONE[row.state]), ...pair("next run", nextText(row, now), columns, 8));
52
- return out;
51
+ const out = new Report(columns, ascii).titled("ahub", `Schedule ${row?.id ?? "?"} ${op === "pause" ? "paused" : "resumed"}`);
52
+ if (row) out.section("Schedule").kv([["state", row.state], ["next run", nextText(row, now)]]);
53
+ return out.lines();
53
54
  }