@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
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.
@@ -1,6 +1,7 @@
1
1
  import type { Database } from "./db-schema.ts";
2
2
  import { openHubDatabase } from "./db-schema.ts";
3
- import { closeSync, existsSync, fstatSync, openSync, readSync } from "node:fs";
3
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
4
+ import { segmentsOf, streamEnd } from "./log-rotation.ts";
4
5
 
5
6
  /**
6
7
  * The usage roll-up (#683 U2): `events.jsonl` folded into `hub.db`, so a view never rescans the whole log.
@@ -84,6 +85,10 @@ export class UsageRollup {
84
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,
85
86
  tokens INTEGER NOT NULL DEFAULT 0, increments INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, peer, task, pii))`);
86
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))`);
87
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)`);
88
93
  this.db.run(`CREATE TABLE IF NOT EXISTS rollup_seen (key TEXT PRIMARY KEY)`);
89
94
  /** A task the log has marked private stays private for every later record, even one written before the mark. */
@@ -103,30 +108,44 @@ export class UsageRollup {
103
108
  poll(maxMs = 20): { bytes: number; done: boolean } {
104
109
  const deadline = performance.now() + Math.max(0, Math.min(20, maxMs));
105
110
  if (this.closed) return { bytes: 0, done: true };
106
- if (!existsSync(this.eventsFile)) return { bytes: 0, done: true };
107
- const fd = openSync(this.eventsFile, "r");
111
+ // #1546: the log is the rotated segments plus the live file, one byte stream; the stored offset is a position in that stream, so it survives a rotation unchanged.
112
+ const segments = segmentsOf(this.eventsFile);
113
+ if (!segments.length) return { bytes: 0, done: true };
114
+ const end = streamEnd(segments);
115
+ let { offset } = this.state();
116
+ if (end < offset) { this.reset(); offset = 0; }
117
+ if (end === offset) return { bytes: 0, done: true };
118
+ // Kept history starts at the oldest segment: bytes below it were dropped by retention after the roll-up folded them (or, on a first fold, never will be).
119
+ if (offset < segments[0]!.start) {
120
+ const first = segments[0]!.start;
121
+ const moved = this.db.transaction(() => { if (this.state().offset !== offset) return false; this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(first); return true; }).immediate();
122
+ return { bytes: 0, done: !moved ? false : first >= end };
123
+ }
124
+ const segment = segments.find(candidate => offset < candidate.start + candidate.size)!;
125
+ const base = segment.start, local = offset - base;
126
+ const fd = openSync(segment.path, "r");
108
127
  try {
109
128
  const size = fstatSync(fd).size;
110
- let { offset } = this.state();
111
- if (size < offset) { this.reset(); offset = 0; }
112
- if (size === offset) return { bytes: 0, done: true };
129
+ if (size === local) return { bytes: 0, done: true };
113
130
  // The cap bounds a pass, but one line is never split: a line longer than the cap makes this pass read on, up to MAX_LINE_BYTES, until it
114
131
  // holds a whole line, so a single large event can never stall the roll-up. A line past that bound is skipped as corrupt.
115
- let want = Math.min(size - offset, this.opts.maxBytesPerPass ?? DEFAULT_MAX_BYTES), buffer: Buffer, got = 0, end = -1;
132
+ let want = Math.min(size - local, this.opts.maxBytesPerPass ?? DEFAULT_MAX_BYTES), buffer: Buffer, got = 0, last = -1;
116
133
  for (;;) {
117
134
  buffer = Buffer.alloc(want); got = 0;
118
- while (got < want) { const n = readSync(fd, buffer, got, want - got, offset + got); if (!n) break; got += n; }
119
- end = buffer.subarray(0, got).lastIndexOf(0x0a);
120
- if (end >= 0 || offset + want >= size) break; // a whole line, or the end of the file (a line still being written)
135
+ while (got < want) { const n = readSync(fd, buffer, got, want - got, local + got); if (!n) break; got += n; }
136
+ last = buffer.subarray(0, got).lastIndexOf(0x0a);
137
+ if (last >= 0 || local + want >= size) break; // a whole line, or the end of the file (a line still being written)
121
138
  if (want >= MAX_LINE_BYTES) { // an unbounded line: skip what was read up to the next newline
122
- const next = this.skipLongLine(fd, offset, size);
139
+ const next = this.skipLongLine(fd, local, size);
123
140
  if (next === undefined) return { bytes: 0, done: true };
124
- const moved = this.db.transaction(() => { if (this.state().offset !== offset) return false; this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(next); return true; }).immediate();
125
- return moved ? { bytes: next - offset, done: next >= size } : { bytes: 0, done: false };
141
+ const moved = this.db.transaction(() => { if (this.state().offset !== offset) return false; this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(base + next); return true; }).immediate();
142
+ return moved ? { bytes: next - local, done: base + next >= end } : { bytes: 0, done: false };
126
143
  }
127
- want = Math.min(size - offset, want * 2);
144
+ want = Math.min(size - local, want * 2);
128
145
  }
129
- if (end < 0) return { bytes: 0, done: true }; // the last line is still being written: it waits for the next pass
146
+ // A rotated segment always ends in a newline; one that does not (a hand-made file) is folded to its end rather than stalling the stream.
147
+ if (last < 0 && !segment.live && local + got >= size) last = got - 1;
148
+ if (last < 0) return { bytes: 0, done: true }; // the last line is still being written: it waits for the next pass
130
149
  let consumed = 0;
131
150
  // The offset was read before the slice was; another roll-up on this hub.db (a restart that overlaps the old process) may have folded the same
132
151
  // bytes since. The transaction takes the write lock first and checks the stored offset again: a pass whose start is stale is abandoned whole,
@@ -136,18 +155,18 @@ export class UsageRollup {
136
155
  // Commit only complete processed records with their offset. Yield between records;
137
156
  // ponytail: one whole record and the existing corrupt-line skip are indivisible;
138
157
  // a streaming parser would be needed to preempt within either operation.
139
- for (let start = 0; start <= end;) {
140
- const newline = buffer.indexOf(0x0a, start);
141
- if (newline < 0 || newline > end) break;
158
+ for (let start = 0; start <= last;) {
159
+ let newline = buffer.indexOf(0x0a, start);
160
+ if (newline < 0 || newline > last) { if (newline < 0 && start <= last) newline = last + 1; else break; }
142
161
  this.fold(buffer.subarray(start, newline).toString("utf8"));
143
- consumed = newline + 1; start = consumed;
162
+ consumed = Math.min(newline + 1, got); start = consumed;
144
163
  if (performance.now() >= deadline) break;
145
164
  }
146
165
  this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(offset + consumed);
147
166
  return true;
148
167
  }).immediate();
149
168
  if (!applied) return { bytes: 0, done: false }; // stale: the next pass starts from the stored offset
150
- return { bytes: consumed, done: offset + consumed >= size };
169
+ return { bytes: consumed, done: offset + consumed >= end };
151
170
  } finally { closeSync(fd); }
152
171
  }
153
172
 
@@ -177,11 +196,22 @@ export class UsageRollup {
177
196
  rebuild(): void { this.reset(); this.catchUp(); }
178
197
 
179
198
  private reset(): void {
180
- 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"); })();
181
200
  }
182
201
 
183
202
  private day(at: string): string | undefined { const t = Date.parse(at); return Number.isFinite(t) ? new Date(t).toISOString().slice(0, 10) : undefined; }
184
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
+
185
215
  private fold(line: string): void {
186
216
  if (!line.trim()) return;
187
217
  let e: any;
@@ -222,6 +252,11 @@ export class UsageRollup {
222
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 };
223
253
  const withUsage = [e.inputTokens, e.outputTokens, e.cacheReadTokens, e.cacheWriteTokens, e.totalTokens].some(known) ? 1 : 0;
224
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);
225
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 };
226
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);
227
262
  const sets = ["records = records + 1", "with_usage = with_usage + $with"];
@@ -235,6 +270,7 @@ export class UsageRollup {
235
270
  const l = this.link(e);
236
271
  this.db.query(`INSERT OR IGNORE INTO token_rollup (day, peer, task, pii) VALUES (?, ?, ?, ?)`).run(day, e.peer, l.task, l.pii);
237
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);
238
274
  }
239
275
 
240
276
  private foldLimit(e: any): void {
@@ -417,10 +453,29 @@ export class UsageRollup {
417
453
  return { days: resultDays, peers: allPeers };
418
454
  }
419
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
+
420
474
  /** Every roll-up row, in key order, for the rebuild-equals-incremental test. */
421
475
  dump(): unknown {
422
476
  const all = (table: string, order: string) => this.db.query(`SELECT * FROM ${table} ORDER BY ${order}`).all();
423
- 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"),
424
479
  limits: this.db.query("SELECT at, type, peer, window, detail FROM limit_events ORDER BY seq").all(), offset: this.state().offset };
425
480
  }
426
481
 
@@ -100,6 +100,8 @@ export interface ToolContext {
100
100
  permit: (title: string, tool?: string, signal?: AbortSignal, canonicalTarget?: string, observe?: ApprovalObserver, originalPath?: string, input?: unknown, policy?: ShellPermitPolicy) => Promise<ToolApproval>;
101
101
  /** Host-only synchronous recheck, immediately before a shell process can be spawned. */
102
102
  shellExecutionCheck?: (input: unknown) => ShellExecutionCheck;
103
+ /** Host-owned guard: absent unless an admitted edit policy is active. */
104
+ editGuard?: { read(file: string, bytes: Buffer, full: boolean): void; write(file: string): boolean | undefined; written(file: string, unverified: boolean | undefined): void; shell(command: string): (() => void) | undefined };
103
105
  /** #515: present only when the project opted in (`local.doc_read`), so `doc_read` exists for this worker and nothing else gets it. `pii`: this turn is a PII task turn. */
104
106
  docRead?: DocReadPort & { pii: boolean };
105
107
  /** #515b: present only when the project opted in (`local.web_fetch.allow` names a host), so `web_fetch` exists for this worker and nothing else gets it. `pii`: this turn is a PII task turn, for which it is refused. */
@@ -273,9 +275,11 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
273
275
  case "read": {
274
276
  const file = guardPath(ctx, String(a.path), "read");
275
277
  if (statSync(file).size > 5_000_000) return "error: file is larger than 5 MB; use bash (head, grep, sed -n) to look at parts of it";
276
- const lines = readFileSync(file, "utf8").split("\n");
278
+ const bytes = readFileSync(file);
279
+ const lines = bytes.toString("utf8").split("\n");
277
280
  const from = Math.max(1, Number(a.offset) || 1);
278
281
  const out = lines.slice(from - 1, from - 1 + (Number(a.limit) || 2000)).map((l, i) => `${from + i}\t${l}`).join("\n");
282
+ ctx.editGuard?.read(file, bytes, a.offset === undefined && a.limit === undefined && out.split("\n").length === lines.length && out.length <= OUTPUT_CAP);
279
283
  return out.length > OUTPUT_CAP ? `${out.slice(0, OUTPUT_CAP)}\n(truncated: read again with offset/limit)` : out;
280
284
  }
281
285
  case "write": {
@@ -296,8 +300,11 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
296
300
  if (ctx.signal?.aborted) return formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped"));
297
301
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget) return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
298
302
  }
303
+ // ponytail: another process can write between this check and the write; Design 1.2 0444/ahub-edit isolation is the upgrade.
304
+ const unverified = ctx.editGuard?.write(file);
299
305
  mkdirSync(dirname(file), { recursive: true });
300
306
  writeFileSync(file, content);
307
+ try { ctx.editGuard?.written(file, unverified); } catch { /* evidence cannot undo a completed write */ }
301
308
  return `wrote ${a.path}`;
302
309
  }
303
310
  case "edit": {
@@ -324,7 +331,10 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
324
331
  if (ctx.signal?.aborted) return formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped"));
325
332
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget || readFileSync(file, "utf8") !== text) return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
326
333
  }
334
+ // ponytail: another process can write between this check and the write; Design 1.2 0444/ahub-edit isolation is the upgrade.
335
+ const unverified = ctx.editGuard?.write(file);
327
336
  writeFileSync(file, replacement);
337
+ try { ctx.editGuard?.written(file, unverified); } catch { /* evidence cannot undo a completed write */ }
328
338
  return `edited ${a.path}`;
329
339
  }
330
340
  case "bash": {
@@ -343,7 +353,9 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
343
353
  if(check==="valid")break;
344
354
  if(attempt)return "error: read-only shell proof remained unstable; no command was executed";
345
355
  }
356
+ const observedShell = ctx.editGuard?.shell(command);
346
357
  const res = await sandboxedExec(["/bin/bash", "-c", command], { cwd: ctx.cwd, profile: ctx.sandboxProfile, readOnlyData: !!ctx.readOnly?.length, timeoutMs: (Number(a.timeout_s) || 120) * 1000, ...(ctx.sandboxEnv ? { env: ctx.sandboxEnv } : {}), ...(ctx.signal ? { signal: ctx.signal } : {}) });
358
+ try { observedShell?.(); } catch { /* optional observation cannot change an executed command result */ }
347
359
  try { ctx.onProcessExit?.(res.code); } catch { /* optional status observer never changes a tool result */ }
348
360
  return `${res.output}\n(exit ${res.code})`;
349
361
  }
@@ -1,6 +1,6 @@
1
- import packageJson from "../../package.json";
2
1
  import { createHash } from "node:crypto";
3
2
  import { controlWriteSpan } from "../hub/control-write-trace.ts";
3
+ import { AGENT_MEM_VERSION } from "../hub/memory-profile.ts";
4
4
  import { CaptureStore, SearchIndex, looksSecret, memoryBase, readCaptureConfig, type CaptureOptions as StoreCaptureOptions, type MemoryStore, type CandidateStore, type View } from "@staix/agent-mem";
5
5
 
6
6
  export interface CaptureEvent {
@@ -149,6 +149,7 @@ export class MemoryClient {
149
149
  });
150
150
  }
151
151
  async health(): Promise<{ ok: boolean; version?: string }> {
152
- return this.run(() => ({ ok: true, version: packageJson.dependencies["@staix/agent-mem"] })) ?? { ok: false };
152
+ // #1605: the dependency is a range, so report the attested loaded release rather than a range as a version.
153
+ return this.run(() => ({ ok: true, version: AGENT_MEM_VERSION })) ?? { ok: false };
153
154
  }
154
155
  }
@@ -33,6 +33,11 @@ let shutdown: (() => void) | undefined;
33
33
  let runtimeCtx: any;
34
34
  let modelRegistry: any;
35
35
 
36
+ function contextObservation(message: any, ctx: any): Record<string, unknown> {
37
+ const usage = message?.role === "assistant" && typeof message.model === "string" && message.model === ctx?.model?.id ? message.usage : undefined;
38
+ return { input: usage?.input, cacheRead: usage?.cacheRead, cacheWrite: usage?.cacheWrite, contextWindow: ctx?.model?.contextWindow };
39
+ }
40
+
36
41
  async function post(path: string, body: unknown): Promise<any> {
37
42
  if (!bridgeUrl || !bridgeToken) throw new Error("Pi bridge is not configured");
38
43
  const response = await fetch(`${bridgeUrl}${path}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${bridgeToken}` }, body: JSON.stringify(body) });
@@ -127,6 +132,8 @@ async function poll(pi: ExtensionAPI): Promise<void> {
127
132
  ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}),
128
133
  idle: runtimeCtx.isIdle() === true,
129
134
  empty: entries.every((entry: any) => ["model_change", "thinking_level_change"].includes(entry.type)),
135
+ model: runtimeCtx?.model ? { id: runtimeCtx.model.id } : undefined,
136
+ context: contextObservation(entries.slice().reverse().find((entry: any) => entry.type === "message" && entry.message?.role === "assistant")?.message, runtimeCtx),
130
137
  } });
131
138
  continue;
132
139
  } else if (command.type === "set_model") {
@@ -178,7 +185,7 @@ export default function(pi: ExtensionAPI): void {
178
185
  sessionId = String(state?.id ?? "");
179
186
  titleRevision = 0; titleEpoch = crypto.randomUUID();
180
187
  try {
181
- const claimed = await post("/event", { type: "session_start", ownerToken, pid: process.pid, signature: processSignature(process.pid), ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), sessionId: state?.id, sessionFile: ctx.sessionManager.getSessionFile(), approvalTurnAbort: typeof ctx.abort === "function", fencedPrompt: true });
188
+ const claimed = await post("/event", { type: "session_start", ownerToken, pid: process.pid, signature: processSignature(process.pid), ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), sessionId: state?.id, sessionFile: ctx.sessionManager.getSessionFile(), model: ctx.model ? { id: ctx.model.id } : undefined, approvalTurnAbort: typeof ctx.abort === "function", fencedPrompt: true });
182
189
  if (claimed?.ok === false) { ctx.shutdown?.(); return; }
183
190
  } catch (error) { ctx.shutdown?.(); throw error; }
184
191
  if (!pollStarted) { pollStarted = true; void poll(pi); }
@@ -190,7 +197,12 @@ export default function(pi: ExtensionAPI): void {
190
197
  const cancelled = !forcedFailure && message?.stopReason === "aborted";
191
198
  await post("/event", { type: "agent_end", generation: turnGeneration, ...(activePromptId ? { promptId: activePromptId } : {}), text: text ?? "", failed, cancelled, ...(failed ? { error: forcedFailure || message?.errorMessage || message?.stopReason } : {}) });
192
199
  });
193
- pi.on("message_end", async (event: any) => {
200
+ pi.on("message_end", async (event: any, ctx: any) => {
201
+ if (ctx) runtimeCtx = ctx;
202
+ if (event.message?.role === "assistant") {
203
+ try { await post("/event", { type: "pi_usage", sessionId, generation: turnGeneration, model: (ctx ?? runtimeCtx)?.model ? { id: (ctx ?? runtimeCtx).model.id } : undefined, context: contextObservation(event.message, ctx ?? runtimeCtx) }); }
204
+ catch { /* telemetry must not break a native turn */ }
205
+ }
194
206
  const tokens = assistantTokens(event.message);
195
207
  if (tokens === undefined) return;
196
208
  // Message-end is the sole usage source: agent_end carries those same messages again.
@@ -210,7 +222,7 @@ export default function(pi: ExtensionAPI): void {
210
222
  });
211
223
  // Native retries/continuations emit more starts before the one logical agent_settled.
212
224
  pi.on("agent_start", async () => { toolSteps = 0; forcedFailure = ""; turnGeneration++; activePromptId = pendingPromptId ?? activePromptId; pendingPromptId = undefined; await post("/event", { type: "agent_start", sessionId, ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), generation: turnGeneration, ...(activePromptId ? { promptId: activePromptId } : {}) }); });
213
- pi.on("model_select", async (_event: any, ctx: any) => { if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") ctx.shutdown?.(); });
225
+ pi.on("model_select", async (_event: any, ctx: any) => { runtimeCtx = ctx; if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") ctx.shutdown?.(); else try { await post("/event", { type: "pi_model", sessionId, model: ctx.model ? { id: ctx.model.id } : undefined }); } catch { /* optional telemetry */ } });
214
226
  pi.on("before_agent_start", async (event: any, ctx: any) => {
215
227
  if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") { ctx.abort?.(); return { systemPrompt: event.systemPrompt }; }
216
228
  return undefined;
@@ -5,6 +5,19 @@ import { createHash } from "node:crypto";
5
5
  import { PreEffectToolRefusal } from "../hub/tool-refusal.ts";
6
6
 
7
7
  export const PI_TOOL_RESULT_CAP = 100_000;
8
+ /** #1555 AC6: what a settled receipt of a closed session keeps. A replay inside that session never needs more than the outcome and, for a shell, its exit code. */
9
+ export const PI_CLOSED_RESULT_CAP = 2_000;
10
+ const COMPACTED = "\n[result compacted after the session closed]";
11
+ export function compactPiResult(result: string, cap = PI_CLOSED_RESULT_CAP): string {
12
+ if (result.length <= cap) return result;
13
+ try {
14
+ const parsed = JSON.parse(result) as { kind?: unknown; text?: unknown; exitCode?: unknown };
15
+ if (parsed && parsed.kind === "user-bash-result" && typeof parsed.text === "string") return JSON.stringify({ kind: parsed.kind, text: parsed.text.slice(0, Math.max(0, cap - 200)) + COMPACTED, exitCode: parsed.exitCode });
16
+ } catch { /* plain text result */ }
17
+ // bash and git results end with "(exit N)", which toolResultFailed reads to tell a failure from a success on a replay: keep that line.
18
+ const exit = result.match(/\n\(exit [^\n)]+\)$/u)?.[0] ?? "";
19
+ return result.slice(0, Math.max(0, cap - exit.length)) + COMPACTED + exit;
20
+ }
8
21
  /** Bound encoded text before wrapping it so escaping never cuts off trusted exit metadata. */
9
22
  export function packPiShellResult(text: string, exitCode: number | null): string {
10
23
  const pack = (value: string) => JSON.stringify({ kind: "user-bash-result", text: value, exitCode });
@@ -26,6 +39,7 @@ export class PiToolReceipts {
26
39
  private closing = false;
27
40
  private closed = false;
28
41
  private readonly pending = new Map<string, Promise<string>>();
42
+ private currentSession: string | undefined;
29
43
  constructor(file: string) {
30
44
  this.db = openHubDatabase(file, { create: true });
31
45
  chmodSync(file, 0o600);
@@ -37,6 +51,7 @@ export class PiToolReceipts {
37
51
  async execute(session: string, callId: string, name: string, args: unknown, run: () => Promise<string>): Promise<string> {
38
52
  if (this.closing) return "error: Pi tool ledger is shutting down; no new operation was executed";
39
53
  if (!session || !callId || session.length > 512 || callId.length > 512) return "error: invalid Pi session/tool call identity";
54
+ this.closeOthers(session);
40
55
  const fingerprint = createHash("sha256").update(JSON.stringify({ name, args })).digest("hex");
41
56
  const key = JSON.stringify([session, callId]);
42
57
  const row = this.db.query("SELECT fingerprint,state,result FROM pi_tool_receipts WHERE session=? AND call_id=?").get(session, callId) as { fingerprint: string; state: string; result: string | null } | null;
@@ -63,6 +78,17 @@ export class PiToolReceipts {
63
78
  return work;
64
79
  }
65
80
 
81
+ /** A call from a new session closes the previous one: its settled results shrink, while the active session's receipts are never touched. */
82
+ private closeOthers(session: string): void {
83
+ if (this.currentSession === session) return;
84
+ this.currentSession = session;
85
+ try {
86
+ const rows = this.db.query("SELECT session,call_id,result FROM pi_tool_receipts WHERE state='done' AND session != ? AND length(result) > ?").all(session, PI_CLOSED_RESULT_CAP) as { session: string; call_id: string; result: string }[];
87
+ const update = this.db.query("UPDATE pi_tool_receipts SET result=? WHERE session=? AND call_id=? AND state='done'");
88
+ this.db.transaction(() => { for (const row of rows) update.run(compactPiResult(row.result), row.session, row.call_id); })();
89
+ } catch { /* retention only: a failed pass leaves every receipt as it was */ }
90
+ }
91
+
66
92
  get unsettled(): boolean { return this.pending.size > 0 || !!this.db.query("SELECT 1 FROM pi_tool_receipts WHERE state != 'done' LIMIT 1").get(); }
67
93
  get inFlight(): number { return this.pending.size; }
68
94
  async drain(): Promise<void> { await Promise.allSettled(this.pending.values()); }