@staix/agent-hub 0.38.0 → 0.40.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 (195) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +28 -12
  3. package/docs/adding-an-ai-tool.md +7 -5
  4. package/docs/agent-notes/README.md +23 -0
  5. package/docs/agent-notes/adapters.md +9 -5
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +9 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +21 -9
  10. package/docs/agent-notes/local-worker.md +4 -2
  11. package/docs/agent-notes/security-review.md +56 -0
  12. package/docs/agent-notes/tasks.md +22 -6
  13. package/docs/agent-notes/tests.md +10 -9
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +142 -0
  16. package/docs/design/agent-hub-architecture.md +46 -1
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +185 -5
  23. package/docs/dogfood.md +30 -9
  24. package/docs/events.md +7 -7
  25. package/docs/memory.md +5 -5
  26. package/docs/operations.md +315 -54
  27. package/docs/profiles.md +101 -8
  28. package/docs/quickstart.md +47 -6
  29. package/docs/research.md +6 -3
  30. package/docs/roles.md +52 -0
  31. package/docs/sdlc.md +190 -2
  32. package/docs/security.md +90 -15
  33. package/docs/text-projection.md +1 -0
  34. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  35. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  36. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  37. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  38. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  39. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  40. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  41. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  42. package/docs/verification/pi-152-model-free.ts +57 -0
  43. package/docs/verification/pi-152-native.mjs +21 -0
  44. package/docs/verified.json +48 -25
  45. package/package.json +4 -4
  46. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  47. package/plugins/agent-hub/kimi-hook.js +2266 -530
  48. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  49. package/plugins/agent-hub/server.js +2423 -645
  50. package/src/adapters/acp-model-policy.ts +1 -1
  51. package/src/adapters/acp-session-model.ts +35 -0
  52. package/src/adapters/acp.ts +14 -0
  53. package/src/adapters/agy/definition.ts +2 -2
  54. package/src/adapters/agy/hooks.ts +7 -0
  55. package/src/adapters/claude-channel.ts +1 -1
  56. package/src/adapters/claude-implementer.ts +8 -0
  57. package/src/adapters/claude-print-child.ts +26 -2
  58. package/src/adapters/claude-print.ts +4 -0
  59. package/src/adapters/codex-appserver.ts +90 -16
  60. package/src/adapters/codex-review-isolation.ts +63 -17
  61. package/src/adapters/compat.ts +10 -10
  62. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  63. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  64. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  65. package/src/adapters/definitions/builtin-metadata.ts +12 -12
  66. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  67. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  68. package/src/adapters/definitions/native-config-policy.ts +1 -1
  69. package/src/adapters/definitions/native-quota.ts +122 -0
  70. package/src/adapters/definitions/native-recovery.ts +3 -0
  71. package/src/adapters/definitions/qwen.ts +2 -2
  72. package/src/adapters/kimi-review.ts +23 -0
  73. package/src/adapters/kimi-wire-usage.ts +39 -16
  74. package/src/adapters/local-worker.ts +9 -4
  75. package/src/adapters/pi-state-model.ts +12 -0
  76. package/src/adapters/pi.ts +76 -11
  77. package/src/adapters/print-result-model.ts +24 -0
  78. package/src/adapters/registry-types.ts +12 -2
  79. package/src/adapters/registry.ts +19 -2
  80. package/src/adapters/reviewer-print.ts +132 -16
  81. package/src/adapters/role-eligibility.ts +99 -0
  82. package/src/adapters/same-directory.ts +16 -0
  83. package/src/cli/agy-mcp.ts +18 -7
  84. package/src/cli/answer-args.ts +11 -3
  85. package/src/cli/console-question.ts +1 -1
  86. package/src/cli/console-state.ts +98 -11
  87. package/src/cli/console.ts +6 -2
  88. package/src/cli/error-format.ts +19 -0
  89. package/src/cli/free-text.ts +20 -0
  90. package/src/cli/handoff-args.ts +1 -1
  91. package/src/cli/help.ts +350 -30
  92. package/src/cli/identity-audit.ts +8 -7
  93. package/src/cli/identity.ts +27 -4
  94. package/src/cli/init-prompt.ts +31 -2
  95. package/src/cli/init-roles.ts +156 -0
  96. package/src/cli/init-settings.ts +24 -2
  97. package/src/cli/init.ts +232 -17
  98. package/src/cli/main.js +2 -2
  99. package/src/cli/main.ts +250 -69
  100. package/src/cli/model.ts +1 -1
  101. package/src/cli/output-standard.ts +56 -0
  102. package/src/cli/output.ts +199 -9
  103. package/src/cli/preview.ts +1 -1
  104. package/src/cli/recovery-launch.ts +114 -0
  105. package/src/cli/recovery-package.ts +14 -7
  106. package/src/cli/recovery-version-preflight.ts +104 -0
  107. package/src/cli/roadmap.ts +215 -0
  108. package/src/cli/role-doctor.ts +39 -0
  109. package/src/cli/sdlc-output.ts +66 -1
  110. package/src/cli/smoke-pty-bridge.ts +7 -24
  111. package/src/cli/study-output.ts +54 -0
  112. package/src/cli/study.ts +14 -1
  113. package/src/cli/task-output.ts +3 -1
  114. package/src/cli/terminal-recovery.ts +14 -0
  115. package/src/cli/upgrade-presentation-flags.ts +2 -2
  116. package/src/cli/upgrade-presentation.ts +4 -0
  117. package/src/cli/upgrade-restore-state.ts +12 -3
  118. package/src/cli/upgrade-runtime.ts +40 -2
  119. package/src/cli/upgrade.ts +8 -4
  120. package/src/hub/advisor-survey.ts +139 -0
  121. package/src/hub/audit-source.ts +66 -0
  122. package/src/hub/board.ts +677 -15
  123. package/src/hub/budget.ts +54 -4
  124. package/src/hub/bus.ts +9 -0
  125. package/src/hub/check-runner.ts +3 -4
  126. package/src/hub/ci-watch.ts +19 -4
  127. package/src/hub/conductor.ts +14 -8
  128. package/src/hub/config-apply.ts +2 -1
  129. package/src/hub/config-edit-host.ts +77 -5
  130. package/src/hub/considered-findings.ts +47 -0
  131. package/src/hub/control-client.ts +1 -1
  132. package/src/hub/daemon.ts +585 -98
  133. package/src/hub/deliverable-files.ts +17 -1
  134. package/src/hub/dogfood-profile.ts +3 -2
  135. package/src/hub/events.ts +25 -4
  136. package/src/hub/execution-reference.ts +1 -1
  137. package/src/hub/folder-trigger.ts +11 -4
  138. package/src/hub/github-import.ts +81 -0
  139. package/src/hub/hub-tools.ts +117 -20
  140. package/src/hub/install-policy.ts +23 -0
  141. package/src/hub/kimi-usage.ts +34 -2
  142. package/src/hub/lifecycle-schema.ts +3 -3
  143. package/src/hub/memory-profile.ts +9 -1
  144. package/src/hub/memory-sync-state.ts +1 -0
  145. package/src/hub/model-overrides.ts +2 -1
  146. package/src/hub/no-writes.ts +5 -0
  147. package/src/hub/operational-authority.ts +8 -1
  148. package/src/hub/operational-view.ts +6 -2
  149. package/src/hub/peers.ts +2 -0
  150. package/src/hub/pi-failure.ts +7 -0
  151. package/src/hub/plan-conformance.ts +20 -2
  152. package/src/hub/question-desk.ts +26 -7
  153. package/src/hub/questions.ts +33 -5
  154. package/src/hub/quota-account.ts +34 -0
  155. package/src/hub/recovery-policy.ts +18 -4
  156. package/src/hub/research-evidence.ts +51 -3
  157. package/src/hub/research.ts +77 -13
  158. package/src/hub/restart.ts +21 -0
  159. package/src/hub/review-budget.ts +88 -0
  160. package/src/hub/review-findings.ts +93 -12
  161. package/src/hub/reviewer-pool-config.ts +6 -2
  162. package/src/hub/reviewer-pool.ts +39 -6
  163. package/src/hub/roadmap-triage.ts +86 -0
  164. package/src/hub/roadmap-unplaced.ts +169 -0
  165. package/src/hub/roadmap-view.ts +83 -0
  166. package/src/hub/roadmap.ts +127 -0
  167. package/src/hub/routing.ts +7 -3
  168. package/src/hub/sdlc-merge.ts +6 -5
  169. package/src/hub/sdlc-queue.ts +17 -7
  170. package/src/hub/sdlc-release.ts +1 -1
  171. package/src/hub/sdlc.ts +47 -8
  172. package/src/hub/security-audit.ts +178 -0
  173. package/src/hub/security-pass.ts +115 -0
  174. package/src/hub/settings.ts +11 -5
  175. package/src/hub/source-read.ts +80 -2
  176. package/src/hub/sources.ts +57 -9
  177. package/src/hub/specs-task.ts +7 -0
  178. package/src/hub/startup-event-seeds.ts +5 -3
  179. package/src/hub/startup-timing.ts +1 -0
  180. package/src/hub/synthesis-readiness.ts +279 -0
  181. package/src/hub/task-sweep.ts +29 -2
  182. package/src/hub/task-worktree.ts +37 -0
  183. package/src/hub/tasks.ts +1464 -76
  184. package/src/hub/text-projection.ts +11 -1
  185. package/src/memory/capture.ts +2 -1
  186. package/src/pi/dependency-publish.ts +50 -0
  187. package/src/pi/extension.ts +1 -1
  188. package/src/pi/launch.ts +1 -1
  189. package/src/pi/task-dependencies.ts +249 -0
  190. package/src/ui/index.html +56 -13
  191. package/src/ui/office-model.ts +11 -3
  192. package/src/ui/office-space.ts +50 -30
  193. package/src/ui/plugin-questions.ts +5 -0
  194. package/src/ui/plugin.ts +27 -12
  195. package/templates/config.json +1 -1
@@ -66,7 +66,10 @@ export class KimiUsage {
66
66
  private readonly window = new TokenWindow(KIMI_WINDOW_MS);
67
67
  private readonly seen = new Set<string>();
68
68
  /** A log that stopped matching the count leaves the window short of the truth until its rows age out. */
69
+ private reviewerReplayUnknown = false;
70
+ private readonly reviewerAttempts = new Set<string>();
69
71
  private readonly taintedUntil = new Map<string, number>();
72
+ private readonly reviewerSources = new Set<string>();
70
73
  private stopped = false;
71
74
 
72
75
  constructor(private readonly ports: KimiUsagePorts) {}
@@ -87,8 +90,9 @@ export class KimiUsage {
87
90
  if (!this.ports.ceiling()) return { state: "off" };
88
91
  for (const state of this.bound.values()) if (state.unknown) return { state: "unreadable", reason: state.unknown };
89
92
  const now = this.ports.now();
93
+ if (this.reviewerReplayUnknown || this.reviewerAttempts.size) return { state: "unreadable", reason: "log changed since it was counted" };
90
94
  for (const until of this.taintedUntil.values()) if (now < until) return { state: "unreadable", reason: "log changed since it was counted" };
91
- return { state: this.bound.size ? "counting" : "waiting" };
95
+ return { state: this.bound.size || this.reviewerSources.size ? "counting" : "waiting" };
92
96
  }
93
97
 
94
98
  /** The peer went offline: its log is no longer read, so an unreadable state of it must not hold the other peers' figure unknown. */
@@ -176,6 +180,34 @@ export class KimiUsage {
176
180
  }
177
181
  }
178
182
 
183
+ /** Terminal private-home callers must prove the entire bounded drain completed before forwarding its rows. */
184
+ complete(peer: string): boolean {
185
+ const bound = this.bound.get(peer);
186
+ return !!bound && !bound.unknown && !bound.backlog;
187
+ }
188
+ /** One shared account counter/event attribution, including fresh reviewer profiles read before deletion. */
189
+ observeReviewer(peer: string, row: KimiWireRow, attributed: KimiRowAttribution): boolean {
190
+ const counters = [row.inputOther, row.inputCacheCreation, row.inputCacheRead, row.output];
191
+ if (!/^[a-f0-9]{32}$/.test(row.id) || !Number.isFinite(row.at) || row.at <= 0 || counters.some(value => !Number.isSafeInteger(value) || value < 0)
192
+ || !Number.isSafeInteger(counters.reduce((sum, value) => sum + value, 0))) throw new Error("invalid reviewer usage observation");
193
+ if (this.seen.has(row.id)) return false;
194
+ const counted = kimiCountedTokens(row);
195
+ this.ports.record(peer, row, counted, attributed);
196
+ this.seen.add(row.id); this.reviewerSources.add(peer);
197
+ this.window.add(Math.min(row.at, this.ports.now()), counted);
198
+ this.report(peer);
199
+ return true;
200
+ }
201
+ reviewerReplayIncomplete(peer: string): void { this.reviewerReplayUnknown = true; this.ports.forget(peer); }
202
+ /** Unresolved owned attempts have no proven window end. Neither restart nor a host cap clears them. */
203
+ reviewerAccounting(peer: string, attempt: string, outcome: "started" | "complete" | "unknown"): void {
204
+ if (!/^[a-f0-9]{32}$/.test(attempt)) throw new Error("invalid reviewer accounting identity");
205
+ if (outcome === "complete") this.reviewerAttempts.delete(attempt);
206
+ else this.reviewerAttempts.add(attempt);
207
+ if (this.reviewerReplayUnknown || this.reviewerAttempts.size) this.ports.forget(peer);
208
+ else this.report(peer);
209
+ }
210
+
179
211
  private schedule(peer: string, bound: Bound, scheduled: boolean): void {
180
212
  const schedule = this.ports.schedule;
181
213
  if (!schedule || this.stopped) return;
@@ -232,7 +264,7 @@ export class KimiUsage {
232
264
  /** The window as a reading, only while every Kimi peer's log reads cleanly: otherwise the figure is unknown, never a short count. */
233
265
  private report(peer: string): void {
234
266
  const ceiling = this.ports.ceiling(), now = this.ports.now();
235
- if (!ceiling) return;
267
+ if (!ceiling || this.reviewerReplayUnknown || this.reviewerAttempts.size) return;
236
268
  for (const state of this.bound.values()) if (state.unknown) return;
237
269
  for (const until of this.taintedUntil.values()) if (now < until) return;
238
270
  const oldest = this.window.oldest(now);
@@ -3,7 +3,7 @@ import { configuredToolContext, type ProjectToolContext } from "./hub-tools.ts";
3
3
  import { SDLC_STAGES } from "./sdlc.ts";
4
4
  /** The daemon owns the active definition. Unavailable reads never invent a project-file stage set. */
5
5
  /** The active stage ids and whether the lifecycle is enabled (`criteria`, #481 S8); an older daemon never says so. */
6
- export async function activeLifecycle(stateDir: string, peer: string, projectRoot: string, active?: ControlClient): Promise<({ stages: string[]; criteria: boolean } & ProjectToolContext) | undefined> {
6
+ export async function activeLifecycle(stateDir: string, peer: string, projectRoot: string, active?: ControlClient): Promise<({ stages: string[]; criteria: boolean; audit: boolean; survey?: true; wait?: true } & ProjectToolContext) | undefined> {
7
7
  let client: ControlClient | undefined;
8
8
  try {
9
9
  client = active ?? await ControlClient.connect(stateDir, { role: "tools", peer, projectRoot }, 1000);
@@ -11,10 +11,10 @@ export async function activeLifecycle(stateDir: string, peer: string, projectRoo
11
11
  if (reply.t !== "status" || !reply.status || typeof reply.status !== "object" || Array.isArray(reply.status)) return undefined;
12
12
  const projectTools = configuredToolContext(reply.status, peer);
13
13
  // A live older daemon has the fixed seven-stage contract and no optional metadata field.
14
- if (!Object.hasOwn(reply.status, "lifecycleStages")) return { stages: [...SDLC_STAGES], criteria: false, ...projectTools };
14
+ if (!Object.hasOwn(reply.status, "lifecycleStages")) return { stages: [...SDLC_STAGES], criteria: false, audit: false, ...projectTools };
15
15
  const stages: unknown = reply.status.lifecycleStages;
16
16
  if (!Array.isArray(stages) || !stages.length || stages.length > 32 || stages.some(s => typeof s !== "string" || !/^[a-z][a-z0-9_-]{0,47}$/.test(s)) || new Set(stages).size !== stages.length) return undefined;
17
- return { stages: [...stages] as string[], criteria: reply.status.lifecycleCriteria === true, ...projectTools };
17
+ return { stages: [...stages] as string[], criteria: reply.status.lifecycleCriteria === true, audit: reply.status.lifecycleAudit === true, ...(reply.status.lifecycleSurvey === true ? { survey: true as const } : {}), ...(reply.status.taskWait === true ? { wait: true as const } : {}), ...projectTools };
18
18
  } catch { return undefined; }
19
19
  finally { if (client !== active) client?.close(); }
20
20
  }
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, readFileSync } from "node:fs";
1
+ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { basename, dirname, join, resolve } from "node:path";
3
3
  import {
4
4
  CandidateStore, MemoryStore, realPath, memoryHome, memoryProjectKey, openShardStore, readShardedSelection, resolveAlias, resolveProfile, resolveShardProfile,
@@ -8,6 +8,14 @@ import packageJson from "../../package.json";
8
8
 
9
9
  const EXPECTED_AGENT_MEM_VERSION = packageJson.dependencies["@staix/agent-mem"];
10
10
 
11
+ /**
12
+ * Whether a curated store directory holds a derived index. agent-mem names the file per index version (`index.db` through 0.24.0, `index-v4.db` from 0.25.0, a later release its own), and
13
+ * `indexFileName` is not a root export, so any `index.db` or `index-v<N>.db` counts. Read-only; an unreadable directory has none. Never create or probe by opening the file.
14
+ */
15
+ export function memoryIndexExists(memoryDir: string): boolean {
16
+ try { return readdirSync(memoryDir).some(name => /^index(-v\d+)?\.db$/.test(name)); } catch { return false; }
17
+ }
18
+
11
19
  /** Validate metadata located through the actual imported entry, never the hub pin alone. */
12
20
  export function assertAgentMemVersion(metadata: unknown, expectedVersion = EXPECTED_AGENT_MEM_VERSION): string {
13
21
  if (!metadata || typeof metadata !== "object") throw new Error("cannot attest loaded agent-mem version");
@@ -124,6 +124,7 @@ export function classifyMemorySyncFailure(error: unknown): { cause: "declined";
124
124
  if (text === "stopped") return { cause: "stopped" };
125
125
  if (text === "no sync remote: a person sets one with `amem sync --remote <private git url>`"
126
126
  || text === "no generation sync remote configured"
127
+ || text === "no shard sync remote configured"
127
128
  || text === "the sync remote is public; memory syncs only to a private remote"
128
129
  || text === "generation sync remote is invalid"
129
130
  || text === "generation sync requires positively verified private remote visibility"
@@ -4,7 +4,8 @@ import { isNativeModelToken } from "../adapters/model-token.ts";
4
4
  import type { ModelOverrideSelection } from "../adapters/registry-types.ts";
5
5
 
6
6
  export interface ModelOverrideRow { peer: string; model: string; setAt: number; by: "person" }
7
- export type ModelSource = "override" | "instance" | "launch" | "native default" | "native thread default (was override)";
7
+ /** `observed (served|session)` (#1402 T5): the model the last finished turn reported, with its evidence grade; shown only when no override, instance, launch or native baseline model is known. */
8
+ export type ModelSource = "override" | "instance" | "launch" | "native default" | "native thread default (was override)" | "observed (served)" | "observed (session)";
8
9
  export interface RuntimeModelStatus {
9
10
  peer: string;
10
11
  effectiveModel: string | null;
@@ -38,8 +38,13 @@ export class NoWriteTurns {
38
38
 
39
39
 
40
40
  const OWNER_TOOL_EFFECTS = new Set(["hub_task_propose", "hub_task_decline", "hub_task_done", "hub_task_cancel", "hub_task_assign", "hub_task_escalate", "hub_review", "hub_checkpoint", "hub_remember", "hub_memory_correct", "hub_check_start", "hub_check_cancel", "hub_sdlc_record", "hub_plan_review", "hub_backlog_plan", "hub_backlog_pull", "hub_backlog_undo", "hub_backlog_split", "hub_backlog_return_untouched", "hub_release_new", "hub_release_configure", "hub_release_assign", "hub_release_cut", "hub_study_handoff", "hub_experiment_record", "hub_evidence_record"]);
41
+ OWNER_TOOL_EFFECTS.add("hub_survey_report");
42
+ OWNER_TOOL_EFFECTS.add("hub_roadmap_edit");
43
+ OWNER_TOOL_EFFECTS.add("hub_roadmap_triage");
41
44
  /** A read does not prove progress; failed/pending mutations are handled conservatively by the host. */
42
45
  export function ownerToolEffect(op: string, input: Record<string, unknown> | undefined): boolean {
46
+ if (op === "hub_survey_report" && input?.show === true) return false;
47
+ if (op === "hub_roadmap_triage" && input?.list === true) return false;
43
48
  return OWNER_TOOL_EFFECTS.has(op) || op === "hub_task_accept" && !!input?.plan && typeof input.plan === "object" && Object.keys(input.plan).length > 0;
44
49
  }
45
50
 
@@ -32,7 +32,8 @@ export type ConductorLocalAction = typeof CONDUCTOR_LOCAL_ACTIONS[number];
32
32
  export const conductorLocalAction = (value:unknown): value is ConductorLocalAction => typeof value==="string" && (CONDUCTOR_LOCAL_ACTIONS as readonly string[]).includes(value);
33
33
  /** Daemon-authorized labels. Recovery labels pass the initial role check, then require their separate per-operation proof. */
34
34
  export const CONDUCTOR_DAEMON_OPERATIONS = ["roster add","roster remove","stop","queue show","queue resolve","queue discard","settings set","doctor orphans kill","logs","export",
35
- "board import","intake approve","schedule run","schedule pause","schedule resume","goal link","task unassign","guidance probe register","guidance probe start","guidance probe show","guidance probe receipts","guidance probe cancel","restart","upgrade","recovery resume","recovery abort"] as const;
35
+ "sdlc configure",
36
+ "board import","intake approve","schedule run","schedule pause","schedule resume","goal link","task unassign","guidance probe register","guidance probe start","guidance probe show","guidance probe receipts","guidance probe cancel","restart","upgrade","recovery resume","recovery abort","sdlc survey start","sdlc survey show","sdlc audit start","sdlc audit show"] as const;
36
37
  /**
37
38
  * #933: forms whose effect runs in the CLI process itself (local files). The daemon admits and audits them once at the handshake (`admit`),
38
39
  * after the CLI has validated their arguments. Recovery-bearing restart/upgrade forms use the separate source-issued continuation proof.
@@ -71,7 +72,10 @@ function restartOrUpgrade(command: string, args: readonly string[]): "restart" |
71
72
  export function conductorOperation(command:string,args:readonly string[]): ConductorOperation | undefined {
72
73
  const words=args.filter(arg=>!arg.startsWith("--"));
73
74
  const sub=words[0];
75
+ if (command === "sdlc" && args[0] === "survey" && (args[1] === "start" || args[1] === "show")) return `sdlc survey ${args[1]}`;
76
+ if (command === "sdlc" && args[0] === "audit" && (args[1] === "start" || args[1] === "show")) return `sdlc audit ${args[1]}`;
74
77
  if (command === "restart" || command === "upgrade") return restartOrUpgrade(command, args);
78
+ if (command === "sdlc" && args[0] === "configure") return "sdlc configure";
75
79
  if (command === "recovery") {
76
80
  const action = recoveryConductorAction(args);
77
81
  return action ? `recovery ${action}` : undefined;
@@ -126,6 +130,9 @@ export function operationalRequestLabel(value:unknown):string|undefined {
126
130
  return message.op==="orphans"?"doctor orphans kill":message.op==="logs"||message.op==="export"?message.op:"unknown";
127
131
  }
128
132
  if(message.t==="peer_stop")return "stop";
133
+ if(message.t === "sdlc" && message.op === "configure") return "sdlc configure";
134
+ if(message.t==="sdlc" && (message.op==="survey-start"||message.op==="survey-show"))return message.op==="survey-start"?"sdlc survey start":"sdlc survey show";
135
+ if(message.t==="sdlc" && (message.op==="audit-start"||message.op==="audit-show"))return message.op==="audit-start"?"sdlc audit start":"sdlc audit show";
129
136
  if(message.t==="goal_link")return "goal link";
130
137
  if(message.t==="task" && typeof message.op==="string" && Object.hasOwn(CONDUCTOR_TASK_OPS,message.op))return CONDUCTOR_TASK_OPS[message.op];
131
138
  if (typeof message.t === "string" && message.t.startsWith("guidance_probe_")) {
@@ -1,5 +1,7 @@
1
1
  import { isReviewObserverExcluded } from "./memory-policy.ts";
2
2
  import { sanitize } from "./envelope.ts";
3
+ import { MODEL_EVIDENCE } from "./events.ts";
4
+ import { safeModelLabel } from "../omniroute/usage.ts";
3
5
  import type { BusEvent } from "./bus.ts";
4
6
  import { CLASSES, type Task } from "./board.ts";
5
7
 
@@ -16,8 +18,8 @@ const EVENT_FIELDS: Record<string,readonly string[]>={
16
18
  task:["id","event","by","state","owner","reviewer","class","profile","profileClass","role","pii","reason","release","priority","plannedStart","due"],
17
19
  tokens:["peer","n","task","attribution","pii"],
18
20
  usage:["peer","source","id","task","attribution","pii","reasoningTokens","measuredAt","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","totalTokens"],
19
- turn_end:["peer","turn","ms","tokens","files","snapshotMs","task","attribution","pii"],
20
- conduct:["peer","action","task","target"],agent_cli:["peer","command","refused","delegated"],
21
+ turn_end:["peer","turn","ms","tokens","files","snapshotMs","task","attribution","pii","model","modelEvidence"],
22
+ conduct:["peer","action","task","target"],agent_cli:["peer","command","refused","delegated","instructed"],
21
23
  pii_screen:["task","item","label","source","category","miss","ms"],
22
24
  overflow:["id","from","peer"],undeliverable:["id","from","peer"],stale:["id","from","peer","task"],quiet:["id","from","peers"],
23
25
  envelope:["id","from","to","priority","hop","kind","task","bytes","private","dropped"],
@@ -64,6 +66,8 @@ function metadataValue(type:string,key:string,value:unknown):boolean {
64
66
  if(key==="event")return type==="task"?typeof value==="string"&&TASK_EVENTS.has(value):type==="cohort"?oneOf(value,["formed","joined","lifted"]):oneOf(value,["requested","answered","expired","cancelled"]);
65
67
  if(key==="attribution")return oneOf(value,["delivery","single_open","unattributed"]);
66
68
  if(key==="label")return oneOf(value,["pii","clear"]);
69
+ if(key==="model")return safeModelLabel(value)!==undefined;
70
+ if(key==="modelEvidence")return oneOf(value,MODEL_EVIDENCE);
67
71
  if(key==="item")return oneOf(value,["task","summary","review note","handoff","note"]);
68
72
  if(key==="category")return oneOf(value,["name","student_id","phone","address","grade","health","other"]);
69
73
  if(key==="miss")return oneOf(value,["too long","off campus","timeout","unreadable","failed"]);
package/src/hub/peers.ts CHANGED
@@ -115,6 +115,8 @@ export interface PeerAdapter {
115
115
  detachForRoster?(resetMode: PermissionMode): void | Promise<void>;
116
116
  /** Return to the roster after detachForRoster. */
117
117
  resumeFromRoster?(): Promise<void>;
118
+ /** #1402: the model the native surface reported for the turn that just ended, read once at its `turn_end`. Absent or undefined records nothing: unknown stays unknown. */
119
+ observedModel?(): import("./events.ts").ModelObservation | undefined;
118
120
  /** A peer the hub drives itself (Pi, the local worker). It cannot be trusted to rate its own urgency: the bus caps it. */
119
121
  readonly hubNative?: boolean;
120
122
  /** Never handed a delivery: its queue waits for `Bus.pull` (a Claude session that cannot show channel pushes, issue #205). */
@@ -0,0 +1,7 @@
1
+ import { sanitize } from "./envelope.ts";
2
+
3
+ /** Public failure diagnostics stay one bounded line; private callers omit the text entirely. */
4
+ export const PI_FAILURE_TEXT_LIMIT = 300;
5
+ export function piFailureText(reason: string): string {
6
+ return Array.from(sanitize(reason.replace(/[\p{Cc}\p{Cf}\s]+/gu, " ").trim())).slice(0, PI_FAILURE_TEXT_LIMIT).join("");
7
+ }
@@ -29,7 +29,7 @@ export function completePlanInventory(evidence: { head: string; paths: readonly
29
29
  }
30
30
 
31
31
  /** Compare current complete PR file metadata with the current plan; never inspect patches or the filesystem. */
32
- export function planConformance(planPaths: readonly string[] | undefined, evidence: { head: string; paths: readonly string[]; pathsComplete?: boolean; typesComplete?: boolean } | undefined): PlanConformance {
32
+ export function planConformance(planPaths: readonly string[] | undefined, evidence: { head: string; paths: readonly string[]; pathsComplete?: boolean; typesComplete?: boolean } | undefined, outOfScope: readonly string[] = []): PlanConformance {
33
33
  const head = typeof evidence?.head === "string" && /^[a-f0-9]{40}$/.test(evidence.head) ? evidence.head : undefined;
34
34
  const unknown: PlanConformance = { state: "unknown", ...(head ? { head } : {}), outside: [], untouched: [] };
35
35
  const changed = completePlanInventory(evidence);
@@ -40,11 +40,29 @@ export function planConformance(planPaths: readonly string[] | undefined, eviden
40
40
  const path = pathIdentity(raw); if (path === undefined) return unknown;
41
41
  if (!seenPlan.has(path)) { seenPlan.add(path); planned.push(path); }
42
42
  }
43
- const outside = changed.filter(path => !planned.some(plan => covers(plan, path)));
43
+ if (!Array.isArray(outOfScope) || outOfScope.length > 1000) return unknown;
44
+ const excluded: string[] = [];
45
+ for (const raw of outOfScope) { const path = pathIdentity(raw); if (path === undefined) return unknown; excluded.push(path); }
46
+ const outside = changed.filter(path => excluded.some(scope => covers(scope, path)) || !planned.some(plan => covers(plan, path)));
44
47
  const untouched = planned.filter(plan => !changed.some(path => covers(plan, path)));
45
48
  return { state: outside.length ? "departure" : "covered", head, outside, untouched };
46
49
  }
47
50
 
51
+ export interface PlanDrift {
52
+ state: "none" | "changed" | "unknown";
53
+ paths: string[];
54
+ }
55
+
56
+ /** A complete base-to-upstream-endpoint inventory supplied by the host, independent of PR conformance. Never an admission gate. */
57
+ export function planDrift(planPaths: readonly string[] | undefined, changed: readonly string[] | undefined): PlanDrift {
58
+ // Reuse literal path validation and inventory bounds; the dummy head conveys no repository evidence.
59
+ const report = planConformance(planPaths, changed === undefined ? undefined : { head: "0".repeat(40), paths: changed, pathsComplete: true, typesComplete: true });
60
+ if (report.state === "unknown") return { state: "unknown", paths: [] };
61
+ const planned = planPaths!.map(raw => pathIdentity(raw)!);
62
+ const paths = changed!.map(raw => pathIdentity(raw)!).filter(path => planned.some(scope => covers(scope, path)));
63
+ return { state: paths.length ? "changed" : "none", paths };
64
+ }
65
+
48
66
  /** Hash plain plan data without invoking accessors/toJSON; object key order is immaterial, list order is not. */
49
67
  export function planFingerprint(plan: unknown): string {
50
68
  const seen = new Set<object>();
@@ -1,7 +1,7 @@
1
1
  import { HUB, newEnvelope, USER, type Envelope, type PeerId } from "./envelope.ts";
2
2
  import { PreEffectToolRefusal } from "./tool-refusal.ts";
3
3
  import { QuestionWaitDetached } from "./question-detach.ts";
4
- import { parseAsk, QUESTION_SET, type AnswerResult, type QuestionAnswer, type QuestionReason, type QuestionRow, type QuestionStore, type QuestionSurface } from "./questions.ts";
4
+ import { answerProvenance, parseAnswerInstruction, parseAsk, QUESTION_SET, type AnswerResult, type QuestionAnswer, type QuestionReason, type QuestionRow, type QuestionStore, type QuestionSurface } from "./questions.ts";
5
5
 
6
6
  /**
7
7
  * #1053 T3: what `hub_ask` does with the store. The store owns the row and its one terminal transition; this desk owns the waiting call (in memory, never
@@ -11,7 +11,7 @@ import { parseAsk, QUESTION_SET, type AnswerResult, type QuestionAnswer, type Qu
11
11
  */
12
12
 
13
13
  export type AskResult =
14
- | { status: "answered"; questionSet: string; answers: QuestionAnswer[]; answeredBy: "person"; surface: QuestionSurface }
14
+ | { status: "answered"; questionSet: string; answers: QuestionAnswer[]; answeredBy: "person"; surface: QuestionSurface; actor?: string; instructed?: true; provenance?: string }
15
15
  | { status: "pending"; questionSet: string }
16
16
  | { status: "superseded"; questionSet: string }
17
17
  | { status: "cancelled"; questionSet: string; reason: QuestionReason }
@@ -55,9 +55,13 @@ interface Waiter { resolve(result: AskResult): void; timer: ReturnType<typeof se
55
55
  const KEEP_SETTLED_MS = 7 * 86_400_000;
56
56
 
57
57
  /** The late-answer envelope. `from` is the person, `kind` is `answer`, and the set rides in `refs.question` and as the body's first line `reply_to: <set>` (an envelope has no reply field of its own: `reply_to` is the `hub_send` argument that resolves an envelope id). The id is derived from the set so a republish after a crash is dropped by the bus's own dedupe. */
58
+ function answerResult(row: QuestionRow): AskResult {
59
+ const provenance = answerProvenance(row);
60
+ return { status: "answered", questionSet: row.set, answers: row.answers ?? [], answeredBy: "person", surface: row.surface ?? "console", ...(provenance ? { actor: row.person, instructed: true as const, provenance } : {}) };
61
+ }
58
62
  export function answerEnvelope(row: QuestionRow): Envelope {
59
- const result: AskResult = { status: "answered", questionSet: row.set, answers: row.answers ?? [], answeredBy: "person", surface: row.surface ?? "console" };
60
- const body = `reply_to: ${row.set}\nYour question ${row.set} was answered by the person${row.surface ? ` (${row.surface})` : ""}. Use this answer; do not ask it again.\n${JSON.stringify(result)}`;
63
+ const result = answerResult(row);
64
+ const body = `reply_to: ${row.set}\nYour question ${row.set} was ${answerProvenance(row) ?? `answered by the person${row.surface ? ` (${row.surface})` : ""}`}. Use this answer; do not ask it again.\n${JSON.stringify(result)}`;
61
65
  return { ...newEnvelope(USER, body, { to: [row.peer], kind: "answer", priority: "important", refs: { question: row.set }, ...(row.private ? { private: true } : {}) }), id: `answer-${row.set}` };
62
66
  }
63
67
  /** The expiry notice. A hub notice of kind `status`, never an answer: the agent decides for itself. */
@@ -113,7 +117,7 @@ export class QuestionDesk {
113
117
  * The person's answer, from the console role only (the daemon checks the role before it calls this). Of any number of concurrent answers, stops and expiries,
114
118
  * the store's compare-and-set lets exactly one win; a loser is told the row's real terminal state. An answer to a row with no waiting call is the late path.
115
119
  */
116
- answer(set: unknown, raw: unknown, surface: QuestionSurface, person?: string): AnswerResult {
120
+ answer(set: unknown, raw: unknown, surface: QuestionSurface, person?: string, instruction?: string): AnswerResult {
117
121
  if (typeof set !== "string" || !QUESTION_SET.test(set)) return { ok: false, error: "no such question" };
118
122
  const current = this.p.store.get(set);
119
123
  if (current?.state === "open" && this.sessionChanged(current)) {
@@ -121,14 +125,29 @@ export class QuestionDesk {
121
125
  return { ok: false, error: "question is already cancelled", state: "cancelled" };
122
126
  }
123
127
  const late = !this.waiters.has(set);
124
- const result = this.p.store.answer(set, raw, surface, this.p.now(), late, person);
128
+ const result = this.p.store.answer(set, raw, surface, this.p.now(), late, person, instruction);
125
129
  if (!result.ok) return result;
126
130
  this.p.event({ type: "question", set, peer: result.row.peer, event: "answered", latencyMs: this.p.now() - result.row.created, surface, ...(person ? { person } : {}), private: result.row.private });
127
131
  if (late) this.publishOwed(result.row);
128
- else this.settleWait(set, { status: "answered", questionSet: set, answers: result.row.answers ?? [], answeredBy: "person", surface });
132
+ else this.settleWait(set, answerResult(result.row));
129
133
  return result;
130
134
  }
131
135
 
136
+ /** The daemon authenticates the current conductor before this synchronous admission. */
137
+ instructedAnswer(set: unknown, raw: unknown, instruction: unknown, conductor: PeerId): AnswerResult {
138
+ const refuse = (error: string): AnswerResult => ({ ok: false, error: `${error}; the person can answer with ahub console` });
139
+ if (this.closed || this.p.held()) return refuse("recovery or shutdown is holding answers");
140
+ const quote = parseAnswerInstruction(instruction);
141
+ if (!quote.ok) return refuse(quote.error);
142
+ const row = typeof set === "string" ? this.p.store.get(set) : undefined;
143
+ if (!row) return refuse("no such question");
144
+ if (row.peer === conductor) return refuse("the conductor cannot answer its own question");
145
+ if (row.private || this.p.isPrivate(row.peer, row.task)) return refuse("a private question requires the person");
146
+ if (row.state !== "open") return refuse(`question is already ${row.state}`);
147
+ const result = this.answer(set, raw, "conductor", conductor, quote.value);
148
+ return result.ok ? result : { ...result, error: `${result.error}; the person can answer with ahub console` };
149
+ }
150
+
132
151
  /** The person sent these peers a normal message: every open question of each is superseded and its waiting call told. That message is delivered as usual. */
133
152
  supersede(peers: readonly PeerId[]): void {
134
153
  for (const peer of new Set(peers)) for (const row of this.p.store.settleFor(peer, "superseded", "superseded", this.p.now())) {
@@ -13,11 +13,12 @@ export type QuestionState = (typeof QUESTION_STATES)[number];
13
13
  export const QUESTION_REASONS = ["superseded", "stopped", "turn_aborted", "session_changed", "expired", "unattended"] as const;
14
14
  export type QuestionReason = (typeof QUESTION_REASONS)[number];
15
15
  /** Where an answer came from. `acon` is the plugin action of T5; the others are the console's own surfaces. */
16
- export const QUESTION_SURFACES = ["terminal", "console", "dashboard", "acon"] as const;
16
+ export const QUESTION_SURFACES = ["terminal", "console", "dashboard", "acon", "conductor"] as const;
17
17
  export type QuestionSurface = (typeof QUESTION_SURFACES)[number];
18
18
 
19
19
  export const MAX_QUESTIONS = 4, MAX_OPTIONS = 8, MIN_OPTIONS = 2;
20
20
  export const MAX_PROMPT = 500, MAX_LABEL = 80, MAX_DESCRIPTION = 240, MAX_OTHER = 500;
21
+ export const MAX_INSTRUCTION = 500;
21
22
  /** Bounds on rows that can wait at once: one peer cannot fill the inbox, and the whole table stays small. */
22
23
  export const MAX_OPEN_PER_PEER = 8, MAX_OPEN_TOTAL = 64;
23
24
  const ID = /^[A-Za-z0-9_.-]{1,64}$/;
@@ -45,6 +46,9 @@ export interface QuestionRow {
45
46
  surface?: QuestionSurface;
46
47
  /** The console's verified identity (`ActionMeta.identity`) of an answer given in the acon panel; absent for the terminal and the hub's own console, whose person is the local user. */
47
48
  person?: string;
49
+ /** Claimed per-set person instruction; the quote is database-only, never a public projection. */
50
+ instructed?: true;
51
+ instruction?: string;
48
52
  questions: AskQuestion[];
49
53
  answers?: QuestionAnswer[];
50
54
  /** 0 nothing to publish, 1 a hub envelope (late answer or expiry notice) is owed to the peer, 2 it was published. */
@@ -67,6 +71,22 @@ function text(value: unknown, field: string, max: number, optional = false): Par
67
71
  return { ok: true, value: trimmed };
68
72
  }
69
73
 
74
+ export function parseAnswerInstruction(value: unknown): Parsed<string> {
75
+ const parsed = text(value, "instruction quote", MAX_INSTRUCTION);
76
+ return parsed.ok ? { ok: true, value: parsed.value! } : parsed;
77
+ }
78
+
79
+ /** Display attribution only. The stored instruction quote never leaves this module through a view. */
80
+ export function answerProvenance(row: Pick<QuestionRow, "instructed" | "person">): string | undefined {
81
+ return row.instructed && row.person ? `answered by ${row.person} on the person's instruction` : undefined;
82
+ }
83
+
84
+ export function questionView(row: QuestionRow): Omit<QuestionRow, "instruction"> & { provenance?: string } {
85
+ const { instruction: _quote, ...view } = row;
86
+ const provenance = answerProvenance(row);
87
+ return { ...view, ...(provenance ? { provenance } : {}) };
88
+ }
89
+
70
90
  /** The `hub_ask` input, closed and bounded exactly as the spec's Design section. Never echoes a value. */
71
91
  export function parseAsk(input: unknown): Parsed<AskInput> {
72
92
  if (!plain(input) || !closed(input, ["questions", "task"])) return fail("hub_ask takes questions and an optional task");
@@ -152,7 +172,7 @@ export function validateAnswers(questions: readonly AskQuestion[], input: unknow
152
172
 
153
173
  interface RawRow {
154
174
  set_id: string; peer: string; session: string; task: number | null; private: number; state: string; created: number; settled: number | null; reason: string | null;
155
- surface: string | null; person: string | null; questions: string; answers: string | null; envelope: number;
175
+ surface: string | null; person: string | null; instructed: number; instruction: string | null; questions: string; answers: string | null; envelope: number;
156
176
  }
157
177
  function rowOf(raw: RawRow): QuestionRow {
158
178
  return {
@@ -160,6 +180,7 @@ function rowOf(raw: RawRow): QuestionRow {
160
180
  created: raw.created, ...(raw.settled !== null ? { settled: raw.settled } : {}), ...(raw.reason !== null ? { reason: raw.reason as QuestionReason } : {}),
161
181
  ...(raw.surface !== null ? { surface: raw.surface as QuestionSurface } : {}), ...(raw.person ? { person: raw.person } : {}), questions: JSON.parse(raw.questions) as AskQuestion[],
162
182
  ...(raw.answers !== null ? { answers: JSON.parse(raw.answers) as QuestionAnswer[] } : {}), envelope: raw.envelope as 0 | 1 | 2,
183
+ ...(raw.instructed === 1 ? { instructed: true as const, ...(raw.instruction !== null ? { instruction: raw.instruction } : {}) } : {}),
163
184
  };
164
185
  }
165
186
 
@@ -176,6 +197,9 @@ export class QuestionStore {
176
197
  questions TEXT NOT NULL, answers TEXT, envelope INTEGER NOT NULL DEFAULT 0)`);
177
198
  // The verified person of an acon answer: an additive column, so a table made before it is altered in place and an older hub simply never reads it.
178
199
  if (!(this.db.query("PRAGMA table_info(questions)").all() as { name: string }[]).some(column => column.name === "person")) this.db.run("ALTER TABLE questions ADD COLUMN person TEXT");
200
+ const columns = new Set((this.db.query("PRAGMA table_info(questions)").all() as { name: string }[]).map(column => column.name));
201
+ if (!columns.has("instructed")) this.db.run("ALTER TABLE questions ADD COLUMN instructed INTEGER NOT NULL DEFAULT 0");
202
+ if (!columns.has("instruction")) this.db.run("ALTER TABLE questions ADD COLUMN instruction TEXT");
179
203
  this.db.run("CREATE INDEX IF NOT EXISTS questions_by_state ON questions(state, peer)");
180
204
  }
181
205
  close(): void { try { this.db.close(); } catch { /* already closed */ } }
@@ -192,6 +216,10 @@ export class QuestionStore {
192
216
  if (filter.peer) { where.push("peer = ?"); args.push(filter.peer); }
193
217
  return (this.db.query(`SELECT * FROM questions ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY created, set_id LIMIT ?`).all(...args, limit) as RawRow[]).map(rowOf);
194
218
  }
219
+ /** Most recent instructed answers, separate from the open-question shelf. */
220
+ instructedAnswers(limit = MAX_OPEN_TOTAL): QuestionRow[] {
221
+ return (this.db.query("SELECT * FROM questions WHERE state = 'answered' AND instructed = 1 ORDER BY settled DESC, set_id LIMIT ?").all(limit) as RawRow[]).map(rowOf);
222
+ }
195
223
  openCount(peer?: string): number {
196
224
  const row = (peer === undefined ? this.db.query("SELECT COUNT(*) AS n FROM questions WHERE state = 'open'").get() : this.db.query("SELECT COUNT(*) AS n FROM questions WHERE state = 'open' AND peer = ?").get(peer)) as { n: number };
197
225
  return row.n;
@@ -215,14 +243,14 @@ export class QuestionStore {
215
243
  * The one terminal transition: a compare-and-set on `state = 'open'`. Of any number of concurrent callers (a person's answer, a stop, an expiry) exactly one
216
244
  * sees `changes === 1`; every other gets the row's real terminal state back. `late` says no waiting call will carry the result, so an envelope is owed.
217
245
  */
218
- answer(set: string, raw: unknown, surface: QuestionSurface, now: number, late: boolean, person?: string): AnswerResult {
246
+ answer(set: string, raw: unknown, surface: QuestionSurface, now: number, late: boolean, person?: string, instruction?: string): AnswerResult {
219
247
  const row = this.get(set);
220
248
  if (!row) return { ok: false, error: "no such question" };
221
249
  if (row.state !== "open") return { ok: false, error: `question is already ${row.state}`, state: row.state };
222
250
  const parsed = validateAnswers(row.questions, raw);
223
251
  if (!parsed.ok) return { ok: false, error: parsed.error };
224
- const result = this.db.query("UPDATE questions SET state = 'answered', settled = ?, surface = ?, person = ?, answers = ?, envelope = ? WHERE set_id = ? AND state = 'open'")
225
- .run(now, surface, person ?? null, JSON.stringify(parsed.value), late ? 1 : 0, set);
252
+ const result = this.db.query("UPDATE questions SET state = 'answered', settled = ?, surface = ?, person = ?, answers = ?, envelope = ?, instructed = ?, instruction = ? WHERE set_id = ? AND state = 'open'")
253
+ .run(now, surface, person ?? null, JSON.stringify(parsed.value), late ? 1 : 0, instruction === undefined ? 0 : 1, instruction ?? null, set);
226
254
  if (result.changes !== 1) { const now_ = this.get(set); return { ok: false, error: `question is already ${now_?.state ?? "settled"}`, ...(now_ ? { state: now_.state } : {}) }; }
227
255
  return { ok: true, row: this.get(set)! };
228
256
  }
@@ -0,0 +1,34 @@
1
+ /** Read-only account diagnostics. These fields never participate in quota admission or resume. */
2
+ export interface QuotaAccountUsage {
3
+ resetCreditsAvailable?: number;
4
+ resetCreditsExpireAt?: number;
5
+ resetCreditsExpiryKnown?: boolean;
6
+ ordinaryUsageAllowed?: boolean;
7
+ hasCredits?: boolean;
8
+ unlimited?: boolean;
9
+ }
10
+ export interface QuotaAccountReading extends QuotaAccountUsage { at: number; stale: boolean }
11
+
12
+ /** Copy only counts, times and flags, even when an internal caller supplies extra native fields. */
13
+ export function quotaAccountUsage(value: unknown): QuotaAccountUsage {
14
+ const out: QuotaAccountUsage = {};
15
+ if (!value || typeof value !== "object" || Array.isArray(value)) return out;
16
+ const row = value as Record<string, unknown>;
17
+ if (typeof row.resetCreditsAvailable === "number" && Number.isSafeInteger(row.resetCreditsAvailable) && row.resetCreditsAvailable >= 0) {
18
+ out.resetCreditsAvailable = row.resetCreditsAvailable;
19
+ if (typeof row.resetCreditsExpiryKnown === "boolean") out.resetCreditsExpiryKnown = row.resetCreditsExpiryKnown;
20
+ if (out.resetCreditsExpiryKnown === true && typeof row.resetCreditsExpireAt === "number" && Number.isSafeInteger(row.resetCreditsExpireAt)
21
+ && row.resetCreditsExpireAt > 0 && Number.isFinite(new Date(row.resetCreditsExpireAt).getTime())) out.resetCreditsExpireAt = row.resetCreditsExpireAt;
22
+ }
23
+ for (const field of ["ordinaryUsageAllowed", "hasCredits", "unlimited"] as const) if (typeof row[field] === "boolean") out[field] = row[field];
24
+ return out;
25
+ }
26
+
27
+
28
+ /** Public read projection also validates the host timestamp/freshness marker before copying the allowlist. */
29
+ export function quotaAccountReading(value: unknown): QuotaAccountReading | undefined {
30
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
31
+ const row = value as Record<string, unknown>;
32
+ if (typeof row.at !== "number" || !Number.isFinite(row.at) || typeof row.stale !== "boolean") return undefined;
33
+ return { ...quotaAccountUsage(row), at: row.at, stale: row.stale };
34
+ }
@@ -8,6 +8,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "
8
8
  import { isAbsolute, join, resolve } from "node:path";
9
9
  import { types } from "node:util";
10
10
  import { definitionOf } from "../adapters/registry.ts";
11
+ import { adapterCeiling, applyRoleCeiling } from "../adapters/role-eligibility.ts";
11
12
  import type { HubConfig } from "./daemon.ts";
12
13
  import type { ConfigSourceTexts } from "./config-reload.ts";
13
14
  import { conductorPeer } from "./conductor.ts";
@@ -84,15 +85,28 @@ function canonical(value: unknown, depth = 0): string {
84
85
  return `{${Object.keys(fields).sort().filter(key => fields[key]!.value !== undefined).map(key => `${JSON.stringify(key)}:${canonical(fields[key]!.value, depth + 1)}`).join(",")}}`;
85
86
  }
86
87
 
87
- function freshRoles(layers: readonly InstanceConfigLayer[], scope: ReturnType<typeof readInstanceConfig>): Record<string, string[]> {
88
+ /** Exported for the role-eligibility test: the recovery side of the same ceiling the daemon's loader applies. */
89
+ export function freshRoles(layers: readonly InstanceConfigLayer[], scope: ReturnType<typeof readInstanceConfig>): Record<string, string[]> {
88
90
  const roles = structuredClone(DEFAULT_ROLES);
91
+ // #1408 R2: the same ceiling as the daemon's loader, with each peer's effective start mode (a later layer wins), so a recovery never re-grants a conductor the running hub ignores.
92
+ const startModes: Record<string, "tui" | "headless"> = {};
93
+ for (const { raw } of layers) {
94
+ const peers = raw.peers;
95
+ if (peers && typeof peers === "object" && !Array.isArray(peers)) for (const [id, block] of Object.entries(peers as Record<string, unknown>)) {
96
+ const mode = block && typeof block === "object" ? (block as { start_mode?: unknown }).start_mode : undefined;
97
+ if (mode === "tui" || mode === "headless") startModes[id] = mode;
98
+ }
99
+ }
100
+ // #1063: the loader checks at most one conductor on the declared roles after the adapter ceiling and before the eligibility drop; recovery does the same, merged across layers.
101
+ const declared: Record<string, string[]> = structuredClone(DEFAULT_ROLES);
89
102
  for (const { raw } of layers) if (raw.roles !== undefined) {
90
- conductorPeer(raw.roles);
103
+ if (!raw.roles || typeof raw.roles !== "object" || Array.isArray(raw.roles)) throw new Error("roles must be an object of peer role lists");
91
104
  for (const [id, list] of Object.entries(raw.roles as Record<string, string[]>)) {
92
- const definition = definitionOf(id), ceiling = definition?.routing?.allowedRoles;
93
- roles[id] = (ceiling ? list.filter(role => ceiling.includes(role)) : list).filter(role => role !== "planner" || !definition || definition.projection?.plannerEligible === true);
105
+ conductorPeer({ [id]: list });
106
+ declared[id] = adapterCeiling(id, list); roles[id] = applyRoleCeiling(id, list, startModes[id]).roles;
94
107
  }
95
108
  }
109
+ conductorPeer(declared);
96
110
  const configured = Object.fromEntries(scope.catalog.definitions.filter(d => !definitionOf(d.kind)).map(d => [d.kind, [...d.roles]]));
97
111
  const extras = Object.fromEntries(Object.keys(scope.instances ?? {}).map(id => [id, effectiveInstanceRoles(id, scope.instances, roles, scope.catalog)]));
98
112
  return { ...configured, ...roles, ...extras };