@staix/agent-hub 0.44.0 → 0.46.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 (168) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +12 -11
  3. package/docs/adding-an-ai-tool.md +1 -0
  4. package/docs/agent-notes/adapters.md +35 -6
  5. package/docs/agent-notes/budget.md +2 -1
  6. package/docs/agent-notes/daemon.md +5 -1
  7. package/docs/agent-notes/local-worker.md +1 -1
  8. package/docs/agent-notes/security-review.md +3 -2
  9. package/docs/agent-notes/tasks.md +6 -2
  10. package/docs/agent-notes/tests.md +4 -3
  11. package/docs/design/adapters.md +20 -2
  12. package/docs/design/agent-hub-architecture.md +12 -0
  13. package/docs/design/agent-hub.md +1 -1
  14. package/docs/design/cli-output.md +2 -0
  15. package/docs/design/roadmap.md +158 -4
  16. package/docs/design/supervision.md +21 -1
  17. package/docs/design/task-board.md +32 -4
  18. package/docs/dogfood.md +28 -4
  19. package/docs/events.md +7 -3
  20. package/docs/influences.md +7 -0
  21. package/docs/memory.md +4 -4
  22. package/docs/operations.md +151 -36
  23. package/docs/quickstart.md +16 -4
  24. package/docs/research.md +16 -0
  25. package/docs/roadmap.json +4 -0
  26. package/docs/roadmap.md +9 -0
  27. package/docs/sdlc.md +15 -3
  28. package/docs/security.md +9 -7
  29. package/docs/smoke.md +1 -1
  30. package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
  31. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  32. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  33. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  34. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  35. package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
  36. package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
  37. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  38. package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
  39. package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
  40. package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
  41. package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
  42. package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
  43. package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
  44. package/docs/verification/2026-11-23-0.46.0.md +44 -0
  45. package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
  46. package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
  47. package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
  48. package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
  49. package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
  50. package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
  51. package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
  52. package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
  53. package/docs/verified.json +33 -27
  54. package/package.json +3 -2
  55. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  56. package/plugins/agent-hub/kimi-hook.js +4743 -4048
  57. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  58. package/plugins/agent-hub/server.js +1641 -1265
  59. package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
  60. package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
  61. package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
  62. package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
  63. package/scripts/check-docs.mjs +9 -1
  64. package/src/adapters/acp.ts +11 -1
  65. package/src/adapters/claude-channel.ts +2 -1
  66. package/src/adapters/compat.ts +15 -14
  67. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  68. package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
  69. package/src/adapters/definitions/native-cli-doctor.ts +8 -5
  70. package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
  71. package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
  72. package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
  73. package/src/adapters/definitions/native-cli-skills.ts +29 -0
  74. package/src/adapters/definitions/native-context.ts +10 -0
  75. package/src/adapters/jcode.ts +10 -0
  76. package/src/adapters/local-worker.ts +3 -2
  77. package/src/adapters/pi.ts +15 -4
  78. package/src/cli/claude-profile-hook.ts +40 -3
  79. package/src/cli/console-state.ts +58 -27
  80. package/src/cli/console-usage.ts +5 -3
  81. package/src/cli/console.ts +35 -4
  82. package/src/cli/help.ts +17 -10
  83. package/src/cli/identity.ts +4 -2
  84. package/src/cli/instruction-hook.ts +28 -0
  85. package/src/cli/jcode-mcp.ts +2 -1
  86. package/src/cli/main.js +8 -0
  87. package/src/cli/main.ts +149 -23
  88. package/src/cli/output-standard.ts +3 -55
  89. package/src/cli/output.ts +8 -2
  90. package/src/cli/recovery-package.ts +62 -13
  91. package/src/cli/roadmap-write.ts +59 -0
  92. package/src/cli/roadmap.ts +115 -4
  93. package/src/cli/sdlc-output.ts +4 -0
  94. package/src/cli/setup-homes.ts +1 -0
  95. package/src/cli/setup.ts +1 -1
  96. package/src/cli/skills-install.ts +463 -0
  97. package/src/cli/task-output.ts +1 -1
  98. package/src/cli/upgrade-presentation-flags.ts +1 -1
  99. package/src/cli/upgrade-runtime.ts +10 -6
  100. package/src/hub/agent-mem-range.ts +43 -0
  101. package/src/hub/board.ts +144 -5
  102. package/src/hub/budget-projection.ts +99 -0
  103. package/src/hub/check-runner.ts +25 -1
  104. package/src/hub/claude-launch-proof.ts +5 -1
  105. package/src/hub/conductor.ts +8 -3
  106. package/src/hub/config-apply.ts +6 -3
  107. package/src/hub/config-tier.ts +1 -1
  108. package/src/hub/config-trust.ts +1 -1
  109. package/src/hub/context-window.ts +1 -1
  110. package/src/hub/control-client.ts +9 -2
  111. package/src/hub/cost-governance.ts +11 -7
  112. package/src/hub/daemon.ts +707 -53
  113. package/src/hub/dogfood-read.ts +4 -2
  114. package/src/hub/edit-guard.ts +100 -0
  115. package/src/hub/events.ts +80 -9
  116. package/src/hub/execution-budget.ts +29 -8
  117. package/src/hub/facts.ts +57 -4
  118. package/src/hub/hub-tools.ts +3 -1
  119. package/src/hub/inference.ts +1 -1
  120. package/src/hub/instances.ts +10 -1
  121. package/src/hub/instructed-exact.ts +95 -0
  122. package/src/hub/instructed-intent.ts +64 -0
  123. package/src/hub/instructed-ipc.ts +33 -0
  124. package/src/hub/instructed-runtime.ts +19 -0
  125. package/src/hub/instruction-receipt.ts +218 -0
  126. package/src/hub/lifecycle.ts +6 -1
  127. package/src/hub/log-rotation.ts +130 -0
  128. package/src/hub/manager.ts +46 -3
  129. package/src/hub/memory-profile.ts +137 -21
  130. package/src/hub/no-writes.ts +1 -0
  131. package/src/hub/operational-authority.ts +3 -2
  132. package/src/hub/operational-settings.ts +2 -2
  133. package/src/hub/recovery-store.ts +49 -21
  134. package/src/hub/registry.ts +1 -1
  135. package/src/hub/research-experiments.ts +132 -0
  136. package/src/hub/research-quality.ts +8 -2
  137. package/src/hub/research-record.ts +35 -0
  138. package/src/hub/research.ts +128 -28
  139. package/src/hub/roadmap-check.ts +65 -0
  140. package/src/hub/roadmap-decompose.ts +139 -0
  141. package/src/hub/roadmap-export.ts +27 -0
  142. package/src/hub/roadmap-sync.ts +97 -0
  143. package/src/hub/roadmap.ts +59 -1
  144. package/src/hub/routing.ts +18 -1
  145. package/src/hub/runtime-capture-prune.ts +2 -1
  146. package/src/hub/sdlc-branch-ci.ts +128 -0
  147. package/src/hub/sdlc-merge.ts +6 -3
  148. package/src/hub/sdlc-metrics.ts +19 -5
  149. package/src/hub/sdlc.ts +73 -5
  150. package/src/hub/settings.ts +3 -1
  151. package/src/hub/snapshots.ts +13 -1
  152. package/src/hub/startup-event-seeds.ts +21 -15
  153. package/src/hub/startup-timing.ts +3 -1
  154. package/src/hub/supervision-proposals.ts +10 -2
  155. package/src/hub/supervision-rules.ts +26 -3
  156. package/src/hub/supervision.ts +7 -0
  157. package/src/hub/task-pr.ts +47 -0
  158. package/src/hub/task-worktree.ts +18 -11
  159. package/src/hub/tasks.ts +694 -44
  160. package/src/hub/ui.ts +6 -2
  161. package/src/hub/usage-rollup.ts +77 -22
  162. package/src/local/tools.ts +13 -1
  163. package/src/memory/client.ts +3 -2
  164. package/src/pi/extension.ts +15 -3
  165. package/src/pi/tool-receipts.ts +26 -0
  166. package/src/ui/index.html +342 -8
  167. package/src/ui/plugin.ts +6 -2
  168. package/src/ui/roadmap-model.ts +70 -0
@@ -45,3 +45,13 @@ export function jcodeContextValue(value: unknown, sessionId: string, measuredAt:
45
45
  const tokens = okay ? raw.used as number : null, window = okay ? raw.size as number : null;
46
46
  return { source: "jcode_usage_update", sessionId, measuredAt, tokens, window, used: tokens !== null && window !== null ? Math.min(1, tokens / window) : null };
47
47
  }
48
+
49
+ /** Pi reports the last assistant prompt's input and cache counters, not cumulative consumption. */
50
+ export function piContext(value: unknown, sessionId: string, measuredAt: number): ContextReading {
51
+ const raw = object(value), parts = [raw.input, raw.cacheRead, raw.cacheWrite];
52
+ const valid = parts.every(n => Number.isSafeInteger(n) && (n as number) >= 0);
53
+ const sum = valid ? parts.reduce<number>((a, n) => a + (n as number), 0) : null;
54
+ const tokens = Number.isSafeInteger(sum) ? sum : null;
55
+ const window = Number.isSafeInteger(raw.contextWindow) && (raw.contextWindow as number) > 0 ? raw.contextWindow as number : null;
56
+ return { source: "pi_usage", sessionId, measuredAt, tokens, window, used: tokens !== null && window !== null ? Math.min(1, tokens / window) : null };
57
+ }
@@ -27,6 +27,16 @@ export function jcodeCommand(command: string[], kind: "serve" | "acp", socket: s
27
27
  return [...command, kind, "--socket", socket, "--cwd", cwd, "--no-update", "--no-selfdev", ...(provider ? ["-p", provider] : []), ...(model ? ["--model", model] : []), ...(profile ? ["--provider-profile", profile] : []),
28
28
  ...(kind === "serve" ? ["--temporary-server", "--owner-pid", String(process.pid), "--server-name", `agent-hub-${peer}`] : ["--mcp-tools", "eager"])];
29
29
  }
30
+ /**
31
+ * #1601: the one host sentence a configured Jcode may write to hub.log, because the daemon replaces every line this adapter's
32
+ * own `log` port would carry with "Jcode native diagnostic: details withheld". It names the cause class, the ceiling's minutes,
33
+ * the launch that restarts this peer and the row the person settles, and it takes only the ceiling and the host's own peer id,
34
+ * so no tool title or native text can reach the log through it. `peer` is `jcode` for the base peer, an instance id otherwise (#685).
35
+ */
36
+ export function jcodeToolCeilingCause(ceilingMs: number, peer: string): string {
37
+ const launch = peer === "jcode" ? "ahub jcode" : `ahub jcode --as ${peer}`;
38
+ return `Jcode turn cancelled by the open-tool ceiling (${Math.round(ceilingMs / 60_000)} min, adapter_timing.acp_tool_ceiling_min) after a tool call stayed silent; the delivery is held for review and the peer is offline with queued work retained - restart it with '${launch}', then settle the held row ('ahub queue list --peer ${peer}' names it; 'ahub queue show <id>' prints the resolve command)`;
39
+ }
30
40
  /** The session preamble of a Jcode peer: the deferred-tools guidance (#912), then the hub's role contract when there is one. Sent once, with the session's first prompt. */
31
41
  export function jcodePreamble(roleContract?: string): string {
32
42
  return roleContract ? `${JCODE_DEFERRED_TOOLS_INSTRUCTION}\n\n${roleContract}` : JCODE_DEFERRED_TOOLS_INSTRUCTION;
@@ -70,7 +70,7 @@ export interface LocalOptions {
70
70
  turnId?: () => string | undefined;
71
71
  onApprovalStop?: (reason: string) => void;
72
72
  onTool?: (observation: ToolObservation, task?: string) => void;
73
- tools: { docRead?: DocReadPort; webFetch?: WebFetchPort; deny: string[]; permit: ToolContext["permit"]; shellExecutionCheck?: ToolContext["shellExecutionCheck"]; bashNetwork?: SandboxNetwork; readAllow?: string[]; readOnly?: string[] };
73
+ tools: { docRead?: DocReadPort; webFetch?: WebFetchPort; deny: string[]; permit: ToolContext["permit"]; shellExecutionCheck?: ToolContext["shellExecutionCheck"]; editGuard?: (task: string | undefined, current: () => boolean) => ToolContext["editGuard"]; bashNetwork?: SandboxNetwork; readAllow?: string[]; readOnly?: string[] };
74
74
  capture?: Capture;
75
75
  /** Runs a hub task tool (hub_task_*, hub_review, hub_remember) as this peer. Absent = the tools are not offered. */
76
76
  taskTool?: (name: string, args: Record<string, unknown>, turn: { pii: boolean; signal?: AbortSignal }) => Promise<string>;
@@ -523,7 +523,7 @@ export class LocalPeer extends BasePeer {
523
523
  ? Promise.resolve("error: anchored review in this batch; save notes in a later turn")
524
524
  : (TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name)) && this.opts.taskTool
525
525
  ? this.opts.taskTool(name, safeParse(call.function.arguments), { pii: !!policy?.pii, signal: turnSignal }).catch((e: Error) => `error: ${e.message}`)
526
- : runTool(name, call.function.arguments, ctx);
526
+ : runTool(name, call.function.arguments, this.probeConfinement ? ctx : this.toolContext(envs, turnSignal, !!policy?.pii, reply, policy?.task));
527
527
  const probe = this.probeSession;
528
528
  const running = probe ? (async () => {
529
529
  try {
@@ -566,6 +566,7 @@ export class LocalPeer extends BasePeer {
566
566
  ...(this.opts.tools.docRead ? { docRead: { ...this.opts.tools.docRead, pii } } : {}),
567
567
  ...(this.opts.tools.webFetch ? { webFetch: { ...this.opts.tools.webFetch, pii } } : {}),
568
568
  cwd: this.opts.cwd,
569
+ ...(this.opts.tools.editGuard && !probe ? { editGuard: this.opts.tools.editGuard(task, () => !turnSignal.aborted && executionGeneration === this.turn) } : {}),
569
570
  deny: this.opts.tools.deny,
570
571
  readOnly: this.opts.tools.readOnly,
571
572
  ...(probe ? { probe: { root: probe.workspace.root, writableRoots: probe.workspace.allowedWrites,
@@ -56,6 +56,8 @@ export interface PiOptions {
56
56
  admitBudget?: (envs: Envelope[], unit: ExecutionUnit) => Promise<ExecutionBudgetDecision[]>;
57
57
  /** Reported message usage as increments, before agent_settled releases the turn. */
58
58
  onTokens?: (added: number) => void;
59
+ /** Current-session prompt occupancy; unknown observations invalidate stale readings. */
60
+ onContext?: (value: unknown, sessionId: string) => void;
59
61
  /** `ceiling` is the validated, session/turn-bound tool-step ceiling signal (#179), present only when the trusted extension emitted one for this turn. */
60
62
  onTurnFailure?: (envs: Envelope[], reason: string, ceiling?: PiToolStepCeiling, settledCeiling?: boolean) => Promise<void>;
61
63
  /** Observation only: cancelled/stopped logical turns never request failure handoff. */
@@ -113,6 +115,7 @@ function ownerStillAlive(pid: number, signature: string | undefined): boolean {
113
115
 
114
116
 
115
117
  export class PiPeer extends BasePeer {
118
+ private sessionModel: string | undefined;
116
119
  readonly hubNative = true;
117
120
  readonly hubOwned: boolean = true;
118
121
  private proc?: ChildProcessWithoutNullStreams;
@@ -295,6 +298,7 @@ export class PiPeer extends BasePeer {
295
298
  const session = this.recoveryMetadata().sessionId;
296
299
  return typeof session === "string" ? session : undefined;
297
300
  }
301
+ get verifiedRecordSession(): string | undefined { return this.verifiedOwner() ? this.nativeSession : undefined; }
298
302
 
299
303
  /** Verify the live source before choosing ID-only restoration. Never infer emptiness from a missing file. */
300
304
  async captureResume(): Promise<Record<string, unknown>> {
@@ -311,6 +315,7 @@ export class PiPeer extends BasePeer {
311
315
  ? (await this.waitRpc("get_state", 15_000)).data
312
316
  : await this.sendTui({ type: "get_session_state" });
313
317
  if (this.state !== "idle" || this.activeTools || snapshot?.sessionId !== this.sessionId || snapshot?.sessionFile !== this.sessionFile) throw new Error("Pi source session changed during capture");
318
+ if (this.opts.mode === "tui" && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(snapshot); this.opts.onContext?.(snapshot.context, this.sessionId); }
314
319
  if (!this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore)) throw new Error("Pi source session title changed during capture; retry with a fresh native session snapshot");
315
320
  const empty = this.opts.mode === "headless"
316
321
  ? snapshot.messageCount === 0 && snapshot.pendingMessageCount === 0 && snapshot.isStreaming === false && snapshot.isCompacting !== true && !snapshot.sessionName
@@ -690,6 +695,7 @@ export class PiPeer extends BasePeer {
690
695
  const snapshot = await this.sendTui({ type: "get_session_state" });
691
696
  if (epoch !== this.rosterEpoch || this.stopping || !this.verifiedOwner() || this.activeTools || snapshot?.sessionId !== session || snapshot?.sessionFile !== file || typeof snapshot?.idle !== "boolean") throw new Error("Pi roster return could not verify the current native session");
692
697
  if (lifecycle !== this.rosterLifecycleRevision) throw new Error("Pi native activity changed during roster return; retry with a fresh session snapshot");
698
+ if (session) { this.sessionModel = stateModelId(snapshot); this.opts.onContext?.(snapshot.context, session); }
693
699
  this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore);
694
700
  this.rosterDetached = false;
695
701
  this.hubPromptId = undefined; this.hubPromptGeneration = undefined;
@@ -811,7 +817,7 @@ export class PiPeer extends BasePeer {
811
817
  this.noteActivity();
812
818
  attempted = true;
813
819
  if (deliveryId) this.activeDeliveryIds.add(deliveryId);
814
- const recordPrompt = this.opts.mode === "tui" ? "" : this.turnRecordPrompt("");
820
+ const recordPrompt = this.turnRecordPrompt("");
815
821
  const message = [recordPrompt, envs.some(env => env.private || remoteEnvelope(env)) ? undefined : this.opts.titlePreface?.(), renderDigest(envs, true)].filter(Boolean).join("\n");
816
822
  if (this.opts.mode === "tui") { const pending = this.sendTui({ type: "prompt", message }); promptId = this.pendingPromptId; await pending; }
817
823
  else await this.sendRpc({ type: "prompt", message });
@@ -884,8 +890,7 @@ export class PiPeer extends BasePeer {
884
890
  }
885
891
 
886
892
  /**
887
- * #1402 T4: a headless Pi reports its current model in `get_state`; that is `session` evidence. The TUI snapshot (`get_session_state`) carries no model, and a failed or placeholder read leaves the model the hub
888
- * itself set through `set_model` (Pi acknowledged it), which is only `configured`. A read that fails never fails the delivery.
893
+ * Pi's current native session model is session evidence; a failed or placeholder read leaves the acknowledged configured model.
889
894
  */
890
895
  private async captureTurnModel(requested: string | undefined): Promise<void> {
891
896
  this.turnModel = undefined;
@@ -895,6 +900,8 @@ export class PiPeer extends BasePeer {
895
900
  const id = state.success === true ? stateModelId(state.data) : undefined;
896
901
  if (id) { this.turnModel = { model: id, evidence: "session" }; return; }
897
902
  } catch { /* optional metadata: the turn goes on without it */ }
903
+ } else {
904
+ if (this.verifiedOwner() && this.sessionModel) { this.turnModel = { model: this.sessionModel, evidence: "session" }; return; }
898
905
  }
899
906
  if (requested) this.turnModel = { model: requested, evidence: "configured" };
900
907
  }
@@ -910,7 +917,7 @@ export class PiPeer extends BasePeer {
910
917
  const slash = model.indexOf("/");
911
918
  const provider = "agent-hub-local";
912
919
  const modelId = model;
913
- if (this.opts.mode === "tui") await this.sendTui({ type: "set_model", provider, modelId }); else await this.sendRpc({ type: "set_model", provider, modelId });
920
+ if (this.opts.mode === "tui") { if (this.sessionModel !== modelId) this.sessionModel = undefined; await this.sendTui({ type: "set_model", provider, modelId }); } else await this.sendRpc({ type: "set_model", provider, modelId });
914
921
  this.requestedModel = model;
915
922
  }
916
923
 
@@ -969,6 +976,7 @@ export class PiPeer extends BasePeer {
969
976
  this.sessionId = String(event.sessionId ?? ""); this.sessionFile = String(event.sessionFile ?? "");
970
977
  this.ownerPid = Number.isInteger(event.pid) ? event.pid : undefined; this.ownerSignature = typeof event.signature === "string" ? event.signature : undefined;
971
978
  if ((this.opts.sessionId && this.sessionId !== this.opts.sessionId) || (this.opts.sessionFile && this.sessionFile !== this.opts.sessionFile)) { this.opts.log?.(`[${this.id}] Pi session identity mismatch`); return; }
979
+ this.sessionModel = stateModelId(event);
972
980
  this.titleRevision = -1; this.titleEpoch++;
973
981
  this.nativeTitleEpoch = typeof event.titleEpoch === "string" && event.titleEpoch ? event.titleEpoch : undefined;
974
982
  this.observeTitle(event.sessionName, event.titleRevision, event.titleEpoch);
@@ -1000,6 +1008,7 @@ export class PiPeer extends BasePeer {
1000
1008
  if (event.type === "agent_start") {
1001
1009
  const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration + 1;
1002
1010
  if (generation <= this.budgetGeneration) return;
1011
+ if (this.opts.mode === "tui" && this.sessionModel && this.verifiedOwner() && (event.sessionId === undefined || event.sessionId === this.sessionId)) this.turnModel = { model: this.sessionModel, evidence: "session" };
1003
1012
  this.modelStep = 0;
1004
1013
  this.ceilingUnsafe = false; this.turnObserved = false;
1005
1014
  this.approvalExpiries = 0; this.approvalAnswerEpoch = undefined; this.approvalStopReason = ""; this.approvalAbortSent = false; this.abortedToolIds.clear(); this.abortIdsOverflow = false;
@@ -1018,6 +1027,8 @@ export class PiPeer extends BasePeer {
1018
1027
  }
1019
1028
  }
1020
1029
  if (event.type === "activity" && this.state === "busy") this.touch();
1030
+ if (event.type === "pi_model" && event.sessionId === this.sessionId && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(event); this.opts.onContext?.(undefined, this.sessionId); }
1031
+ if (event.type === "pi_usage" && this.agentRunning && this.state === "busy" && event.sessionId === this.sessionId && event.generation === this.budgetGeneration && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(event); this.opts.onContext?.(event.context, this.sessionId); }
1021
1032
  if (event.type === "tokens" && this.state === "busy" && typeof event.id === "string" && event.id.length <= 100 && Number.isSafeInteger(event.tokens) && event.tokens >= 0 && !this.usageSeen.has(event.id)) {
1022
1033
  this.usageSeen.add(event.id);
1023
1034
  if (this.usageSeen.size > 1000) this.usageSeen.delete(this.usageSeen.values().next().value!);
@@ -6,7 +6,7 @@ import { shellQuote } from "./shell-quote.ts";
6
6
  import { stableBunRuntime, stablePackageRoot } from "./install-paths.ts";
7
7
  import type { ClaudeHome } from "./claude-homes.ts";
8
8
 
9
- export interface ClaudeProfileHookOptions { script?: string; runtime?: string }
9
+ export interface ClaudeProfileHookOptions { script?: string; runtime?: string; instruction?: boolean }
10
10
  export interface ClaudeProfileHookCheck { state: "installed" | "missing" | "refused"; reason: string }
11
11
  export interface ClaudeProfileHookInstall extends ClaudeProfileHookCheck { changed: boolean }
12
12
  const MAX_SETTINGS_BYTES = 1024 * 1024;
@@ -30,6 +30,23 @@ function hookEntry(options: ClaudeProfileHookOptions): Record<string, unknown> {
30
30
  return { matcher: "*", hooks: [{ type: "command", command: `${shellQuote(runtime)} ${shellQuote(script)} --run`, timeout: 5 }] };
31
31
  }
32
32
 
33
+ function instructionEntry(options: ClaudeProfileHookOptions): Record<string, unknown> {
34
+ const script = join(stablePackageRoot(join(import.meta.dir, "../..")), "src/cli/main.js"), runtime = options.runtime ?? stableBunRuntime();
35
+ if (!validPath(script) || !validPath(runtime)) throw new Error("invalid instruction hook command");
36
+ return { hooks: [{ type: "command", command: `${shellQuote(runtime)} ${shellQuote(script)} instruction-hook`, timeout: 5 }] };
37
+ }
38
+
39
+ function managedInstructionHook(candidate: unknown): ManagedProfileHook | undefined {
40
+ if (!object(candidate) || !Array.isArray(candidate.hooks) || candidate.hooks.length !== 1) return;
41
+ const hook = candidate.hooks[0];
42
+ if (!object(hook) || hook.type !== "command" || typeof hook.command !== "string") return;
43
+ const match = /^'((?:[^']|'\\'')*)' '((?:[^']|'\\'')*)' instruction-hook$/.exec(hook.command);
44
+ if (!match) return;
45
+ const runtime = match[1]!.replace(/'\\''/g, "'"), script = match[2]!.replace(/'\\''/g, "'");
46
+ if (!validPath(runtime) || !validPath(script) || !script.endsWith("/src/cli/main.js") || hook.command !== `${shellQuote(runtime)} ${shellQuote(script)} instruction-hook`) return;
47
+ return { entry: candidate, hook, runtime, script };
48
+ }
49
+
33
50
  interface ManagedProfileHook { entry: Record<string, unknown>; hook: Record<string, unknown>; runtime: string; script: string }
34
51
  /** Own only the generated command grammar; matcher, timeout and caller metadata remain theirs. */
35
52
  function managedProfileHook(candidate: unknown): ManagedProfileHook | undefined {
@@ -96,13 +113,33 @@ function planClaudeProfileHook(home: ClaudeHome, options: ClaudeProfileHookOptio
96
113
  return owned === first ? [{ ...owned.entry, hooks: [{ ...owned.hook, command: expectedCommand }] }] : [];
97
114
  });
98
115
  if (!first) normalized.push(entry);
99
- const next = configured ? undefined : `${JSON.stringify({ ...value, hooks: { ...hooks, PreToolUse: normalized } }, null, 2)}\n`;
116
+ const nextHooks: Record<string, unknown> = { ...hooks, PreToolUse: normalized };
117
+ let instructionConfigured = true;
118
+ if (options.instruction) {
119
+ const entry = instructionEntry(options), expected = (entry.hooks as { command: string }[])[0]!.command;
120
+ for (const event of ["UserPromptSubmit", "Stop"]) {
121
+ const list = hooks[event] ?? [];
122
+ if (!Array.isArray(list)) return refuse(`Claude's ${event} hook list is malformed.`);
123
+ const managed = list.map(managedInstructionHook), first = managed.find(candidate => candidate !== undefined);
124
+ const count = managed.filter(candidate => candidate !== undefined).length;
125
+ const current = count === 1 && first?.hook.command === expected && hookPathPresent(first.runtime) && hookPathPresent(first.script);
126
+ if (!current) instructionConfigured = false;
127
+ const rewritten = list.flatMap((candidate, index) => {
128
+ const owned = managed[index];
129
+ if (!owned) return [candidate];
130
+ return owned === first ? [{ ...owned.entry, hooks: [{ ...owned.hook, command: expected }] }] : [];
131
+ });
132
+ if (!first) rewritten.push(entry);
133
+ nextHooks[event] = rewritten;
134
+ }
135
+ }
136
+ const next = configured && instructionConfigured ? undefined : `${JSON.stringify({ ...value, hooks: nextHooks }, null, 2)}\n`;
100
137
  if (next !== undefined && Buffer.byteLength(next, "utf8") > MAX_SETTINGS_BYTES) return refuse("Claude's settings would exceed the bounded profile settings size.");
101
138
  let reason = "The project-neutral profile hook is not configured for this install; run ahub setup.";
102
139
  if (count > 1) reason = "Duplicate managed profile hooks need normalization; run ahub setup.";
103
140
  if (stale) reason = "A managed profile hook script or runtime is missing; run ahub setup to refresh the selected home's hook.";
104
141
  if (configured) reason = "The project-neutral profile hook is configured; this does not prove live permission enforcement.";
105
- return { file, home: directory, parent, source, next, check: { state: configured ? "installed" : "missing", reason } };
142
+ return { file, home: directory, parent, source, next, check: { state: configured && instructionConfigured ? "installed" : "missing", reason } };
106
143
  } catch { return refuse("Claude profile settings could not be safely inspected; no settings were changed."); }
107
144
  }
108
145
 
@@ -1,3 +1,4 @@
1
+ import { Report as SharedReport, paint as sharedPaint, wrap as sharedWrap } from "@staix/cli-output";
1
2
  import { consoleNeeds, characterAttentionLine, attentionCommand } from "./attention.ts";
2
3
  import { CHARACTERS, petFrame, petSize, petFooterRows, type CharacterId, type PetSize, type PetPose } from "../pet/frame.ts";
3
4
  import { PEER_PALETTE } from "../ui/peer-palette.ts";
@@ -72,6 +73,8 @@ export interface ConsoleState {
72
73
  usage?: UsageState; usageTask?: number;
73
74
  /** Absent on older hubs, null when the current hub cannot report room status. */
74
75
  rooms?: RoomStatusView[] | null; roomSelection?: string;
76
+ /** #1483 R5: the Roadmap panel (9): the public milestones, the drift count read when the panel opens, and why either is missing. */
77
+ roadmap?: ConsoleMilestone[]; roadmapKnown?: boolean; roadmapProblem?: string; roadmapDrift?: { at: number; findings: number; unknown?: number; problem?: string };
75
78
  actionLock?: { prefix: string[]; id: string; revision: number; state: string; owner?: string; reserved?: string; reviewer?: string; waiting?: boolean; syntax?: "planning" | "ownerless-return"; revisionField?: "planningRevision" | "flowRevision" };
76
79
  confirm?: { type: "permission"; id: string; option: string; peer: string } | { type: "command"; args: string[]; prompt?: string; lock?: ConsoleState["actionLock"] } | { type: "permission_default"; peer: string; source: string };
77
80
  optionChoice?: string;
@@ -84,6 +87,12 @@ export interface ConsoleState {
84
87
  permissionDefaultsHandled: string[];
85
88
  }
86
89
  const roomsVisible = (s: Pick<ConsoleState, "rooms">) => s.rooms === null || Array.isArray(s.rooms) && s.rooms.length > 0;
90
+ /** #1483 R5: what the Roadmap panel shows per milestone; `approved`/`total` are its task roll-up and `withheld` counts private members. */
91
+ export interface ConsoleMilestone { id: number; title: string; horizon: string; state: string; order: number; approved: number; total: number; withheld: number }
92
+ const ROADMAP_LANES = ["now", "next", "later"] as const;
93
+ const laneOrder = (horizon: string) => { const at = ROADMAP_LANES.indexOf(horizon as typeof ROADMAP_LANES[number]); return at < 0 ? ROADMAP_LANES.length : at; };
94
+ /** The Roadmap panel is offered only by a hub that advertises it, so an older hub keeps its eight tabs. */
95
+ const roadmapVisible = (s: Pick<ConsoleState, "features">) => s.features?.includes("roadmap") === true;
87
96
  /** A detail view: text as the stream shows it, or labeled fields. */
88
97
  export type Detail = string | Record<string, unknown>;
89
98
  export type ConsoleEffect = { type: "exit" } | { type: "permit"; id: string; option?: string } | { type: "answer"; set: string; answers: { questionId: string; optionIds: string[]; other?: string }[] } | { type: "peer_takeover"; peer: string; standbyId: string } |
@@ -127,6 +136,7 @@ export function permissionDefaultText(row: Pick<PermissionDefault, "peer" | "sou
127
136
  return `never-ask default for ${row.peer} from ${quoted(row.source)}\n${permissionBoundary(row.peer, undefined, createProjectAdapterCatalog())}\nUntil you answer y, this default stays ask. y enables; n cancels for this hub; Esc defers.`;
128
137
  }
129
138
  /** Strip terminal controls before any daemon or child output reaches a terminal. Preserve printable Unicode. */
139
+ // Preserve the hub's control and header policy for non-Report output.
130
140
  export function terminalText(value: unknown): string {
131
141
  return sanitize(String(value ?? "")
132
142
  .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, "")
@@ -147,11 +157,7 @@ export const TONE_ROLE: Readonly<Partial<Record<Tone, Role>>> = Object.freeze({
147
157
  info: "accent", strong: "header", success: "success", attention: "warning", failure: "error", muted: "hint", number: "value",
148
158
  });
149
159
  export function paint(line: Span[], color: boolean): string {
150
- return line.map(span => {
151
- const text = terminalText(span.text);
152
- const sgr = span.role && Object.hasOwn(ROLE_SGR, span.role) ? ROLE_SGR[span.role] : span.tone && Object.hasOwn(PALETTE, span.tone) ? PALETTE[span.tone] : undefined;
153
- return color && sgr && text ? sgr + text + SGR_RESET : text;
154
- }).join("");
160
+ return sharedPaint(line.map(({ tone, ...span }) => ({ ...span, text: terminalText(span.text), ...(tone ? { style: tone } : {}) })), color, PALETTE);
155
161
  }
156
162
  /** Console stream headers only. Tokenize sanitized text; bodies and command output stay plain. */
157
163
  export function streamTokens(value: string, eventTone?: Tone, kind?: string): Span[] {
@@ -235,6 +241,7 @@ export function wrapStreamTokens(value: string, columns: number, tone?: Tone, ki
235
241
  * and summary line. Blank lines follow the standard: exactly one before each section, none after it, never two in a row, none at the
236
242
  * end. Lines are Span arrays; `paint(line, color)` prints them. The builder never colors by itself: it names roles.
237
243
  */
244
+ // Shared Report supplies matching primitives; layout uses shared wrapping with the legacy fallback below.
238
245
  export class Report {
239
246
  private readonly out: Span[][] = [];
240
247
  /** `columns` undefined means no wrap width: standard v1 wraps on a pipe only when COLUMNS is set, so a script reading `ahub doctor | grep` gets whole lines. */
@@ -246,13 +253,13 @@ export class Report {
246
253
  private push(line: Span[]) { this.out.push(line); }
247
254
  /** ` <tool> <Report>` in `header`, then one line of context in `hint` on the same line. At most one per report. */
248
255
  header(tool: string, name: string, context?: string): this {
249
- this.push([{ text: ` ${tool} ${name}`, role: "header" }, ...(context ? [{ text: ` ${context}`, role: "hint" as const }] : [])]);
256
+ this.out.push(...new SharedReport(this.columns, this.ascii).header(tool, name, context).lines());
250
257
  return this;
251
258
  }
252
259
  /** One blank line, then `▸ <Name>` (ASCII `> <Name>`) in `section`, with an optional count in `hint`. */
253
260
  section(name: string, count?: string): this {
254
261
  if (this.out.length && this.out.at(-1)!.length) this.push([]);
255
- this.push([{ text: `${this.ascii ? SECTION_MARKER.ascii : SECTION_MARKER.glyph} ${name}`, role: "section" }, ...(count ? [{ text: ` (${count})`, role: "hint" as const }] : [])]);
262
+ this.out.push(...new SharedReport(this.columns, this.ascii).section(name, count).lines());
256
263
  return this;
257
264
  }
258
265
  /**
@@ -295,19 +302,13 @@ export class Report {
295
302
  }
296
303
  /** ` → <command>` in `accent`: complete and copyable, never shortened. */
297
304
  next(command: string): this {
298
- this.push([{ text: " " }, { text: `${markerCell("next", this.ascii)} ${terminalText(command)}`, role: "accent" }]);
305
+ this.out.push(...new SharedReport(this.columns, this.ascii, { sanitize: terminalText, sanitizeFirst: true, wrapNext: false }).next(command).lines());
299
306
  return this;
300
307
  }
301
308
  /** The last line of a check command: `✗ 2 failed ⚠ 3 warnings ✓ 18 ok`, zero counts omitted, unknowns as `? 2 unknown`. */
302
309
  summary(counts: { failed?: number; warnings?: number; unknown?: number; ok?: number }): this {
303
- const parts: Span[] = [];
304
- const add = (n: number | undefined, name: MarkerName, word: string) => {
305
- if (!n) return;
306
- if (parts.length) parts.push({ text: " " });
307
- parts.push({ text: `${this.ascii ? MARKERS[name].ascii : MARKERS[name].glyph} ${n} ${word}`, role: MARKERS[name].role });
308
- };
309
- add(counts.failed, "fail", "failed"); add(counts.warnings, "warn", counts.warnings === 1 ? "warning" : "warnings"); add(counts.unknown, "unknown", "unknown"); add(counts.ok, "ok", "ok");
310
- if (parts.length) { if (this.out.length) this.push([]); this.push(parts); }
310
+ const lines = new SharedReport(this.columns, this.ascii).summary(counts).lines();
311
+ if (lines.length) { if (this.out.length) this.push([]); this.out.push(...lines); }
311
312
  return this;
312
313
  }
313
314
  lines(): Span[][] { return this.out.map(line => line.map(item => ({ ...item }))); }
@@ -354,13 +355,21 @@ export function fit(value: unknown, columns: number): string {
354
355
  * at whitespace, which they drop; only a word longer than a whole line is split. A tab counts as one space.
355
356
  * Lines come out sanitized: a width counts the `> ` that sanitize() puts before a line starting like a hub header.
356
357
  */
358
+ const wrapGraphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
357
359
  export function wrap(value: unknown, columns: number, hang = 4): string[] {
360
+ const text = terminalText(value);
361
+ // A bare chunk ending in "--- from" becomes a header marker when table padding follows it.
362
+ const quoteChunk = (chunk: string) => sanitize(chunk + " ").slice(0, -1);
363
+ let complex = false;
364
+ if (/[^\p{ASCII}]/u.test(text)) for (const { segment } of wrapGraphemes.segment(text)) {
365
+ if (segment !== Array.from(segment)[0]) { complex = true; break; }
366
+ }
367
+ if (Number.isFinite(columns) && columns >= 1 && !complex) return sharedWrap(text, columns, hang, quoteChunk);
368
+ // Retain code-point splitting and non-positive widths for legacy output: STAIxBWLB/cli-output#36.
358
369
  const lines: string[] = [];
359
370
  const half = Math.floor(columns / 2);
360
- // A bare chunk ending in "--- from" becomes a header marker when table padding follows it.
361
- const quoteChunk = (text: string) => sanitize(text + " ").slice(0, -1);
362
- const width = (text: string) => Bun.stringWidth(quoteChunk(text));
363
- for (const part of terminalText(value).replace(/\t/g, " ").split("\n")) {
371
+ const width = (chunk: string) => Bun.stringWidth(quoteChunk(chunk));
372
+ for (const part of text.replace(/\t/g, " ").split("\n")) {
364
373
  const indent = /^\s*/.exec(part)![0];
365
374
  const lead = Math.min(Bun.stringWidth(indent), half);
366
375
  const pad = " ".repeat(Math.min(lead + hang, half));
@@ -517,9 +526,10 @@ const KEYS: [string, string[]][] = [
517
526
  ["Usage", ["7 Usage panel", "Enter view a peer", "tokens today/7d/lifetime with sources", "task from Tasks (3)"]],
518
527
  ];
519
528
  /** The `?` key table: one group per panel, its keys kept whole and packed into the width after the group column. */
520
- export function keyTable(columns: number, attention = false, characters = false, roomsAvailable = false): Span[][] {
529
+ export function keyTable(columns: number, attention = false, characters = false, roomsAvailable = false, roadmapAvailable = false): Span[][] {
521
530
  const lines: Span[][] = []; const pad = 12;
522
- for (const [group, items] of [...KEYS, ...(roomsAvailable ? [["Rooms", ["8 Rooms panel (read only)", "j/k move", "Enter details"]] as [string, string[]]] : []), ...(attention ? [[characters ? "Pet" : "Attention", ["n next need", characters ? "P next character/off" : "P STAI/off"]] as [string, string[]]] : [])]) {
531
+ for (const [group, items] of [...KEYS, ...(roomsAvailable ? [["Rooms", ["8 Rooms panel (read only)", "j/k move", "Enter details"]] as [string, string[]]] : []),
532
+ ...(roadmapAvailable ? [["Roadmap", ["9 Roadmap panel", "Enter show a milestone", "lanes now/next/later"]] as [string, string[]]] : []), ...(attention ? [[characters ? "Pet" : "Attention", ["n next need", characters ? "P next character/off" : "P STAI/off"]] as [string, string[]]] : [])]) {
523
533
  let text = ""; let head = group;
524
534
  const flush = () => { lines.push([span(head.padEnd(pad), head ? "info" : undefined), span(text)]); head = ""; text = ""; };
525
535
  for (const item of items) { if (text && pad + Bun.stringWidth(`${text} ${item}`) > columns) flush(); text = text ? `${text} ${item}` : item; }
@@ -579,6 +589,8 @@ export function commandNeedsConfirmation(args: string[]): boolean {
579
589
  export function panelRows(s: ConsoleState): any[] {
580
590
  if (s.panel === 1) return Object.entries(s.peers).map(([id, peer]) => ({ id, ...peer, budget: s.budget[id] }));
581
591
  if (s.panel === 8) return s.rooms ?? [];
592
+ // #1483 R5: lanes are the horizon order (now, next, later), then the milestone's own order; an unknown horizon trails.
593
+ if (s.panel === 9) return [...(s.roadmap ?? [])].sort((left, right) => laneOrder(left.horizon) - laneOrder(right.horizon) || left.order - right.order || left.id - right.id);
582
594
  if (s.panel === 2) return s.approvals;
583
595
  if (s.panel === 3) {
584
596
  if (s.backlogView) return s.tasks.filter(t => t.state === "backlog").sort((a, b) => (a.rank ?? Number.MAX_SAFE_INTEGER) - (b.rank ?? Number.MAX_SAFE_INTEGER) || a.id - b.id);
@@ -863,6 +875,7 @@ export function reduceConsole(state: ConsoleState, key: string, now = Date.now()
863
875
  s.panel = panel; s.selection = panel === 5 ? newestEvent(s) : 0; s.taskSelection = undefined; s.queueSelection = undefined; s.roomSelection = undefined; s.detail = undefined; s.requestDetail = undefined; return done(); };
864
876
  if (s.mode === "panels" && /^[1-7]$/.test(key) && !s.optionChoice) return switchPanel(Number(key));
865
877
  if (s.mode === "panels" && key === "8" && !s.optionChoice && roomsVisible(s)) return switchPanel(8);
878
+ if (s.mode === "panels" && key === "9" && !s.optionChoice && roadmapVisible(s)) return switchPanel(9);
866
879
  // Right and Left are the digit of the next or previous tab, wrapping at both ends (#309); the same guards as the
867
880
  // digits apply (the confirm, mode-choice, key-table and editing branches above returned already).
868
881
  if (s.mode === "panels" && (key === "\x1b[C" || key === "\x1b[D") && !s.optionChoice) return switchPanel(s.panel >= 6 ? key === "\x1b[C" ? 1 : 5 : (s.panel + (key === "\x1b[C" ? 0 : 3)) % 5 + 1);
@@ -956,6 +969,7 @@ export function reduceConsole(state: ConsoleState, key: string, now = Date.now()
956
969
  const item = selected?.id;
957
970
  if (s.mode === "panels" && row && s.detail === undefined && (key === "\r" || key === "\n")) {
958
971
  if (s.panel === 3 || s.panel === 4) effects.push({ type: "show", panel: s.panel, id: String(row.id) });
972
+ else if (s.panel === 9) effects.push({ type: "show", panel: 9, id: String(row.id) }); // the hub's public milestone view, with its links and roll-up
959
973
  else if (s.panel === 2) { s.requestDetail = row.id; s.detailOffset = 0; } // the row is the selected request
960
974
  else if (s.panel === 7) { s.detail = { usagePeer: row.id }; s.detailOffset = 0; } // rendered live from s.usage, so a refresh updates it
961
975
  else if (s.panel === 8) { s.roomSelection = row.name; s.detail = { roomName: row.name }; s.detailOffset = 0; }
@@ -1071,6 +1085,8 @@ export const TABLES: Record<number, string[]> = {
1071
1085
  6: ["GROUP", "KEY", "VALUE", "SOURCE", "APPLIES"],
1072
1086
  7: USAGE_HEAD,
1073
1087
  8: ["ROOM", "LINK", "MEMBERS", "REMOTE"],
1088
+ // `PRIVATE` is a count: a withheld member is never named here (#1483 R5).
1089
+ 9: ["ID", "HORIZON", "STATE", "PROGRESS", "PRIVATE", "TITLE"],
1074
1090
  };
1075
1091
  const showPermissionModes = (s: ConsoleState) => Object.values(s.peers).some(peer => peer.permissionMode && peer.permissionMode !== "ask");
1076
1092
  const count = (n: unknown) => typeof n === "number" && n ? String(n) : "-";
@@ -1082,6 +1098,9 @@ export function cells(s: ConsoleState, row: any, selected: boolean, now: number,
1082
1098
  if (s.panel === 8) return [id(row.name, "info"), span(row.link ?? "unknown", row.link ? stateTone(row.link) : "muted"),
1083
1099
  span(row.memberCount === null ? "unknown" : String(row.memberCount), row.memberCount === null ? "muted" : undefined),
1084
1100
  span(row.remotePeers === null ? "unknown" : String(row.remotePeers.length), row.remotePeers === null ? "muted" : undefined)];
1101
+ if (s.panel === 9) return [id(String(row.id), "info"), span(String(row.horizon ?? "later"), row.horizon === "now" ? "attention" : undefined), span(String(row.state ?? "")),
1102
+ span(row.total ? `${row.approved}/${row.total}` : "-", row.total ? undefined : "muted"),
1103
+ span(row.withheld ? String(row.withheld) : "-", row.withheld ? "muted" : undefined), span(String(row.title ?? ""))];
1085
1104
  if (s.panel === 1) {
1086
1105
  const b = s.budget[row.id];
1087
1106
  const wip = s.taskWip?.[row.id];
@@ -1147,6 +1166,7 @@ function roomDetail(row: RoomStatusView): Record<string, unknown> {
1147
1166
  * widest cell or header (Bun.stringWidth, at most a third of the width, wider cells cut with the marker); the last column
1148
1167
  * takes the rest. One-shot callers may supply widths for already-wrapped cells; console defaults stay unchanged.
1149
1168
  */
1169
+ // Local tables retain styled separators, untouched final cells and narrow STAGE geometry: STAIxBWLB/cli-output#37.
1150
1170
  export function table(head: string[], rows: Span[][], columns: number, explicitWidths?: readonly number[]): Span[][] {
1151
1171
  const cap = Math.max(24, Math.floor(columns / 3));
1152
1172
  const width = (cell: Span | undefined) => Bun.stringWidth(flat(cell?.text));
@@ -1239,9 +1259,11 @@ function header(s: ConsoleState, columns: number): Span[] {
1239
1259
  // The tabs can fill an 80-column line, which would squeeze the project name out: below that, one space before a tab instead of two (#683 U3).
1240
1260
  const build = (lead: string) => {
1241
1261
  const tabs: Span[] = [];
1242
- const names = ["Peers", "Approvals", "Tasks", "Queue", "Events", "Settings", "Usage", ...(roomsVisible(s) ? ["Rooms"] : [])];
1243
- for (const [i, name] of names.entries()) {
1244
- const number = i === 7 ? 8 : i + 1, active = number === s.panel, tone = active ? "strong" : "info";
1262
+ // Each tab carries its own number, so hiding Rooms never renumbers the Roadmap panel (#1483 R5).
1263
+ const names: [number, string][] = [[1, "Peers"], [2, "Approvals"], [3, "Tasks"], [4, "Queue"], [5, "Events"], [6, "Settings"], [7, "Usage"],
1264
+ ...(roomsVisible(s) ? [[8, "Rooms"] as [number, string]] : []), ...(roadmapVisible(s) ? [[9, "Roadmap"] as [number, string]] : [])];
1265
+ for (const [i, [number, name]] of names.entries()) {
1266
+ const active = number === s.panel, tone = active ? "strong" : "info";
1245
1267
  tabs.push(span(active ? lead.slice(1) + "[" : lead, tone), span(`${number} ${name}`, tone));
1246
1268
  if (counts[i]) tabs.push(span(` ${counts[i]}`, i === 1 ? "attention" : "failure"));
1247
1269
  tabs.push(span(active ? "]" : " ", tone));
@@ -1364,7 +1386,7 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1364
1386
  // Options that do not fit even wrapped are shown one per line (clipped to the width, but a label is at most 80 characters) rather than dropped: no option is ever off screen.
1365
1387
  lines.push([span(body.head, "attention")], ...shown.map(text => [span(text)]), ...(optionLines.length <= height - 1 ? optionLines : body.options.map(option => fitLine([span(option, "info")], columns))));
1366
1388
  }
1367
- else if (s.help) lines.push(...keyTable(columns, !!s.petEnabled || !!s.petChoices?.length, !!s.petChoices?.length, roomsVisible(s)));
1389
+ else if (s.help) lines.push(...keyTable(columns, !!s.petEnabled || !!s.petChoices?.length, !!s.petChoices?.length, roomsVisible(s), roadmapVisible(s)));
1368
1390
  else if (s.detail !== undefined || (s.requestDetail && permission)) {
1369
1391
  const usagePeer = s.panel === 7 && s.detail && typeof s.detail === "object" ? (s.detail as { usagePeer?: unknown }).usagePeer : undefined;
1370
1392
  const roomName = s.panel === 8 && s.detail && typeof s.detail === "object" ? (s.detail as { roomName?: unknown }).roomName : undefined;
@@ -1390,7 +1412,6 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1390
1412
  const selectedTask = s.panel === 3 ? data[at] : undefined;
1391
1413
  const holders = selectedTask && (selectedTask.planner !== undefined || selectedTask.plannerReason !== undefined)
1392
1414
  ? fieldLines((["planner", "owner", "reviewer"] as const).map((role): [string, unknown] => [role, taskHolderText(selectedTask, role)]), columns, now).flat() : [];
1393
- const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : s.panel === 7 ? height - 2 - taskLines.length : height - (s.panel === 3 ? 2 + holders.length : s.panel === 1 && s.versions ? 2 : 1)); const start = Math.max(0, at - capacity + 1);
1394
1415
  const stages = new Map(progress.stages.map(stage => [stage.id, stage]));
1395
1416
  const cellRows = head ? data.map((row, i) => cells(s, row, i === at, now, stages)) : [];
1396
1417
  const rowsOf = head ? s.panel === 7 ? optionalTable(head, cellRows, columns, USAGE_DROP) : s.panel === 1 ? optionalTable(head, cellRows, columns) : s.panel === 3 && s.backlogView ? optionalTable(head, cellRows, columns, ["AGE", "CLASS", "DEPS", "PRI"]) : table(head, cellRows, columns) : undefined;
@@ -1411,6 +1432,13 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1411
1432
  }
1412
1433
  if (s.panel === 1 && s.versions) lines.push(fitLine(versionsLine(s), columns));
1413
1434
  if (s.panel === 8 && s.rooms === null) lines.push(fitLine([span("Room status unavailable", "attention")], columns));
1435
+ if (s.panel === 9) {
1436
+ const drift = s.roadmapDrift;
1437
+ const note = s.roadmapProblem ? `roadmap unavailable: ${s.roadmapProblem}` : !s.roadmapKnown ? "roadmap loading..."
1438
+ : drift?.problem ? `drift: ${drift.problem}`
1439
+ : `drift ${drift ? `${plural(drift.findings, "finding")}${drift.unknown ? `, ${drift.unknown} unknown` : ""}` : "not checked yet"}${drift ? `, ${relative(drift.at, now)}` : ""}; lanes now, next, later`;
1440
+ lines.push(fitLine([span(note, s.roadmapProblem || drift?.problem ? "failure" : !s.roadmapKnown ? "attention" : "info")], columns));
1441
+ }
1414
1442
  if (s.panel === 3 && s.backlogView) {
1415
1443
  lines.push(fitLine([span(s.tasksKnown === false ? "backlog loading..." : `backlog ${data.length}`, s.tasksKnown === false ? "attention" : "info")], columns));
1416
1444
  } else if (s.panel === 3) {
@@ -1425,6 +1453,9 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
1425
1453
  }
1426
1454
  lines.push(fitLine(parts, columns));
1427
1455
  }
1456
+ // #1607: the row window is what is left after the lines already above the table (panel notes), its header and what
1457
+ // follows it, so the selected row is never cut off by the body height.
1458
+ const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : height - lines.length - 1 - (s.panel === 3 ? holders.length : s.panel === 7 ? taskLines.length : 0)); const start = Math.max(0, at - capacity + 1);
1428
1459
  lines.push(fitLine([span(" "), ...(rowsOf?.[0] ?? [span(`peer ${s.peerFilter ?? "all"} kind ${s.kindFilter ?? "all"}`, "info")])], columns));
1429
1460
  for (let i = start; i < Math.min(data.length, start + capacity); i++) {
1430
1461
  const selected = i === at;
@@ -1,5 +1,6 @@
1
1
  import { windowKind, type WindowKind } from "../hub/window-kind.ts";
2
2
  import type { Counter, LimitsResult, UsageResult, UsageRow } from "../hub/usage-rollup.ts";
3
+ import { projectionText, type ExhaustionProjection } from "../hub/budget-projection.ts";
3
4
 
4
5
  // #683 U3: what the console's Usage panel shows, as plain strings. No terminal code and no state import here: console-state.ts renders it.
5
6
  // Every number names its source, an unknown counter reads `unknown` (never 0), and a private task is `#id [pii]` with no title.
@@ -33,9 +34,10 @@ export function usagePeers(usage: UsageState | undefined, budget: Record<string,
33
34
  return [...ids].sort().map(id => ({ id }));
34
35
  }
35
36
 
36
- interface Budget { windows?: { id: string; used: number; resetsAt?: number; kind?: string; source?: string }[]; paused?: { resetsAt: number }; note?: string }
37
- const windowText = (w: { id: string; used: number; resetsAt?: number }, rel: (at: number) => string) =>
38
- `${w.id} ${Math.round(w.used * 100)}%${typeof w.resetsAt === "number" ? ` ${rel(w.resetsAt)}` : ""}`;
37
+ interface Budget { windows?: { id: string; used: number; resetsAt?: number; kind?: string; source?: string; left?: number | null; projection?: ExhaustionProjection }[]; paused?: { resetsAt: number }; note?: string }
38
+ // #1513 AC2: the console cell carries the same remainder and forecast the dashboard row and `ahub budget` print.
39
+ const windowText = (w: { id: string; used: number; resetsAt?: number; left?: number | null; projection?: ExhaustionProjection }, rel: (at: number) => string) =>
40
+ `${w.id} ${Math.round(w.used * 100)}%${typeof w.left === "number" ? ` (${Math.round(w.left * 100)}% left)` : ""}${w.projection ? `, ${projectionText(w.projection, rel)}` : ""}${typeof w.resetsAt === "number" ? ` ${rel(w.resetsAt)}` : ""}`;
39
41
  const lastResets = (limits: LimitsResult | undefined, peer: string, count: number) =>
40
42
  (limits?.history ?? []).filter(h => h.type === "quota_reset" && h.peer === peer).slice(-count).reverse();
41
43
 
@@ -95,7 +95,7 @@ function labeled(text: string): Detail {
95
95
  /** One terminal client, no daemon ownership. All text crosses terminalText before writing. */
96
96
  export async function runConsole(options: ConsoleOptions): Promise<void> {
97
97
  const { client } = options; const terminal = options.terminal ?? nativeTerminal();
98
- const color = options.color ?? resolveColor(undefined, streamEnv(terminal.isTTY)) === true;
98
+ const color = options.color ?? resolveColor(undefined, streamEnv(terminal.isTTY), "ahub") === true;
99
99
  let state = initialConsoleState(!!options.panels); state.project = basename(options.cwd);
100
100
  let pet = loadPetConfig(options.cwd);
101
101
  let petSignature = JSON.stringify([pet.enabled, pet.character, pet.size, pet.glyphs, pet.blink, pet.bell]);
@@ -216,6 +216,15 @@ export async function runConsole(options: ConsoleOptions): Promise<void> {
216
216
  client.request({ t: "usage", by: "peer" }, 5000), client.request({ t: "usage", op: "limits", limit: 1000 }, 5000),
217
217
  ...(usageTask !== undefined ? [client.request({ t: "usage", by: "peer", task: usageTask }, 5000)] : [])]);
218
218
  })() : undefined;
219
+ // #1483 R5: the Roadmap panel reads the public milestone list while it is open, and the drift check at most every five minutes.
220
+ // Both are read-only hub ops; an older hub never sees either because its status does not advertise `roadmap`.
221
+ const roadmapOpen = panels && state.panel === 9 && state.features?.includes("roadmap") === true;
222
+ const roadmapReplies = roadmapOpen ? await (async () => {
223
+ const list = await client.request({ t: "task", op: "hub_roadmap_list", args: {} }, 5000);
224
+ const stale = list.ok !== false && (!state.roadmapDrift || Date.now() - state.roadmapDrift.at > 300_000);
225
+ const drift = stale ? await client.request({ t: "task", op: "hub_roadmap_check", args: {} }, 30_000) : undefined;
226
+ return { list, drift };
227
+ })() : undefined;
219
228
  if (!active) return;
220
229
  // #1053 T4: the person's own read of the open questions, asked only of a hub whose status lists the `questions` feature: an older hub is never sent a request it does not know.
221
230
  const hasQuestions = Array.isArray(replies[0]?.status?.features) && replies[0].status.features.includes("questions");
@@ -293,6 +302,28 @@ export async function runConsole(options: ConsoleOptions): Promise<void> {
293
302
  else state.usage = { today: today.usage, week: week.usage, life: life.usage, limits: limits.limits, at: Date.now(), ...(usageReplies.some(reply => reply?.behind) ? { behind: true } : {}),
294
303
  ...(usageTask !== undefined && task?.usage && state.usageTask === usageTask ? { task: task.usage, taskId: usageTask } : {}) };
295
304
  }
305
+ if (roadmapReplies) {
306
+ const { list, drift } = roadmapReplies;
307
+ if (list.ok === false) { state.roadmap = []; state.roadmapKnown = false; state.roadmapProblem = String(list.error ?? "the hub refused the roadmap read"); }
308
+ else {
309
+ let report: any;
310
+ try { report = JSON.parse(String(list.text ?? "")); } catch { report = undefined; }
311
+ const rows = Array.isArray(report?.milestones) ? report.milestones : [];
312
+ state.roadmap = rows.filter((row: any) => row && Number.isSafeInteger(Number(row.id))).map((row: any) => ({
313
+ id: Number(row.id), title: String(row.title ?? ""), horizon: String(row.horizon ?? "later"), state: String(row.state ?? ""), order: Number(row.order ?? 0),
314
+ approved: Number(row.rollup?.tasks?.approved ?? 0), total: Number(row.rollup?.tasks?.total ?? 0), withheld: Number(row.withheld ?? 0) }));
315
+ state.roadmapKnown = true; state.roadmapProblem = undefined;
316
+ }
317
+ if (drift) {
318
+ if (drift.ok === false) state.roadmapDrift = { at: Date.now(), findings: 0, problem: String(drift.error ?? "the hub refused the drift check") };
319
+ else {
320
+ let report: any;
321
+ try { report = JSON.parse(String(drift.text ?? "")); } catch { report = undefined; }
322
+ state.roadmapDrift = { at: Date.now(), findings: Array.isArray(report?.findings) ? report.findings.length : 0,
323
+ ...(Array.isArray(report?.unknown) && report.unknown.length ? { unknown: report.unknown.length } : {}), ...(report?.truncated === true ? { problem: "more findings exist; run ahub roadmap check" } : {}) };
324
+ }
325
+ }
326
+ }
296
327
  if (tasks?.ok) { const parsed = JSON.parse(tasks.text); if (Array.isArray(parsed)) {
297
328
  const readyIds = new Set(ready?.ok ? JSON.parse(ready.text).map((task: any) => task.id) : []);
298
329
  state.tasks = parsed.map(task => ({ ...task, ready: readyIds.has(task.id) }));
@@ -416,15 +447,15 @@ export async function runConsole(options: ConsoleOptions): Promise<void> {
416
447
  if (!action.option) stream({ text: ` ! denial requested for permission ${action.id}`, kind: "permission", tone: "failure" });
417
448
  return;
418
449
  }
419
- if (action.type === "keys") return stream({ text: keyTable(columns, !!state.petEnabled || !!state.petChoices?.length, !!state.petChoices?.length, state.rooms === null || Array.isArray(state.rooms) && state.rooms.length > 0).map(line => paint(line, false)).join("\n"), kind: "console" }, false);
450
+ if (action.type === "keys") return stream({ text: keyTable(columns, !!state.petEnabled || !!state.petChoices?.length, !!state.petChoices?.length, state.rooms === null || Array.isArray(state.rooms) && state.rooms.length > 0, state.features?.includes("roadmap") === true).map(line => paint(line, false)).join("\n"), kind: "console" }, false);
420
451
  if (action.type === "print") return stream({ text: action.text, kind: action.kind, ...(action.tone ? { tone: action.tone } : {}) }, false);
421
452
  if (action.type === "show") {
422
- const result = await client.request(action.panel === 3 ? { t: "task", op: "task_show", args: { id: action.id } } : { t: "queue", op: "show", id: action.id }, 3000);
453
+ const result = await client.request(action.panel === 3 ? { t: "task", op: "task_show", args: { id: action.id } } : action.panel === 9 ? { t: "task", op: "hub_roadmap_show", args: { id: Number(action.id) } } : { t: "queue", op: "show", id: action.id }, 3000);
423
454
  // A late reply is for the panel and row it was asked for: once the person has moved on, it would show one item
424
455
  // while the keys act on another, so it is dropped.
425
456
  if (!active || state.mode !== "panels" || state.panel !== action.panel || state.help || state.detail !== undefined || String(selectedPanelRow(state)?.id) !== action.id) return;
426
457
  state.detailOffset = 0;
427
- state.detail = result.ok === false ? String(result.error) : action.panel === 3 ? labeled(String(result.text)) : result.delivery ?? "delivery not found";
458
+ state.detail = result.ok === false ? String(result.error) : action.panel === 3 || action.panel === 9 ? labeled(String(result.text)) : result.delivery ?? "delivery not found";
428
459
  draw(); return;
429
460
  }
430
461
  if (childRunning) { notice("a command is already running"); draw(); return; }