@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
@@ -2,46 +2,49 @@
2
2
  // Layout follows #284: aligned columns from the shared `table`, long text wrapped under its label (never cut),
3
3
  // semantic tones, readable times (`2026-10-25 14:20 UTC (3h05m ago)`, never a raw ISO string). `--json` is the caller's
4
4
  // branch and prints the hub's reply untouched, so nothing here may be the only copy of a field.
5
- import { duration, plural, relative, table, terminalText, wrap, type Span, type Tone } from "./console-state.ts";
5
+ import { duration, plural, relative, table, terminalText, wrap, Report as LayoutReport, type Span, type Tone } from "./console-state.ts";
6
+ import { readbackSummary, type ReadbackView } from "../hub/spec-readback.ts";
6
7
 
7
8
  type Line = Span[];
8
9
  /** Configuration remains restart-bound; the claim is caller provenance, not inferred release consent. */
9
- export function renderSdlcConfiguration(value: unknown, columns?: number): Span[][] {
10
+ export function renderSdlcConfiguration(value: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
10
11
  const row = value as any;
11
- const out = heading(list(row?.restartPending).length ? "SDLC configuration saved; restart pending" : "SDLC configuration saved", columns);
12
- out.push(...pair("actor", row?.by ?? "unknown", columns, 12));
13
- out.push(...pair("instruction", "person's explicit instruction claimed for this session", columns, 12));
14
- for (const line of list(row?.lines)) out.push(...para(String(line), columns));
15
- if (row?.backup) out.push(...pair("backup", row.backup, columns, 12));
16
- return out;
12
+ const out = new LayoutReport(columns, ascii).titled("ahub", "SDLC configuration", list(row?.restartPending).length ? "saved; restart pending" : "saved");
13
+ const rows: [string, unknown][] = [["actor", row?.by ?? "unknown"], ["instruction", "person's explicit instruction claimed for this session"]];
14
+ if (row?.backup) rows.push(["backup", row.backup]);
15
+ out.section("Receipt").kv(rows);
16
+ if (list(row?.lines).length) { out.section("Details"); for (const line of list(row.lines)) out.note(String(line), "value"); }
17
+ return out.lines();
17
18
  }
18
19
  /** Survey fields already passed the host's task and security disclosure policy. */
19
- export function renderSdlcSurvey(value: unknown, columns?: number): Span[][] {
20
+ export function renderSdlcSurvey(value: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
20
21
  const row = value as any;
21
- if (!row) return [[s("no advisor survey", "muted")]];
22
- const out: Span[][] = [...heading(`Advisor survey, task ${row.task ?? "unknown"}`, columns)];
23
- for (const field of ["survey", "ref", "focus"]) if (row[field] !== undefined) out.push(...pair(field, row[field], columns, 12));
24
- if (row.withheld || row.status === "private") return [...out, [s("report withheld by current privacy", "attention")]];
22
+ if (!row) return new LayoutReport(columns, ascii).header("ahub", "Advisor survey").note("no advisor survey").lines();
23
+ const out = new LayoutReport(columns, ascii).titled("ahub", "Advisor survey", `task ${row.task ?? "unknown"}`);
24
+ const head = ["survey", "ref", "focus"].filter(field => row[field] !== undefined).map((field): [string, unknown] => [field, row[field]]);
25
+ if (head.length) out.section("Survey").kv(head);
26
+ if (row.withheld || row.status === "private") return out.bullet("warn", "report withheld by current privacy").lines();
27
+ const rejectedRows = (rejected: any, unknownWhen: boolean): [string, unknown][] => {
28
+ const rows: [string, unknown][] = [["rejected before", rejected.id]];
29
+ if (unknownWhen) rows.push(["change", "unknown (suppression retained)"]);
30
+ if (!rejected.withheld && rejected.reason) rows.push(["reason", rejected.reason]);
31
+ return rows;
32
+ };
25
33
  for (const item of list(row.items)) {
26
34
  const finding = item.finding ?? item;
27
- out.push(...pair("finding", finding.id, columns, 12));
28
- if (finding.withheld || item.withheld) { out.push(...pair("details", "withheld", columns, 12)); continue; }
29
- for (const field of ["evidence", "impact", "effort", "risk", "confidence", "fix_sketch"]) if (finding[field] !== undefined) out.push(...pair(field, finding[field], columns, 12));
30
- if (item.decision) out.push(...pair("decision", item.decision.verdict, columns, 12));
31
- else if (item.verdict) out.push(...pair("decision", item.verdict, columns, 12));
32
- if (item.rejectedBefore?.rejectedBefore || item.rejectedBefore === true) out.push(...pair("history", "rejected before", columns, 12, "attention"));
33
- for (const rejected of list(item.rejected)) {
34
- out.push(...pair("rejected before", rejected.id, columns, 16));
35
- if (rejected.change === "unknown") out.push(...pair("change", "unknown (suppression retained)", columns, 16, "attention"));
36
- if (!rejected.withheld && rejected.reason) out.push(...pair("reason", rejected.reason, columns, 16));
37
- }
38
- }
39
- for (const rejected of list(row.rejected)) {
40
- out.push(...pair("rejected before", rejected.id, columns, 16));
41
- if (rejected.status === "unknown" || rejected.change === "unknown") out.push(...pair("change", "unknown (suppression retained)", columns, 16, "attention"));
42
- if (!rejected.withheld && rejected.reason) out.push(...pair("reason", rejected.reason, columns, 16));
35
+ out.section(`Finding ${terminalText(finding.id ?? "unknown")}`);
36
+ if (finding.withheld || item.withheld) { out.kv([["details", "withheld"]]); continue; }
37
+ const rows: [string, unknown][] = [];
38
+ for (const field of ["evidence", "impact", "effort", "risk", "confidence", "fix_sketch"]) if (finding[field] !== undefined) rows.push([field, finding[field]]);
39
+ if (item.decision) rows.push(["decision", item.decision.verdict]);
40
+ else if (item.verdict) rows.push(["decision", item.verdict]);
41
+ if (item.rejectedBefore?.rejectedBefore || item.rejectedBefore === true) rows.push(["history", "rejected before"]);
42
+ for (const rejected of list(item.rejected)) rows.push(...rejectedRows(rejected, rejected.change === "unknown"));
43
+ out.kv(rows.length ? rows : [["details", "none recorded"]]);
43
44
  }
44
- return out;
45
+ const rejected = list(row.rejected);
46
+ if (rejected.length) out.section("Rejected before", String(rejected.length)).kv(rejected.flatMap((entry: any) => rejectedRows(entry, entry.status === "unknown" || entry.change === "unknown")));
47
+ return out.lines();
45
48
  }
46
49
  export const s = (value: unknown, tone?: Tone): Span => ({ text: terminalText(value).replace(/[\n\t]/g, " "), ...(tone ? { tone } : {}) });
47
50
  const room = (columns?: number) => columns ?? Infinity;
@@ -58,16 +61,12 @@ export function moment(at: unknown, now: number): string {
58
61
  }
59
62
  const span = (ms: unknown) => typeof ms === "number" && Number.isFinite(ms) ? duration(ms) : "unknown";
60
63
 
61
- /** Text wrapped to the width, continuation lines hanging under `indent`. */
62
- function para(text: string, columns: number | undefined, tone?: Tone, indent = "", hang = 2): Line[] {
63
- return wrap(indent + text, room(columns), hang).map(line => [s(line, tone)]);
64
- }
65
64
  /**
66
65
  * `label value`, the value wrapped beside its own label so narrow terminals never separate them. When the longest word of
67
66
  * the value does not fit in the room left of the label column, the value moves under the label instead, so a path or id
68
67
  * is broken only when it is wider than the whole terminal.
69
68
  */
70
- export function pair(label: string, value: unknown, columns: number | undefined, labelWidth: number, tone?: Tone, indent = ""): Line[] {
69
+ function pair(label: string, value: unknown, columns: number | undefined, labelWidth: number, tone?: Tone, indent = ""): Line[] {
71
70
  const text = terminalText(value).replace(/[\n\t]/g, " ");
72
71
  const head = indent + label.padEnd(labelWidth) + " ";
73
72
  const longest = Math.max(0, ...text.split(/\s+/).map(textWidth));
@@ -78,11 +77,6 @@ export function pair(label: string, value: unknown, columns: number | undefined,
78
77
  const lines = wrap(head + text, room(columns), head.length);
79
78
  return lines.map((line, i) => i === 0 ? [s(line.slice(0, head.length), "muted"), s(line.slice(head.length), tone)] : [s(line, tone)]);
80
79
  }
81
- /** Items under a label, one per line, wrapped under the dash. */
82
- function bullets(label: string, items: readonly unknown[], columns: number | undefined, tone?: Tone, indent = ""): Line[] {
83
- if (!items.length) return [];
84
- return [[s(indent + label, "muted")], ...items.flatMap(item => para(`- ${terminalText(item)}`, columns, tone, indent + (columns !== undefined && indent.length + 2 + 2 + Math.max(0, ...terminalText(item).split(/\s+/).map(textWidth)) > columns ? "" : " "), 2))];
85
- }
86
80
  const GAP = 2;
87
81
  const textWidth = (text: string) => Bun.stringWidth(text);
88
82
  /**
@@ -110,15 +104,13 @@ export function grid(head: string[], data: Span[][], columns: number | undefined
110
104
  });
111
105
  return table(head, physical, columns, widths);
112
106
  }
107
+ const blank: Line = [s("")];
113
108
  /** Narrow terminal: each row becomes its own block, the first column as its heading and every other column beside its label. */
114
109
  function blocks(head: string[], data: Span[][], columns: number): Line[] {
115
110
  const label = Math.max(...head.slice(1).map(textWidth));
116
111
  return data.flatMap((row, n) => [...(n ? [blank] : []), ...wrap(row[0]?.text ?? "", columns, 2).map((line): Line => [{ ...(row[0] ?? s("")), text: line }]),
117
112
  ...head.slice(1).flatMap((name, i) => pair(name.toLowerCase(), row[i + 1]?.text ?? "", columns, label, row[i + 1]?.tone, " "))]);
118
113
  }
119
- /** A heading wraps to the width like any paragraph; a long repository name never pushes it past the terminal. */
120
- export const heading = (text: string, columns?: number): Line[] => wrap(text, room(columns), 2).map(line => [s(line, "strong")]);
121
- export const blank: Line = [s("")];
122
114
  const readyTone = (ready: unknown): Tone => ready === true ? "success" : "attention";
123
115
 
124
116
  // ---- sdlc status / explain ----------------------------------------------------------------------------------------
@@ -128,89 +120,107 @@ function receiptLine(receipt: any): string {
128
120
  receipt?.pr ? `PR #${receipt.pr}` : undefined, receipt?.head ? `head ${short(receipt.head)}` : undefined].filter(Boolean);
129
121
  return parts.length ? parts.join(", ") : "no issue or PR recorded";
130
122
  }
131
- function taskBlock(row: any, columns: number | undefined, detail: boolean): Line[] {
132
- const id = `#${row.id}`;
133
- const out: Line[] = para(`${id} ${row.title ?? ""}`, columns, undefined, "", 6)
134
- .map((line, i) => i === 0 ? [s(id, "taskRef"), s(line[0]!.text.slice(id.length), "strong")] : line);
135
- out.push(...pair("lifecycle", `stage ${row.stage ?? "unknown"}, mode ${row.mode ?? "unknown"}, ready ${yes(row.ready)}, actor ${row.actor ?? "unknown"}`, columns, 11, readyTone(row.ready), " "));
136
- out.push(...pair("next", row.next ?? "unknown", columns, 11, undefined, " "));
137
- out.push(...pair("receipt", receiptLine(row.receipt), columns, 11, undefined, " "));
138
- out.push(...bullets("blockers", list(row.blockers), columns, "attention", " "));
139
- if (!detail) return out;
140
- if (row.spec) out.push(...pair("spec", `issue #${row.spec.issue}, ${row.spec.state}`, columns, 11, undefined, " "));
141
- if (row.playbook) out.push(...pair("playbook", row.playbook, columns, 11, undefined, " "));
142
- if (row.definition?.name || row.definition?.id) out.push(...pair("stage", row.definition.name ?? row.definition.id, columns, 11, undefined, " "));
143
- out.push(...bullets("entry", list(row.entry), columns, undefined, " "), ...bullets("exit", list(row.exit), columns, undefined, " "));
123
+ function taskBlock(out: LayoutReport, row: any, detail: boolean, readback = true): void {
124
+ out.section(`Task #${row.id}`);
125
+ out.kv([["title", row.title ?? ""], ["stage", row.stage ?? "unknown"], ["mode", row.mode ?? "unknown"], ["ready", yes(row.ready)], ["actor", row.actor ?? "unknown"], ["next", row.next ?? "unknown"], ["receipt", receiptLine(row.receipt)]]);
126
+ for (const item of list(row.blockers)) out.bullet("warn", `blocker: ${terminalText(item)}`);
127
+ if (readback && row.readback) {
128
+ const view = row.readback as ReadbackView;
129
+ out.kv([["read-back", readbackSummary(view)]]);
130
+ if (view.state === "stale" || view.state === "unavailable") out.bullet("warn", `read-back is ${view.state}`);
131
+ }
132
+ if (!detail) return;
133
+ const rows: (readonly [string, unknown])[] = [];
134
+ if (row.spec) rows.push(["spec", `issue #${row.spec.issue}, ${row.spec.state}`]);
135
+ if (row.playbook) rows.push(["playbook", row.playbook]);
136
+ if (row.definition?.name || row.definition?.id) rows.push(["stage", row.definition.name ?? row.definition.id]);
137
+ if (list(row.entry).length) rows.push(["entry", list(row.entry).join("; ")]);
138
+ if (list(row.exit).length) rows.push(["exit", list(row.exit).join("; ")]);
144
139
  const f = row.findings;
145
- if (f) out.push(...pair("findings", `${plural(f.important ?? 0, "important")} (${f.openImportant ?? 0} open), ${plural(f.nit ?? 0, "nit")} (${f.openNit ?? 0} open), ${f.fixed ?? 0} fixed, ${f.falsePositive ?? 0} false positive, ${f.accepted ?? 0} accepted${f.needsValidation ? `, ${f.needsValidation} needs validation (not blocking)` : ""}${f.preExisting ? `, ${f.preExisting} pre-existing (not blocking)` : ""}`, columns, 11, f.openImportant ? "attention" : undefined, " "));
140
+ if (f) rows.push(["findings", `${plural(f.important ?? 0, "important")} (${f.openImportant ?? 0} open), ${plural(f.nit ?? 0, "nit")} (${f.openNit ?? 0} open), ${f.fixed ?? 0} fixed, ${f.falsePositive ?? 0} false positive, ${f.accepted ?? 0} accepted${f.needsValidation ? `, ${f.needsValidation} needs validation (not blocking)` : ""}${f.preExisting ? `, ${f.preExisting} pre-existing (not blocking)` : ""}`]);
146
141
  const p = row.planConformance;
147
142
  if (p) {
148
- out.push(...pair("plan files", `${p.state}${p.accepted ? ", departure accepted" : ""}, ${list(p.outside).length} outside the plan, ${list(p.untouched).length} planned and untouched`, columns, 11, p.state === "departure" && !p.accepted ? "attention" : undefined, " "));
149
- out.push(...bullets("outside the plan", list(p.outside), columns, "attention", " "), ...bullets("untouched", list(p.untouched), columns, "muted", " "));
143
+ rows.push(["plan files", `${p.state}${p.accepted ? ", departure accepted" : ""}, ${list(p.outside).length} outside the plan, ${list(p.untouched).length} planned and untouched`]);
144
+ if (list(p.outside).length) rows.push(["outside the plan", list(p.outside).join(", ")]);
145
+ if (list(p.untouched).length) rows.push(["untouched", list(p.untouched).join(", ")]);
150
146
  }
151
- const t = row.testIntegrity;
152
- if (t) {
153
- out.push(...pair("tests", `${t.applicability === "bug" ? "bug fix" : t.applicability === "not_bug" ? "not a bug fix" : "bug status unknown"}, red-first ${String(t.redFirst).replace("_", " ")}, files ${t.fileState}`, columns, 11, undefined, " "));
154
- out.push(...bullets("modified tests", list(t.modifiedTests), columns, undefined, " "), ...bullets("test blockers", list(t.blockers), columns, "attention", " "));
147
+ const tests = row.testIntegrity;
148
+ if (tests) {
149
+ rows.push(["tests", `${tests.applicability === "bug" ? "bug fix" : tests.applicability === "not_bug" ? "not a bug fix" : "bug status unknown"}, red-first ${String(tests.redFirst).replace("_", " ")}, files ${tests.fileState}`]);
150
+ if (list(tests.modifiedTests).length) rows.push(["modified tests", list(tests.modifiedTests).join(", ")]);
151
+ if (list(tests.blockers).length) rows.push(["test blockers", list(tests.blockers).join("; ")]);
155
152
  }
156
153
  const sp = row.securityPass;
157
154
  if (sp) {
158
155
  const shown = sp.state === "required" ? `required (${sp.matched} sensitive path${sp.matched === 1 ? "" : "s"} changed), none recorded at this head`
159
156
  : sp.state === "recorded" ? `recorded at this head (${sp.recorded?.covered ?? 0} covered, ${sp.recorded?.notCovered ?? 0} not covered)`
160
157
  : sp.state === "unknown" ? "unknown (PR file inventory incomplete or unreadable)" : "not required";
161
- out.push(...pair("security pass", `${shown}${list(sp.companions).length ? `; companions ${list(sp.companions).join(", ")}` : ""}`, columns, 11, sp.state === "required" || sp.state === "unknown" ? "attention" : undefined, " "));
158
+ rows.push(["security pass", `${shown}${list(sp.companions).length ? `; companions ${list(sp.companions).join(", ")}` : ""}`]);
162
159
  }
163
160
  const e = row.evalGate;
164
161
  if (e) {
165
162
  const shown = e.state === "not_configured" ? "eval check not configured (suite choice pending the person)" : e.state === "coverage_unknown" ? "PR file coverage unknown" : `${e.check} ${String(e.state)}${e.passRate !== undefined ? `, pass rate ${e.passRate}` : ""}${e.suite !== undefined ? `, suite ${e.suite}` : ""}`;
166
- out.push(...pair("eval gate", `configuration PR, ${shown}`, columns, 11, e.state === "passed" && !list(e.gaps).length ? undefined : "attention", " "));
167
- out.push(...bullets("eval gaps", [...list(e.gaps), ...list(e.notes)], columns, "attention", " "));
163
+ rows.push(["eval gate", `configuration PR, ${shown}`]);
164
+ const gaps = [...list(e.gaps), ...list(e.notes)];
165
+ if (gaps.length) rows.push(["eval gaps", gaps.join("; ")]);
168
166
  }
169
167
  const c = row.criteria;
170
168
  if (c) {
171
- out.push(...pair("criteria", `${c.ready ? "all met" : "not all met"}${c.id ? `, checklist ${c.id}` : ""}${c.note ? `, ${c.note}` : ""}`, columns, 11, readyTone(c.ready), " "));
172
- out.push(...bullets("unmet", list(c.blockers), columns, "attention", " "));
169
+ rows.push(["criteria", `${c.ready ? "all met" : "not all met"}${c.id ? `, checklist ${c.id}` : ""}${c.note ? `, ${c.note}` : ""}`]);
170
+ if (list(c.blockers).length) rows.push(["unmet", list(c.blockers).join("; ")]);
173
171
  }
174
- return out;
172
+ out.kv(rows);
173
+ // the attention tones the older layout colored become a marker line, so they survive without color
174
+ if (f?.openImportant) out.bullet("warn", `${plural(f.openImportant, "open important finding")}`);
175
+ if (p?.state === "departure" && !p.accepted) out.bullet("warn", "plan departure not accepted");
176
+ if (sp?.state === "required" || sp?.state === "unknown") out.bullet("warn", `security pass ${sp.state}`);
177
+ if (e && !(e.state === "passed" && !list(e.gaps).length)) out.bullet("warn", "eval gate not passed");
178
+ if (c && !c.ready) out.bullet("warn", "criteria not all met");
175
179
  }
176
- function lifecycleView(reply: any, columns: number | undefined, detail: boolean): Line[] {
180
+ function lifecycleView(reply: any, columns: number | undefined, detail: boolean, ascii: boolean): Span[][] {
177
181
  const rows = list(reply?.rows);
178
- const out: Line[] = [...heading(`SDLC lifecycle, mode ${reply?.mode ?? "unknown"}`, columns)];
179
- if (reply?.securityScan && typeof reply.securityScan === "object") {
180
- out.push(...pair("security scan", Object.entries(reply.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", "), columns, 14));
181
- }
182
- if (!rows.length) return [...out, [s("no task has lifecycle state yet", "muted")]];
182
+ const out = new LayoutReport(columns, ascii).titled("ahub", "SDLC lifecycle", `mode ${reply?.mode ?? "unknown"}`);
183
+ if (reply?.securityScan && typeof reply.securityScan === "object") out.section("Security scan").kv([["security scan", Object.entries(reply.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", ")]]);
184
+ if (!rows.length) return out.note("no task has lifecycle state yet").lines();
183
185
  if (!detail || rows.length > 1) {
184
- out.push(...grid(["ID", "STAGE", "READY", "ACTOR", "PR"], rows.map(row => [s(`#${row.id}`, "taskRef"), s(row.stage ?? "unknown"), s(yes(row.ready), readyTone(row.ready)), s(row.actor ?? "-"), s(row.receipt?.pr ? `#${row.receipt.pr}` : "-")]), columns));
186
+ out.section("Tasks", String(rows.length)).append(grid(["ID", "STAGE", "READY", "ACTOR", "PR"], rows.map(row => [s(`#${row.id}`, "taskRef"), s(row.stage ?? "unknown"), s(yes(row.ready), readyTone(row.ready)), s(row.actor ?? "-"), s(row.receipt?.pr ? `#${row.receipt.pr}` : "-")]), columns));
185
187
  }
186
- for (const row of rows) out.push(blank, ...taskBlock(row, columns, detail));
187
- if (reply?.truncated) out.push(blank, ...para("showing the first 100 tasks; name a task to read one", columns, "muted"));
188
- return out;
188
+ // #1658: the read-back line belongs to one task's view; a list of rows has no single issue body to read it against.
189
+ for (const row of rows) taskBlock(out, row, detail, detail || rows.length === 1);
190
+ if (reply?.truncated) out.bullet("warn", "showing the first 100 tasks; name a task to read one");
191
+ return out.lines();
189
192
  }
190
193
  /** `ahub sdlc status [task]`: one row per task, then each task's next step and blockers. */
191
- export const renderSdlcStatus = (reply: unknown, columns?: number, _now = Date.now()): Span[][] => lifecycleView(reply, columns, false);
194
+ export const renderSdlcStatus = (reply: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] => lifecycleView(reply, columns, false, ascii);
192
195
  /** `ahub sdlc explain <task>`: the same task with every gate the hub read. */
193
- export const renderSdlcExplain = (reply: unknown, columns?: number, _now = Date.now()): Span[][] => lifecycleView(reply, columns, true);
196
+ export const renderSdlcExplain = (reply: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] => lifecycleView(reply, columns, true, ascii);
194
197
 
195
198
  // ---- sdlc queue / release -----------------------------------------------------------------------------------------
196
199
 
197
200
  /** `ahub sdlc queue <repo>`: the merge order, then each open PR's gates. */
198
- export function renderSdlcQueue(reply: unknown, columns?: number, _now = Date.now()): Span[][] {
201
+ export function renderSdlcQueue(reply: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
199
202
  const report = (reply as any)?.report ?? {};
200
203
  const rows = list(report.rows);
201
- const out: Line[] = [...heading(`Merge queue ${report.repo ?? "unknown repository"}`, columns)];
202
- if (report.complete === false) out.push(...para("incomplete: a read failed or the board changed during it; do not merge from this order", columns, "attention"));
203
- if (report.truncated) out.push(...para("truncated: more open PRs than one read covers", columns, "attention"));
204
- if (!rows.length) return [...out, [s("no open PR is linked to a task", "muted")]];
205
- out.push(...pair("order", list(report.order).length ? list(report.order).map((pr: number) => `#${pr}`).join(", ") : "none decided", columns, 9));
206
- if (list(report.unordered).length) out.push(...pair("unordered", list(report.unordered).map((pr: number) => `#${pr}`).join(", "), columns, 9, "attention"));
207
- out.push(blank, ...grid(["PR", "TASKS", "READY", "HEAD", "AFTER"], rows.map(row => [s(`#${row.pr}`, "issueRef"), s(list(row.tasks).map((id: number) => `#${id}`).join(" ") || "-", "taskRef"), s(yes(row.ready), readyTone(row.ready)), s(row.private ? "private" : short(row.head)), s(list(row.after).map((pr: number) => `#${pr}`).join(" ") || "-")]), columns));
208
- for (const row of rows) {
209
- if (!list(row.blockers).length && !row.findings?.openImportant) continue;
210
- out.push(blank, [s(`#${row.pr}`, "issueRef")], ...bullets("blockers", list(row.blockers), columns, "attention", " "));
204
+ const out = new LayoutReport(columns, ascii).titled("ahub", "Merge queue", String(report.repo ?? "unknown repository"), true);
205
+ if (report.complete === false || report.truncated) {
206
+ out.section("Caution");
207
+ if (report.complete === false) out.bullet("warn", "incomplete: a read failed or the board changed during it; do not merge from this order");
208
+ if (report.truncated) out.bullet("warn", "truncated: more open PRs than one read covers");
211
209
  }
212
- if (list(report.conflicts).length) out.push(blank, ...bullets("file conflicts", list(report.conflicts).map((c: any) => `#${c.left} and #${c.right} share ${plural(c.files ?? 0, "file")} (${c.order === "person_required" ? "the person orders them" : "dependency order"})`), columns, "attention"));
213
- return out;
210
+ if (!rows.length) return out.note("no open PR is linked to a task").lines();
211
+ const prs = (items: unknown) => list(items).map((pr: number) => `#${pr}`).join(", ");
212
+ out.section("Order").kv([["order", list(report.order).length ? prs(report.order) : "none decided"], ...(list(report.unordered).length ? [["unordered", prs(report.unordered)] as const] : [])]);
213
+ out.section("Pull requests", String(rows.length)).append(grid(["PR", "TASKS", "READY", "HEAD", "AFTER"], rows.map(row => [s(`#${row.pr}`, "issueRef"), s(list(row.tasks).map((id: number) => `#${id}`).join(" ") || "-", "taskRef"), s(yes(row.ready), readyTone(row.ready)), s(row.private ? "private" : short(row.head)), s(list(row.after).map((pr: number) => `#${pr}`).join(" ") || "-")]), columns));
214
+ const blocked = rows.filter(row => list(row.blockers).length || row.findings?.openImportant);
215
+ if (blocked.length) {
216
+ out.section("Blockers", String(blocked.length));
217
+ for (const row of blocked) { out.note(`#${row.pr}`, "value"); for (const item of list(row.blockers)) out.bullet("warn", terminalText(item), true); }
218
+ }
219
+ if (list(report.conflicts).length) {
220
+ out.section("File conflicts", String(list(report.conflicts).length));
221
+ for (const c of list(report.conflicts) as any[]) out.bullet("warn", `#${c.left} and #${c.right} share ${plural(c.files ?? 0, "file")} (${c.order === "person_required" ? "the person orders them" : "dependency order"})`);
222
+ }
223
+ return out.lines();
214
224
  }
215
225
  /** One line for the audit's unit states, shared by `audit show` and the release readback. */
216
226
  function auditStates(a: any): string {
@@ -218,49 +228,59 @@ function auditStates(a: any): string {
218
228
  return `${c.covered ?? 0} covered${a?.prior ? ` (${a.prior} prior)` : ""}, ${c.deferred ?? 0} deferred, ${c.out_of_scope ?? 0} out of scope, ${c.planned ?? 0} planned`;
219
229
  }
220
230
  /** `ahub sdlc audit show`: the ledger's counts first, then each unit, then the findings. An open important finding shows its id and status only, unless the caller is the person. */
221
- export function renderSdlcAudit(reply: unknown, columns?: number, _now = Date.now()): Span[][] {
231
+ export function renderSdlcAudit(reply: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
222
232
  const a = (reply as any)?.audit;
223
- if (!a) return [...heading("Security audit", columns), ...pair("audits", "none started: run ahub sdlc audit start", columns, 10, "muted")];
224
- const out: Line[] = [...heading(`Security audit ${a.audit} (task #${a.task})`, columns)];
225
- out.push(...pair("source", `${short(a.ref)}, profile ${a.profile}${a.scoped ? ", scoped" : ""}`, columns, 10), ...pair("coverage", `${a.partial ? "partial: " : ""}${auditStates(a)}`, columns, 10, a.partial || a.counts?.planned ? "attention" : undefined));
233
+ if (!a) return new LayoutReport(columns, ascii).header("ahub", "Security audit").section("Audit").kv([["audits", "none started: run ahub sdlc audit start"]]).lines();
234
+ const out = new LayoutReport(columns, ascii).titled("ahub", "Security audit", `${a.audit} (task #${a.task})`, true);
226
235
  const f = a.findings ?? {};
227
- out.push(...pair("findings", `${f.verified ?? 0} verified, ${f.candidate ?? 0} candidate (unverified), ${f.needsValidation ?? 0} needs validation, ${f.rejected ?? 0} rejected, ${f.settled ?? 0} settled, ${f.other ?? 0} other`, columns, 10, f.candidate ? "attention" : undefined));
228
- for (const u of list(a.units)) out.push(...pair(String(u.state).replace("_", " "), `${u.unit}${u.prior ? ` (prior audit ${u.prior.audit})` : ""}${u.reason ? `: ${u.reason}` : ""}`, columns, 14, u.state === "planned" ? "attention" : undefined, " "));
229
- for (const item of list(a.items)) out.push(...pair(String(item.status), `${item.id} (${item.severity}, ${item.disposition})${item.withheld ? ", details withheld" : item.path ? ` ${item.path}` : ""}`, columns, 14, item.status === "candidate" ? "attention" : undefined, " "));
230
- if (a.withheld) out.push(...pair("withheld", `${a.withheld} open important finding${a.withheld === 1 ? "" : "s"}: boundary text is shown to the person only`, columns, 10, "muted"));
231
- return out;
236
+ out.section("Summary").kv([["source", `${short(a.ref)}, profile ${a.profile}${a.scoped ? ", scoped" : ""}`], ["coverage", `${a.partial ? "partial: " : ""}${auditStates(a)}`],
237
+ ["findings", `${f.verified ?? 0} verified, ${f.candidate ?? 0} candidate (unverified), ${f.needsValidation ?? 0} needs validation, ${f.rejected ?? 0} rejected, ${f.settled ?? 0} settled, ${f.other ?? 0} other`]]);
238
+ if (list(a.units).length) {
239
+ out.section("Units", String(list(a.units).length));
240
+ for (const u of list(a.units) as any[]) out.bullet(u.state === "planned" ? "warn" : "ok", `${String(u.state).replace("_", " ")}: ${terminalText(u.unit)}${u.prior ? ` (prior audit ${u.prior.audit})` : ""}${u.reason ? `: ${terminalText(u.reason)}` : ""}`);
241
+ }
242
+ if (list(a.items).length) {
243
+ out.section("Findings", String(list(a.items).length));
244
+ for (const item of list(a.items) as any[]) out.bullet(item.status === "candidate" ? "warn" : "ok", `${String(item.status)}: ${terminalText(item.id)} (${item.severity}, ${item.disposition})${item.withheld ? ", details withheld" : item.path ? ` ${terminalText(item.path)}` : ""}`);
245
+ }
246
+ if (a.withheld) out.note(`${a.withheld} open important finding${a.withheld === 1 ? "" : "s"}: boundary text is shown to the person only`);
247
+ return out.lines();
232
248
  }
233
249
  /** `ahub sdlc release <repo> [live-issue...]`: source, document, issue and authorization evidence, then what blocks the release. */
234
- export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.now()): Span[][] {
250
+ export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
235
251
  const r = (reply as any)?.report ?? {};
236
- const out: Line[] = [...heading(`Release readiness ${r.repo ?? "unknown repository"}`, columns)];
237
- const w = 12;
238
- out.push(...pair("version", r.version ?? (r.releasePolicy ? "undetermined" : "unknown"), columns, w), ...pair("head", short(r.head), columns, w), ...pair("tag", r.tag ? `${r.tag} at ${short(r.tagCommit)}` : "none", columns, w));
239
- out.push(...pair("source ready", yes(r.sourceReady), columns, w, readyTone(r.sourceReady)), ...pair("native", String(r.native ?? "unverified"), columns, w, "attention"), ...pair("release ready", yes(r.ready), columns, w, readyTone(r.ready)));
240
- out.push(...pair("commits", `${plural(list(r.commits).length, "commit")} since the last tag`, columns, w));
241
- if (list(r.mergedPrs).length) out.push(...pair("merged PRs", list(r.mergedPrs).map((p: any) => `#${p.pr}`).join(", "), columns, w));
252
+ const out = new LayoutReport(columns, ascii).titled("ahub", "Release readiness", String(r.repo ?? "unknown repository"), true);
253
+ out.section("Source").kv([["version", r.version ?? (r.releasePolicy ? "undetermined" : "unknown")], ["head", short(r.head)], ["tag", r.tag ? `${r.tag} at ${short(r.tagCommit)}` : "none"],
254
+ ["commits", `${plural(list(r.commits).length, "commit")} since the last tag`], ...(list(r.mergedPrs).length ? [["merged PRs", list(r.mergedPrs).map((p: any) => `#${p.pr}`).join(", ")] as const] : [])]);
255
+ out.section("Readiness").kv([["source ready", yes(r.sourceReady)], ["native", String(r.native ?? "unverified")], ["release ready", yes(r.ready)]]);
256
+ if (r.ready !== true) out.bullet("warn", "release is not ready");
257
+ if (String(r.native ?? "unverified") === "unverified") out.bullet("warn", "native verification is unverified");
242
258
  const docs = r.documents;
243
- if (r.releasePolicy?.docsSource === "none") out.push(blank, ...pair("documents", r.releasePolicy.authorization === "matched" ? "none (explicit exemption recorded)" : "none (configured exemption; no matching authorization)", columns, w, "muted"));
259
+ out.section("Documents");
260
+ if (r.releasePolicy?.docsSource === "none") out.kv([["documents", r.releasePolicy.authorization === "matched" ? "none (explicit exemption recorded)" : "none (configured exemption; no matching authorization)"]]);
244
261
  else {
245
- out.push(blank, ...pair("documents", docs ? `${docs.fresh ? "fresh" : "not fresh"}, ${plural(docs.errors ?? 0, "error")}, ${plural(list(docs.documents).length, "document")}` : "not read", columns, w, docs?.fresh ? "success" : "attention"));
246
- for (const d of list(docs?.documents)) if (d.state !== "fresh") out.push(...pair(d.state, `${d.path ?? "(path withheld)"}${d.dirty ? " (uncommitted changes)" : ""}`, columns, w, "attention", " "));
262
+ out.kv([["documents", docs ? `${docs.fresh ? "fresh" : "not fresh"}, ${plural(docs.errors ?? 0, "error")}, ${plural(list(docs.documents).length, "document")}` : "not read"]]);
263
+ for (const d of list(docs?.documents) as any[]) if (d.state !== "fresh") out.bullet("warn", `${d.state}: ${terminalText(d.path ?? "(path withheld)")}${d.dirty ? " (uncommitted changes)" : ""}`);
264
+ }
265
+ if (r.releasePolicy) out.kv([["release policy", `version ${r.releasePolicy.versionSource}, docs ${r.releasePolicy.docsSource}, authorization ${r.releasePolicy.authorization}`]]);
266
+ if (list(r.liveIssues).length) out.section("Live issues", String(list(r.liveIssues).length)).append(grid(["ISSUE", "STATE"], list(r.liveIssues).map((i: any) => [s(`#${i.id}`, "issueRef"), s(i.state, i.state === "closed" ? "success" : "attention")]), columns));
267
+ const au = r.authorization;
268
+ out.section("Authorization").kv([["authorization", au ? `${au.state}: version ${au.receipt?.version ?? "unknown"} at ${short(au.receipt?.commit)}, approved ${moment(au.receipt?.at, now)}`
269
+ : r.releasePolicy ? `none recorded for ${r.releasePolicy.versionSource}: run ahub sdlc authorize-release <version>` : "none recorded: run ahub sdlc authorize-release <version>"]]);
270
+ if (list(r.trains).length) {
271
+ out.section("Trains", String(list(r.trains).length));
272
+ for (const tr of list(r.trains) as any[]) out.bullet(list(tr.readiness?.blockers).length ? "warn" : "ok", `train #${tr.release?.id ?? "?"}: ${tr.readiness?.trigger ?? "unknown"}${list(tr.readiness?.blockers).length ? `, ${list(tr.readiness.blockers).join("; ")}` : ""}`);
247
273
  }
248
- if (r.releasePolicy) out.push(...pair("release policy", `version ${r.releasePolicy.versionSource}, docs ${r.releasePolicy.docsSource}, authorization ${r.releasePolicy.authorization}`, columns, w, r.releasePolicy.authorization === "matched" ? "success" : "attention"));
249
- if (list(r.liveIssues).length) out.push(blank, ...grid(["ISSUE", "STATE"], list(r.liveIssues).map((i: any) => [s(`#${i.id}`, "issueRef"), s(i.state, i.state === "closed" ? "success" : "attention")]), columns));
250
- const a = r.authorization;
251
- if (a) out.push(blank, ...pair("authorization", `${a.state}: version ${a.receipt?.version ?? "unknown"} at ${short(a.receipt?.commit)}, approved ${moment(a.receipt?.at, now)}`, columns, w, a.state === "matched" ? "success" : "attention"));
252
- else out.push(blank, ...pair("authorization", r.releasePolicy ? `none recorded for ${r.releasePolicy.versionSource}: run ahub sdlc authorize-release <version>` : "none recorded: run ahub sdlc authorize-release <version>", columns, w, "muted"));
253
- for (const t of list(r.trains)) out.push(...pair(`train #${t.release?.id ?? "?"}`, `${t.readiness?.trigger ?? "unknown"}${list(t.readiness?.blockers).length ? `, ${list(t.readiness.blockers).join("; ")}` : ""}`, columns, w, list(t.readiness?.blockers).length ? "attention" : undefined));
254
274
  const sa = r.securityAudit;
255
- if (sa) out.push(blank, ...pair("security audit", `${short(sa.ref)} ${sa.profile}${sa.partial ? " (partial)" : ""}: ${auditStates(sa)}${sa.findings?.candidate ? `, ${sa.findings.candidate} unverified candidate${sa.findings.candidate === 1 ? "" : "s"}` : ""}`, columns, w, sa.partial || sa.counts?.planned ? "attention" : undefined));
275
+ if (sa) out.section("Security audit").kv([["security audit", `${short(sa.ref)} ${sa.profile}${sa.partial ? " (partial)" : ""}: ${auditStates(sa)}${sa.findings?.candidate ? `, ${sa.findings.candidate} unverified candidate${sa.findings.candidate === 1 ? "" : "s"}` : ""}`]]);
256
276
  const rm = r.releaseMetrics;
257
277
  if (rm) {
258
- const mean = (values: unknown[]) => { const known = values.filter((v): v is number => typeof v === "number" && Number.isFinite(v)); return known.length ? span(known.reduce((a, b) => a + b, 0) / known.length) : "unknown"; };
259
- out.push(blank, ...pair("releases", `${list(rm.intervals).length ? `interval ${mean(list(rm.intervals).map((i: any) => i.ms))} mean over ${plural(list(rm.intervals).length, "gap")}` : "interval unknown (needs two shipped releases with history)"}; lead time ${mean(list(rm.approvalToReleaseMs).map((x: any) => x.ms))} mean approval to release; hotfix rate ${percent(rm.hotfixRate)}${rm.hotfixCount === null || rm.hotfixCount === undefined ? "" : ` (${rm.hotfixCount})`}`, columns, w));
260
- if (list(rm.unknown).length) out.push(...pair("unknown", `${plural(list(rm.unknown).length, "release")} without complete history: ${list(rm.unknown).map((id: number) => `#${id}`).join(", ")}`, columns, w, "attention", " "));
278
+ const mean = (values: unknown[]) => { const known = values.filter((v): v is number => typeof v === "number" && Number.isFinite(v)); return known.length ? span(known.reduce((x, y) => x + y, 0) / known.length) : "unknown"; };
279
+ out.section("Release history").kv([["releases", `${list(rm.intervals).length ? `interval ${mean(list(rm.intervals).map((i: any) => i.ms))} mean over ${plural(list(rm.intervals).length, "gap")}` : "interval unknown (needs two shipped releases with history)"}; lead time ${mean(list(rm.approvalToReleaseMs).map((x: any) => x.ms))} mean approval to release; hotfix rate ${percent(rm.hotfixRate)}${rm.hotfixCount === null || rm.hotfixCount === undefined ? "" : ` (${rm.hotfixCount})`}`],
280
+ ...(list(rm.unknown).length ? [["unknown", `${plural(list(rm.unknown).length, "release")} without complete history: ${list(rm.unknown).map((id: number) => `#${id}`).join(", ")}`] as const] : [])]);
261
281
  }
262
- out.push(...bullets("blockers", list(r.blockers), columns, "attention"));
263
- return out;
282
+ if (list(r.blockers).length) { out.section("Blockers", String(list(r.blockers).length)); for (const item of list(r.blockers)) out.bullet("warn", terminalText(item)); }
283
+ return out.lines();
264
284
  }
265
285
 
266
286
  // ---- sdlc metrics / costs -----------------------------------------------------------------------------------------
@@ -273,87 +293,85 @@ const SUMMARY_ROWS: [string, string, boolean][] = [
273
293
  ];
274
294
  const BAND_TONE: Record<string, Tone> = { ok: "success", log: "muted", diagnose: "attention", propose: "failure" };
275
295
  /** `ahub sdlc metrics [--since ...]`: times and counts from board history, the two approval rates, stalls and band tiers. */
276
- export function renderSdlcMetrics(result: unknown, columns?: number, now = Date.now()): Span[][] {
296
+ export function renderSdlcMetrics(result: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
277
297
  const m = result as any;
278
- const out: Line[] = [...heading("SDLC metrics", columns)];
279
- out.push(...pair("window", m?.since === null || m?.since === undefined ? "all recorded history" : `since ${moment(m.since, now)}`, columns, 10),
280
- ...pair("tasks", `${m?.tasks ?? 0} counted${m?.withheldPrivate ? `, ${m.withheldPrivate} private withheld` : ""}`, columns, 10));
281
- if (m?.securityScan && typeof m.securityScan === "object") {
282
- out.push(...pair("security scan", Object.entries(m.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", "), columns, 14));
283
- }
298
+ const out = new LayoutReport(columns, ascii).header("ahub", "SDLC metrics");
299
+ out.section("Scope").kv([["window", m?.since === null || m?.since === undefined ? "all recorded history" : `since ${moment(m.since, now)}`], ["tasks", `${m?.tasks ?? 0} counted${m?.withheldPrivate ? `, ${m.withheldPrivate} private withheld` : ""}`],
300
+ ...(m?.securityScan && typeof m.securityScan === "object" ? [["security scan", Object.entries(m.securityScan).map(([source, value]) => `${source}: ${value === null ? "unknown" : value}`).join(", ")] as const] : [])]);
284
301
  const metrics = m?.metrics ?? {};
285
302
  const value = (n: unknown, time: boolean) => time ? span(n) : count(n);
286
- out.push(blank, ...grid(["METRIC", "N", "UNKNOWN", "MEAN", "MEDIAN", "P90", "MAX"], SUMMARY_ROWS.map(([key, label, time]) => {
303
+ out.section("Times and counts").append(grid(["METRIC", "N", "UNKNOWN", "MEAN", "MEDIAN", "P90", "MAX"], SUMMARY_ROWS.map(([key, label, time]) => {
287
304
  const x = metrics[key] ?? {};
288
305
  return [s(label), s(count(x.n)), s(count(x.unknown), x.unknown ? "attention" : "muted"), s(value(x.mean, time)), s(value(x.median, time)), s(value(x.p90, time)), s(value(x.max, time))];
289
306
  }), columns));
290
- out.push(blank, ...grid(["RATE", "N", "UNKNOWN", "VALUE"], [["first_pass_approval", "first-pass approval"], ["first_pass_check", "first-pass check"]].map(([key, label]) => {
307
+ out.section("Approval rates").append(grid(["RATE", "N", "UNKNOWN", "VALUE"], [["first_pass_approval", "first-pass approval"], ["first_pass_check", "first-pass check"]].map(([key, label]) => {
291
308
  const x = metrics[key!] ?? {};
292
309
  return [s(label), s(count(x.n)), s(count(x.unknown), x.unknown ? "attention" : "muted"), s(percent(x.rate), x.rate === null || x.rate === undefined ? "muted" : "number")];
293
310
  }), columns));
311
+ // #1647: the split reasons, `unset` for tasks proposed without one.
312
+ const reasons = Object.entries((m?.byReason ?? {}) as Record<string, { tasks?: number; reviewRounds?: number; tokens?: number | null }>);
313
+ if (reasons.length) out.section("Split reasons", String(reasons.length)).append(grid(["REASON", "TASKS", "REVIEW ROUNDS", "TOKENS"], reasons.map(([reason, x]) => [s(reason), s(count(x.tasks)), s(count(x.reviewRounds)), s(x.tokens === null || x.tokens === undefined ? "unknown" : count(x.tokens), x.tokens === null || x.tokens === undefined ? "muted" : "number")]), columns));
294
314
  const st = m?.stalls;
295
- if (st) out.push(blank, ...pair("stalls", `${st.open ?? 0} open${Object.keys(st.byKind ?? {}).length ? ` (${Object.entries(st.byKind).map(([k, n]) => `${k} ${n}`).join(", ")})` : ""}, ${st.doneWithoutWrites ?? 0} done without writes`, columns, 10, st.open ? "attention" : undefined));
296
- if (m?.bands === "off" || m?.bands === undefined) out.push(...pair("bands", "off", columns, 10, "muted"));
315
+ if (st) out.section("Stalls").kv([["stalls", `${st.open ?? 0} open${Object.keys(st.byKind ?? {}).length ? ` (${Object.entries(st.byKind).map(([k, n]) => `${k} ${n}`).join(", ")})` : ""}, ${st.doneWithoutWrites ?? 0} done without writes`]]);
316
+ out.section("Bands");
317
+ if (m?.bands === "off" || m?.bands === undefined) out.kv([["bands", "off"]]);
297
318
  else {
298
- out.push(blank, ...grid(["BAND", "TIER", "BASELINE", "LAST", "Z", "SUBJECT"], list(m.bands).map((b: any) => [s(String(b.metric).replaceAll("_", " ")), s(b.tier, BAND_TONE[b.tier] ?? undefined), s(count(b.baseline)), s(count(b.last)), s(count(b.z)), s(b.lastTask ? `${b.subject === "release" ? "release " : b.subject === "scan" ? "scan " : ""}#${b.lastTask}` : "-", "taskRef")]), columns));
299
- for (const b of list(m.bands)) if (b.reason && b.tier !== "ok") out.push(...para(`${String(b.metric).replaceAll("_", " ")}: ${b.reason}`, columns, "muted", " ", 2));
319
+ out.append(grid(["BAND", "TIER", "BASELINE", "LAST", "Z", "SUBJECT"], list(m.bands).map((b: any) => [s(String(b.metric).replaceAll("_", " ")), s(b.tier, BAND_TONE[b.tier] ?? undefined), s(count(b.baseline)), s(count(b.last)), s(count(b.z)), s(b.lastTask ? `${b.subject === "release" ? "release " : b.subject === "scan" ? "scan " : ""}#${b.lastTask}` : "-", "taskRef")]), columns));
320
+ for (const b of list(m.bands) as any[]) if (b.reason && b.tier !== "ok") out.note(`${String(b.metric).replaceAll("_", " ")}: ${terminalText(b.reason)}`);
300
321
  }
301
- return out;
322
+ return out.lines();
302
323
  }
303
324
  /** `ahub sdlc costs [repo]`: review and CI cost of each linked merged PR, grouped by repository. */
304
- export function renderSdlcCosts(result: unknown, columns?: number, _now = Date.now()): Span[][] {
325
+ export function renderSdlcCosts(result: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
305
326
  const c = result as any;
306
327
  const rows = list(c?.rows);
307
- const out: Line[] = [...heading("SDLC costs", columns)];
308
- if (!rows.length) out.push([s("no linked merged PR has cost evidence", "muted")]);
328
+ const out = new LayoutReport(columns, ascii).header("ahub", "SDLC costs");
329
+ if (!rows.length) out.note("no linked merged PR has cost evidence");
309
330
  const repos = [...new Set(rows.map(row => String(row.repo)))];
310
331
  for (const repo of repos) {
311
- out.push(...(out.length > 1 ? [blank] : []), ...wrap(repo, room(columns), 2).map((line): Line => [s(line, "info")]), ...grid(["PR", "ROUNDS", "CI", "RERUNS", "FULL", "DELTA", "REVIEW", "UNK", "OK"], rows.filter(row => String(row.repo) === repo).map(row => [
332
+ const own = rows.filter(row => String(row.repo) === repo);
333
+ out.section("Repository", String(own.length)).note(repo, "value").append(grid(["PR", "ROUNDS", "CI", "RERUNS", "FULL", "DELTA", "REVIEW", "UNK", "OK"], own.map(row => [
312
334
  s(`#${row.pr}`, "issueRef"), s(count(row.reviewRounds)), s(count(row.ciRuns)), s(count(row.ciReruns)), s(count(row.fullReReviews)), s(count(row.deltaReviews)), s(span(row.reviewMs)),
313
335
  s(count(row.unknownReviewScopes), row.unknownReviewScopes ? "attention" : "muted"), s(row.complete ? "yes" : "no", row.complete ? "success" : "attention")]), columns));
314
- for (const row of rows.filter(row => String(row.repo) === repo && row.fullGateRuns !== undefined)) {
315
- out.push(...para(`#${row.pr}: full gates ${count(row.fullGateRuns)} (success ${count(row.successfulGateRuns)}, failed ${count(row.failedGateRuns)}, cancelled ${count(row.cancelledGateRuns)}, other ${count(row.otherGateRuns)}); macOS shards ${count(row.macosShardRuns)}`, columns));
336
+ for (const row of own.filter(row => row.fullGateRuns !== undefined)) {
337
+ out.note(`#${row.pr}: full gates ${count(row.fullGateRuns)} (success ${count(row.successfulGateRuns)}, failed ${count(row.failedGateRuns)}, cancelled ${count(row.cancelledGateRuns)}, other ${count(row.otherGateRuns)}); macOS shards ${count(row.macosShardRuns)}`, "value");
316
338
  }
317
339
  }
318
- if (c?.truncated) out.push(blank, ...para("truncated: more PRs than one read covers, or a read was incomplete", columns, "attention"));
319
- if (c?.privateTasks === "withheld") out.push(...para("private tasks are withheld", columns, "muted"));
320
- return out;
340
+ if (c?.truncated) out.bullet("warn", "truncated: more PRs than one read covers, or a read was incomplete");
341
+ if (c?.privateTasks === "withheld") out.note("private tasks are withheld");
342
+ return out.lines();
321
343
  }
322
344
 
323
345
  // ---- sdlc authorize-release ---------------------------------------------------------------------------------------
324
346
 
325
347
  /** `ahub sdlc authorize-release <version>`: what the person just approved. */
326
- export function renderAuthorization(authorization: unknown, columns?: number, now = Date.now()): Span[][] {
348
+ export function renderAuthorization(authorization: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
327
349
  const a = authorization as any;
328
- const w = 8;
329
- return [...heading("Release authorized", columns),
330
- ...pair("version", a?.version ?? "unknown", columns, w), ...pair("commit", short(a?.commit), columns, w), ...pair("by", a?.by ?? "unknown", columns, w),
331
- ...pair("at", moment(a?.at, now), columns, w), ...pair("docs", a?.docs?.source === "none" ? "none (explicit exemption)" : a?.docs ? `${a.docs.fresh ? "fresh" : "not fresh"}, ${plural(a.docs.documents ?? 0, "document")}, digest ${short(a.docs.digest)}` : "unknown", columns, w),
332
- ...pair("id", a?.id ?? "unknown", columns, w, "muted"), blank,
333
- ...para("A daemon restart revokes this authorization.", columns, "muted")];
350
+ const docs = a?.docs?.source === "none" ? "none (explicit exemption)" : a?.docs ? `${a.docs.fresh ? "fresh" : "not fresh"}, ${plural(a.docs.documents ?? 0, "document")}, digest ${short(a.docs.digest)}` : "unknown";
351
+ return new LayoutReport(columns, ascii).header("ahub", "Release authorized")
352
+ .section("Authorization")
353
+ .kv([["version", a?.version ?? "unknown"], ["commit", short(a?.commit)], ["by", a?.by ?? "unknown"], ["at", moment(a?.at, now)], ["docs", docs], ["id", a?.id ?? "unknown"]])
354
+ .note("A daemon restart revokes this authorization.").lines();
334
355
  }
335
356
 
336
357
  // ---- sdlc merge ---------------------------------------------------------------------------------------------------
337
358
 
338
- const MERGE_STATE: Record<string, [string, Tone]> = { merged: ["merged", "success"], not_merged: ["not merged", "failure"], unknown: ["merge state unknown", "attention"] };
359
+ const MERGE_STATE: Record<string, [string, "ok" | "fail" | "warn"]> = { merged: ["merged", "ok"], not_merged: ["not merged", "fail"], unknown: ["merge state unknown", "warn"] };
339
360
  /** `ahub sdlc merge <task> [--dry-run]` (#899): the hub's decision, every gate that refused it, the `gh` command, and GitHub's readback after a run. */
340
- export function renderSdlcMerge(view: unknown, columns?: number, _now = Date.now()): Span[][] {
361
+ export function renderSdlcMerge(view: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
341
362
  const v = view as any;
342
- const w = 8, refused = list(v?.refused), argv = list(v?.argv);
343
- const out: Line[] = [...heading(`Guarded merge of task #${v?.task ?? "unknown"}`, columns)];
344
- out.push(...pair("mode", v?.mode ?? "unknown", columns, w, v?.mode === "off" ? "attention" : undefined));
345
- if (v?.decision === "merge") out.push(...pair("decision", "merge: every gate passed", columns, w, "success"));
346
- else if (v?.decision === "refused") out.push(...pair("decision", `refused by ${plural(refused.length, "gate")}`, columns, w, "attention"));
347
- else out.push(...pair("decision", "unknown", columns, w, "attention"));
348
- out.push(...bullets("refused", refused, columns, "attention", " "));
349
- if (argv.length) out.push(...pair("command", `gh ${argv.join(" ")}`, columns, w));
363
+ const refused = list(v?.refused), argv = list(v?.argv);
364
+ const decision = v?.decision === "merge" ? "merge: every gate passed" : v?.decision === "refused" ? `refused by ${plural(refused.length, "gate")}` : "unknown";
350
365
  const ran = v?.ran === true ? "yes" : v?.ran === false ? (v?.mode === "dry-run" && argv.length ? "no (dry run: the command above was not run)" : "no") : "unknown";
351
- out.push(...pair("ran", ran, columns, w, v?.ran === true ? undefined : "muted"));
366
+ const report = new LayoutReport(columns, ascii).titled("ahub", "Guarded merge of task", `#${v?.task ?? "unknown"}`, true).section("Decision")
367
+ .kv([["mode", v?.mode ?? "unknown"], ["decision", decision], ...(argv.length ? [["command", `gh ${argv.join(" ")}`] as const] : []), ["ran", ran]]);
368
+ if (refused.length) { report.section("Refused", String(refused.length)); for (const gate of refused) report.bullet("fail", terminalText(gate)); }
352
369
  const r = v?.result;
353
370
  if (r && typeof r === "object") {
354
- const [state, tone] = MERGE_STATE[String(r.state)] ?? ["merge state unknown", "attention" as Tone];
355
- out.push(blank, ...pair("result", `${state}, gh exit ${count(r.exit)}${r.mergeCommit ? `, merge commit ${short(r.mergeCommit)}` : ""}`, columns, w, tone));
356
- if (r.cleanup) out.push(...pair("cleanup", `branch cleanup ${String(r.cleanup).replaceAll("_", " ")}${r.reason ? ` (${String(r.reason).replaceAll("_", " ")})` : ""}`, columns, w, r.cleanup === "deleted" ? undefined : "muted"));
371
+ const [state, marker] = MERGE_STATE[String(r.state)] ?? ["merge state unknown", "warn" as const];
372
+ report.section("Result");
373
+ report.bullet(marker, `${state}, gh exit ${count(r.exit)}${r.mergeCommit ? `, merge commit ${short(r.mergeCommit)}` : ""}`);
374
+ if (r.cleanup) report.kv([["cleanup", `branch cleanup ${String(r.cleanup).replaceAll("_", " ")}${r.reason ? ` (${String(r.reason).replaceAll("_", " ")})` : ""}`]]);
357
375
  }
358
- return out;
376
+ return report.lines();
359
377
  }