@staix/agent-hub 0.46.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +12 -6
  3. package/docs/adding-an-ai-tool.md +20 -4
  4. package/docs/agent-notes/adapters.md +3 -3
  5. package/docs/agent-notes/benchmarks.md +7 -1
  6. package/docs/agent-notes/daemon.md +5 -4
  7. package/docs/agent-notes/tasks.md +4 -2
  8. package/docs/agent-notes/tests.md +3 -0
  9. package/docs/contracts/companion-cli-v1.json +3 -0
  10. package/docs/data-policy.md +9 -0
  11. package/docs/design/adapters.md +14 -0
  12. package/docs/design/cli-output-inventory.md +362 -0
  13. package/docs/design/cli-output.md +42 -1
  14. package/docs/design/execution-reference.md +5 -2
  15. package/docs/design/guidance-probes.md +14 -2
  16. package/docs/design/refusal-inventory.md +26 -0
  17. package/docs/design/roadmap.md +4 -0
  18. package/docs/design/task-board.md +17 -1
  19. package/docs/dogfood.md +27 -11
  20. package/docs/events.md +9 -0
  21. package/docs/friction.md +46 -0
  22. package/docs/memory.md +35 -3
  23. package/docs/operations.md +95 -16
  24. package/docs/profiles.md +1 -0
  25. package/docs/quickstart.md +14 -2
  26. package/docs/roles.md +6 -0
  27. package/docs/sdlc.md +44 -1
  28. package/docs/security.md +29 -12
  29. package/docs/specs/2026-09-19-agent-hub-design.md +17 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +7 -1
  31. package/docs/verification/2026-11-25-agy-1.5.16.md +31 -0
  32. package/docs/verification/2026-11-25-claude-implementer-2.1.332.md +47 -0
  33. package/docs/verification/2026-11-25-codex-0172-reviewer-isolation.md +47 -0
  34. package/docs/verification/2026-11-25-kimi-272-reviewer-compat.md +38 -0
  35. package/docs/verification/2026-11-25-kimi-tui-272.md +14 -0
  36. package/docs/verification/2026-11-25-pi-160-compat.md +40 -0
  37. package/docs/verification/2026-11-26-0.47.0.md +43 -0
  38. package/docs/verification/2026-11-26-0.48.0.md +45 -0
  39. package/docs/verification/2026-11-26-codex-0172-reviewer-tool-call.md +29 -0
  40. package/docs/verification/dogfood/2026-11-24.md +2829 -0
  41. package/docs/verification/pi-160-model-free.ts +57 -0
  42. package/docs/verification/pi-160-native.mjs +21 -0
  43. package/docs/verified.json +44 -32
  44. package/package.json +2 -2
  45. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  46. package/plugins/agent-hub/kimi-hook.js +598 -131
  47. package/plugins/agent-hub/server.js +687 -143
  48. package/src/adapters/acp.ts +5 -0
  49. package/src/adapters/channel-peer.ts +7 -0
  50. package/src/adapters/claude-print-child.ts +27 -5
  51. package/src/adapters/codex-appserver.ts +9 -0
  52. package/src/adapters/compat.ts +12 -11
  53. package/src/adapters/configured-acp.ts +45 -2
  54. package/src/adapters/configured-print.ts +163 -0
  55. package/src/adapters/conformance/index.ts +1 -0
  56. package/src/adapters/conformance/print.ts +57 -0
  57. package/src/adapters/definitions/native-activity.ts +57 -0
  58. package/src/adapters/definitions/native-factories.ts +4 -2
  59. package/src/adapters/jcode.ts +10 -2
  60. package/src/adapters/local-probe.ts +59 -14
  61. package/src/adapters/local-worker.ts +20 -6
  62. package/src/adapters/registry-types.ts +5 -3
  63. package/src/adapters/role-eligibility.ts +5 -0
  64. package/src/cli/bench.ts +2 -1
  65. package/src/cli/broker.ts +2 -1
  66. package/src/cli/capabilities-output.ts +10 -14
  67. package/src/cli/configured-acp-entry.ts +10 -2
  68. package/src/cli/console-state.ts +25 -5
  69. package/src/cli/error-format.ts +2 -0
  70. package/src/cli/guidance.ts +1 -1
  71. package/src/cli/handoff-output.ts +20 -17
  72. package/src/cli/help.ts +79 -41
  73. package/src/cli/init-settings.ts +15 -0
  74. package/src/cli/intake-output.ts +13 -13
  75. package/src/cli/launch.ts +3 -2
  76. package/src/cli/learn-output.ts +40 -21
  77. package/src/cli/main.ts +150 -79
  78. package/src/cli/memory.ts +47 -2
  79. package/src/cli/output.ts +54 -31
  80. package/src/cli/roadmap.ts +2 -2
  81. package/src/cli/room-output.ts +71 -0
  82. package/src/cli/room.ts +19 -33
  83. package/src/cli/schedule-output.ts +20 -19
  84. package/src/cli/sdlc-output.ts +188 -170
  85. package/src/cli/source-output.ts +17 -14
  86. package/src/cli/specs.ts +13 -13
  87. package/src/cli/study-output.ts +66 -69
  88. package/src/cli/task-output.ts +106 -158
  89. package/src/cli/terminal-recovery.ts +2 -1
  90. package/src/cli/upgrade-runtime.ts +2 -1
  91. package/src/cli/warn-line.ts +18 -0
  92. package/src/cli/worktrees-output.ts +25 -23
  93. package/src/hub/audit-source.ts +45 -0
  94. package/src/hub/board.ts +141 -5
  95. package/src/hub/bus.ts +13 -2
  96. package/src/hub/config-apply.ts +14 -1
  97. package/src/hub/config-trust.ts +1 -0
  98. package/src/hub/control-client.ts +1 -1
  99. package/src/hub/daemon.ts +390 -47
  100. package/src/hub/guidance-probe-store.ts +51 -10
  101. package/src/hub/guidance-probes.ts +25 -7
  102. package/src/hub/handoff.ts +5 -1
  103. package/src/hub/hub-tools.ts +23 -5
  104. package/src/hub/instance-config.ts +3 -3
  105. package/src/hub/learn-followup.ts +103 -0
  106. package/src/hub/learning.ts +63 -1
  107. package/src/hub/manager.ts +15 -1
  108. package/src/hub/memory-policy.ts +2 -1
  109. package/src/hub/memory-review.ts +217 -0
  110. package/src/hub/peer-activity.ts +37 -0
  111. package/src/hub/peers.ts +3 -0
  112. package/src/hub/project-move.ts +258 -0
  113. package/src/hub/registry.ts +16 -5
  114. package/src/hub/restart.ts +7 -0
  115. package/src/hub/review-brief.ts +8 -4
  116. package/src/hub/review-checkout.ts +26 -0
  117. package/src/hub/review-findings.ts +6 -3
  118. package/src/hub/risk-tier.ts +129 -0
  119. package/src/hub/roadmap-check.ts +1 -0
  120. package/src/hub/routing.ts +3 -1
  121. package/src/hub/sdlc-merge.ts +9 -0
  122. package/src/hub/sdlc-metrics.ts +24 -1
  123. package/src/hub/sdlc-queue.ts +1 -1
  124. package/src/hub/sdlc.ts +15 -6
  125. package/src/hub/settings.ts +2 -0
  126. package/src/hub/spec-readback.ts +136 -0
  127. package/src/hub/specs.ts +1 -1
  128. package/src/hub/task-list-page.ts +1 -1
  129. package/src/hub/tasks.ts +586 -80
  130. package/src/hub/ui.ts +4 -2
  131. package/src/local/probe-types.ts +1 -0
  132. package/src/local/probe-workspace.ts +49 -0
  133. package/src/omniroute/client.ts +19 -3
  134. package/src/ui/guidance-panel.ts +2 -2
  135. package/src/ui/guidance-view.ts +4 -2
  136. package/src/ui/index.html +26 -2
  137. package/src/ui/overview-model.ts +138 -0
  138. package/src/ui/plugin.ts +30 -4
  139. package/templates/roles/ops/project-manager.md +1 -1
@@ -64,9 +64,16 @@ const line = (text: string) => text.replace(/[^\x20-\x7e]/g, " ").replace(/\s+/g
64
64
  * says; nothing here reads or writes any config file.
65
65
  */
66
66
  export function overridesDiff(group: Pick<CriterionGroup, "profile" | "class" | "criterion" | "tasks">): { profile_overrides: { review_checklist: string[] } } {
67
- return { profile_overrides: { review_checklist: [line(`${group.criterion}: confirm this first; it was unmet on ${group.tasks.length} ${group.class} tasks`)] } };
67
+ return { profile_overrides: { review_checklist: [line(checklistLineOf(group.criterion, group.tasks.length, group.class))] } };
68
68
  }
69
69
 
70
+ /**
71
+ * #1642 T3: the fixed opening of the one line `ahub learn accept` writes, which is how a followed line is found again in the person's checklist. The count in the
72
+ * line moves as reviews recur, so the line is identified by this prefix and never by its full text.
73
+ */
74
+ export const checklistLineMarker = (criterion: string): string => `${criterion}: confirm this first; it was unmet on `;
75
+ const checklistLineOf = (criterion: string, tasks: number, cls: string): string => `${checklistLineMarker(criterion)}${tasks} ${cls} tasks`;
76
+
70
77
  /** A stable dedupe key: one card per (profile, class, criterion) however many reviews recur. */
71
78
  export const criterionKey = (group: Pick<CriterionGroup, "profile" | "class" | "criterion">) => `Criterion candidate key: ${group.profile}:${group.class}:${group.criterion}`;
72
79
 
@@ -115,3 +122,58 @@ export function withChecklistLine(current: readonly string[], line: string): { l
115
122
  if (current.length + 1 > CHECKLIST_MAX_LINES) return { refused: `the checklist already has ${current.length} lines and the profile allows ${CHECKLIST_MAX_LINES}; remove one in .agenthub/config.local.json first` };
116
123
  return { list: [...current, line] };
117
124
  }
125
+
126
+ /**
127
+ * The checklist to store after accepting a removal card: the person's CURRENT checklist with the one generated line whose prefix is `marker` gone. Exactly one line must
128
+ * match: none means the person edited or removed it by hand and nothing is guessed, two mean the card cannot name which one it means. Refused, never trimmed.
129
+ */
130
+ export function withoutChecklistLine(current: readonly string[], marker: string): { list: string[]; removed: string } | { refused: string } {
131
+ const hits = current.filter(entry => entry.startsWith(marker));
132
+ if (!hits.length) return { refused: `no checklist line starts with ${JSON.stringify(marker)}: it was removed or edited by hand, so nothing was removed` };
133
+ if (hits.length > 1) return { refused: `${hits.length} checklist lines start with ${JSON.stringify(marker)}: remove the one you mean in .agenthub/config.local.json, then reject this card` };
134
+ return { list: current.filter(entry => entry !== hits[0]), removed: hits[0]! };
135
+ }
136
+
137
+ /** What a removal card states, as the caller measured it: the counts on both sides of the acceptance and the window the follow-up runs from. */
138
+ interface RemovalSubject {
139
+ profile: string;
140
+ class: string;
141
+ criterion: string;
142
+ acceptedAt: number;
143
+ windowStart: number;
144
+ before: { reviewed: number; unmet: number };
145
+ since: { reviewed: number; unmet: number };
146
+ status: string;
147
+ }
148
+
149
+ /** A stable dedupe key: one removal card per line per follow-up window, so a rejection (which resets the window) can be followed by a new card later. */
150
+ export const removalKey = (subject: Pick<RemovalSubject, "profile" | "class" | "criterion" | "windowStart">): string =>
151
+ `Checklist removal key: ${subject.profile}:${subject.class}:${subject.criterion}:${subject.windowStart}`;
152
+
153
+ /** The backlog card's title and detail: ids and counts only, no review text, no task title, no path. */
154
+ export function removalCard(subject: RemovalSubject, windowDays: number): { title: string; detail: string } {
155
+ return {
156
+ title: `Review checklist removal for ${subject.profile}/${subject.class} criterion ${subject.criterion}`,
157
+ detail: [
158
+ removalKey(subject),
159
+ line(`Criterion ${subject.criterion} on ${subject.profile}/${subject.class} was accepted into the checklist on ${new Date(subject.acceptedAt).toISOString()}. Since then ${subject.since.reviewed} task(s) of that profile and class were reviewed and ${subject.since.unmet} named it unmet, against ${subject.before.reviewed} reviewed and ${subject.before.unmet} unmet in the ${windowDays} days before the acceptance (status ${subject.status}).`),
160
+ "This is a candidate for a person to review. Nothing was removed: ahub learn accept on this card removes that one line from .agenthub/config.local.json (this machine only) through the settings writer, and ahub settings undo puts the previous file back. ahub learn reject on this card closes it and starts the follow-up window again. A checklist line can matter for reasons the unmet count does not show, so nothing is removed on its own.",
161
+ ].join("\n"),
162
+ };
163
+ }
164
+
165
+ /**
166
+ * A removal card the hub filed, read the same way as a candidate card: ONLY the key line first, the three parts re-checked against the loaders' shapes, and the title
167
+ * matched to the key line. The line to remove is rebuilt from the criterion by the caller, never taken from the card.
168
+ */
169
+ type RemovalCard = { profile: string; class: string; criterion: string; windowStart: number } | { refused: string };
170
+ export function parseRemovalCard(task: Pick<Task, "class" | "detail" | "history" | "title">): RemovalCard {
171
+ if (task.class !== "plan" || task.history[0]?.by !== "hub") return { refused: "not a card the hub filed" };
172
+ const first = task.detail.split("\n", 1)[0] ?? "";
173
+ const match = /^Checklist removal key: ([^:\s]+):([^:\s]+):([^:\s]+):(\d{1,16})$/.exec(first);
174
+ if (!match) return { refused: "not a checklist removal card (no removal key line first)" };
175
+ const [, profile, cls, criterion, start] = match as unknown as [string, string, string, string, string];
176
+ if (!PROFILE.test(profile) || !CLASS.test(cls) || !CRITERION.test(criterion) || !Number.isSafeInteger(Number(start))) return { refused: "the key line names a profile, class, criterion or window the hub would not accept" };
177
+ if (task.title !== `Review checklist removal for ${profile}/${cls} criterion ${criterion}`) return { refused: "the card's title does not match its key line" };
178
+ return { profile, class: cls, criterion, windowStart: Number(start) };
179
+ }
@@ -323,7 +323,21 @@ export function projectConsole(options: { registry: Registry; lifecycle: Lifecyc
323
323
  } catch { return { ok: false, error: "guidance probe status is unavailable; refresh the probe id or upgrade the hub before retrying" }; }
324
324
  finally { client?.close(); }
325
325
  };
326
- return { list, act, answer, receipt, consoleControl, lineage, guidance, guidanceProbe };
326
+ // #1635: the acon provider's cheap board change token. A port of its own like `lineage`, never an `act` action: it sends the console-role `board_revision` message and gets one bare number back,
327
+ // instead of the full board snapshot. An older hub answers an unknown message with ok:false, and any failure is `undefined` so the caller serves "always fetch".
328
+ const boardRevision = async (target: { projectId: unknown; instanceId: unknown }): Promise<number | undefined> => {
329
+ if (options.stopping?.()) return undefined;
330
+ const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined;
331
+ if (!project || typeof target.instanceId !== "string" || !target.instanceId) return undefined;
332
+ let client: ControlClient | undefined;
333
+ try {
334
+ client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId });
335
+ const result = await client.request({ t: "board_revision" }, options.forwardTimeoutMs?.("board_revision", 3_000) ?? 3_000);
336
+ return result.ok === true && typeof result.boardRevision === "number" && Number.isSafeInteger(result.boardRevision) ? result.boardRevision : undefined;
337
+ } catch { return undefined; }
338
+ finally { client?.close(); }
339
+ };
340
+ return { list, act, answer, receipt, consoleControl, lineage, guidance, guidanceProbe, boardRevision };
327
341
  }
328
342
 
329
343
  export async function startManager(options: ManagerOptions = {}): Promise<ManagerHandle> {
@@ -69,7 +69,8 @@ export function isTrustedReviewPackage(env: Pick<Envelope, "from" | "kind" | "re
69
69
  export function reviewCaptureExcluded(tool: string, args: string): boolean {
70
70
  const name = tool.replace(/^mcp__[^ ]+__/, "");
71
71
  if (name === "hub_visual" || name === "hub_visual_show") return true;
72
- if (["review_comment_put", "review_comment_delete", "review_comment_send", "review_blob"].includes(name)) return true;
72
+ // #1646: a brief file body is the reviewed commit's content, read for one verdict; it belongs to no memory.
73
+ if (["review_comment_put", "review_comment_delete", "review_comment_send", "review_blob", "hub_review_file"].includes(name)) return true;
73
74
  if (name !== "hub_review") return false;
74
75
  try {
75
76
  const input: unknown = JSON.parse(args);
@@ -0,0 +1,217 @@
1
+ import { parseEvery, scheduleKeyOf, type ScheduleEntry } from "./schedules.ts";
2
+
3
+ // #1329 part 1: the scheduled memory review is a `review`-class task built from one fixed template, driven by one
4
+ // machine-local schedule. Nothing here reads the board, a clock, a file or a memory store: the config in, an entry out.
5
+
6
+ /**
7
+ * The schedule id the review runs under, in the same machine-local store as the configured schedules, so the timer,
8
+ * `ahub schedule list`, the open-task rule and the pause epoch read it exactly like a configured entry. The id is
9
+ * fixed, never configurable: one review per project, and a person turns it off rather than filing a second one.
10
+ */
11
+ export const MEMORY_REVIEW_SCHEDULE_ID = "memory-review";
12
+
13
+ /** Notes one run may review. The template names the cap; the run reads no note itself. */
14
+ export const MEMORY_REVIEW_MAX_NOTES = 200;
15
+ /** Projects named in one config: enough for a person's own projects, never a machine-wide sweep. */
16
+ const MEMORY_REVIEW_MAX_PROJECTS = 16;
17
+ /** A token cap is a whole count the person sets; this only keeps a typo out of the scheduler's arithmetic. */
18
+ export const MEMORY_REVIEW_CAP_MAX = 100_000_000;
19
+
20
+ export interface MemoryReviewConfig {
21
+ /** Off until a person turns it on with both caps set (AC1). */
22
+ enabled: boolean;
23
+ /** `<n>m`, `<n>h` or `<n>d`, the same spelling a configured schedule takes. */
24
+ every: string;
25
+ /** Project paths or directory names the review runs for; empty means every project this machine holds. */
26
+ projects: string[];
27
+ /** The peer the card is filed for; unset leaves the role's own owner choice to routing. */
28
+ peer?: string;
29
+ max_notes: number;
30
+ /** Both are required to enable: a run and a week, so one runaway review cannot spend the week's allowance. */
31
+ max_tokens_run?: number;
32
+ max_tokens_week?: number;
33
+ }
34
+
35
+ export const MEMORY_REVIEW_DEFAULTS: MemoryReviewConfig = { enabled: false, every: "1d", projects: [], max_notes: 20 };
36
+
37
+ const KEYS = new Set(["enabled", "every", "projects", "peer", "max_notes", "max_tokens_run", "max_tokens_week"]);
38
+ const PEER = /^[a-z][a-z0-9-]{0,31}$/;
39
+ const control = /[\x00-\x1f\x7f]/;
40
+ const cap = (value: unknown, name: string): number => {
41
+ if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > MEMORY_REVIEW_CAP_MAX) throw new Error(`memory.review.${name} must be a whole token count from 1 to ${MEMORY_REVIEW_CAP_MAX}`);
42
+ return value as number;
43
+ };
44
+
45
+ /**
46
+ * The checked `memory.review` block. Enabling without both caps is refused here, in the config path, so no daemon ever
47
+ * schedules a review whose spend nothing bounds (#1329 AC1). Every other refusal names the key it is about.
48
+ */
49
+ export function memoryReviewConfig(input: unknown): MemoryReviewConfig {
50
+ if (input === undefined) return { ...MEMORY_REVIEW_DEFAULTS };
51
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("memory.review must be an object");
52
+ const row = input as Record<string, unknown>;
53
+ for (const key of Object.keys(row)) if (!KEYS.has(key)) throw new Error(`memory.review has no key ${key}`);
54
+ if (row.enabled !== undefined && typeof row.enabled !== "boolean") throw new Error("memory.review.enabled must be true or false");
55
+ let every = MEMORY_REVIEW_DEFAULTS.every;
56
+ if (row.every !== undefined) {
57
+ try { parseEvery(row.every); } catch (error) { throw new Error(`memory.review.${(error as Error).message}`); }
58
+ every = row.every as string;
59
+ }
60
+ const projects: string[] = [];
61
+ if (row.projects !== undefined) {
62
+ if (!Array.isArray(row.projects) || row.projects.length > MEMORY_REVIEW_MAX_PROJECTS) throw new Error(`memory.review.projects is a list of at most ${MEMORY_REVIEW_MAX_PROJECTS} project paths or directory names`);
63
+ for (const entry of row.projects) {
64
+ if (typeof entry !== "string" || !entry.trim() || entry.length > 300 || control.test(entry)) throw new Error("memory.review.projects entries are project paths or directory names of at most 300 printable characters");
65
+ if (!projects.includes(entry)) projects.push(entry);
66
+ }
67
+ }
68
+ if (row.peer !== undefined && (typeof row.peer !== "string" || !PEER.test(row.peer))) throw new Error("memory.review.peer is a peer id");
69
+ let maxNotes = MEMORY_REVIEW_DEFAULTS.max_notes;
70
+ if (row.max_notes !== undefined) {
71
+ if (!Number.isInteger(row.max_notes) || (row.max_notes as number) < 1 || (row.max_notes as number) > MEMORY_REVIEW_MAX_NOTES) throw new Error(`memory.review.max_notes must be a whole number of notes from 1 to ${MEMORY_REVIEW_MAX_NOTES}`);
72
+ maxNotes = row.max_notes as number;
73
+ }
74
+ const run = row.max_tokens_run === undefined ? undefined : cap(row.max_tokens_run, "max_tokens_run");
75
+ const week = row.max_tokens_week === undefined ? undefined : cap(row.max_tokens_week, "max_tokens_week");
76
+ if (run !== undefined && week !== undefined && week < run) throw new Error("memory.review.max_tokens_week must be at least memory.review.max_tokens_run, or one run could not finish inside its own week");
77
+ const enabled = row.enabled === true;
78
+ if (enabled && (run === undefined || week === undefined)) throw new Error("memory.review.enabled needs both caps: set memory.review.max_tokens_run and memory.review.max_tokens_week, then run ahub memory review on");
79
+ return { enabled, every, projects, ...(row.peer === undefined ? {} : { peer: row.peer as string }), max_notes: maxNotes, ...(run === undefined ? {} : { max_tokens_run: run }), ...(week === undefined ? {} : { max_tokens_week: week }) };
80
+ }
81
+
82
+ /** Whether this project is one the review was turned on for: an exact path, or the directory name of one. */
83
+ function memoryReviewSelects(config: { projects?: string[] } | undefined, project: string): boolean {
84
+ const projects = config?.projects ?? [];
85
+ if (!projects.length) return true;
86
+ const name = project.split("/").filter(Boolean).pop();
87
+ return projects.some(selected => selected === project || selected === name);
88
+ }
89
+
90
+ /**
91
+ * The card's words: one fixed template, so a person reading the board sees the same scope every run and the review
92
+ * cannot be widened by whatever a scheduler happened to remember. The inputs are the notes whose code anchors moved
93
+ * (`ahub memory stale-anchors`), which is the only input agent-mem exposes before agent-mem#324.
94
+ */
95
+ function memoryReviewTemplate(config: MemoryReviewConfig, project: string): string {
96
+ return [
97
+ `The machine-local memory.review switch schedules this review for ${project} every ${config.every ?? MEMORY_REVIEW_DEFAULTS.every}.`,
98
+ "",
99
+ `List the inputs with \`ahub memory stale-anchors --json\` and review only the notes it reports as stale, at most ${config.max_notes ?? MEMORY_REVIEW_DEFAULTS.max_notes}.`,
100
+ "For each note, either re-point the anchor it names or report the note as no longer true; change no code and no note outside that list.",
101
+ `Caps: ${config.max_tokens_run} per run, ${config.max_tokens_week} per week. The hub counts this run's own tokens; at a cap it asks you for one checkpoint and then stops the task as escalated with reason "budget".`,
102
+ ].join("\n");
103
+ }
104
+
105
+ /**
106
+ * The schedule entry the config stands for, or undefined when the review is off or this project is not selected. The
107
+ * daemon reads this at every schedule path, so it must be total over the live config object: a reload applies one key at a
108
+ * time, and a block missing a scalar is read with the default here rather than throwing inside a status reply.
109
+ *
110
+ * The block is validated again here rather than trusted, and that is deliberate: `memoryReviewConfig` is the one place the
111
+ * both-caps rule (AC1) lives, so a live block a key-by-key reload left half applied schedules nothing, and the entry cannot
112
+ * come back for a review nothing bounds without the rule itself changing.
113
+ */
114
+ export function memoryReviewEntry(config: Partial<MemoryReviewConfig> | undefined, project: string): ScheduleEntry | undefined {
115
+ if (config?.enabled !== true) return undefined;
116
+ if (!memoryReviewSelects(config, project)) return undefined;
117
+ // A block the validator would refuse schedules nothing. This runs inside status and the schedules pass, so it fails closed
118
+ // rather than throwing there; the config write is what names the key at fault.
119
+ let selected: MemoryReviewConfig;
120
+ try { selected = memoryReviewConfig({ ...MEMORY_REVIEW_DEFAULTS, ...config }); } catch { return undefined; }
121
+ return {
122
+ id: MEMORY_REVIEW_SCHEDULE_ID, every: selected.every, class: "review",
123
+ title: "Memory review: notes whose code anchors no longer resolve",
124
+ detail: memoryReviewTemplate(selected, project), ...(selected.peer ? { owner: selected.peer } : {}), queue: "backlog",
125
+ };
126
+ }
127
+
128
+ /**
129
+ * #1329 part 2 (AC3): one card is in scope when the hub wrote its detail from the review schedule. The schedule marker is
130
+ * written by `scheduledDetail` when the hub proposes the run, so a card a peer wrote cannot claim the scope, and the class
131
+ * alone is never enough: an audit and a code review are `review`-class too and keep their memory tools.
132
+ */
133
+ export function memoryReviewTask(task: { detail?: string } | undefined): boolean {
134
+ return !!task && scheduleKeyOf(task.detail) === MEMORY_REVIEW_SCHEDULE_ID;
135
+ }
136
+
137
+ /** A tool's bare name: the MCP server prefix is the caller's transport, never part of the rule. */
138
+ const bareTool = (tool: string): string => tool.replace(/^mcp__[A-Za-z0-9_.-]{1,64}__/, "").toLowerCase();
139
+
140
+ /** Every hub tool a review card may call: reads, proposal-only memory writes, its own lifecycle and plain messages. */
141
+ const MEMORY_REVIEW_HUB_OPS: ReadonlySet<string> = new Set([
142
+ "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_memory_correct", "hub_remember",
143
+ "hub_task_show", "hub_task_list", "hub_task_accept", "hub_task_decline", "hub_task_done", "hub_task_wait",
144
+ "hub_checkpoint", "hub_task_escalate", "hub_send", "hub_inbox", "hub_specs", "hub_set_title", "hub_ask",
145
+ "hub_delivery_retry", "hub_delivery_resolve", "hub_check_result", "hub_check_cancel", "hub_source_read",
146
+ "hub_study_show", "hub_experiment_show", "hub_evidence_read", "hub_lineage_show", "hub_guidance_list",
147
+ "hub_guidance_show", "hub_supervision_list", "hub_supervision_dismiss", "hub_permission_request",
148
+ ]);
149
+
150
+ /** Memory reads, the consolidation preview and vault reads are the review's own inputs; they are allowed by name wherever they come from. */
151
+ const REVIEW_READS: ReadonlySet<string> = new Set([
152
+ "amem_search", "amem_show", "amem_related", "amem_work_state_read", "amem_brief", "amem_consolidate", "amem_consolidate_preview",
153
+ "vmem_search", "vmem_show", "vmem_list", "vmem_read", "vmem_get", "vmem_report", "vmem_links", "vmem_graph", "vmem_backlinks",
154
+ ]);
155
+ /** Mutations a review may never make: accepting a candidate, or changing a note's tier, life or lineage. */
156
+ const MEMORY_MUTATIONS: ReadonlySet<string> = new Set([
157
+ "memory_promote", "memory_demote", "memory_forget", "memory_supersede", "memory_accept",
158
+ "amem_promote", "amem_demote", "amem_forget", "amem_supersede", "amem_accept", "amem_review_accept", "amem_review_reject",
159
+ "hub_memory_promote", "hub_memory_demote", "hub_memory_forget", "hub_memory_supersede", "hub_memory_accept",
160
+ "hub_learn_accept", "hub_learn_reject",
161
+ ]);
162
+ const VAULT_WRITES: ReadonlySet<string> = new Set(["vmem_create", "vmem_patch", "vmem_move", "vmem_delete", "vmem_promote", "vmem_demote", "vmem_merge", "vmem_rewrite", "vmem_archive"]);
163
+ const CODE_EDITS: ReadonlySet<string> = new Set(["edit", "write", "multiedit", "notebookedit", "str_replace_editor", "apply_patch", "hub_check_start"]);
164
+ const PEER_STARTS: ReadonlySet<string> = new Set(["peer_start", "hub_peer_start", "hub_peer_hold", "hub_peer_release"]);
165
+
166
+ /**
167
+ * The refusal sentence for one tool call inside a review card, or undefined when the call is allowed. Every refusal names
168
+ * its cause and the next step the caller can take; none of them edits anything before it throws.
169
+ */
170
+ export function memoryReviewScope(tool: string): string | undefined {
171
+ if (typeof tool !== "string" || !tool) return undefined;
172
+ const name = bareTool(tool);
173
+ if (MEMORY_REVIEW_HUB_OPS.has(name) || REVIEW_READS.has(name)) return undefined;
174
+ if (MEMORY_MUTATIONS.has(name)) return `${tool} changes shared memory, and a memory review only proposes: record it with hub_memory_correct or hub_remember for a person's amem review, and make the mutation in a turn outside this review task`;
175
+ if (VAULT_WRITES.has(name)) return `${tool} writes a vault note, and a memory review reads the vault and writes none: report the finding with vmem report, and make the note change in a turn outside this review task`;
176
+ if (CODE_EDITS.has(name)) return `${tool} edits code or runs a check, and a memory review changes no code: record the finding with hub_checkpoint, and make the edit in an ordinary task`;
177
+ if (PEER_STARTS.has(name)) return `${tool} starts or holds a peer, and a memory review runs no other work: ask the person or the conductor to start it outside this review task`;
178
+ if (name.startsWith("hub_")) return `${tool} is outside a memory-review card's scope (memory reads and proposals, checkpoint, done, messaging, specs and supervision reads): record the need with hub_checkpoint, and do it in an ordinary task`;
179
+ return undefined;
180
+ }
181
+
182
+ /** #1329 AC4: a review's note text is a candidate attributed to the card and to the peer that wrote it. */
183
+ interface ReviewCandidateInput { text: string; title?: string; noteKind?: "decision" | "finding" | "contract" | "fail" | "preference" }
184
+ export function memoryReviewCandidate(input: ReviewCandidateInput, task: number, peer: string, at = new Date()): { input: { kind: "memory"; text: string; title?: string; noteKind?: ReviewCandidateInput["noteKind"]; about: string[] }; origin: { peer: string; at: string } } {
185
+ return {
186
+ input: { kind: "memory", text: input.text, ...(input.title ? { title: input.title } : {}), ...(input.noteKind ? { noteKind: input.noteKind } : {}), about: [`task:${task}`] },
187
+ origin: { peer, at: at.toISOString() },
188
+ };
189
+ }
190
+
191
+ /** The counted spend one review has made, in the hub's own tokens (never an estimate). */
192
+ export interface ReviewSpend { run: number; week: number }
193
+ interface ReviewBudgetStop { cap: "run" | "week"; used: number; limit: number }
194
+
195
+ /**
196
+ * #1329 AC5: whether a review has reached either cap. A cap that is unset cannot stop anything, and a reading equal to the
197
+ * cap is a stop: the run's allowance is spent, and one more turn would exceed it.
198
+ */
199
+ export function reviewBudgetStop(spend: ReviewSpend, config: Pick<MemoryReviewConfig, "max_tokens_run" | "max_tokens_week">): ReviewBudgetStop | undefined {
200
+ const run = config.max_tokens_run, week = config.max_tokens_week;
201
+ if (run !== undefined && spend.run >= run) return { cap: "run", used: spend.run, limit: run };
202
+ if (week !== undefined && spend.week >= week) return { cap: "week", used: spend.week, limit: week };
203
+ return undefined;
204
+ }
205
+
206
+ /** The checkpoint the peer is asked for before the card stops, and the note the escalation records (counts only). */
207
+ export const reviewCheckpointRequest = (task: number, stop: ReviewBudgetStop): string =>
208
+ `Memory review task #${task} reached its ${stop.cap} token cap (${stop.used} of ${stop.limit}). First call hub_checkpoint with what you reviewed, the proposals you filed and what is left, then stop: the hub escalates the task with reason "budget".`;
209
+ export const reviewBudgetNote = (task: number, stop: ReviewBudgetStop, spend: ReviewSpend): string =>
210
+ `memory review budget: task #${task} spent ${spend.run} tokens this run and ${spend.week} this week; the ${stop.cap} cap is ${stop.limit}, so the run stopped.`;
211
+
212
+ /** #1329: the done summary and the research record carry counts only, never a note or a line of the reviewed text. */
213
+ interface MemoryReviewCounts { notes: number; corrections: number; remembered: number; originsFound: number; originsExpired: number; tokens: number }
214
+ export function memoryReviewCountLine(counts: Partial<MemoryReviewCounts>): string {
215
+ const n = (value: number | undefined) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? String(value) : "unknown");
216
+ return `memory review counts: notes checked ${n(counts.notes)}, proposals ${n(counts.corrections)} corrections and ${n(counts.remembered)} notes, origin sessions ${n(counts.originsFound)} found and ${n(counts.originsExpired)} expired, tokens ${n(counts.tokens)}`;
217
+ }
@@ -0,0 +1,37 @@
1
+ const ACTIVITY_KINDS = ["files", "shell", "network", "hub", "memory", "agents", "model", "unknown"] as const;
2
+ export type ActivityKind = (typeof ACTIVITY_KINDS)[number];
3
+ interface PeerActivity { kind: ActivityKind; since: number }
4
+
5
+ function isActivityKind(value: unknown): value is ActivityKind {
6
+ return typeof value === "string" && (ACTIVITY_KINDS as readonly string[]).includes(value);
7
+ }
8
+
9
+ /** One transient row per busy peer. Privacy suppression lasts through the current turn. */
10
+ export class PeerActivityTracker {
11
+ private readonly rows = new Map<string, PeerActivity>();
12
+ private readonly hidden = new Set<string>();
13
+
14
+ observe(peer: string, kind: unknown, isPrivate: () => boolean, now = Date.now()): void {
15
+ if (kind === undefined) { this.clear(peer); return; }
16
+ if (!isActivityKind(kind) || this.withheld(peer, isPrivate)) return;
17
+ this.rows.set(peer, { kind, since: now });
18
+ }
19
+
20
+ view(peer: string, isPrivate: () => boolean): PeerActivity | undefined {
21
+ if (!this.rows.has(peer) || this.withheld(peer, isPrivate)) return undefined;
22
+ return this.rows.get(peer);
23
+ }
24
+
25
+ private withheld(peer: string, isPrivate: () => boolean): boolean {
26
+ if (this.hidden.has(peer)) return true;
27
+ try { if (!isPrivate()) return false; } catch { /* Unknown privacy withholds the row. */ }
28
+ this.hidden.add(peer);
29
+ this.rows.delete(peer);
30
+ return true;
31
+ }
32
+
33
+ private clear(peer: string): void {
34
+ this.rows.delete(peer);
35
+ this.hidden.delete(peer);
36
+ }
37
+ }
package/src/hub/peers.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ActivityKind } from "./peer-activity.ts";
1
2
  import type { DeliveryFailureCause } from "./delivery-failure.ts";
2
3
  import type { Envelope, EnvelopeOpts, PeerId, PeerState } from "./envelope.ts";
3
4
  import type { PermissionMode } from "./permission-mode.ts";
@@ -141,6 +142,7 @@ export interface PeerAdapter {
141
142
  onDelivery?: (receipt: DeliveryReceipt) => void;
142
143
  /** Set by the bus (#878): a native session title or current plan item the adapter observed; `reset` on a new session. */
143
144
  onDoing?: (kind: DoingKind, text?: unknown) => void;
145
+ onActivity?: (kind: ActivityKind | undefined) => void;
144
146
  /** Safe restart metadata only: ids and launch parameters, never prompt/message text. */
145
147
  recoveryMetadata?(): Record<string, unknown>;
146
148
  /** Current native TUI ownership, correlated to one launcher. A start acknowledgement is never evidence. */
@@ -161,6 +163,7 @@ export abstract class BasePeer implements PeerAdapter {
161
163
  onFailed?: (envs: Envelope[], failure?: { quota?: true; failureCause?: DeliveryFailureCause }) => void;
162
164
  onDelivery?: (receipt: DeliveryReceipt) => void;
163
165
  onDoing?: (kind: DoingKind, text?: unknown) => void;
166
+ onActivity?: (kind: ActivityKind | undefined) => void;
164
167
  private _state: PeerState = "offline";
165
168
  private timer: ReturnType<typeof setTimeout> | undefined;
166
169
  private nextWatchdogMs: number | undefined;