@staix/agent-hub 0.46.1 → 0.47.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 (130) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +8 -4
  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 +2 -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 +26 -10
  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 +63 -15
  24. package/docs/profiles.md +1 -0
  25. package/docs/quickstart.md +8 -2
  26. package/docs/roles.md +6 -0
  27. package/docs/sdlc.md +44 -1
  28. package/docs/security.md +16 -7
  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-codex-0172-reviewer-tool-call.md +29 -0
  39. package/docs/verification/dogfood/2026-11-24.md +2829 -0
  40. package/docs/verification/pi-160-model-free.ts +57 -0
  41. package/docs/verification/pi-160-native.mjs +21 -0
  42. package/docs/verified.json +43 -31
  43. package/package.json +2 -2
  44. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  45. package/plugins/agent-hub/kimi-hook.js +579 -126
  46. package/plugins/agent-hub/server.js +668 -138
  47. package/src/adapters/acp.ts +5 -0
  48. package/src/adapters/channel-peer.ts +7 -0
  49. package/src/adapters/claude-print-child.ts +27 -5
  50. package/src/adapters/codex-appserver.ts +9 -0
  51. package/src/adapters/compat.ts +12 -11
  52. package/src/adapters/configured-acp.ts +45 -2
  53. package/src/adapters/configured-print.ts +163 -0
  54. package/src/adapters/conformance/index.ts +1 -0
  55. package/src/adapters/conformance/print.ts +57 -0
  56. package/src/adapters/definitions/native-activity.ts +57 -0
  57. package/src/adapters/definitions/native-factories.ts +4 -2
  58. package/src/adapters/jcode.ts +10 -2
  59. package/src/adapters/local-worker.ts +2 -0
  60. package/src/adapters/registry-types.ts +5 -3
  61. package/src/adapters/role-eligibility.ts +5 -0
  62. package/src/cli/bench.ts +2 -1
  63. package/src/cli/broker.ts +2 -1
  64. package/src/cli/capabilities-output.ts +10 -14
  65. package/src/cli/configured-acp-entry.ts +10 -2
  66. package/src/cli/console-state.ts +25 -5
  67. package/src/cli/error-format.ts +2 -0
  68. package/src/cli/guidance.ts +1 -1
  69. package/src/cli/handoff-output.ts +20 -17
  70. package/src/cli/help.ts +78 -40
  71. package/src/cli/init-settings.ts +15 -0
  72. package/src/cli/intake-output.ts +13 -13
  73. package/src/cli/launch.ts +3 -2
  74. package/src/cli/learn-output.ts +40 -21
  75. package/src/cli/main.ts +148 -77
  76. package/src/cli/memory.ts +47 -2
  77. package/src/cli/output.ts +54 -31
  78. package/src/cli/roadmap.ts +2 -2
  79. package/src/cli/room-output.ts +71 -0
  80. package/src/cli/room.ts +19 -33
  81. package/src/cli/schedule-output.ts +20 -19
  82. package/src/cli/sdlc-output.ts +188 -170
  83. package/src/cli/source-output.ts +17 -14
  84. package/src/cli/specs.ts +13 -13
  85. package/src/cli/study-output.ts +66 -69
  86. package/src/cli/task-output.ts +106 -158
  87. package/src/cli/terminal-recovery.ts +2 -1
  88. package/src/cli/upgrade-runtime.ts +2 -1
  89. package/src/cli/warn-line.ts +18 -0
  90. package/src/cli/worktrees-output.ts +25 -23
  91. package/src/hub/audit-source.ts +45 -0
  92. package/src/hub/board.ts +141 -5
  93. package/src/hub/bus.ts +13 -2
  94. package/src/hub/config-apply.ts +14 -1
  95. package/src/hub/config-trust.ts +1 -0
  96. package/src/hub/control-client.ts +1 -1
  97. package/src/hub/daemon.ts +371 -45
  98. package/src/hub/handoff.ts +5 -1
  99. package/src/hub/hub-tools.ts +23 -5
  100. package/src/hub/instance-config.ts +3 -3
  101. package/src/hub/learn-followup.ts +103 -0
  102. package/src/hub/learning.ts +63 -1
  103. package/src/hub/manager.ts +15 -1
  104. package/src/hub/memory-policy.ts +2 -1
  105. package/src/hub/memory-review.ts +217 -0
  106. package/src/hub/peer-activity.ts +37 -0
  107. package/src/hub/peers.ts +3 -0
  108. package/src/hub/project-move.ts +258 -0
  109. package/src/hub/registry.ts +16 -5
  110. package/src/hub/restart.ts +7 -0
  111. package/src/hub/review-brief.ts +8 -4
  112. package/src/hub/review-checkout.ts +26 -0
  113. package/src/hub/review-findings.ts +6 -3
  114. package/src/hub/risk-tier.ts +129 -0
  115. package/src/hub/roadmap-check.ts +1 -0
  116. package/src/hub/routing.ts +3 -1
  117. package/src/hub/sdlc-merge.ts +9 -0
  118. package/src/hub/sdlc-metrics.ts +24 -1
  119. package/src/hub/sdlc-queue.ts +1 -1
  120. package/src/hub/sdlc.ts +15 -6
  121. package/src/hub/settings.ts +2 -0
  122. package/src/hub/spec-readback.ts +136 -0
  123. package/src/hub/specs.ts +1 -1
  124. package/src/hub/task-list-page.ts +1 -1
  125. package/src/hub/tasks.ts +558 -65
  126. package/src/hub/ui.ts +4 -2
  127. package/src/ui/index.html +26 -2
  128. package/src/ui/overview-model.ts +138 -0
  129. package/src/ui/plugin.ts +30 -4
  130. package/templates/roles/ops/project-manager.md +1 -1
@@ -1,221 +1,169 @@
1
1
  // Human output for `ahub task show|cancel`, the backlog mutations and grooming, and the release commands (#814 T2).
2
2
  // Pure: parsed hub-tool JSON in, spans out. The hub tools keep returning JSON to agents; the CLI parses the text and
3
- // renders it, and `--json` prints that text untouched. Built from the same primitives as sdlc-output.ts (#814 T1), so
4
- // every table fits the terminal and no identifier is cut. A private task arrives from the hub as a stub (`[pii]` title
3
+ // renders it, and `--json` prints that text untouched. Built on the shared `Report` (#1654 AC3): a header, a `▸` section per
4
+ // group and key/value rows, with tables from the one `grid`, so every row fits the terminal and no identifier is cut. A private task arrives from the hub as a stub (`[pii]` title
5
5
  // and detail, empty refs and plan): this module shows that stub and never asks for more.
6
- import { type Span, type Tone, plural, table, terminalText, wrap } from "./console-state.ts";
7
- import { moment } from "./sdlc-output.ts";
6
+ import { type Span, Report, plural, terminalText } from "./console-state.ts";
7
+ import { grid, moment, s } from "./sdlc-output.ts";
8
8
  import { taskHolderText } from "./role-holders.ts";
9
9
 
10
- type Line = Span[];
11
- // Local copies of the layout primitives of sdlc-output.ts (#814 T1), the source of these helpers: that file stays untouched by this task
12
- // (its plan names no edit), so a change to a primitive there is made here too. `moment` is already exported there and imported.
13
- const s = (value: unknown, tone?: Tone): Span => ({ text: terminalText(value).replace(/[\n\t]/g, " "), ...(tone ? { tone } : {}) });
14
- const room = (columns?: number) => columns ?? Infinity;
10
+ type Rows = [string, unknown][];
15
11
  const list = (value: unknown): any[] => Array.isArray(value) ? value : [];
16
12
  const yes = (value: unknown) => value === true ? "yes" : value === false ? "no" : "unknown";
17
13
  const short = (sha: unknown) => typeof sha === "string" && sha ? sha.slice(0, 8) : "-";
18
14
  const count = (n: unknown) => typeof n === "number" && Number.isFinite(n) ? (Number.isInteger(n) ? String(n) : n.toFixed(1)) : "unknown";
19
-
20
- /** Text wrapped to the width, continuation lines hanging under `indent`. */
21
- function para(text: string, columns: number | undefined, tone?: Tone, indent = "", hang = 2): Line[] {
22
- return wrap(indent + text, room(columns), hang).map(line => [s(line, tone)]);
23
- }
24
- /**
25
- * `label value`, the value wrapped beside its own label so narrow terminals never separate them. When the longest word of
26
- * 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
27
- * is broken only when it is wider than the whole terminal.
28
- */
29
- function pair(label: string, value: unknown, columns: number | undefined, labelWidth: number, tone?: Tone, indent = ""): Line[] {
30
- const text = terminalText(value).replace(/[\n\t]/g, " ");
31
- const head = indent + label.padEnd(labelWidth) + " ";
32
- const longest = Math.max(0, ...text.split(/\s+/).map(textWidth));
33
- if (columns !== undefined && head.length + longest > columns && text) {
34
- const under = indent.length + 1 + longest <= columns ? indent + " " : "";
35
- return [[s(indent + label, "muted")], ...wrap(under + text, columns, under.length).map((line): Line => [s(line, tone)])];
36
- }
37
- const lines = wrap(head + text, room(columns), head.length);
38
- return lines.map((line, i) => i === 0 ? [s(line.slice(0, head.length), "muted"), s(line.slice(head.length), tone)] : [s(line, tone)]);
39
- }
40
- /** Items under a label, one per line, wrapped under the dash. */
41
- function bullets(label: string, items: readonly unknown[], columns: number | undefined, tone?: Tone, indent = ""): Line[] {
42
- if (!items.length) return [];
43
- 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))];
44
- }
45
- const GAP = 2;
46
- const textWidth = (text: string) => Bun.stringWidth(text);
47
- /**
48
- * A table that fits the terminal and never cuts a character. At its natural widths when they fit; otherwise the
49
- * widest cells wrap inside their column (a PR linked to thirty tasks wraps its TASKS cell, it does not push the
50
- * table to 134 columns); and when even each column's longest unbreakable word cannot fit, one labelled block per row.
51
- */
52
- function grid(head: string[], data: Span[][], columns: number | undefined): Line[] {
53
- const natural = head.map((name, i) => Math.max(textWidth(name), ...data.map(row => textWidth(row[i]?.text ?? ""))));
54
- const gaps = GAP * (head.length - 1);
55
- if (columns === undefined || natural.reduce((sum, n) => sum + n, 0) + gaps <= columns) return table(head, data, room(columns), natural);
56
- const floor = head.map((name, i) => Math.max(textWidth(name), ...data.flatMap(row => (row[i]?.text ?? "").split(/\s+/).map(textWidth))));
57
- if (floor.reduce((sum, n) => sum + n, 0) + gaps > columns) return blocks(head, data, columns);
58
- // Hand the spare width to the column that is cut most, one cell at a time, so the wide list cell wraps and the short ones do not.
59
- const widths = [...floor];
60
- for (let spare = columns - widths.reduce((sum, n) => sum + n, 0) - gaps; spare > 0; spare--) {
61
- let at = -1;
62
- for (let i = 0; i < widths.length; i++) if (widths[i]! < natural[i]! && (at < 0 || natural[i]! - widths[i]! > natural[at]! - widths[at]!)) at = i;
63
- if (at < 0) break;
64
- widths[at]!++;
65
- }
66
- const physical = data.flatMap(row => {
67
- const cells = row.map((cell, i) => wrap(cell.text, widths[i]!, 0));
68
- return Array.from({ length: Math.max(1, ...cells.map(lines => lines.length)) }, (_, n) => head.map((_, i): Span => ({ ...(row[i] ?? s("")), text: cells[i]?.[n] ?? "" })));
69
- });
70
- return table(head, physical, columns, widths);
71
- }
72
- /** Narrow terminal: each row becomes its own block, the first column as its heading and every other column beside its label. */
73
- function blocks(head: string[], data: Span[][], columns: number): Line[] {
74
- const label = Math.max(...head.slice(1).map(textWidth));
75
- return data.flatMap((row, n) => [...(n ? [blank] : []), ...wrap(row[0]?.text ?? "", columns, 2).map((line): Line => [{ ...(row[0] ?? s("")), text: line }]),
76
- ...head.slice(1).flatMap((name, i) => pair(name.toLowerCase(), row[i + 1]?.text ?? "", columns, label, row[i + 1]?.tone, " "))]);
77
- }
78
- /** A heading wraps to the width like any paragraph; a long repository name never pushes it past the terminal. */
79
- const heading = (text: string, columns?: number): Line[] => wrap(text, room(columns), 2).map(line => [s(line, "strong")]);
80
- const blank: Line = [s("")];
81
15
  const dash = (value: unknown) => value === undefined || value === null || value === "" ? "-" : String(value);
82
16
  const ids = (values: unknown) => list(values).map(id => `#${id}`).join(" ") || "none";
83
17
  const when = (at: unknown, now: number) => typeof at === "number" && Number.isFinite(at) ? moment(at, now) : "-";
84
- const STATE_TONE: Record<string, Tone> = { approved: "success", in_review: "attention", in_progress: "info", proposed: "muted", backlog: "muted", cancelled: "muted", blocked: "failure" };
85
- const stateTone = (state: unknown): Tone | undefined => typeof state === "string" ? STATE_TONE[state] : undefined;
86
18
  const isStub = (task: any) => task?.title === "[pii]" && task?.detail === "[pii]";
87
19
 
88
- /** The first task of a result: a stub when the hub withheld it, which says so in one line and points at the console. */
89
- function stubNote(task: any, columns: number | undefined): Line[] {
90
- return isStub(task) ? [blank, ...para(`private task: the title, detail, paths and plan are withheld here. Read it where it is allowed: \`ahub task show ${task.id}\` in a console terminal.`, columns, "muted")] : [];
91
- }
92
- const planBlock = (plan: any, columns: number | undefined): Line[] => {
93
- const keys = ["paths", "symbols", "signatures", "insertion_points", "sections", "sources", "claims"];
94
- return keys.flatMap(key => bullets(key.replace("_", " "), list(plan?.[key]), columns, undefined, " "));
95
- };
20
+ const planRows = (plan: any): Rows => ["paths", "symbols", "signatures", "insertion_points", "sections", "sources", "claims"]
21
+ .filter(key => list(plan?.[key]).length).map((key): [string, unknown] => [key.replace("_", " "), list(plan[key]).map(item => terminalText(item)).join(", ")]);
96
22
  const historyRows = (history: any[], now: number): Span[][] => history.map(entry => [s(when(entry.at, now), "muted"), s(entry.instructed && entry.instructedPeer ? `${entry.by ?? "user"} via ${entry.instructedPeer}` : entry.by ?? "-"), s(entry.event ?? "-", entry.event === "approved" ? "success" : entry.event === "changes_requested" ? "attention" : undefined), s(dash(entry.note))]);
97
23
 
98
- /** The one task block: identity, who holds it, what it waits for, then plan, receipt and history. */
99
- function taskBlock(task: any, columns: number | undefined, now: number, detail: boolean): Line[] {
100
- const id = `#${task?.id ?? "?"}`;
101
- const out: Line[] = [...para(`${id} ${dash(task?.title)}`, columns, undefined, "", 6).map((line, i): Line => i === 0 ? [s(id, "taskRef"), s(line[0]!.text.slice(id.length), "strong")] : line)];
102
- const w = 10;
103
- out.push(...pair("state", `${dash(task?.state)}${task?.cancelled ? " (cancelled)" : ""}`, columns, w, stateTone(task?.state), " "),
104
- ...pair("class", dash(task?.class), columns, w, undefined, " "), ...pair("owner", taskHolderText(task, "owner"), columns, w, undefined, " "), ...pair("reviewer", taskHolderText(task, "reviewer"), columns, w, undefined, " "));
105
- if (task?.planner !== undefined) out.push(...pair("planner", taskHolderText(task, "planner"), columns, w, undefined, " "));
106
- if (task?.reserved) out.push(...pair("reserved", task.reserved, columns, w, undefined, " "));
107
- // #1454: a recorded wait, with whether it has passed: a passed one means the idle ladder restarts, so it reads as attention.
108
- if (task?.wait && typeof task.wait.until === "number") out.push(...pair("waiting", `${task.wait.passed ? "passed " : "until "}${new Date(task.wait.until).toISOString()}${task.wait.by ? `, set by ${task.wait.by}` : ""}${task.wait.reason ? `: ${task.wait.reason}` : ""}`, columns, w, task.wait.passed ? "attention" : undefined, " "));
109
- if (task?.handoffOrigin) out.push(...pair("from", `project ${task.handoffOrigin.projectId}, handed off by ${task.handoffOrigin.peer}${typeof task.handoffOrigin.task === "number" ? ` (their task #${task.handoffOrigin.task})` : ""}`, columns, w, "attention", " "));
110
- out.push(...pair("after", ids(task?.deps), columns, w, undefined, " "));
111
- if (typeof task?.release === "number") out.push(...pair("release", `#${task.release}`, columns, w, undefined, " "));
112
- if (typeof task?.rank === "number" || typeof task?.priority === "number") out.push(...pair("planning", [typeof task.rank === "number" ? `rank ${task.rank}` : "", typeof task.priority === "number" ? `priority P${task.priority}` : "", task.pinned ? "pinned" : ""].filter(Boolean).join(", "), columns, w, undefined, " "));
24
+ /** The one task block: identity, who holds it, what it waits for, then plan, receipt and history. The caller owns the header. */
25
+ function taskBlock(out: Report, task: any, now: number, detail: boolean): void {
26
+ const rows: Rows = [["title", dash(task?.title)], ["state", `${dash(task?.state)}${task?.cancelled ? " (cancelled)" : ""}`], ["class", dash(task?.class)], ["owner", taskHolderText(task, "owner")], ["reviewer", taskHolderText(task, "reviewer")]];
27
+ if (typeof task?.reason === "string") rows.push(["reason", task.reason]);
28
+ if (task?.planner !== undefined) rows.push(["planner", taskHolderText(task, "planner")]);
29
+ if (task?.reserved) rows.push(["reserved", task.reserved]);
30
+ // #1454: a recorded wait, with whether it has passed: a passed one means the idle ladder restarts.
31
+ if (task?.wait && typeof task.wait.until === "number") rows.push(["waiting", `${task.wait.passed ? "passed " : "until "}${new Date(task.wait.until).toISOString()}${task.wait.by ? `, set by ${task.wait.by}` : ""}${task.wait.reason ? `: ${task.wait.reason}` : ""}`]);
32
+ if (task?.handoffOrigin) rows.push(["from", `project ${task.handoffOrigin.projectId}, handed off by ${task.handoffOrigin.peer}${typeof task.handoffOrigin.task === "number" ? ` (their task #${task.handoffOrigin.task})` : ""}`]);
33
+ rows.push(["after", ids(task?.deps)]);
34
+ if (typeof task?.release === "number") rows.push(["release", `#${task.release}`]);
35
+ if (typeof task?.rank === "number" || typeof task?.priority === "number") rows.push(["planning", [typeof task.rank === "number" ? `rank ${task.rank}` : "", typeof task.priority === "number" ? `priority P${task.priority}` : "", task.pinned ? "pinned" : ""].filter(Boolean).join(", ")]);
113
36
  // The operands the next command needs: backlog plan|pin|split|pull-ready|undo take the planning revision (0 on an unedited card),
114
37
  // task cancel and assign --revision take the flow revision. A person must not have to switch to --json to read them.
115
- if (task?.state === "backlog" || typeof task?.planningRevision === "number") out.push(...pair("planning rev", count(task?.planningRevision ?? 0), columns, w, undefined, " "));
116
- if (typeof task?.flowRevision === "number") out.push(...pair("flow rev", count(task.flowRevision), columns, w, undefined, " "));
117
- out.push(...pair("created", when(task?.created, now), columns, w, undefined, " "), ...pair("updated", when(task?.updated, now), columns, w, undefined, " "));
118
- if (!detail) return out;
119
- out.push(...stubNote(task, columns));
120
- if (!isStub(task) && task?.detail) out.push(blank, [s("detail", "muted")], ...para(String(task.detail), columns, undefined, " ", 2));
38
+ const revisions = [task?.state === "backlog" || typeof task?.planningRevision === "number" ? `planning rev ${count(task?.planningRevision ?? 0)}` : "", typeof task?.flowRevision === "number" ? `flow rev ${count(task.flowRevision)}` : ""].filter(Boolean);
39
+ if (revisions.length) rows.push(["revisions", revisions.join(", ")]);
40
+ rows.push(["created", when(task?.created, now)], ["updated", when(task?.updated, now)]);
41
+ out.section("Task").kv(rows);
42
+ if (!detail) return;
43
+ if (isStub(task)) {
44
+ out.section("Private").note("private task: the title, detail, paths and plan are withheld here; read it in a console terminal", "value").next(`ahub task show ${task.id}`);
45
+ } else if (task?.detail) out.section("Detail").note(String(task.detail), "value");
121
46
  const refs = task?.refs ?? {};
47
+ const refRows: Rows = [];
122
48
  const refText = [refs.repo, refs.branch ? `branch ${refs.branch}` : "", refs.commit ? `commit ${short(refs.commit)}` : ""].filter(Boolean).join(", ");
123
- if (refText) out.push(blank, ...pair("refs", refText, columns, w, undefined, " "));
124
- out.push(...bullets("ref paths", list(refs.paths), columns, undefined, " "));
49
+ if (refText) refRows.push(["refs", refText]);
50
+ if (list(refs.paths).length) refRows.push(["ref paths", list(refs.paths).map(item => terminalText(item)).join(", ")]);
51
+ if (refRows.length) out.section("Refs").kv(refRows);
125
52
  if (!isStub(task) && task?.approval) {
126
53
  const approval = task.approval;
127
- const binding = `head ${approval.head ?? "unknown"}; latest ${approval.latestHead ?? "unknown"}; ${approval.mismatch ? "HEAD MISMATCH, approval is stale" : approval.current ? "current" : "not current, review required"}`;
128
- out.push(...pair("approval", binding, columns, w, approval.current ? "success" : "attention", " "));
54
+ out.section("Approval").kv([["approval", `head ${approval.head ?? "unknown"}; latest ${approval.latestHead ?? "unknown"}; ${approval.mismatch ? "HEAD MISMATCH, approval is stale" : approval.current ? "current" : "not current, review required"}`]]);
55
+ if (!approval.current) out.bullet("warn", approval.mismatch ? "approval is stale" : "review required");
129
56
  }
130
- const plan = planBlock(task?.plan, columns);
131
- if (plan.length) out.push(blank, [s("plan", "muted")], ...plan);
57
+ const plan = planRows(task?.plan);
58
+ if (plan.length) out.section("Plan").kv(plan);
132
59
  const sdlc = task?.sdlc;
133
- if (sdlc) out.push(blank, ...pair("lifecycle", [sdlc.stage ? `stage ${sdlc.stage}` : "", sdlc.repo && sdlc.issue ? `${sdlc.repo}#${sdlc.issue}` : "", sdlc.pr ? `PR #${sdlc.pr}` : "", sdlc.head ? `head ${short(sdlc.head)}` : ""].filter(Boolean).join(", ") || "recorded", columns, w, undefined, " "));
134
- if (task?.relatedMemory) out.push(...pair("memory", `${task.relatedMemory.state}${typeof task.relatedMemory.count === "number" ? `, ${plural(task.relatedMemory.count, "related note")}` : ""}`, columns, w, undefined, " "));
60
+ const context: Rows = [];
61
+ if (sdlc) context.push(["lifecycle", [sdlc.stage ? `stage ${sdlc.stage}` : "", sdlc.repo && sdlc.issue ? `${sdlc.repo}#${sdlc.issue}` : "", sdlc.pr ? `PR #${sdlc.pr}` : "", sdlc.head ? `head ${short(sdlc.head)}` : ""].filter(Boolean).join(", ") || "recorded"]);
62
+ if (task?.relatedMemory) context.push(["memory", `${task.relatedMemory.state}${typeof task.relatedMemory.count === "number" ? `, ${plural(task.relatedMemory.count, "related note")}` : ""}`]);
63
+ if (context.length) out.section("Context").kv(context);
135
64
  // Tasks.symbolOverlaps: { task, files, sameFileDifferentSymbols } per overlapping task, public file names only.
136
- if (list(task?.symbolOverlaps).length) out.push(...bullets("overlaps", list(task.symbolOverlaps).map((o: any) => `#${o?.task ?? "?"} touches ${list(o?.files).join(", ") || "files withheld"}${o?.sameFileDifferentSymbols ? " (same file, different symbols)" : ""}`), columns, "attention", " "));
65
+ const overlaps = list(task?.symbolOverlaps);
66
+ if (overlaps.length) {
67
+ out.section("Overlaps", String(overlaps.length));
68
+ for (const o of overlaps) out.bullet("warn", `#${o?.task ?? "?"} touches ${list(o?.files).join(", ") || "files withheld"}${o?.sameFileDifferentSymbols ? " (same file, different symbols)" : ""}`);
69
+ }
137
70
  // Tasks.deliverableStatus: { state, changedSinceReview, files: [{ id, sha256, state, path?, format, version?, private? }] }.
138
71
  const delivered = task?.deliverables;
139
72
  if (delivered) {
140
- out.push(blank, ...pair("deliverables", `${dash(delivered.state)}${delivered.changedSinceReview ? ", changed since review" : ""}`, columns, w, delivered.changedSinceReview ? "attention" : undefined, " "));
141
- out.push(...grid(["FILE", "FORMAT", "STATE", "SHA256"], list(delivered.files).map((file: any) => [s(file.private ? "(private)" : dash(file.path ?? file.id)), s(`${dash(file.format)}${file.version ? ` ${file.version}` : ""}`), s(dash(file.state), file.state === "changed" || file.state === "missing" ? "attention" : undefined), s(short(file.sha256))]), columns));
73
+ out.section("Deliverables", String(list(delivered.files).length)).kv([["deliverables", `${dash(delivered.state)}${delivered.changedSinceReview ? ", changed since review" : ""}`]]);
74
+ if (delivered.changedSinceReview) out.bullet("warn", "changed since review");
75
+ if (list(delivered.files).length) out.append(grid(["FILE", "FORMAT", "STATE", "SHA256"], list(delivered.files).map((file: any) => [s(file.private ? "(private)" : dash(file.path ?? file.id)), s(`${dash(file.format)}${file.version ? ` ${file.version}` : ""}`), s(dash(file.state), file.state === "changed" || file.state === "missing" ? "attention" : undefined), s(short(file.sha256))]), out.columns));
142
76
  }
143
77
  const reviews = list(task?.reviews);
144
- if (reviews.length) out.push(blank, [s("reviews", "muted")], ...grid(["KIND", "REVIEWER", "AT"], reviews.map((r: any) => [s(r.kind, r.kind === "approved" ? "success" : "attention"), s(r.reviewer), s(when(r.at, now), "muted")]), columns));
78
+ if (reviews.length) out.section("Reviews", String(reviews.length)).append(grid(["KIND", "REVIEWER", "AT"], reviews.map((r: any) => [s(r.kind, r.kind === "approved" ? "success" : "attention"), s(r.reviewer), s(when(r.at, now), "muted")]), out.columns));
145
79
  const history = list(task?.history);
146
- if (history.length) out.push(blank, [s(`history (${plural(history.length, "entry")}${typeof task?.flowRevision === "number" && task.flowRevision > history.length ? `, last ${history.length} shown` : ""})`, "muted")], ...grid(["AT", "BY", "EVENT", "NOTE"], historyRows(history, now), columns));
147
- return out;
80
+ if (history.length) {
81
+ out.section("History", String(history.length));
82
+ if (typeof task?.flowRevision === "number" && task.flowRevision > history.length) out.note(`${plural(history.length, "entry")}, last ${history.length} shown`);
83
+ out.append(grid(["AT", "BY", "EVENT", "NOTE"], historyRows(history, now), out.columns));
84
+ }
148
85
  }
149
86
 
150
87
  /** `ahub task show <id>`: the full block. A task that does not exist arrives as a JSON string and prints as that sentence. */
151
- export function renderTaskShow(task: unknown, columns?: number, now = Date.now()): Span[][] {
152
- if (typeof task === "string") return para(task, columns);
153
- return taskBlock(task, columns, now, true);
88
+ export function renderTaskShow(task: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
89
+ if (typeof task === "string") return new Report(columns, ascii).header("ahub", "Task").note(task, "value").lines();
90
+ const out = new Report(columns, ascii).titled("ahub", "Task", `#${(task as any)?.id ?? "?"}`, true);
91
+ taskBlock(out, task, now, true);
92
+ return out.lines();
154
93
  }
155
94
 
156
95
  /** `ahub task cancel`: the cancelled task, with who superseded it and why. */
157
- export function renderTaskCancel(task: unknown, columns?: number, now = Date.now()): Span[][] {
96
+ export function renderTaskCancel(task: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
158
97
  const t = task as any;
159
- const out = [...heading(`Task #${t?.id ?? "?"} cancelled`, columns), ...taskBlock(t, columns, now, false)];
98
+ const out = new Report(columns, ascii).titled("ahub", `Task #${t?.id ?? "?"} cancelled`);
99
+ taskBlock(out, t, now, false);
160
100
  const c = t?.cancelled;
161
- if (c) out.push(...pair("reason", dash(c.reason), columns, 10, undefined, " "), ...(c.supersededBy ? pair("superseded", String(c.supersededBy), columns, 10, undefined, " ") : []));
162
- return out;
101
+ if (c) out.section("Cancelled").kv([["reason", dash(c.reason)], ...(c.supersededBy ? [["superseded", String(c.supersededBy)] as [string, unknown]] : [])]);
102
+ return out.lines();
163
103
  }
164
104
 
165
105
  const BACKLOG_HEAD: Record<string, string> = { plan: "Backlog card planned", pin: "Backlog card pinned", "return-untouched": "Task returned to the backlog", "pull-ready": "Backlog card pulled and routed", undo: "Planning change undone", split: "Backlog card split" };
166
106
  /** The backlog mutations: the card as the hub now holds it; a split shows its parent and each child. */
167
- export function renderBacklogResult(op: keyof typeof BACKLOG_HEAD, result: unknown, columns?: number, now = Date.now()): Span[][] {
107
+ export function renderBacklogResult(op: keyof typeof BACKLOG_HEAD, result: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
168
108
  const r = result as any;
169
- const out: Line[] = [...heading(BACKLOG_HEAD[op] ?? "Backlog", columns)];
109
+ const out = new Report(columns, ascii).titled("ahub", BACKLOG_HEAD[op] ?? "Backlog");
170
110
  if (op === "split") {
171
- out.push(...taskBlock(r?.parent, columns, now, false));
111
+ taskBlock(out, r?.parent, now, false);
172
112
  const children = list(r?.children);
173
- out.push(blank, [s(`${plural(children.length, "child card")}`, "muted")], ...grid(["ID", "STATE", "AFTER", "TITLE"], children.map((c: any) => [s(`#${c.id}`, "taskRef"), s(dash(c.state), stateTone(c.state)), s(ids(c.deps)), s(dash(c.title))]), columns));
174
- return out;
113
+ out.section("Children", String(children.length));
114
+ if (children.length) out.append(grid(["ID", "STATE", "AFTER", "TITLE"], children.map((c: any) => [s(`#${c.id}`, "taskRef"), s(dash(c.state)), s(ids(c.deps)), s(dash(c.title))]), columns));
115
+ else out.note("no child cards");
116
+ if (children.length) out.note(plural(children.length, "child card"));
117
+ return out.lines();
175
118
  }
176
- out.push(...taskBlock(r, columns, now, false), ...stubNote(r, columns));
119
+ taskBlock(out, r, now, false);
120
+ if (isStub(r)) out.section("Private").note("private task: the title, detail, paths and plan are withheld here; read it in a console terminal", "value").next(`ahub task show ${r.id}`);
177
121
  const last = list(r?.history).at(-1);
178
- if (last?.note) out.push(...pair("note", String(last.note), columns, 10, "muted", " "));
179
- return out;
122
+ if (last?.note) out.section("Note").note(String(last.note), "value");
123
+ return out.lines();
180
124
  }
181
125
 
182
126
  const GROOM_TEXT: Record<string, string> = { "text-dependency": "text names a dependency the card does not declare", overlap: "overlaps other open work", duplicate: "may duplicate another card", "over-wip": "its owner is over the WIP limit", stale: "has not moved for a long time", superseded: "was superseded", blocked: "cannot be routed", "closed-issue": "its issue is closed", "wait-passed": "its recorded wait has passed, so the idle sweep runs again: record a new wait or check the owner" };
183
127
  /** `ahub backlog groom`: what the planner would look at, one line per finding. */
184
- export function renderGroom(digest: unknown, columns?: number, _now = Date.now()): Span[][] {
128
+ export function renderGroom(digest: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
185
129
  const d = digest as any;
186
130
  const items = list(d?.items);
187
- const out: Line[] = [...heading("Backlog grooming", columns)];
188
- if (!items.length) out.push([s("nothing to groom", "muted")]);
189
- else out.push(...grid(["TASK", "FINDING", "RELATED", "CODE"], items.map((i: any) => [s(`#${i.task}`, "taskRef"), s(GROOM_TEXT[i.kind] ?? String(i.kind)), s(i.related?.length ? ids(i.related) : "-"), s(dash(i.code), "muted")]), columns));
190
- for (const item of items) if (item.personCommand) out.push(...pair(`#${item.task}`, String(item.personCommand), columns, 6, "info", ""));
191
- if (list(d?.unknown).length) out.push(blank, ...pair("unknown", `${ids(d.unknown)}: not enough evidence to judge`, columns, 8, "attention"));
192
- if (d?.truncated) out.push(...para("truncated: the board has more cards than one grooming pass reads", columns, "attention"));
193
- if (d?.privateTasks === "withheld") out.push(...para("private tasks are withheld", columns, "muted"));
194
- return out;
131
+ const out = new Report(columns, ascii).header("ahub", "Backlog grooming");
132
+ if (!items.length) out.note("nothing to groom");
133
+ else {
134
+ out.section("Findings", String(items.length)).append(grid(["TASK", "FINDING", "RELATED", "CODE"], items.map((i: any) => [s(`#${i.task}`, "taskRef"), s(GROOM_TEXT[i.kind] ?? String(i.kind)), s(i.related?.length ? ids(i.related) : "-"), s(dash(i.code), "muted")]), columns));
135
+ const commands = items.filter((item: any) => item.personCommand).map((item: any): [string, unknown] => [`#${item.task}`, String(item.personCommand)]);
136
+ if (commands.length) out.section("Person commands").kv(commands);
137
+ }
138
+ if (list(d?.unknown).length) out.bullet("unknown", `${ids(d.unknown)}: not enough evidence to judge`);
139
+ if (d?.truncated) out.bullet("warn", "truncated: the board has more cards than one grooming pass reads");
140
+ if (d?.privateTasks === "withheld") out.note("private tasks are withheld");
141
+ return out.lines();
195
142
  }
196
143
 
197
- const RELEASE_TONE: Record<string, Tone> = { active: "success", frozen: "attention", shipped: "muted", dropped: "muted", planned: "info" };
198
- function releaseBlock(row: any, columns: number | undefined, now: number): Line[] {
199
- const w = 14, out: Line[] = [...para(`#${row?.id ?? "?"} ${dash(row?.name)}`, columns, undefined, "", 6).map((line, i): Line => i === 0 ? [s(`#${row?.id ?? "?"}`, "issueRef"), s(line[0]!.text.slice(`#${row?.id ?? "?"}`.length), "strong")] : line)];
200
- out.push(...pair("state", dash(row?.state), columns, w, RELEASE_TONE[row?.state], " "), ...pair("goal", dash(row?.goal), columns, w, undefined, " "), ...pair("order", count(row?.order), columns, w, undefined, " "), ...pair("revision", count(row?.revision), columns, w, undefined, " "));
201
- out.push(...pair("planned start", when(row?.plannedStart, now), columns, w, undefined, " "), ...pair("cut", when(row?.cut, now), columns, w, undefined, " "), ...pair("ship", when(row?.ship, now), columns, w, undefined, " "));
144
+ function releaseBlock(out: Report, row: any, now: number): void {
145
+ const rows: Rows = [["name", dash(row?.name)], ["state", dash(row?.state)], ["goal", dash(row?.goal)], ["order", count(row?.order)], ["revision", count(row?.revision)], ["planned start", when(row?.plannedStart, now)], ["cut", when(row?.cut, now)], ["ship", when(row?.ship, now)]];
202
146
  const tasks = list(row?.tasks);
203
- out.push(...pair("scope", tasks.length ? `${plural(tasks.length, "task")}: ${tasks.map((t: any) => `#${t.id} ${t.state}`).join(", ")}` : "no task assigned", columns, w, undefined, " "));
204
- if (row?.afterCut !== undefined && row?.afterCut !== null) out.push(...pair("after the cut", `${count(row.afterCutCount)} approved outside this release: ${ids(row.afterCut)}${row.afterCutCount > list(row.afterCut).length ? " and more" : ""}`, columns, w, row.afterCutCount ? "attention" : undefined, " "));
205
- if (row?.afterCutUnknownCount) out.push(...pair("unknown date", `${count(row.afterCutUnknownCount)} approved without a recorded date: ${ids(row.afterCutUnknown)}`, columns, w, "attention", " "));
206
- if (row?.train) out.push(...pair("train", `${yes(row.train.active)} active${row.train.hotfix ? `, hotfix ${row.train.hotfix}` : ""}`, columns, w, undefined, " "));
207
- return out;
147
+ rows.push(["scope", tasks.length ? `${plural(tasks.length, "task")}: ${tasks.map((t: any) => `#${t.id} ${t.state}`).join(", ")}` : "no task assigned"]);
148
+ if (row?.afterCut !== undefined && row?.afterCut !== null) rows.push(["after the cut", `${count(row.afterCutCount)} approved outside this release: ${ids(row.afterCut)}${row.afterCutCount > list(row.afterCut).length ? " and more" : ""}`]);
149
+ if (row?.afterCutUnknownCount) rows.push(["unknown date", `${count(row.afterCutUnknownCount)} approved without a recorded date: ${ids(row.afterCutUnknown)}`]);
150
+ if (row?.train) rows.push(["train", `${yes(row.train.active)} active${row.train.hotfix ? `, hotfix ${row.train.hotfix}` : ""}`]);
151
+ out.section(`Release #${row?.id ?? "?"}`).kv(rows);
208
152
  }
209
153
  /** `ahub release list`: one block per release, in order. */
210
- export function renderReleaseList(rows: unknown, columns?: number, now = Date.now()): Span[][] {
154
+ export function renderReleaseList(rows: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
211
155
  const releases = list(rows);
212
- if (!releases.length) return [[s("no releases")]];
213
- return releases.flatMap((row, i): Line[] => [...(i ? [blank] : []), ...releaseBlock(row, columns, now)]);
156
+ const out = new Report(columns, ascii).titled("ahub", "Releases", releases.length ? plural(releases.length, "release") : undefined);
157
+ if (!releases.length) return out.note("no releases").lines();
158
+ for (const row of releases) releaseBlock(out, row, now);
159
+ return out.lines();
214
160
  }
215
161
  /** `ahub release show <name>` and the result of `release new|plan|activate|freeze|ship|drop`: the release as the hub holds it. */
216
- export function renderReleaseShow(row: unknown, columns?: number, now = Date.now()): Span[][] {
217
- if (typeof row === "string") return para(row, columns);
218
- return releaseBlock(row, columns, now);
162
+ export function renderReleaseShow(row: unknown, columns?: number, now = Date.now(), ascii = false, title = "Release"): Span[][] {
163
+ if (typeof row === "string") return new Report(columns, ascii).header("ahub", title).note(row, "value").lines();
164
+ const out = new Report(columns, ascii).titled("ahub", title);
165
+ releaseBlock(out, row, now);
166
+ return out.lines();
219
167
  }
220
- export const renderReleaseChange = (row: unknown, columns?: number, now = Date.now()): Span[][] => [...heading("Release updated", columns), ...renderReleaseShow(row, columns, now)];
221
- export const renderReleaseNew = (row: unknown, columns?: number, now = Date.now()): Span[][] => [...heading("Release created", columns), ...renderReleaseShow(row, columns, now)];
168
+ export const renderReleaseChange = (row: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] => renderReleaseShow(row, columns, now, ascii, "Release updated");
169
+ export const renderReleaseNew = (row: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] => renderReleaseShow(row, columns, now, ascii, "Release created");
@@ -12,6 +12,7 @@ import { randomUUID } from "node:crypto";
12
12
  import { processLiveness, processSignature } from "../pi/process-signature.ts";
13
13
  import { atomicPrivateJSON } from "../hub/recovery-store.ts";
14
14
  import type { ControlClient } from "../hub/control-client.ts";
15
+ import { warnLine } from "./warn-line.ts";
15
16
 
16
17
  /** The only terminal commands used by this adapter. Keep this list in sync with Orca's public CLI. */
17
18
  export type OrcaTerminalCommand = "list" | "show" | "wait" | "close" | "create";
@@ -544,7 +545,7 @@ export function terminalLaunchCandidate(value: unknown, projectRoot: string, sta
544
545
  /** Old daemons may launch the TUI, but cannot turn a pre-attach candidate into recovery authority. */
545
546
  export async function registerTerminalLaunch(client: Pick<ControlClient, "features" | "request">, row: RecordedTerminalLaunch, operationId?: string): Promise<void> {
546
547
  if (!client.features.includes("terminal_owner")) {
547
- console.error("terminal launcher is unrecorded; upgrade the running hub for managed terminal recovery");
548
+ warnLine("terminal launcher is unrecorded: upgrade the running hub for managed terminal recovery", "ahub upgrade");
548
549
  return;
549
550
  }
550
551
  const result = await client.request({ t: "terminal_launch", launch: row, ...(operationId ? { operationId } : {}) });
@@ -32,6 +32,7 @@ import { recoveryLock } from "../hub/recovery-store.ts";
32
32
  import { decodeRestoreReceipt, restoreTransition, type RestoreReceipt, type RestoreEvidence, type RestoreTransition } from "./upgrade-restore-state.ts";
33
33
  import { RecoveryDeferredHubError } from "../hub/deferred-hub.ts";
34
34
  import { RecoveryPreservationError, RecoveryPresentationError, type RecoveryNativeCause } from "./upgrade-presentation-data.ts";
35
+ import { warnLine } from "./warn-line.ts";
35
36
 
36
37
  // #489 H4: the reconnect, unmanaged reconnect, control request, terminal idle and shutdown waits are settings now (`recovery.*`, src/hub/operational-settings.ts), read by `readRecoveryWaits` at the start of
37
38
  // each wait. Their defaults are the constants that stood here: an unmanaged Claude's plugin retries with a backoff of at most 30 s and three of those bound its reconnect wait (#206, 90 s); managed TUI startup
@@ -849,7 +850,7 @@ export function makeRecoveryDriver(run: RunCommand = runCommand, liveTestPeer?:
849
850
  await control(p, "release", id, instance);
850
851
  if (previous.state === "ready" && previous.bookmark.operationId !== id) {
851
852
  try { retireRecoveryContinuity(p.stateDir, { projectId: p.id, projectRoot: p.root, operationId: previous.bookmark.operationId, digest: previous.digest }, "recovery_released"); }
852
- catch { console.error("Pi continuity retirement is unconfirmed after successful recovery release; inspect the retained bookmark before another automatic start"); }
853
+ catch { warnLine("Pi continuity retirement is unconfirmed after successful recovery release: inspect the retained bookmark before another automatic start"); }
853
854
  }
854
855
  },
855
856
  closeTerminals: async (planned, progress, op, save) => {
@@ -0,0 +1,18 @@
1
+ import { MARKERS, asciiMarkers } from "./output-standard.ts";
2
+
3
+ // Deliberately imports only the light output-standard module: launch.ts, bench.ts and the other modules that warn reach this file early, and
4
+ // console-state.ts (through error-format.ts) would close an import cycle through the adapter registry.
5
+ /** Control characters out of a message or next step, so a daemon-supplied string cannot move the cursor. */
6
+ const plain = (text: string) => text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
7
+
8
+ /** The one warning format (standard v1, Messages): `ahub: warning: <what>: <why>`, a marker only on a terminal, and an optional `→ next` line. Pure; `error-format.ts` re-exports it. */
9
+ export function warningLines(message: string, next: string | undefined, terminal: boolean, ascii: boolean): string[] {
10
+ const line = `ahub: warning: ${plain(message).replace(/[\r\n]+/g, " ")}`;
11
+ const first = terminal ? `${MARKERS.warn[ascii ? "ascii" : "glyph"]} ${line}` : line;
12
+ return next ? [first, ` ${MARKERS.next[ascii ? "ascii" : "glyph"]} ${plain(next)}`] : [first];
13
+ }
14
+
15
+ /** `warningLines` on stderr for this process; main.ts's `warn()` is this same function. */
16
+ export function warnLine(message: string, next?: string): void {
17
+ console.error(warningLines(message, next, !!process.stderr.isTTY, asciiMarkers(process.env, process.argv.includes("--ascii"))).join("\n"));
18
+ }
@@ -1,43 +1,45 @@
1
1
  // Human output for `ahub worktrees` and `ahub worktrees tidy` (#1057). Pure: data in, spans out, no I/O. `--json` is the caller's branch and prints the same data.
2
- import { blank, grid, heading, pair, s } from "./sdlc-output.ts";
3
- import { moment } from "./sdlc-output.ts";
4
- import type { Span } from "./console-state.ts";
2
+ import { grid, moment, s } from "./sdlc-output.ts";
3
+ import { Report, type Span } from "./console-state.ts";
5
4
 
6
5
  const list = (value: unknown): any[] => Array.isArray(value) ? value : [];
7
6
  const reasonLabel = (row: any): string => row?.reason === "merged" ? "PR merged" : row?.reason === "closed" ? "PR closed" : row?.reason === "quiet" ? "quiet" : row?.reason === "parked" ? "parked" : row?.reason === "settled" ? "settled" : "";
8
7
  const taskLabel = (row: any): string => row?.private === true ? "task: private" : typeof row?.task === "number" ? `#${row.task}${typeof row.pr === "number" ? ` PR ${row.pr}` : ""}` : "";
9
8
 
10
9
  /** `ahub worktrees`: live rows, then the shelf with each settled row's reason. */
11
- export function renderWorktrees(reply: unknown, columns?: number, now = Date.now()): Span[][] {
10
+ export function renderWorktrees(reply: unknown, columns?: number, now = Date.now(), ascii = false): Span[][] {
12
11
  const r = reply as any, live = list(r?.live), settled = list(r?.settled);
13
12
  const rows = (items: any[], withReason: boolean) => items.map((row: any) => [
14
13
  s(row.path), s(row.branch ?? "(detached)", "muted"), s(taskLabel(row), "issueRef"), ...(withReason ? [s(reasonLabel(row), "attention")] : []), s(moment(row.lastActiveAt, now), "muted"),
15
14
  ]);
16
- const out: Span[][] = [...heading(`Worktrees: ${live.length} live, ${settled.length} settled`, columns)];
17
- if (live.length) out.push(...grid(["PATH", "BRANCH", "TASK", "ACTIVE"], rows(live, false), columns));
18
- if (settled.length) out.push(blank, ...heading("Shelf (settled)", columns), ...grid(["PATH", "BRANCH", "TASK", "WHY", "ACTIVE"], rows(settled, true), columns));
19
- if (!live.length && !settled.length) out.push([s("no worktrees", "muted")]);
20
- if (r?.complete === false) out.push(blank, [s("the list was cut off at its bound; some worktrees are not shown", "attention")]);
21
- if (settled.length) out.push(blank, [s("preview what could be removed with ahub worktrees tidy; nothing is removed until you confirm", "muted")]);
22
- return out;
15
+ const out = new Report(columns, ascii).titled("ahub", "Worktrees", `${live.length} live, ${settled.length} settled`);
16
+ if (live.length) out.section("Live", String(live.length)).append(grid(["PATH", "BRANCH", "TASK", "ACTIVE"], rows(live, false), columns));
17
+ if (settled.length) out.section("Shelf (settled)", String(settled.length)).append(grid(["PATH", "BRANCH", "TASK", "WHY", "ACTIVE"], rows(settled, true), columns));
18
+ if (!live.length && !settled.length) out.note("no worktrees");
19
+ if (r?.complete === false) out.bullet("warn", "the list was cut off at its bound; some worktrees are not shown");
20
+ if (settled.length) out.note("preview what could be removed with ahub worktrees tidy; nothing is removed until you confirm");
21
+ return out.lines();
23
22
  }
24
23
 
25
24
  /** `ahub worktrees tidy`: each settled row that is safe to remove, each refused row with its reasons, and the fingerprint to confirm. */
26
- export function renderTidyPreview(plan: unknown, columns?: number): Span[][] {
25
+ export function renderTidyPreview(plan: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
27
26
  const p = plan as any, entries = list(p?.entries), removable = list(p?.removable), refused = entries.filter((e: any) => list(e.refused).length);
28
- const out: Span[][] = [...heading(`Tidy preview: ${removable.length} safe to remove, ${refused.length} refused`, columns)];
29
- if (removable.length) out.push(...grid(["PATH", "BRANCH", "WHY SETTLED"], removable.map((e: any) => [s(e.shown), s(e.branch ?? ""), s(reasonLabel(e))]), columns));
30
- if (refused.length) out.push(blank, ...heading("Refused", columns), ...grid(["PATH", "BRANCH", "REFUSED BECAUSE"], refused.map((e: any) => [s(e.shown), s(e.branch ?? ""), s(list(e.refused).join("; "), "attention")]), columns));
31
- if (!entries.length) out.push([s("nothing is on the shelf", "muted")]);
32
- if (removable.length) out.push(blank, ...pair("fingerprint", String(p.fingerprint), columns, 12), [s(`confirm with: ahub worktrees tidy --confirm ${p.fingerprint}`, "muted")], [s("each removal runs git worktree remove and git branch -d, without force; git keeps anything it considers unsafe", "muted")]);
33
- return out;
27
+ const out = new Report(columns, ascii).titled("ahub", "Tidy preview", `${removable.length} safe to remove, ${refused.length} refused`);
28
+ if (removable.length) out.section("Safe to remove", String(removable.length)).append(grid(["PATH", "BRANCH", "WHY SETTLED"], removable.map((e: any) => [s(e.shown), s(e.branch ?? ""), s(reasonLabel(e))]), columns));
29
+ if (refused.length) out.section("Refused", String(refused.length)).append(grid(["PATH", "BRANCH", "REFUSED BECAUSE"], refused.map((e: any) => [s(e.shown), s(e.branch ?? ""), s(list(e.refused).join("; "), "attention")]), columns));
30
+ if (!entries.length) out.note("nothing is on the shelf");
31
+ if (removable.length) {
32
+ out.section("Confirm").kv([["fingerprint", String(p.fingerprint)]]);
33
+ out.note(`confirm with: ahub worktrees tidy --confirm ${p.fingerprint}`).note("each removal runs git worktree remove and git branch -d, without force; git keeps anything it considers unsafe");
34
+ }
35
+ return out.lines();
34
36
  }
35
37
 
36
38
  /** `ahub worktrees tidy --confirm`: what happened to each row. */
37
- export function renderTidyResult(outcomes: unknown, columns?: number): Span[][] {
39
+ export function renderTidyResult(outcomes: unknown, columns?: number, _now = Date.now(), ascii = false): Span[][] {
38
40
  const rows = list(outcomes);
39
- const out: Span[][] = [...heading(`Tidy: ${rows.filter((o: any) => o.worktreeRemoved).length} of ${rows.length} removed`, columns)];
40
- out.push(...grid(["PATH", "BRANCH", "WORKTREE", "BRANCH"], rows.map((o: any) => [s(o.shown), s(o.branch), s(o.worktreeRemoved ? "removed" : "kept", o.worktreeRemoved ? "muted" : "attention"), s(o.branchDeleted ? "deleted" : "kept", o.branchDeleted ? "muted" : "attention")]), columns));
41
- for (const o of rows.filter((x: any) => x.note)) out.push([s(`${o.shown}: ${o.note}`, "muted")]);
42
- return out;
41
+ const out = new Report(columns, ascii).titled("ahub", "Tidy", `${rows.filter((o: any) => o.worktreeRemoved).length} of ${rows.length} removed`);
42
+ out.section("Outcome", String(rows.length)).append(grid(["PATH", "BRANCH", "WORKTREE", "BRANCH"], rows.map((o: any) => [s(o.shown), s(o.branch), s(o.worktreeRemoved ? "removed" : "kept", o.worktreeRemoved ? "muted" : "attention"), s(o.branchDeleted ? "deleted" : "kept", o.branchDeleted ? "muted" : "attention")]), columns));
43
+ for (const o of rows.filter((x: any) => x.note)) out.note(`${o.shown}: ${o.note}`);
44
+ return out.lines();
43
45
  }
@@ -1,5 +1,6 @@
1
1
  import { hubGitEnv, hubGitSync } from "./git.ts";
2
2
  import { childEnv } from "./child-process.ts";
3
+ import { realPath } from "./project.ts";
3
4
 
4
5
  /**
5
6
  * #1403 A4: what an audit reads from the checkout, behind one injectable port so `Tasks` stays testable and the daemon wires the real thing. Read-only git, hardened like the review brief's
@@ -12,6 +13,11 @@ export interface AuditSource {
12
13
  resolve(ref: string): string | undefined;
13
14
  /** Repository-relative paths that differ between `from` and `to`, or undefined when they cannot be listed completely. */
14
15
  changed(from: string, to: string): string[] | undefined;
16
+ /**
17
+ * #1646: among `paths`, those the checkout's worktree holds differently from `reviewed`, and those it holds as
18
+ * untracked files. Undefined when either read is incomplete: an unread checkout is unknown, never clean.
19
+ */
20
+ readsAt?(reviewed: string, paths: readonly string[]): { differing: string[]; untracked: string[] } | undefined;
15
21
  /** Local origin/HEAD remote-tracking commit, never a checkout HEAD or guessed branch. */
16
22
  defaultTip?(): string | undefined;
17
23
  /** Unique local common ancestor; shallow, missing, unrelated or ambiguous history is unknown. */
@@ -62,5 +68,44 @@ export function gitAuditSource(cwd: string): AuditSource {
62
68
  const paths = r.stdout.split("\0").filter(Boolean);
63
69
  return paths.length > MAX_CHANGED_PATHS ? undefined : paths;
64
70
  },
71
+ readsAt: (reviewed, paths) => {
72
+ if (!SHA.test(reviewed) || commit(reviewed) !== reviewed) return undefined;
73
+ // Only the caller's own list, and only names git accepts as pathspecs: never a flag, never a control character.
74
+ const scoped = [...new Set(paths.filter(path => typeof path === "string" && path && !path.startsWith("-") && !/[\p{Cc}]/u.test(path)))];
75
+ if (!scoped.length) return { differing: [], untracked: [] };
76
+ // The reviewed commit against the worktree (index and unstaged alike), then the files git does not track yet.
77
+ const diff = run(["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "-z", reviewed, "--", ...scoped]);
78
+ if (diff.status !== 0 || typeof diff.stdout !== "string") return undefined;
79
+ const others = run(["ls-files", "--others", "--exclude-standard", "-z", "--", ...scoped]);
80
+ if (others.status !== 0 || typeof others.stdout !== "string") return undefined;
81
+ // A reviewed path the checkout does not track is reported once, as untracked: git also diffs such a file by path
82
+ // when it happens to exist, and one state per path keeps the evidence readable.
83
+ const untracked = others.stdout.split("\0").filter(Boolean), loose = new Set(untracked);
84
+ const differing = diff.stdout.split("\0").filter(path => path && !loose.has(path));
85
+ return differing.length > MAX_CHANGED_PATHS || untracked.length > MAX_CHANGED_PATHS ? undefined : { differing, untracked };
86
+ },
65
87
  };
66
88
  }
89
+
90
+ /** The common Git directory of `dir` as it is on disk, or undefined when `dir` is no checkout of a readable repository. */
91
+ const commonDirectory = (dir: string): string | undefined => {
92
+ const result = hubGitSync(["-C", dir, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8", env: hubGitEnv(childEnv(process.env), { repositoryIsolation: true, readOnlyDiagnostic: true }), maxBuffer: 4096, timeout: 5_000 });
93
+ const out = result.status === 0 && typeof result.stdout === "string" ? result.stdout.trim() : "";
94
+ if (!out) return undefined;
95
+ try { return realPath(out); } catch { return undefined; }
96
+ };
97
+
98
+ /**
99
+ * #1646 T2: a read-only reader for a checkout other than the project's own, such as the checkout a reviewing session reports for
100
+ * itself. It answers only when `root` is a worktree of `anchor`'s repository on disk, compared by canonical path and common Git
101
+ * directory, never by the names a caller typed; the project checkout itself is refused so a caller records it as the project's
102
+ * rather than as a peer's. A root that is not a checkout of this repository is unknown, never read.
103
+ */
104
+ export function checkoutAuditSource(anchor: string, root: string): AuditSource | undefined {
105
+ try {
106
+ const here = realPath(anchor), there = realPath(root);
107
+ if (here === there) return undefined;
108
+ const common = commonDirectory(here), other = commonDirectory(there);
109
+ return common && common === other ? gitAuditSource(there) : undefined;
110
+ } catch { return undefined; }
111
+ }