@staix/agent-hub 0.45.0 → 0.46.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +10 -4
  3. package/docs/adding-an-ai-tool.md +1 -0
  4. package/docs/agent-notes/adapters.md +33 -4
  5. package/docs/agent-notes/budget.md +2 -1
  6. package/docs/agent-notes/daemon.md +5 -1
  7. package/docs/agent-notes/security-review.md +3 -2
  8. package/docs/agent-notes/tasks.md +3 -1
  9. package/docs/agent-notes/tests.md +1 -1
  10. package/docs/design/adapters.md +16 -0
  11. package/docs/design/agent-hub-architecture.md +12 -0
  12. package/docs/design/cli-output.md +2 -0
  13. package/docs/design/roadmap.md +86 -5
  14. package/docs/design/task-board.md +2 -2
  15. package/docs/dogfood.md +15 -0
  16. package/docs/events.md +2 -2
  17. package/docs/operations.md +103 -21
  18. package/docs/quickstart.md +15 -3
  19. package/docs/security.md +7 -5
  20. package/docs/smoke.md +1 -1
  21. package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
  22. package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
  23. package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
  24. package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
  25. package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
  26. package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
  27. package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
  28. package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
  29. package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
  30. package/docs/verification/2026-11-23-0.46.0.md +44 -0
  31. package/docs/verification/2026-11-24-0.46.1.md +48 -0
  32. package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
  33. package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
  34. package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
  35. package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
  36. package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
  37. package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
  38. package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
  39. package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
  40. package/docs/verified.json +23 -23
  41. package/package.json +3 -2
  42. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  43. package/plugins/agent-hub/kimi-hook.js +6053 -5509
  44. package/plugins/agent-hub/server.js +1300 -1087
  45. package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
  46. package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
  47. package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
  48. package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
  49. package/src/adapters/claude-channel.ts +2 -1
  50. package/src/adapters/compat.ts +12 -11
  51. package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
  52. package/src/adapters/definitions/native-cli-doctor.ts +8 -5
  53. package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
  54. package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
  55. package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
  56. package/src/adapters/definitions/native-cli-skills.ts +29 -0
  57. package/src/cli/claude-profile-hook.ts +40 -3
  58. package/src/cli/console-state.ts +55 -26
  59. package/src/cli/console-usage.ts +5 -3
  60. package/src/cli/console.ts +35 -4
  61. package/src/cli/help.ts +15 -10
  62. package/src/cli/identity.ts +2 -1
  63. package/src/cli/instruction-hook.ts +28 -0
  64. package/src/cli/jcode-mcp.ts +2 -1
  65. package/src/cli/main.js +8 -0
  66. package/src/cli/main.ts +138 -18
  67. package/src/cli/output-standard.ts +3 -55
  68. package/src/cli/output.ts +8 -2
  69. package/src/cli/recovery-package.ts +53 -12
  70. package/src/cli/roadmap.ts +37 -3
  71. package/src/cli/setup-homes.ts +1 -0
  72. package/src/cli/setup.ts +1 -1
  73. package/src/cli/skills-install.ts +463 -0
  74. package/src/cli/task-output.ts +1 -1
  75. package/src/cli/upgrade-presentation-flags.ts +1 -1
  76. package/src/hub/board.ts +42 -4
  77. package/src/hub/budget-projection.ts +99 -0
  78. package/src/hub/claude-launch-proof.ts +5 -1
  79. package/src/hub/conductor.ts +8 -3
  80. package/src/hub/config-apply.ts +3 -2
  81. package/src/hub/config-tier.ts +1 -1
  82. package/src/hub/config-trust.ts +1 -1
  83. package/src/hub/control-client.ts +9 -2
  84. package/src/hub/daemon.ts +457 -26
  85. package/src/hub/events.ts +1 -1
  86. package/src/hub/execution-budget.ts +29 -8
  87. package/src/hub/hub-tools.ts +2 -2
  88. package/src/hub/inference.ts +1 -1
  89. package/src/hub/instances.ts +10 -1
  90. package/src/hub/instructed-exact.ts +95 -0
  91. package/src/hub/instructed-intent.ts +64 -0
  92. package/src/hub/instructed-ipc.ts +33 -0
  93. package/src/hub/instructed-runtime.ts +19 -0
  94. package/src/hub/instruction-receipt.ts +218 -0
  95. package/src/hub/manager.ts +46 -3
  96. package/src/hub/registry.ts +1 -1
  97. package/src/hub/roadmap-decompose.ts +60 -1
  98. package/src/hub/roadmap-sync.ts +2 -2
  99. package/src/hub/roadmap.ts +19 -1
  100. package/src/hub/routing.ts +18 -1
  101. package/src/hub/runtime-capture-prune.ts +2 -1
  102. package/src/hub/settings.ts +2 -1
  103. package/src/hub/tasks.ts +194 -12
  104. package/src/hub/ui.ts +6 -2
  105. package/src/hub/usage-rollup.ts +42 -2
  106. package/src/ui/index.html +342 -8
  107. package/src/ui/plugin.ts +6 -2
  108. package/src/ui/roadmap-model.ts +70 -0
package/src/hub/tasks.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { requireConductor } from "./conductor.ts";
2
+ import { instructedExecution, instructedHistory } from "./instructed-exact.ts";
2
3
  import { managedTaskPullRequest } from "./task-pr.ts";
3
- import { parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneLinkRef, githubRepo, MILESTONE_STATES, type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type SuggestionItemKind, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition } from "./roadmap.ts";
4
+ import { parseMilestoneInput, parseMilestonePatch, milestoneId, milestoneRevision, milestoneLinkRef, githubRepo, MILESTONE_STATES, type Milestone, type MilestoneLinkKind, type MilestonePatch, type MilestoneState, type MilestoneSuggestion, type SuggestionItemKind, type DecomposePart, type DecomposeIntake, type MilestoneDecomposition, type DecompositionAccept } from "./roadmap.ts";
4
5
  import { milestoneViews, type MilestoneView, type RoadmapSnapshot } from "./roadmap-view.ts";
5
6
  import { readMirrorSnapshot, planRoadmapMirror, recoverMirrorBinding } from "./roadmap-sync.ts";
6
7
  import { roadmapExport } from "./roadmap-export.ts";
@@ -8,7 +9,7 @@ import { checkRoadmap, type DriftMilestone, type RoadmapDrift } from "./roadmap-
8
9
  import type { RoadmapConfig } from "./roadmap.ts";
9
10
  import { computeUnplaced, withTree, type ReadyToClose, type TreeRollup, type UnplacedResult } from "./roadmap-unplaced.ts";
10
11
  import { buildTriagePrompt, parseTriage, TRIAGE_BATCH, type TriageItem } from "./roadmap-triage.ts";
11
- import { buildDecomposePrompt, parseDecomposition, DECOMPOSE_ITEMS, DECOMPOSE_PATHS, type DecomposeItem } from "./roadmap-decompose.ts";
12
+ import { buildDecomposePrompt, parseDecomposition, planPartPublish, DECOMPOSE_ITEMS, DECOMPOSE_PATHS, type DecomposeItem, type PublishDraft, type PublishPlanPart } from "./roadmap-decompose.ts";
12
13
  import { pathCandidates } from "@staix/agent-mem";
13
14
  import { renderGuidanceVariantV1 } from "./guidance-variants.ts";
14
15
  import { GuidanceProbeFixtureHost, type GuidanceProbeStore } from "./guidance-probe-store.ts";
@@ -117,7 +118,7 @@ import { HOST_SPEC_ACCEPTANCE_CARRY, HOST_MERGE_ADOPTION, HOST_ROADMAP_DRAFT, pa
117
118
  import type { Bus } from "./bus.ts";
118
119
  import { HUB, newEnvelope, NOTE_KINDS, noteLine, sanitize, USER, type Envelope, type PeerId, type PeerState } from "./envelope.ts";
119
120
  import type { PiiVerdict, ScreenItem, ScreenRecord } from "./inference.ts";
120
- import { assign, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCandidates, writesRepository, ownerRoleOfClass, type Assignment, type InstanceRoutingOptions, type PeerCapabilities, type Routing, type SplitObservation, type SplitPrediction } from "./routing.ts";
121
+ import { assign, expandClassPeers, isRemotePeerId, detectSignals, peerEntry, predictSplit, relayCandidates, writesRepository, ownerRoleOfClass, type Assignment, type InstanceRoutingOptions, type PeerCapabilities, type Routing, type SplitObservation, type SplitPrediction } from "./routing.ts";
121
122
  import { ExecutionBudget, type ExecutionBudgetConfig, type ExecutionBudgetDecision, type ExecutionBudgetStatus, type ExecutionUnit } from "./execution-budget.ts";
122
123
  import { Cohorts, MAX_REQUESTS, type Cohort, type Completion } from "./cohorts.ts";
123
124
  import { realPath } from "./project.ts";
@@ -856,6 +857,8 @@ export class Tasks {
856
857
  private readonly incomingBacklog = new Set<number>();
857
858
  /** One accept attempt per (answer, part), so two concurrent accepts of one part make one draft (#1480 R2 part 2). */
858
859
  private readonly decompositionAccepts = new Map<string, Promise<unknown>>();
860
+ /** One apply per milestone while it creates issues, so a retried call cannot POST every planned issue twice (#1480 R2 part 3). */
861
+ private readonly roadmapPublishes = new Set<number>();
859
862
  private readonly plannerBacklog = new Map<PeerId, Set<number>>();
860
863
  private readonly plannerBlockedQueue = new Map<PeerId, string>();
861
864
  private readonly knownPlanners = new Set<PeerId>();
@@ -911,7 +914,9 @@ export class Tasks {
911
914
  if (d.bus.stateOf(peer) === "idle") this.autoPullForAttachment(peer);
912
915
  };
913
916
  d.bus.tap((e) => {
914
- if (e.t === "state" && e.state === "offline") this.autoPullAttached.delete(e.peer);
917
+ if (e.t === "state" && e.state === "offline") { this.autoPullAttached.delete(e.peer); this.capacityBackoff.delete(e.peer); }
918
+ // #1626 A2: the back-off ends at the peer's next idle state, and that idle is a trigger to offer it work (B).
919
+ if (e.t === "state" && e.state === "idle" && this.capacityBackoff.delete(e.peer) && this.d.autoPull?.() === true && (this.topReservedReady(e.peer, undefined, true) || this.fillPick(e.peer))) this.queueAutoPulls(new Set([e.peer]), "idle after a capacity decline");
915
920
  if (e.t === "state" && e.state === "idle" && !this.autoPullAttached.has(e.peer) && this.d.autoPull?.() === true) {
916
921
  this.autoPullForAttachment(e.peer);
917
922
  }
@@ -935,7 +940,8 @@ export class Tasks {
935
940
  private autoPullForAttachment(peer: PeerId): void {
936
941
  if (this.autoPullAttached.has(peer) || this.d.autoPull?.() !== true) return;
937
942
  this.autoPullAttached.add(peer);
938
- if (this.topReservedReady(peer, undefined, true)) this.queueAutoPulls(new Set([peer]), "peer available");
943
+ // #1626 B: a ready unowned task also starts a pull, so a reservation is not needed.
944
+ if (this.topReservedReady(peer, undefined, true) || this.fillPick(peer)) this.queueAutoPulls(new Set([peer]), "peer available");
939
945
  }
940
946
 
941
947
  isPii = (task: Pick<Task, "signals">) => task.signals.includes("pii_path") || (task.signals.includes("pii") && this.d.routing().constraints.pii === "local_only");
@@ -1182,10 +1188,10 @@ export class Tasks {
1182
1188
  else this.d.bus.publish(newEnvelope(HUB, body, { to: [peer], kind: "task", refs: { task: String(task.id), taskRecipient } }));
1183
1189
  }
1184
1190
 
1185
- configureExecutionBudget = (config: ExecutionBudgetConfig): ExecutionBudgetStatus | undefined => {
1191
+ configureExecutionBudget = (config: ExecutionBudgetConfig, meta: { reason?: string; by?: string } = {}): ExecutionBudgetStatus | undefined => {
1186
1192
  if (!this.d.executionBudget) return undefined;
1187
1193
  if (config.kind === "task" && (!config.taskId || !this.d.board.get(config.taskId))) throw new Error(`task #${config.taskId ?? "?"} does not exist`);
1188
- return this.d.executionBudget.configure(config);
1194
+ return this.d.executionBudget.configure(config, meta);
1189
1195
  };
1190
1196
  disableExecutionBudget = (id: string): boolean => this.d.executionBudget?.disable(id) ?? false;
1191
1197
  executionBudgetStatus = (id?: string): ExecutionBudgetStatus | ExecutionBudgetStatus[] | undefined => this.d.executionBudget?.status(id);
@@ -1437,6 +1443,7 @@ export class Tasks {
1437
1443
  const screenHistoryText = (text: string, field: string, withheld = false): string => !withheld && this.nameable(text) ? text : `[history ${field} withheld: ${this.whyWithheld(text)}; ahub task show ${task.id}]`;
1438
1444
  const publicHistory = (fullHistory ? history : history.slice(-5)).map(h => ({
1439
1445
  at: h.at, by: h.by, event: h.event,
1446
+ ...(h.instructed && h.instructedPeer && h.instructionReceipt ? { instructed: true, instructedPeer: h.instructedPeer, instructionReceipt: h.instructionReceipt } : {}),
1440
1447
  ...(h.note === undefined ? {} : { note: screenHistoryText(h.note, "note", h.withheld) }),
1441
1448
  ...(h.reviewFindings ? { reviewFindings: !h.withheld && this.findingTextAllowed(task, h.reviewFindings.items) ? h.reviewFindings
1442
1449
  : { ...(h.reviewFindings.head ? { head: h.reviewFindings.head } : {}), tally: findingTally(h.reviewFindings.items), withheld: true } } : {}),
@@ -2630,6 +2637,11 @@ export class Tasks {
2630
2637
  const now = this.studyTime(), deadline = Date.parse(original.contract.stopPolicy.deadline);
2631
2638
  if (deadline <= now || deadline - now > 90 * 86_400_000) throw new PreEffectToolRefusal("study deadline must be in the next ninety days at approval");
2632
2639
  priv ||= latest.private || current.private;
2640
+ const instruction = instructedExecution.getStore();
2641
+ if (instruction?.active) {
2642
+ instruction.current();
2643
+ if (priv || prepared.some(unit => unit.create?.signals?.some(signal => signal === "pii" || signal === "pii_path"))) throw new PreEffectToolRefusal("an instructed study approval cannot create private work; run it in a terminal");
2644
+ }
2633
2645
  if (priv && [...current.adopted.values(), ...current.reused.values()].some(task => !this.isPii(task)))
2634
2646
  throw new PreEffectToolRefusal("a private study cannot retain a public task without changing its authority");
2635
2647
  for (const unit of prepared) if (unit.create) {
@@ -2641,6 +2653,7 @@ export class Tasks {
2641
2653
  const mode = this.d.coordination?.();
2642
2654
  let result: ReturnType<Board["activateCampaign"]>;
2643
2655
  requestCheck();
2656
+ instruction?.beginStudy?.(); // The synchronous board transaction now owns the screened binding.
2644
2657
  try { result = this.d.board.activateCampaign(id, revision, this.d.project, by, now, prepared, current.parent.history.length, priv, { eligibleOwners: this.studyEligibleOwners(original.contract) }); }
2645
2658
  catch (error) { throw new PreEffectToolRefusal(error instanceof Error ? error.message : "study approval was not saved"); }
2646
2659
  for (const child of result.children) {
@@ -3170,7 +3183,7 @@ export class Tasks {
3170
3183
  private async autoPull(peer: PeerId, cause: string): Promise<void> {
3171
3184
  if (!this.autoPullAdmitted()) return;
3172
3185
  const card = this.topReservedReady(peer, undefined, true);
3173
- if (!card) return;
3186
+ if (!card) { await this.fillSlot(peer, cause); return; }
3174
3187
  // The planner of record is the card's own: its bound planner, else the first current holder, and it must be rostered. A private card never gets here (topReservedReady skips it).
3175
3188
  const planner = this.taskPlanner(card)[0];
3176
3189
  if (!planner || !this.d.bus.isRostered(planner)) return;
@@ -3189,6 +3202,47 @@ export class Tasks {
3189
3202
  }
3190
3203
  }
3191
3204
 
3205
+ /** The first ready unowned task `peer` could be offered now, or undefined. Read-only. */
3206
+ private fillPick(peer: PeerId): Task | undefined {
3207
+ if (!this.autoPullAdmitted() || this.capacityBackoff.has(peer)) return undefined;
3208
+ const now = this.d.now?.() ?? Date.now();
3209
+ let routing: Routing;
3210
+ try { routing = this.d.routing(); } catch { return undefined; }
3211
+ return this.d.board.list("proposed").filter(task => this.fillEligible(task, peer, routing, now)).sort(this.readyOrder)[0];
3212
+ }
3213
+ private fillEligible(task: Task, peer: PeerId, routing: Routing, now: number, mine = false): boolean {
3214
+ if (task.state !== "proposed" || task.owner || (!mine && (this.offered.has(task.id) || this.readyInFlight.has(task.id))) || (task.reserved && task.reserved !== peer)) return false;
3215
+ if (task.pinned || task.draft || task.needsPerson || this.isPii(task) || this.personUnassigned(task) || plannedStartPending(task, now) || this.waitsFor(task).length) return false;
3216
+ if (task.release != null && !["planning", "active"].includes(this.d.board.release(task.release)?.state ?? "")) return false;
3217
+ if (this.excluded(task).includes(peer)) return false;
3218
+ // `candidates: [peer]` replaces the class's peer list inside assign(), so the class list is checked here: a freed slot never takes a class routing keeps the peer out of. A class with no entry offers nothing.
3219
+ const weights = this.weights(task.class, task);
3220
+ if (!expandClassPeers(routing.classes[task.class]?.peers ?? [], this.states(), weights).includes(peer)) return false;
3221
+ return assign(task, this.states(), routing, { candidates: [peer], exclude: this.excluded(task), excludeOwners: this.hubOfferFull(task), waitsFor: this.waitsFor(task), ...weights }).owner === peer;
3222
+ }
3223
+ /**
3224
+ * #1626 B: no reserved card was ready for `peer`, so offer it the first ready, unowned `proposed` task it is an eligible owner for, in the board's ready order, one per trigger.
3225
+ * Runs on the serialized auto-pull chain through `assignOwner` as the hub with `peer` the only candidate, so every routing gate still runs. A task another offer path holds is skipped.
3226
+ */
3227
+ private async fillSlot(peer: PeerId, cause: string): Promise<void> {
3228
+ const pick = this.fillPick(peer);
3229
+ if (!pick) return;
3230
+ // The check and the slot are one synchronous step, as in offerReady: a second offer must see this one as taking the slot.
3231
+ this.offered.add(pick.id); this.readyInFlight.set(pick.id, peer);
3232
+ try {
3233
+ const fresh = this.d.board.get(pick.id);
3234
+ if (!fresh || !this.autoPullAdmitted() || !this.fillEligible(fresh, peer, this.d.routing(), this.d.now?.() ?? Date.now(), true)) return;
3235
+ const ready = fresh.history.at(-1)?.event === "ready" ? fresh : this.d.board.update(fresh.id, HUB, "ready", {}, `auto_pull: ${cause} for ${peer}`);
3236
+ await this.assignOwner(ready, HUB, { candidates: [peer], current: () => { if (!this.autoPullAdmitted()) throw new PreEffectToolRefusal("auto pull is no longer admitted"); } });
3237
+ } catch (e) {
3238
+ if (e instanceof PreEffectToolRefusal || e instanceof AssignmentUndeliveredError || !this.autoPullAdmitted()) return;
3239
+ this.releaseNotice(`task ${this.publicTitle(pick)}: auto_pull for ${peer} could not offer it: ${e instanceof Error ? e.message : String(e)}`);
3240
+ } finally {
3241
+ this.readyInFlight.delete(pick.id);
3242
+ if (!this.d.board.get(pick.id)?.owner) this.offered.delete(pick.id);
3243
+ }
3244
+ }
3245
+
3192
3246
  /** #784 AC3: the read-only breakdown of `wip` for status, the console and the dashboard: one grouped query for every peer. Admission still reads `wip()`. */
3193
3247
  wipBreakdown(peers: readonly PeerId[]): Record<string, { wip: number; active: number; reviewWait: number; reserved: number; wipLimit: number }> {
3194
3248
  const grouped = this.d.board.plannerWipBreakdown();
@@ -3202,6 +3256,21 @@ export class Tasks {
3202
3256
  while (pending.length) { const id = pending.pop()!; if (id === prerequisite) return true; if (seen.has(id)) continue; seen.add(id); pending.push(...(this.d.board.get(id)?.deps ?? [])); }
3203
3257
  return false;
3204
3258
  }
3259
+ /**
3260
+ * Peers that capacity-declined and have not reported idle since (#1626 A2). A TUI or headless agent works one task per turn, so it declines an offer far below its WIP cap while mid-turn.
3261
+ * ponytail: kept in memory, not derived from history. A restart reattaches every peer idle, which is exactly when the back-off ends, so nothing is lost; deriving it from history would need an idle marker the board does not record.
3262
+ */
3263
+ private readonly capacityBackoff = new Set<PeerId>();
3264
+ /** #1626 A: peers a hub-initiated offer skips: at the WIP cap (counting offers not yet accepted and in flight, as `reservedHold` does), a held queue, or backing off after a capacity decline. */
3265
+ private hubOfferFull(task: Task): PeerId[] {
3266
+ const full = new Set(this.plannerFull(task));
3267
+ for (const peer of Object.keys(this.states())) {
3268
+ if (this.capacityBackoff.has(peer)) { full.add(peer); continue; }
3269
+ const flying = [...this.readyInFlight].filter(([id, p]) => p === peer && id !== task.id && !this.d.board.get(id)?.owner).length;
3270
+ if (this.wip(peer, task.id) + (this.pendingClaims.get(peer) ?? 0) + flying >= this.wipLimit(peer)) full.add(peer);
3271
+ }
3272
+ return [...full];
3273
+ }
3205
3274
  private plannerFull(task: Task): PeerId[] {
3206
3275
  return Object.keys(this.states()).filter(peer => { const queue = this.d.bus.queueSummary(peer); return this.wip(peer, task.id) >= this.wipLimit(peer) || !!queue.heldBy || queue.needsReview > 0; });
3207
3276
  }
@@ -3255,7 +3324,8 @@ export class Tasks {
3255
3324
  let queueAssignment: { current: () => void } | undefined;
3256
3325
  // `opts.guard` (the auto pull's own admission, #785 P1c) throws a PreEffectToolRefusal once the pull is no longer wanted; it runs wherever authority is rechecked, so it
3257
3326
  // also runs after the awaited PII screen and right before the assignment write, where a setting turned off or a recovery that began meanwhile must still stop it.
3258
- const authorized = () => { this.planningAuthority(planner); opts.guard?.(); queueAssignment?.current(); };
3327
+ const instructionCheck = this.requestCheck(by);
3328
+ const authorized = () => { instructionCheck(); this.planningAuthority(planner); opts.guard?.(); queueAssignment?.current(); };
3259
3329
  authorized();
3260
3330
  if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0 || typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("planner pull needs an id, revision and bounded reason");
3261
3331
  queueAssignment = by !== HUB && opts.onBehalfOf === undefined && this.d.board.get(input.id)?.reserved
@@ -3541,7 +3611,9 @@ export class Tasks {
3541
3611
  this.roadmapWriteAuthority(by); this.roadmapStateAuthority(by, state);
3542
3612
  this.roadmapParsed(() => parseMilestonePatch({ state }));
3543
3613
  const row = this.roadmapCurrent(id, state);
3544
- if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"] });
3614
+ // #1622 family 4: an instructed person verdict records the same three provenance keys task history does, for done and dropped only.
3615
+ const instruction = by === USER && (state === "done" || state === "dropped") ? instructedHistory(by) : {};
3616
+ if (row.state !== state) this.d.board.updateMilestone(id, { state }, row.revision, { by, at: this.d.now?.() ?? Date.now(), event: "state", fields: ["state"], ...instruction });
3545
3617
  return this.roadmapResult(by, id);
3546
3618
  }
3547
3619
 
@@ -3997,6 +4069,94 @@ export class Tasks {
3997
4069
  return [part.detail, `Milestone ${milestone} part ${index} of ${total}: ${kind}. Cites: ${part.cites.join(", ")}.`, `Held until released: ahub intake approve`].join("\n\n");
3998
4070
  }
3999
4071
 
4072
+ /**
4073
+ * R2 (#1480) part 3: publish the milestone's held drafts to GitHub. `--publish` plans one issue per held `spec` part from a
4074
+ * complete reading of the holds and writes nothing; apply creates each issue through one gh call and links it to the
4075
+ * milestone: R1's own `issue` link, and the R4 membership field the create carries when the mirror has a binding, so this
4076
+ * path adds no second link. A `task` part is its own held draft, a released draft is no longer the hold's work, a private part
4077
+ * is only counted, and a refused or unconfirmed call leaves the draft held and names the failure.
4078
+ */
4079
+ async roadmapDecomposePublish(by: PeerId, rawId: unknown, input: { apply?: boolean; confirm?: string } = {}): Promise<{
4080
+ milestone: number; repo: string; githubMilestone: number | null; parts: PublishPlanPart[]; calls: string[][];
4081
+ skippedPrivate: number; skippedUnknown: number; fingerprint: string; applied: boolean; created: { part: number; task: number; issue: number }[];
4082
+ }> {
4083
+ const current = this.roadmapWriteAuthority(by);
4084
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "apply" && key !== "confirm")
4085
+ || input.apply !== undefined && typeof input.apply !== "boolean"
4086
+ || input.confirm !== undefined && (typeof input.confirm !== "string" || !/^[a-f0-9]{64}$/.test(input.confirm)))
4087
+ throw new PreEffectToolRefusal("invalid roadmap publish options; preview with ahub roadmap decompose <id> --publish before applying");
4088
+ if (input.apply && input.confirm === undefined) throw new PreEffectToolRefusal("roadmap decompose --apply needs its preview fingerprint; preview with ahub roadmap decompose <id> --publish first");
4089
+ if (input.apply) this.roadmapApplyAuthority(by);
4090
+ const id = this.roadmapParsed(() => milestoneId(rawId)), view = this.milestoneShow(by, id);
4091
+ if (view.title === "[withheld]" || view.outcome === "[withheld]") throw new PreEffectToolRefusal("milestone text is not cleared for public planning; remove private content before publishing a part");
4092
+ // A milestone settled while its drafts are held refuses here, before any read of GitHub or any write.
4093
+ this.roadmapCurrent(id);
4094
+ current();
4095
+ const repo = this.roadmapRepository(), config = this.d.roadmapConfig?.() ?? { github_mirror: false, github_write: "off" as const };
4096
+ // The GitHub milestone comes from the mirror binding, never from an argument; with the mirror off nothing is attached.
4097
+ const githubMilestone = config.github_mirror ? this.d.board.mirrorMilestone(repo, id) ?? null : null;
4098
+ const drafts: PublishDraft[] = [], held = new Map<number, DecompositionAccept>();
4099
+ let skippedPrivate = 0, skippedUnknown = 0;
4100
+ for (const accept of this.d.board.decompositionAcceptsFor(id)) {
4101
+ const task = this.d.board.get(accept.task);
4102
+ if (!task) continue;
4103
+ const part = this.d.board.decomposition(accept.decomposition)?.parts[accept.part - 1];
4104
+ // Without the answer a part's own words are gone; the draft stays held and the preview says to propose the parts again.
4105
+ const text = part ? [part.title, part.detail, ...part.cites].join("\n") : "";
4106
+ let privatePart = true;
4107
+ try { privatePart = this.isPii(task) || !part || !this.publicMetadataText(text); } catch { privatePart = true; }
4108
+ if (part && !privatePart && this.screenOn()) { const label = (await this.screenCall(text)).label; current(); privatePart = label !== "clear"; }
4109
+ if (!part) { skippedUnknown++; continue; }
4110
+ if (privatePart) { skippedPrivate++; continue; }
4111
+ held.set(task.id, accept);
4112
+ drafts.push({ part: accept.part, task: task.id, intake: accept.intake, title: part.title, detail: part.detail, cites: part.cites,
4113
+ published: this.d.board.decompositionPublish(accept.decomposition, accept.part) ?? null,
4114
+ hold: task.draft === true && task.state === "backlog" ? "held" : "released" });
4115
+ }
4116
+ const planned = planPartPublish({ project: this.d.project, repo, milestone: id, githubMilestone, parts: drafts });
4117
+ const fingerprint = createHash("sha256").update(JSON.stringify({ repo, milestone: id, githubMilestone, calls: planned.calls })).digest("hex");
4118
+ const reply = { milestone: id, repo, githubMilestone, ...planned, skippedPrivate, skippedUnknown, fingerprint, applied: false as boolean, created: [] as { part: number; task: number; issue: number }[] };
4119
+ if (!input.apply) return reply;
4120
+ if (input.confirm !== fingerprint) throw new PreEffectToolRefusal(`roadmap publish preview changed; run ahub roadmap decompose ${id} --publish and retry with --confirm ${fingerprint}`);
4121
+ current(); this.roadmapApplyAuthority(by); if (this.roadmapRepository() !== repo) throw new PreEffectToolRefusal("roadmap GitHub origin changed; preview the publish again");
4122
+ // A retried call whose first attempt is still creating must not POST every planned issue again: `INSERT OR IGNORE` would keep
4123
+ // the first publish row and GitHub would keep both issues. One apply per milestone, refused with the next step it can take.
4124
+ if (this.roadmapPublishes.has(id))
4125
+ throw new PreEffectToolRefusal(`a publish for milestone ${id} is already running; wait for it to finish and run ahub roadmap decompose ${id} --publish again`);
4126
+ this.roadmapPublishes.add(id);
4127
+ try {
4128
+ const creating = planned.parts.filter(row => row.action === "create"), created = reply.created;
4129
+ for (const [index, call] of planned.calls.entries()) {
4130
+ const row = creating[index]!, accept = held.get(row.task)!;
4131
+ // A part an earlier attempt already recorded has its issue: never POST it a second time.
4132
+ if (this.d.board.decompositionPublish(accept.decomposition, row.part) !== undefined) continue;
4133
+ const refused = `roadmap publish was refused for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`;
4134
+ let result: Awaited<ReturnType<SdlcGh>>;
4135
+ try { result = await this.roadmapGh()(call, 10_000, undefined, 64 * 1024); }
4136
+ catch { throw new Error(`roadmap publish was not confirmed for milestone ${id} part ${row.part}; the draft stays held and no issue was linked. Inspect ${repo} before retrying`); }
4137
+ if (result.code !== 0 || Buffer.byteLength(result.stdout) > 64 * 1024) throw new Error(refused);
4138
+ let issue: number;
4139
+ try {
4140
+ const made = JSON.parse(result.stdout) as Record<string, unknown>;
4141
+ issue = milestoneId(made.number);
4142
+ if (made.title !== call.find(value => value.startsWith("title="))?.slice(6)
4143
+ || typeof made.html_url !== "string" || made.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${issue}`) throw new Error("mismatch");
4144
+ } catch { throw new Error(`roadmap publish created an issue for milestone ${id} part ${row.part} but its answer was not confirmed; inspect ${repo} before retrying`); }
4145
+ // The issue exists, so nothing below may refuse the caller: the publish record and the milestone link are best effort.
4146
+ this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its publish record`, () => {
4147
+ this.d.board.recordDecompositionPublish({ decomposition: accept.decomposition, milestone: id, part: row.part, issue }, by, this.d.now?.() ?? Date.now());
4148
+ });
4149
+ this.releaseNotice(`milestone ${id} part ${row.part}: issue ${repo}#${issue} created without its milestone link`, () => {
4150
+ const milestone = this.roadmapCurrent(id);
4151
+ this.d.board.linkMilestone(id, "issue", `${repo}#${issue}`, by, milestone.revision, this.d.now?.() ?? Date.now());
4152
+ });
4153
+ created.push({ part: row.part, task: row.task, issue });
4154
+ }
4155
+ reply.applied = true;
4156
+ return reply;
4157
+ } finally { this.roadmapPublishes.delete(id); }
4158
+ }
4159
+
4000
4160
  /** Apply one suggestion through R1's own writers. A "new milestone" suggestion creates it first; a retry never creates a second. */
4001
4161
  async roadmapAccept(by: PeerId, rawId: unknown): Promise<{ suggestion: MilestoneSuggestion; milestone: MilestoneView }> {
4002
4162
  const current = this.roadmapWriteAuthority(by);
@@ -4124,6 +4284,7 @@ export class Tasks {
4124
4284
  }
4125
4285
 
4126
4286
  async planBacklog(by: PeerId, input: { id: number; revision: number; fields?: unknown; reason: string }): Promise<Task> {
4287
+ const instructionCheck = this.requestCheck(by);
4127
4288
  this.planningAuthority(by);
4128
4289
  if (!Number.isSafeInteger(input.id) || input.id <= 0 || !Number.isSafeInteger(input.revision) || input.revision < 0) throw new PreEffectToolRefusal("invalid planning identity or revision");
4129
4290
  if (typeof input.reason !== "string" || !input.reason.trim() || input.reason.length > 1000) throw new PreEffectToolRefusal("planning needs a bounded reason");
@@ -4181,6 +4342,7 @@ export class Tasks {
4181
4342
  return task;
4182
4343
  };
4183
4344
  const task = validate(), withheld = await this.withholds("note", input.reason, task);
4345
+ instructionCheck();
4184
4346
  this.planningAuthority(by); // #455: or moved the planner
4185
4347
  const latest = validate(); // a person may have changed planning or frozen a release while the screen ran
4186
4348
  let receipt: Task["sdlc"];
@@ -5253,7 +5415,9 @@ export class Tasks {
5253
5415
  }
5254
5416
  const waits = this.waitsFor(task);
5255
5417
  const plannedMove = opts.planner || this.plannerPullRecord(task)?.pull === true && (by === HUB || opts.roster) && (opts.reason !== "manual" || opts.roster);
5256
- const plannerFull = plannedMove ? this.plannerFull(task) : [];
5418
+ // #1626 A: an owner choice the hub makes on its own never offers a peer that must refuse it. A person's or conductor's explicit assignment, a claim and a roster move stay as they were.
5419
+ const hubOffer = !opts.roster && !opts.override && !opts.claim && !opts.namedOwner && !opts.conductorManual && !opts.queueOverride && !opts.plannerPull && this.plannerPullRecord(task)?.pull !== true && opts.reason !== "budget" && opts.reason !== "offline" && (by === HUB || !opts.candidates); // a pause or offline relay moves work that already has an owner, so it is not an offer
5420
+ const plannerFull = plannedMove ? this.plannerFull(task) : hubOffer ? this.hubOfferFull(task) : [];
5257
5421
  const a = assign(opts.plannerPull ? { ...task, state: "proposed" } : task, this.states(), this.d.routing(), { exclude: [...(opts.override ? [] : this.excluded(task)), ...(opts.exclude ?? []), ...(opts.event === "escalated" && task.owner ? [task.owner] : [])], excludeOwners: [...plannerFull, ...this.studyExcludedOwners(task)], ...(opts.candidates ? { candidates: opts.candidates } : {}), waitsFor: waits, ...this.weights(task.class, task), ...(opts.namedOwner ? { namedOwner: opts.namedOwner } : {}), // A self-claim hands over no envelope; reviewer admission remains automatic.
5258
5422
  contextOverride: !!(opts.queueOverride || opts.claim),
5259
5423
  ...(opts.queueOverride || opts.claim ? { queueOverride: opts.queueOverride ?? "owner" as const } : {}) });
@@ -9199,8 +9363,26 @@ export class Tasks {
9199
9363
  // The owner it is declined for goes on the entry, also when the console declines for it: `excluded()` keeps it out (#207).
9200
9364
  const capacityBefore = this.capacityBefore(task);
9201
9365
  const planned = this.plannerPullRecord(task)?.pull === true;
9202
- const back = this.d.board.update(task.id, by, "declined", { ...(["in_progress", "changes_requested"].includes(task.state) ? { state: "proposed" as const } : {}), ...(planned ? { reserved: null } : {}) }, reason, task.owner ? { from: task.owner, ...(capacity === true ? { capacity: true as const } : {}) } : {});
9366
+ const record = this.plannerPullRecord(task);
9367
+ // #1626 A3: a capacity decline of a pulled card keeps the planner's reservation and returns the card to backlog; any other decline clears it as before.
9368
+ const keep = planned && capacity === true && !!task.owner && ["proposed", "in_progress"].includes(task.state) && !taskHasWorkEvidence(task);
9369
+ // #1626 A2: the decliner is not offered another task by the hub until it next reports idle. A peer already idle gets no back-off: no later idle edge would end it.
9370
+ if (capacity === true && task.owner && this.d.bus.stateOf(task.owner) !== "idle") this.capacityBackoff.add(task.owner);
9371
+ const back = this.d.board.update(task.id, by, "declined", { ...(["in_progress", "changes_requested"].includes(task.state) ? { state: "proposed" as const } : {}), ...(planned && !keep ? { reserved: null } : {}) }, reason, task.owner ? { from: task.owner, ...(capacity === true ? { capacity: true as const } : {}) } : {});
9203
9372
  if (planned) this.offered.delete(task.id);
9373
+ if (keep) {
9374
+ this.d.notify(`task ${this.publicTitle(back)} declined (capacity only) by ${by}${reason && !this.isPii(back) ? `: ${reason}` : ""}; back in backlog with its reservation`);
9375
+ this.releaseHubWorktree(task, task.owner ?? by);
9376
+ try {
9377
+ const returned = this.d.board.update(back.id, HUB, "backlog returned untouched", { state: "backlog", owner: null, reviewer: null, reserved: record?.previous.reserved ?? back.reserved ?? null }, "capacity decline: back in backlog with its reservation", {}, back.history.length);
9378
+ this.cohorts.leave(task.id);
9379
+ this.withdrawRoleRequest(task, returned, "owner");
9380
+ this.incomingBacklog.add(task.id);
9381
+ return returned;
9382
+ } finally {
9383
+ this.writePlannerNotices(this.d.board.get(task.id) ?? back, capacityBefore);
9384
+ }
9385
+ }
9204
9386
  this.d.notify(`task ${this.publicTitle(back)} declined${capacity === true ? " (capacity only)" : ""} by ${by}${reason && !this.isPii(back) ? `: ${reason}` : ""}`);
9205
9387
  this.releaseHubWorktree(task, task.owner ?? by);
9206
9388
  // A capacity decline is not in excluded(), so this move's own reroute leaves the decliner out explicitly.
package/src/hub/ui.ts CHANGED
@@ -7,6 +7,7 @@ import { taskProgress } from "../ui/task-progress.ts";
7
7
  import { officeModel } from "../ui/office-model.ts";
8
8
  import { OFFICE_PEER_ORDER, ADAPTER_DISPLAY } from "../adapters/registry.ts";
9
9
  import { needs } from "../ui/needs.ts";
10
+ import { roadmapModel } from "../ui/roadmap-model.ts";
10
11
  import { createHash, randomBytes } from "node:crypto";
11
12
  import { readFileSync } from "node:fs";
12
13
 
@@ -26,7 +27,7 @@ const SESSION_MS = 60 * 60_000;
26
27
  /** How long a session opened by `ahub ui --settings` may change settings that raise authority; it stays an ordinary session after. */
27
28
  export const SETTINGS_MS = 15 * 60_000;
28
29
  /** The page's view names (index.html DASHBOARD_VIEWS): the only values a snapshot request's `view` may carry to a project hub. */
29
- export const DASHBOARD_VIEWS = ["board", "office", "stream", "agents", "message", "memory", "settings"] as const;
30
+ export const DASHBOARD_VIEWS = ["board", "office", "stream", "agents", "message", "memory", "settings", "roadmap"] as const;
30
31
  export const dashboardView = (value: unknown): typeof DASHBOARD_VIEWS[number] | undefined => (DASHBOARD_VIEWS as readonly unknown[]).includes(value) ? value as typeof DASHBOARD_VIEWS[number] : undefined;
31
32
  const LIMIT = 64;
32
33
  const secret = () => randomBytes(32).toString("hex");
@@ -41,7 +42,8 @@ export function renderDashboard(): { html: string; styles: string[]; markup: str
41
42
  .replace("/* TASK_PROGRESS_MODEL */", () => `const taskProgress = ${taskProgress.toString()};`)
42
43
  .replace("/* PEER_START_RETRY_MS */", () => `const PEER_START_RETRY_MS = ${PEER_START_RETRY_MS};`)
43
44
  .replace("/* OFFICE_MODEL */", () => `const officeModel = ((OFFICE_PEER_ORDER) => ${officeModel.toString()})(${JSON.stringify(OFFICE_PEER_ORDER)});`)
44
- .replace("/* NEEDS_MODEL */", () => `const needs = ${needs.toString()};`);
45
+ .replace("/* NEEDS_MODEL */", () => `const needs = ${needs.toString()};`)
46
+ .replace("/* ROADMAP_MODEL */", () => `const roadmapModel = ${roadmapModel.toString()};`);
45
47
  const blocks = (tag: string) => [...html.matchAll(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`, "g"))].map((m) => m[1]!);
46
48
  const body = /<body>([\s\S]*)<\/body>/.exec(html)?.[1] ?? "";
47
49
  return { html, styles: blocks("style"), markup: body.replace(/<script>[\s\S]*?<\/script>/g, ""), script: blocks("script").join("\n") };
@@ -156,6 +158,8 @@ export function startDashboard(options: DashboardOptions) {
156
158
  else if (input.action === "worktrees_refresh_prs") server.timeout(req, 45); // #1057: bounded gh reads (25 s) and two git passes
157
159
  else if (input.action === "backlog_split") server.timeout(req, Math.ceil((BACKLOG_SPLIT_SCREEN_TIMEOUT_MS + HUB_DB_BUSY_TIMEOUT_MS + 5_000) / 1000) + 5);
158
160
  else if (input.action === "intake") server.timeout(req, 95); // the CLI's 90 s intake cap plus the HTTP response margin
161
+ // #1483 R5: both roadmap reads are bounded GitHub metadata passes, not instant page state.
162
+ else if (input.action === "roadmap_check" || input.action === "roadmap_unplaced") server.timeout(req, 40);
159
163
  return json(await options.action(input, sessionOf(cookie)));
160
164
  } catch {
161
165
  // Exceptions may quote private task text or backend details. Never echo them to the page.
@@ -85,6 +85,10 @@ export class UsageRollup {
85
85
  this.db.run(`CREATE TABLE IF NOT EXISTS token_rollup (day TEXT NOT NULL, peer TEXT NOT NULL, task INTEGER NOT NULL, pii INTEGER NOT NULL,
86
86
  tokens INTEGER NOT NULL DEFAULT 0, increments INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, peer, task, pii))`);
87
87
  this.db.run(`CREATE TABLE IF NOT EXISTS limit_events (seq INTEGER PRIMARY KEY, at TEXT NOT NULL, type TEXT NOT NULL, peer TEXT NOT NULL, window TEXT NOT NULL, detail TEXT NOT NULL)`);
88
+ // #1513: an hourly burn series for the quota projection. Same fold as the daily rows, so a rebuild equals the
89
+ // incremental result; `tokens` is each record's own total (or the closest proxy, see recordTokens).
90
+ this.db.run(`CREATE TABLE IF NOT EXISTS usage_points (hour TEXT NOT NULL, peer TEXT NOT NULL, code TEXT NOT NULL, tokens INTEGER NOT NULL DEFAULT 0,
91
+ records INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (hour, peer, code))`);
88
92
  this.db.run(`CREATE TABLE IF NOT EXISTS rollup_state (id INTEGER PRIMARY KEY CHECK (id = 1), byte_offset INTEGER NOT NULL, first_at TEXT)`);
89
93
  this.db.run(`CREATE TABLE IF NOT EXISTS rollup_seen (key TEXT PRIMARY KEY)`);
90
94
  /** A task the log has marked private stays private for every later record, even one written before the mark. */
@@ -192,11 +196,22 @@ export class UsageRollup {
192
196
  rebuild(): void { this.reset(); this.catchUp(); }
193
197
 
194
198
  private reset(): void {
195
- this.db.transaction(() => { for (const table of ["usage_rollup", "token_rollup", "limit_events", "rollup_seen", "rollup_pii"]) this.db.run(`DELETE FROM ${table}`); this.db.run("UPDATE rollup_state SET byte_offset = 0, first_at = NULL WHERE id = 1"); })();
199
+ this.db.transaction(() => { for (const table of ["usage_rollup", "token_rollup", "limit_events", "usage_points", "rollup_seen", "rollup_pii"]) this.db.run(`DELETE FROM ${table}`); this.db.run("UPDATE rollup_state SET byte_offset = 0, first_at = NULL WHERE id = 1"); })();
196
200
  }
197
201
 
198
202
  private day(at: string): string | undefined { const t = Date.parse(at); return Number.isFinite(t) ? new Date(t).toISOString().slice(0, 10) : undefined; }
199
203
 
204
+ /** The point series is hourly; a stamp that does not parse contributes no point. */
205
+ private hour(at: string): string | undefined { const t = Date.parse(at); return Number.isFinite(t) ? new Date(t).toISOString().slice(0, 13) : undefined; }
206
+
207
+ private addPoint(measured: string, peer: string, code: "native" | "count", tokens: number): void {
208
+ if (!(tokens > 0)) return;
209
+ const hour = this.hour(measured);
210
+ if (!hour) return;
211
+ this.db.query(`INSERT OR IGNORE INTO usage_points (hour, peer, code) VALUES (?, ?, ?)`).run(hour, peer, code);
212
+ this.db.query(`UPDATE usage_points SET tokens = tokens + ?, records = records + 1 WHERE hour = ? AND peer = ? AND code = ?`).run(tokens, hour, peer, code);
213
+ }
214
+
200
215
  private fold(line: string): void {
201
216
  if (!line.trim()) return;
202
217
  let e: any;
@@ -237,6 +252,11 @@ export class UsageRollup {
237
252
  const fields: Record<Kind, unknown> = { input: e.inputTokens, output: e.outputTokens, cache_read: e.cacheReadTokens, cache_write: e.cacheWriteTokens, reasoning: e.reasoningTokens, total: known(e.totalTokens) ? e.totalTokens : derived };
238
253
  const withUsage = [e.inputTokens, e.outputTokens, e.cacheReadTokens, e.cacheWriteTokens, e.totalTokens].some(known) ? 1 : 0;
239
254
  const l = this.link(e);
255
+ // #1513: the point series burns what the record says it spent: the provider's total, its derived total, or the
256
+ // counters that do not carry a cached part. A record with none of them adds no point, so the rate understates
257
+ // rather than inventing burn.
258
+ const spent = known(e.totalTokens) ? e.totalTokens : derived ?? [e.inputTokens, e.outputTokens, e.reasoningTokens].filter(known).reduce((sum: number, v: number) => sum + v, 0);
259
+ this.addPoint(measured, e.peer, "native", spent);
240
260
  const params: Record<string, number | string> = { $day: day, $peer: e.peer, $model: model, $source: e.source, $task: l.task, $pii: l.pii, $with: withUsage };
241
261
  this.db.query(`INSERT OR IGNORE INTO usage_rollup (day, peer, model, source, task, pii) VALUES ($day, $peer, $model, $source, $task, $pii)`).run(params as any);
242
262
  const sets = ["records = records + 1", "with_usage = with_usage + $with"];
@@ -250,6 +270,7 @@ export class UsageRollup {
250
270
  const l = this.link(e);
251
271
  this.db.query(`INSERT OR IGNORE INTO token_rollup (day, peer, task, pii) VALUES (?, ?, ?, ?)`).run(day, e.peer, l.task, l.pii);
252
272
  this.db.query(`UPDATE token_rollup SET tokens = tokens + ?, increments = increments + 1 WHERE day = ? AND peer = ? AND task = ? AND pii = ?`).run(e.n, day, e.peer, l.task, l.pii);
273
+ this.addPoint(e.at, e.peer, "count", e.n);
253
274
  }
254
275
 
255
276
  private foldLimit(e: any): void {
@@ -432,10 +453,29 @@ export class UsageRollup {
432
453
  return { days: resultDays, peers: allPeers };
433
454
  }
434
455
 
456
+ /**
457
+ * #1513: the hourly burn series for one peer, for the quota projection. An hour a provider reported uses the
458
+ * provider's number, exactly as `total()` chooses native over the hub's count, so one hour is never counted twice.
459
+ * A point is its hour's start, so the last one is a partial hour (`budget-projection.ts` measures the rate to `now`).
460
+ */
461
+ points(peer: string, since: number, until: number): { at: number; tokens: number }[] {
462
+ if (!Number.isFinite(since) || !Number.isFinite(until) || until < since) return [];
463
+ const rows = this.db.query(`SELECT hour, code, tokens FROM usage_points WHERE peer = ? AND hour >= ? AND hour <= ?`)
464
+ .all(peer, new Date(since).toISOString().slice(0, 13), new Date(until).toISOString().slice(0, 13)) as { hour: string; code: string; tokens: number }[];
465
+ const byHour = new Map<string, { native: number; count: number }>();
466
+ for (const row of rows) {
467
+ const bucket = byHour.get(row.hour) ?? { native: 0, count: 0 };
468
+ if (row.code === "native") bucket.native += row.tokens; else bucket.count += row.tokens;
469
+ byHour.set(row.hour, bucket);
470
+ }
471
+ return [...byHour.entries()].map(([hour, bucket]) => ({ at: Date.parse(`${hour}:00:00.000Z`), tokens: bucket.native > 0 ? bucket.native : bucket.count }));
472
+ }
473
+
435
474
  /** Every roll-up row, in key order, for the rebuild-equals-incremental test. */
436
475
  dump(): unknown {
437
476
  const all = (table: string, order: string) => this.db.query(`SELECT * FROM ${table} ORDER BY ${order}`).all();
438
- return { usage: all("usage_rollup", "day, peer, model, source, task, pii"), tokens: all("token_rollup", "day, peer, task, pii"), pii: all("rollup_pii", "task"),
477
+ return { usage: all("usage_rollup", "day, peer, model, source, task, pii"), tokens: all("token_rollup", "day, peer, task, pii"),
478
+ points: all("usage_points", "hour, peer, code"), pii: all("rollup_pii", "task"),
439
479
  limits: this.db.query("SELECT at, type, peer, window, detail FROM limit_events ORDER BY seq").all(), offset: this.state().offset };
440
480
  }
441
481