@staix/agent-hub 0.38.0 → 0.39.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 (144) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +17 -7
  3. package/docs/adding-an-ai-tool.md +6 -4
  4. package/docs/agent-notes/README.md +16 -0
  5. package/docs/agent-notes/adapters.md +4 -2
  6. package/docs/agent-notes/budget.md +8 -0
  7. package/docs/agent-notes/daemon.md +15 -8
  8. package/docs/agent-notes/local-worker.md +1 -1
  9. package/docs/agent-notes/security-review.md +55 -0
  10. package/docs/agent-notes/tasks.md +15 -4
  11. package/docs/agent-notes/tests.md +3 -2
  12. package/docs/design/adapters.md +51 -0
  13. package/docs/design/agent-hub-architecture.md +29 -1
  14. package/docs/design/task-board.md +151 -5
  15. package/docs/dogfood.md +20 -6
  16. package/docs/events.md +3 -3
  17. package/docs/memory.md +5 -5
  18. package/docs/operations.md +177 -28
  19. package/docs/profiles.md +100 -8
  20. package/docs/quickstart.md +32 -4
  21. package/docs/research.md +6 -3
  22. package/docs/roles.md +52 -0
  23. package/docs/sdlc.md +187 -1
  24. package/docs/security.md +50 -11
  25. package/docs/text-projection.md +1 -0
  26. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  27. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  28. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  29. package/docs/verified.json +48 -25
  30. package/package.json +3 -3
  31. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  32. package/plugins/agent-hub/kimi-hook.js +1953 -460
  33. package/plugins/agent-hub/server.js +2019 -498
  34. package/src/adapters/acp-model-policy.ts +1 -1
  35. package/src/adapters/acp-session-model.ts +35 -0
  36. package/src/adapters/acp.ts +14 -0
  37. package/src/adapters/agy/definition.ts +1 -1
  38. package/src/adapters/agy/hooks.ts +7 -0
  39. package/src/adapters/claude-channel.ts +1 -1
  40. package/src/adapters/claude-implementer.ts +8 -0
  41. package/src/adapters/claude-print-child.ts +26 -2
  42. package/src/adapters/claude-print.ts +4 -0
  43. package/src/adapters/codex-appserver.ts +90 -16
  44. package/src/adapters/codex-review-isolation.ts +2 -0
  45. package/src/adapters/compat.ts +4 -4
  46. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  47. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  48. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  49. package/src/adapters/definitions/builtin-metadata.ts +6 -6
  50. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  51. package/src/adapters/definitions/native-quota.ts +122 -0
  52. package/src/adapters/definitions/native-recovery.ts +3 -0
  53. package/src/adapters/definitions/qwen.ts +1 -1
  54. package/src/adapters/kimi-review.ts +23 -0
  55. package/src/adapters/kimi-wire-usage.ts +39 -16
  56. package/src/adapters/local-worker.ts +6 -3
  57. package/src/adapters/pi-state-model.ts +12 -0
  58. package/src/adapters/pi.ts +22 -0
  59. package/src/adapters/print-result-model.ts +24 -0
  60. package/src/adapters/registry-types.ts +10 -1
  61. package/src/adapters/registry.ts +19 -2
  62. package/src/adapters/reviewer-print.ts +130 -15
  63. package/src/adapters/role-eligibility.ts +99 -0
  64. package/src/adapters/same-directory.ts +16 -0
  65. package/src/cli/agy-mcp.ts +18 -7
  66. package/src/cli/console-state.ts +3 -1
  67. package/src/cli/free-text.ts +20 -0
  68. package/src/cli/handoff-args.ts +1 -1
  69. package/src/cli/help.ts +61 -6
  70. package/src/cli/identity.ts +10 -4
  71. package/src/cli/init-prompt.ts +31 -2
  72. package/src/cli/init-roles.ts +156 -0
  73. package/src/cli/init-settings.ts +24 -2
  74. package/src/cli/init.ts +139 -17
  75. package/src/cli/main.ts +194 -49
  76. package/src/cli/model.ts +1 -1
  77. package/src/cli/output.ts +56 -1
  78. package/src/cli/preview.ts +1 -1
  79. package/src/cli/recovery-launch.ts +114 -0
  80. package/src/cli/recovery-package.ts +14 -7
  81. package/src/cli/recovery-version-preflight.ts +104 -0
  82. package/src/cli/role-doctor.ts +39 -0
  83. package/src/cli/sdlc-output.ts +66 -1
  84. package/src/cli/study-output.ts +54 -0
  85. package/src/cli/study.ts +14 -1
  86. package/src/cli/terminal-recovery.ts +14 -0
  87. package/src/cli/upgrade-presentation.ts +4 -0
  88. package/src/cli/upgrade-restore-state.ts +12 -3
  89. package/src/cli/upgrade-runtime.ts +40 -2
  90. package/src/cli/upgrade.ts +8 -4
  91. package/src/hub/advisor-survey.ts +139 -0
  92. package/src/hub/audit-source.ts +66 -0
  93. package/src/hub/board.ts +479 -14
  94. package/src/hub/budget.ts +54 -4
  95. package/src/hub/conductor.ts +14 -8
  96. package/src/hub/config-apply.ts +2 -1
  97. package/src/hub/config-edit-host.ts +77 -5
  98. package/src/hub/considered-findings.ts +47 -0
  99. package/src/hub/control-client.ts +1 -1
  100. package/src/hub/daemon.ts +343 -58
  101. package/src/hub/deliverable-files.ts +17 -1
  102. package/src/hub/dogfood-profile.ts +3 -2
  103. package/src/hub/events.ts +23 -2
  104. package/src/hub/folder-trigger.ts +11 -4
  105. package/src/hub/hub-tools.ts +88 -16
  106. package/src/hub/kimi-usage.ts +34 -2
  107. package/src/hub/lifecycle-schema.ts +3 -3
  108. package/src/hub/memory-profile.ts +9 -1
  109. package/src/hub/memory-sync-state.ts +1 -0
  110. package/src/hub/model-overrides.ts +2 -1
  111. package/src/hub/no-writes.ts +2 -0
  112. package/src/hub/operational-authority.ts +6 -1
  113. package/src/hub/operational-view.ts +5 -1
  114. package/src/hub/peers.ts +2 -0
  115. package/src/hub/plan-conformance.ts +20 -2
  116. package/src/hub/quota-account.ts +34 -0
  117. package/src/hub/recovery-policy.ts +18 -4
  118. package/src/hub/research-evidence.ts +51 -3
  119. package/src/hub/research.ts +77 -13
  120. package/src/hub/restart.ts +14 -0
  121. package/src/hub/review-budget.ts +88 -0
  122. package/src/hub/review-findings.ts +93 -12
  123. package/src/hub/reviewer-pool-config.ts +6 -2
  124. package/src/hub/reviewer-pool.ts +39 -6
  125. package/src/hub/routing.ts +7 -3
  126. package/src/hub/sdlc-merge.ts +1 -1
  127. package/src/hub/sdlc-queue.ts +14 -4
  128. package/src/hub/sdlc-release.ts +1 -1
  129. package/src/hub/sdlc.ts +10 -6
  130. package/src/hub/security-audit.ts +178 -0
  131. package/src/hub/security-pass.ts +115 -0
  132. package/src/hub/settings.ts +11 -5
  133. package/src/hub/source-read.ts +80 -2
  134. package/src/hub/sources.ts +57 -9
  135. package/src/hub/startup-event-seeds.ts +5 -3
  136. package/src/hub/startup-timing.ts +1 -0
  137. package/src/hub/synthesis-readiness.ts +279 -0
  138. package/src/hub/tasks.ts +1083 -69
  139. package/src/hub/text-projection.ts +11 -1
  140. package/src/memory/capture.ts +2 -1
  141. package/src/ui/index.html +3 -0
  142. package/src/ui/office-model.ts +11 -3
  143. package/src/ui/office-space.ts +50 -30
  144. package/src/ui/plugin.ts +21 -11
package/src/hub/budget.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { quotaAccountUsage, type QuotaAccountUsage, type QuotaAccountReading } from "./quota-account.ts";
1
2
  import { definitionOf, type AdapterDefinition } from "../adapters/registry.ts";
2
3
  import type { Database } from "./db-schema.ts";
3
4
  import { openHubDatabase } from "./db-schema.ts";
@@ -116,6 +117,8 @@ export class Budget {
116
117
  private readonly db: Database;
117
118
  private readonly readings = new Map<PeerId, Map<string, Reading>>();
118
119
  private readonly pausing = new Map<PeerId, object>();
120
+ private readonly accountUsage = new Map<PeerId, QuotaAccountUsage & { at: number }>();
121
+ private readonly pauseObservers = new Map<PeerId, Set<() => void>>();
119
122
  private readonly handingOff = new Set<PeerId>();
120
123
  /** The last reading of each window of an account, for the derived `quota_reset` (see `deriveResets`). */
121
124
  private readonly lastSeen = new Map<PeerId, Map<string, { used: number; resetsAt?: number; at: number }>>();
@@ -199,6 +202,25 @@ export class Budget {
199
202
  return this.readRecord(this.account(peer));
200
203
  }
201
204
 
205
+ /** Observe only the canonical account's existing pause state; observers grant no resume authority. */
206
+ watchPause(peer: PeerId, changed: () => void): () => void {
207
+ if (this.closed) return () => {};
208
+ const key = this.account(peer), observers = this.pauseObservers.get(key) ?? new Set<() => void>();
209
+ observers.add(changed); this.pauseObservers.set(key, observers);
210
+ let watching = true;
211
+ return () => {
212
+ if (!watching) return; watching = false;
213
+ observers.delete(changed);
214
+ if (!observers.size && this.pauseObservers.get(key) === observers) this.pauseObservers.delete(key);
215
+ };
216
+ }
217
+
218
+ private pauseChanged(peer: PeerId): void {
219
+ for (const changed of [...this.pauseObservers.get(this.account(peer)) ?? []]) {
220
+ try { changed(); } catch { /* observational: polling cannot cost a saved pause/resume */ }
221
+ }
222
+ }
223
+
202
224
  private readRecord(peer: PeerId): PauseRecord | undefined {
203
225
  const r = this.db.query("SELECT * FROM budget_pauses WHERE peer = ?").get(peer) as Record<string, any> | null;
204
226
  return r ? { peer: r.peer, since: r.since, resetsAt: r.resets_at, reason: r.reason, summary: r.summary, handedOff: !!r.handed_off, moved: JSON.parse(r.moved) } : undefined;
@@ -227,13 +249,14 @@ export class Budget {
227
249
  continue;
228
250
  }
229
251
  this.hooks.pause(r.peer);
252
+ this.pauseChanged(r.peer);
230
253
  this.hooks.notify(`budget: ${r.peer} is still paused (${r.reason}), resumes ${new Date(r.resetsAt).toLocaleTimeString()}`);
231
254
  }
232
255
  }
233
256
 
234
257
  /** `hard`: the peer cannot run another turn (its provider refused one), so there is nobody to ask for a checkpoint. */
235
258
  /** `at`: when the numbers were measured, for sources that arrive through a file (a leftover file is not a fresh reading). */
236
- report(peer: PeerId, windows: UsageWindow[], hard = false, at = this.now()): void {
259
+ report(peer: PeerId, windows: UsageWindow[], hard = false, at = this.now(), accountUsage?: QuotaAccountUsage): void {
237
260
  // Execution-budget instrumentation is independent of native quota accounting.
238
261
  // Explicit quota exemption or absent budget metadata exempts registered kinds; external ids keep accounting.
239
262
  const reporter = peer;
@@ -241,6 +264,10 @@ export class Budget {
241
264
  const resolve = this.hooks.definitionOf ?? definitionOf;
242
265
  const adapter = resolve(reporter) ?? resolve(peer);
243
266
  if (reporter === "user" || reporter === "hub" || peer === "user" || peer === "hub" || adapter && (!adapter.budget || adapter.budget.quotaExempt === true) || this.closed) return;
267
+ if (accountUsage !== undefined && Number.isFinite(at)) {
268
+ const prior = this.accountUsage.get(peer);
269
+ if (!prior || at >= prior.at) this.accountUsage.set(peer, { ...quotaAccountUsage(accountUsage), at });
270
+ }
244
271
  // An override ignores soft readings, not a provider that has actually refused another turn.
245
272
  if (hard && this.ignoreUntil.delete(peer)) {
246
273
  try { this.hooks.notify(`budget: ${peer} provider refused again; budget override ended`); } catch { /* a notice cannot prevent the hard pause */ }
@@ -397,6 +424,7 @@ export class Budget {
397
424
  if (open) this.writeLedger({ type: "budget_resume", peer, reason: "replaced by a new pause after its window reset", window: reasonWindow(open.reason), resetsAt: open.resetsAt, by: "hub" });
398
425
  this.writeLedger({ type: "budget_pause", peer, reason, window: worst.id, resetsAt, by: "hub" });
399
426
  this.hooks.pause(peer);
427
+ this.pauseChanged(peer);
400
428
  this.hooks.notify(`budget: ${peer} paused, ${reason}; resumes ${new Date(resetsAt).toLocaleTimeString()}${summary ? "; checkpoint received" : hard ? "; hard limit, no checkpoint" : "; no checkpoint"}`);
401
429
  await this.finishHandoff(peer, summary);
402
430
  } finally {
@@ -481,6 +509,7 @@ export class Budget {
481
509
  // before it touches anything that was waiting for it.
482
510
  this.hooks.resumed(record);
483
511
  this.hooks.resume(peer);
512
+ this.pauseChanged(peer);
484
513
  this.hooks.notify(`budget: ${peer} resumed (${why})`);
485
514
  }
486
515
 
@@ -499,25 +528,46 @@ export class Budget {
499
528
  }));
500
529
  }
501
530
 
502
- status(): Record<PeerId, { windows: (Reading & { stale: boolean; superseded: boolean })[]; paused?: { reason: string; resetsAt: number; since: number } }> {
531
+ private readonly reviewerResetProof = new Map<string, { since: number; resetsAt: number }>();
532
+ /** Actual pause, with reset only when every currently blocking window proves the saved timestamp. Fallbacks are not reset evidence. */
533
+ reviewerPause(peer: PeerId): { resetsAt?: number } | undefined {
534
+ const paused = this.record(peer);
535
+ if (!paused) return;
536
+ const key = this.account(peer), blocking = this.gating(peer).filter(row => row.used >= this.cfg.gate);
537
+ if (blocking.length) {
538
+ const known = blocking.every(row => row.resetsAt !== undefined && row.resetsAt > this.now())
539
+ && Math.max(...blocking.map(row => row.resetsAt!)) === paused.resetsAt;
540
+ if (known) this.reviewerResetProof.set(key, { since: paused.since, resetsAt: paused.resetsAt });
541
+ else this.reviewerResetProof.delete(key);
542
+ }
543
+ const proof = this.reviewerResetProof.get(key);
544
+ // Keep the same pause's proven reset until Budget acts, including a phase-late expiry tick; never resume authority.
545
+ return proof?.since === paused.since && proof.resetsAt === paused.resetsAt
546
+ ? { resetsAt: proof.resetsAt } : {};
547
+ }
548
+
549
+ status(): Record<PeerId, { windows: (Reading & { stale: boolean; superseded: boolean })[]; paused?: { reason: string; resetsAt: number; since: number }; accountUsage?: QuotaAccountReading }> {
503
550
  const staleMs = this.cfg.stale_min * 60_000;
504
551
  const peers = new Set([...this.readings.keys(), ...this.records().map((r) => r.peer)]);
505
552
  return Object.fromEntries(
506
553
  [...peers].map((peer) => {
507
- const open = this.record(peer);
554
+ const open = this.record(peer), accountUsage = this.accountUsage.get(peer);
508
555
  const fresh = new Set(this.fresh(peer)), used = new Set(this.gating(peer));
509
556
  // `superseded`: fresh, but information only: a measurement of the same account outranks it (the hub count under a native or manual reading).
510
557
  // The reading the gate acts on is listed first (then the information-only ones, then the stale), so a client that looks a window up by id, as every
511
558
  // client did before kinds existed, lands on the effective number and not on the one it replaced.
512
559
  const rank = (r: Reading) => (used.has(r) ? 0 : fresh.has(r) ? 1 : 2);
513
560
  const ordered = [...(this.readings.get(peer)?.values() ?? [])].sort((a, b) => rank(a) - rank(b));
514
- return [peer, { windows: ordered.map((r) => ({ ...r, stale: this.now() - r.at > staleMs, superseded: fresh.has(r) && !used.has(r) })), ...(open ? { paused: { reason: open.reason, resetsAt: open.resetsAt, since: open.since } } : {}) }];
561
+ return [peer, { windows: ordered.map((r) => ({ ...r, stale: this.now() - r.at > staleMs, superseded: fresh.has(r) && !used.has(r) })), ...(open ? { paused: { reason: open.reason, resetsAt: open.resetsAt, since: open.since } } : {}),
562
+ ...(open && accountUsage ? { accountUsage: { ...quotaAccountUsage(accountUsage), at: accountUsage.at, stale: this.now() - accountUsage.at > staleMs } } : {}) }];
515
563
  }),
516
564
  );
517
565
  }
518
566
 
519
567
  close(): void {
520
568
  this.closed = true;
569
+ this.pauseObservers.clear();
570
+ this.accountUsage.clear();
521
571
  this.db.close();
522
572
  }
523
573
  }
@@ -1,4 +1,5 @@
1
- import { definitionOf, type KindMap, type ProjectAdapterCatalog } from "../adapters/registry.ts";
1
+ import { quotaAccountReading, type QuotaAccountReading } from "./quota-account.ts";
2
+ import { conductorStartText, definitionOf, type KindMap, type ProjectAdapterCatalog } from "../adapters/registry.ts";
2
3
  import type { Database } from "./db-schema.ts";
3
4
  import { openHubDatabase } from "./db-schema.ts";
4
5
  import type { Task } from "./board.ts";
@@ -20,7 +21,7 @@ export function conductorProgressSink(record: (event: HubEvent) => void, feed: P
20
21
  }
21
22
 
22
23
  /** What `Budget.status` returns, with the fields added after it optional so an older shape still projects. */
23
- type PublicBudgetStatus = Record<string, { windows: (Omit<ReturnType<Budget["status"]>[string]["windows"][number], "kind" | "superseded"> & { kind?: WindowKind; superseded?: boolean })[]; paused?: ReturnType<Budget["status"]>[string]["paused"] }>;
24
+ type PublicBudgetStatus = Record<string, { windows: (Omit<ReturnType<Budget["status"]>[string]["windows"][number], "kind" | "superseded"> & { kind?: WindowKind; superseded?: boolean })[]; paused?: ReturnType<Budget["status"]>[string]["paused"]; accountUsage?: QuotaAccountReading }>;
24
25
  export function publicPeerBudget(status: PublicBudgetStatus, nameable: (text: string) => boolean): Record<string, unknown> {
25
26
  return Object.fromEntries(Object.entries(status).map(([peer, value]) => [peer, {
26
27
  windows: value.windows.map(window => ({ id: window.id, kind: windowKind(window), used: window.used, at: window.at, stale: window.stale, ...(window.superseded ? { superseded: true } : {}),
@@ -29,6 +30,7 @@ export function publicPeerBudget(status: PublicBudgetStatus, nameable: (text: st
29
30
  source: nameable(window.source) ? window.source : "[quota source withheld]",
30
31
  })),
31
32
  ...(value.paused ? { paused: { since: value.paused.since, resetsAt: value.paused.resetsAt, reason: "quota" } } : {}),
33
+ ...(value.paused && quotaAccountReading(value.accountUsage) ? { accountUsage: quotaAccountReading(value.accountUsage) } : {}),
32
34
  }]));
33
35
  }
34
36
 
@@ -108,23 +110,24 @@ export class ConductorHolds {
108
110
  close(): void { this.db.close(); }
109
111
  }
110
112
 
111
- export type ConductorStart = { peer: string; mode: "headless" } | { peer: "claude" | "codex" | "pi"; mode: "tui"; command: string };
113
+ /** A start the conductor asked for: the peer's own start mode decides, and a terminal start carries the command the hub itself previews (#1408 R5: any kind whose definition starts in a terminal, not a fixed three). */
114
+ export type ConductorStart = { peer: string; mode: "headless" } | { peer: string; mode: "tui"; command: string };
112
115
  /**
113
116
  * What a conductor's start of `peer` is (#269): the peer's own start mode, which a person sets. A `mode` argument may
114
117
  * only repeat it. Preview commands come from the same launch planner the CLI uses, never caller-supplied shell text.
115
118
  */
116
- export function conductorStart(peer: unknown, mode: unknown, preview: (peer: "claude" | "codex" | "pi") => string, preEffect: boolean, startMode: (peer: string) => StartMode, instances?: KindMap, adapterCatalog?: ProjectAdapterCatalog): ConductorStart {
119
+ export function conductorStart(peer: unknown, mode: unknown, preview: (peer: string) => string, preEffect: boolean, startMode: (peer: string) => StartMode, instances?: KindMap, adapterCatalog?: ProjectAdapterCatalog): ConductorStart {
117
120
  const refuse = (text: string) => new (preEffect ? PreEffectToolRefusal : Error)(text);
118
121
  if (mode !== undefined && mode !== "headless" && mode !== "tui") throw refuse("mode must be headless or tui");
119
122
  const adapter = typeof peer === "string" ? (adapterCatalog?.definitionOf ?? definitionOf)(peer, instances) : undefined;
120
- if (typeof peer !== "string" || !adapter?.start.conductorStartable) throw refuse("only claude, codex, kimi, pi and local, plus opt-in qwen/jcode, may be started by the conductor");
123
+ if (typeof peer !== "string" || !adapter?.start.conductorStartable) throw refuse(conductorStartText().refusal);
121
124
  const selected = peer;
122
125
  const extra = adapter.kind !== selected;
123
126
  if (extra && !supportsHeadlessInstances(adapter)) throw refuse(`${peer}: this native transport does not support extra headless instances`);
124
127
  const own = startMode(selected);
125
128
  if (extra && own !== "headless") throw refuse(`${peer}: extra instances require headless mode in I2`);
126
129
  if (mode !== undefined && mode !== own) throw refuse(`${peer} starts ${own} here; a person sets a start mode (ahub settings), the conductor cannot choose one`);
127
- return own === "tui" ? { peer: peer as "claude" | "codex" | "pi", mode: "tui", command: preview(peer as "claude" | "codex" | "pi") } : { peer: selected, mode: "headless" };
130
+ return own === "tui" ? { peer: selected, mode: "tui", command: preview(selected) } : { peer: selected, mode: "headless" };
128
131
  }
129
132
 
130
133
  const numberOrNull = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null;
@@ -177,7 +180,7 @@ export interface ConductorHooks {
177
180
  /** These callbacks must call Tasks, never Board.update. */
178
181
  assign(actor: string, id: number, peer: string, role?: TaskAssignmentRole): Promise<unknown>;
179
182
  escalate(actor: string, id: number): Promise<unknown>;
180
- preview(peer: "claude" | "codex" | "pi"): string;
183
+ preview(peer: string): string;
181
184
  /** The mode a start of this peer takes: a person's setting. */
182
185
  startMode(peer: string): StartMode;
183
186
  /** Starts the peer in that mode: headless at once, or its fixed command in a terminal; throws with the command to run by hand when no terminal can be opened. */
@@ -245,7 +248,10 @@ export class Conductor {
245
248
  if (id === undefined) throw new PreEffectToolRefusal("id must be a positive integer");
246
249
  const task = this.hooks.task(id);
247
250
  if (!task) throw new PreEffectToolRefusal(`no task #${args.id}`);
248
- if (task.state === "backlog") throw new PreEffectToolRefusal("backlog is read through planner tools, not conductor task tools");
251
+ // #1430: `hub_task_assign` on a backlog card names the planner route out, not only that planner tools read backlog.
252
+ if (task.state === "backlog") throw new PreEffectToolRefusal(tool === "hub_task_assign"
253
+ ? "backlog is read through planner tools: reserve a peer with hub_backlog_plan fields.reserved, then pull again"
254
+ : "backlog is read through planner tools, not conductor task tools");
249
255
  if (tool === "hub_task_show") { const result = publicConductorTask(task, this.hooks.publicView); emit({ task: task.id }); return result; }
250
256
  if (tool === "hub_task_assign") {
251
257
  const peer = peerId(args.peer, true);
@@ -238,7 +238,8 @@ const schema: Record<string, Check> = {
238
238
  terminal: (v, k) => { block({ open: strings })(v, k); terminalTemplate(object(v, k).open); },
239
239
  start: (v, k) => { block({ agents: strings })(v, k); if (object(v, k).agents !== undefined) checkStartAgents(object(v, k).agents, `${k}.agents`); },
240
240
  limits: block({ sender_per_min: number(0), pair_per_min: number(0), important_per_hour: number(0), repeat_window_s: number(0) }),
241
- review: block({ adaptive: bool, min_reviews: number(1, Number.MAX_SAFE_INTEGER, true), pool: v => { reviewerPoolConfig({ pool: v }, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS); }, rerotate: bool, same_family: words(["fallback", "never"]) }), recovery: block({ auto_resume_after_crash: bool, reconnect_wait_s: operationalNumberCheck("recovery.reconnect_wait_s"), unmanaged_reconnect_wait_s: operationalNumberCheck("recovery.unmanaged_reconnect_wait_s"), control_timeout_s: operationalNumberCheck("recovery.control_timeout_s"), shutdown_wait_s: operationalNumberCheck("recovery.shutdown_wait_s"), terminal_idle_wait_s: operationalNumberCheck("recovery.terminal_idle_wait_s") }),
241
+ review: block({ adaptive: bool, min_reviews: number(1, Number.MAX_SAFE_INTEGER, true), pool: v => { reviewerPoolConfig({ pool: v }, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS); }, rerotate: bool, same_family: words(["fallback", "never"]),
242
+ gate: value => { reviewerPoolConfig({ gate: value }, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS); }, unknown_quota: value => { reviewerPoolConfig({ unknown_quota: value }, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS); }, max_minutes: value => { reviewerPoolConfig({ max_minutes: value }, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS); } }), recovery: block({ auto_resume_after_crash: bool, reconnect_wait_s: operationalNumberCheck("recovery.reconnect_wait_s"), unmanaged_reconnect_wait_s: operationalNumberCheck("recovery.unmanaged_reconnect_wait_s"), control_timeout_s: operationalNumberCheck("recovery.control_timeout_s"), shutdown_wait_s: operationalNumberCheck("recovery.shutdown_wait_s"), terminal_idle_wait_s: operationalNumberCheck("recovery.terminal_idle_wait_s") }),
242
243
  capabilities: map(strings), invocation: block({ share: map(map(() => {})), timeout_s: number(10, 86_400, true) }), coordination: words(["advisory", "turn-free"]), experiments: block({ stale_notices: words(["drop", "deliver"]) }),
243
244
  };
244
245
  export const SCHEMA_KEYS: readonly string[] = Object.freeze(Object.keys(schema));
@@ -1,6 +1,10 @@
1
1
  import { configBackups, parseConfigEditRequest, viewRevisions, planConfigEdit, writeConfigEdit, type CandidateCheck, type ConfigEditPlan } from "./config-edit.ts";
2
2
  import { configTier, maskTier3, TIER2_INSTANCE_FIELDS, TIER3_INSTANCE_FIELDS, TIER3_PREFIXES, type ConfigEditFile } from "./config-tier.ts";
3
3
  import type { HubEvent } from "./events.ts";
4
+ import { types } from "node:util";
5
+ import { sdlcConfig } from "./sdlc.ts";
6
+ import { USER } from "./envelope.ts";
7
+ import { VERSION } from "../version.ts";
4
8
 
5
9
  /**
6
10
  * #689: the daemon's side of structural config edits. Everything the daemon decides is here, with its ports injected, so the
@@ -17,7 +21,8 @@ export interface ConfigEditHost {
17
21
  held: () => string | undefined;
18
22
  /** Publishes one changed key through the daemon's only reload path, scoped to it. */
19
23
  reload: (authority: EditAuthority, key: string) => Promise<Record<string, unknown>>;
20
- event: (event: Extract<HubEvent, { type: "config_edit" }>) => void;
24
+ /** Legacy callbacks may return void; the instructed path requires true as its durable result acknowledgement. */
25
+ event: (event: Extract<HubEvent, { type: "config_edit" }>) => unknown;
21
26
  notify: (text: string) => void;
22
27
  /** Called after a write so status.json and the console snapshot show what is now pending. */
23
28
  changed: () => void;
@@ -33,6 +38,10 @@ export interface ConfigEditHost {
33
38
  declared: () => Record<string, Record<string, unknown>>;
34
39
  /** config.local.json as the file holds it now, parsed once per call (`{}` when it is missing or unreadable). Never sent anywhere: it is read for what is set, never shown. */
35
40
  localConfig: () => Record<string, unknown>;
41
+ /** Host-owned current unique conductor, excluding private input. Not a request field. */
42
+ conductor?: () => string | undefined;
43
+ /** Durable intent must exist before this narrow conductor write. Values never enter it. */
44
+ recordSdlcInstruction?: (by: string, paths: string[]) => boolean;
36
45
  }
37
46
  export interface ConfigEditView {
38
47
  revisions: Record<ConfigEditFile, string>;
@@ -125,7 +134,8 @@ export function createConfigEditor(host: ConfigEditHost) {
125
134
  diff: plan.diff.map(row => ({ path: row.path, tier: row.tier, applies: row.applies, before: maskTier3(row.path.split("."), row.before) ?? null, after: maskTier3(row.path.split("."), row.after) ?? null })),
126
135
  ...(plan.tier === 3 ? { confirm: plan.tier3Keys[0], warning: "this runs code with the daemon's rights, or chooses where secrets are read from" } : {}) };
127
136
  }
128
- async function apply(raw: unknown, authority: EditAuthority, confirm?: unknown, rawReason?: unknown): Promise<Record<string, unknown>> {
137
+ async function applyInternal(raw: unknown, authority: EditAuthority, confirm?: unknown, rawReason?: unknown,
138
+ instruction?: { by: string; current: () => void }): Promise<Record<string, unknown>> {
129
139
  let reason: string | undefined;
130
140
  if (rawReason !== undefined) {
131
141
  if (typeof rawReason !== "string" || !rawReason.trim() || Buffer.byteLength(rawReason) > REASON_BYTES) return { ok: false, error: `reason must contain 1..${REASON_BYTES} UTF-8 bytes` };
@@ -135,11 +145,33 @@ export function createConfigEditor(host: ConfigEditHost) {
135
145
  if (!result.ok) return { ok: false, error: result.error, ...(result.field ? { field: result.field } : {}) };
136
146
  const { plan } = result;
137
147
  if (plan.tier === 3 && confirm !== plan.tier3Keys[0]) return { ok: false, error: `${plan.tier3Keys[0]} runs code with the daemon's rights or locates secrets: type the key name to confirm; nothing was written`, confirm: plan.tier3Keys[0] };
148
+ if (instruction) {
149
+ try {
150
+ instruction.current();
151
+ const before = sdlcConfig(plan.before === null ? undefined : Bun.TOML.parse(plan.before), VERSION);
152
+ if (plan.request.file !== "sdlc.toml" || plan.diff.some(row => !["sdlc.mode", "sdlc.required_checks"].includes(row.path)))
153
+ throw new Error("only mode and required_checks may change through sdlc configure");
154
+ if (before.mode === "enforce" || host.runningSdlc().mode === "enforce")
155
+ throw new Error("enforce remains person-only; ask the person to edit .agenthub/sdlc.toml");
156
+ instruction.current();
157
+ let retained = false;
158
+ try { retained = host.recordSdlcInstruction?.(instruction.by, plan.diff.map(row => row.path)) === true; } catch { /* no write without a retained intent */ }
159
+ if (!retained)
160
+ throw new Error("SDLC instruction audit unavailable; nothing was written");
161
+ instruction.current();
162
+ } catch (error) { return { ok: false, error: error instanceof Error ? error.message : "SDLC configuration authority unavailable; nothing was written" }; }
163
+ }
138
164
  let written: ReturnType<typeof writeConfigEdit>;
139
165
  try { written = writeConfigEdit(host.cwd, host.stateDir, plan); }
140
166
  catch (error) { return { ok: false, error: `${(error as Error).message}; nothing was changed` }; }
141
- const source = authority === "terminal" ? "terminal" as const : "dashboard" as const;
142
- host.event({ type: "config_edit", file: plan.request.file, paths: written.paths, fileBefore: written.fileBefore, fileAfter: written.fileAfter, tier: plan.tier, by: "person", source, ...(written.backup ? { backup: written.backup } : {}), ...(reason ? { reason } : {}) });
167
+ const source = instruction && instruction.by !== USER ? "conductor" as const : authority === "terminal" ? "terminal" as const : "dashboard" as const;
168
+ try {
169
+ const retained = host.event({ type: "config_edit", file: plan.request.file, paths: written.paths, fileBefore: written.fileBefore, fileAfter: written.fileAfter, tier: plan.tier, by: instruction?.by ?? "person", source, ...(instruction ? { instructionClaim: "person_direct_instruction" as const } : {}), ...(written.backup ? { backup: written.backup } : {}), ...(reason ? { reason } : {}) });
170
+ if (instruction && retained !== true) throw new Error("SDLC result audit was not retained");
171
+ } catch (error) {
172
+ if (!instruction) throw error;
173
+ return { ok: false, saved: true, error: "SDLC configuration was saved after its instruction intent, but the result audit failed; inspect the config and event log before retrying" };
174
+ }
143
175
  try { host.notify(`config edit: ${plan.request.file} ${plan.diff.map(row => row.path).join(", ")} (${source})`); } catch { /* the write stands */ }
144
176
  const settled = () => { try { host.changed(); } catch { /* the write stands; the next status write shows it */ } };
145
177
  if (plan.request.file === "sdlc.toml") { settled(); return { ok: true, saved: true, ...(written.backup ? { backup: written.backup } : {}), lines: diffText(plan), text: `sdlc.toml written; the lifecycle is read once at hub start: restart pending`, restartPending: allPending() }; }
@@ -153,7 +185,47 @@ export function createConfigEditor(host: ConfigEditHost) {
153
185
  if (failures.length) return { ok: false, saved: true, error: `saved, but not published: ${failures.join("; ")}; run ahub settings reload to review it`, ...(written.backup ? { backup: written.backup } : {}) };
154
186
  return { ok: true, saved: true, ...(written.backup ? { backup: written.backup } : {}), lines: diffText(plan), text: `config.local.json written: ${plan.diff.map(row => row.path).join(", ")}${plan.diff.some(row => row.applies === "restart") ? "; restart pending" : ""}`, restartPending: allPending() };
155
187
  }
156
- return { view, preview, apply, pendingRestart };
188
+ const apply = (raw: unknown, authority: EditAuthority, confirm?: unknown, reason?: unknown) => applyInternal(raw, authority, confirm, reason);
189
+ /** #1432: cooperative own-session instruction claim, never consent inferred from a task or file. */
190
+ async function configureSdlc(by: string, input: unknown, current: () => void): Promise<Record<string, unknown>> {
191
+ const guard = () => {
192
+ current();
193
+ const conductor = host.conductor?.();
194
+ if (by !== USER && (!by || !conductor || conductor !== by)) throw new Error("only the person or current unique conductor may configure SDLC");
195
+ const held = host.held(); if (held) throw new Error(`${held} is holding config edits`);
196
+ };
197
+ try {
198
+ guard();
199
+ if (!input || typeof input !== "object" || types.isProxy(input) || Array.isArray(input)
200
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(input)) || Object.getOwnPropertySymbols(input).length)
201
+ throw new Error("sdlc configure accepts mode, required_checks and an explicit instruction claim");
202
+ const fields = Object.getOwnPropertyDescriptors(input), values: Record<string, unknown> = Object.create(null);
203
+ for (const [key, field] of Object.entries(fields)) {
204
+ if (!["mode", "required_checks", "instructionClaim"].includes(key) || !Object.hasOwn(field, "value") || !field.enumerable)
205
+ throw new Error("sdlc configure accepts only mode and required_checks; protected settings remain person-only");
206
+ values[key] = field.value;
207
+ }
208
+ if (values.instructionClaim !== true) throw new Error("sdlc configure requires the person's explicit instruction in this session; relays, tasks and files do not qualify");
209
+ if (values.mode !== undefined && values.mode !== "off" && values.mode !== "advise")
210
+ throw new Error("sdlc.mode: this path accepts off or advise; ask the person to edit .agenthub/sdlc.toml for enforce");
211
+ if (Object.hasOwn(values, "required_checks")) {
212
+ const checks = values.required_checks;
213
+ const invalidChecks = () => ({ ok: false, field: "sdlc.required_checks", error: "sdlc.required_checks: expected a list of check names" });
214
+ if (!Array.isArray(checks) || types.isProxy(checks) || Object.getPrototypeOf(checks) !== Array.prototype || Object.getOwnPropertySymbols(checks).length) return invalidChecks();
215
+ const fields = Object.getOwnPropertyDescriptors(checks);
216
+ if (Object.keys(fields).length !== checks.length + 1 || Object.entries(fields).some(([key, field]) => key !== "length" && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= checks.length || !Object.hasOwn(field, "value") || !field.enumerable))) return invalidChecks();
217
+ try { values.required_checks = sdlcConfig({ required_checks: checks }, VERSION).requiredChecks; }
218
+ catch (error) { return { ok: false, field: "sdlc.required_checks", error: error instanceof Error ? error.message : "sdlc.required_checks: invalid list of check names" }; }
219
+ }
220
+ const set = ["mode", "required_checks"].filter(key => Object.hasOwn(values, key)).map(key => ({ path: [key], value: values[key] }));
221
+ if (!set.length) throw new Error("sdlc configure needs mode or required_checks");
222
+ guard();
223
+ const raw = { file: "sdlc.toml", revision: viewRevisions(host.cwd)["sdlc.toml"], set };
224
+ const result = await applyInternal(raw, "terminal", undefined, undefined, { by, current: guard });
225
+ return result.ok === true ? { ...result, by, instructionClaim: "person_direct_instruction" } : result;
226
+ } catch (error) { return { ok: false, error: error instanceof Error ? error.message : "SDLC configuration unavailable; nothing was written" }; }
227
+ }
228
+ return { view, preview, apply, configureSdlc, pendingRestart };
157
229
  }
158
230
 
159
231
  /** The leaf keys a plan changed, so each is published through its own scoped reload. */
@@ -0,0 +1,47 @@
1
+ import { surveyArray, surveyObject, surveyPass, surveyPath, surveyFindingId, surveyText, type SurveyPass } from "./advisor-survey.ts";
2
+ import { positionalFindingId } from "./review-findings.ts";
3
+
4
+ export interface ConsideredEntry {
5
+ repo: string; id: string; pass: SurveyPass; paths: string[]; reason: string; ref?: string;
6
+ source: { task: number; created: number; kind: "review" | "audit" | "survey" }; withheld?: true;
7
+ }
8
+ export interface ConsideredDiff { repo: string; base: string; head: string; complete: boolean; paths: readonly string[] }
9
+ export interface ConsideredMatch { status: "applicable" | "changed" | "unknown" | "different"; applicablePaths: string[] }
10
+ const invalid = (): never => { throw new Error("invalid considered finding"); };
11
+ const sha = (value: unknown): string => typeof value === "string" && /^[a-f0-9]{40}$/.test(value) ? value : invalid();
12
+ const integer = (value: unknown, min: number): number => typeof value === "number" && Number.isSafeInteger(value) && value >= min ? value : invalid();
13
+ export function parseConsideredEntry(input: unknown): ConsideredEntry {
14
+ const row = surveyObject(input, ["repo", "id", "pass", "paths", "reason", "ref", "source", "withheld"]);
15
+ const source = surveyObject(row.source, ["task", "created", "kind"]), paths = surveyArray(row.paths, 64).map(surveyPath);
16
+ if (new Set(paths).size !== paths.length || row.withheld !== undefined && row.withheld !== true
17
+ || source.kind !== "review" && source.kind !== "audit" && source.kind !== "survey") return invalid();
18
+ const entry: ConsideredEntry = { repo: surveyText(row.repo, 1024), id: surveyFindingId(row.id), pass: surveyPass(row.pass), paths,
19
+ reason: surveyText(row.reason), ...(row.ref === undefined ? {} : { ref: sha(row.ref) }), source: { task: integer(source.task, 1), created: integer(source.created, 0), kind: source.kind },
20
+ ...(row.withheld === true ? { withheld: true } : {}) };
21
+ if (Buffer.byteLength(JSON.stringify(entry)) > 64 * 1024) return invalid();
22
+ return entry;
23
+ }
24
+ const overlaps = (a: string, b: string) => a === b || a.startsWith(b + "/") || b.startsWith(a + "/");
25
+ /** Host supplies the complete base-to-current changed-name inventory. Unknown is never unchanged. */
26
+ export function consideredFindingMatch(input: unknown, context: { repo: string; id: string; pass: SurveyPass; currentRef: string; diff?: ConsideredDiff }): ConsideredMatch {
27
+ const entry = parseConsideredEntry(input), different: ConsideredMatch = { status: "different", applicablePaths: [] }, unknown: ConsideredMatch = { status: "unknown", applicablePaths: [] };
28
+ if (entry.repo !== context.repo || entry.id !== context.id || entry.pass !== context.pass || positionalFindingId(entry.id) || positionalFindingId(context.id)) return different;
29
+ try {
30
+ sha(context.currentRef);
31
+ if (!entry.ref || !entry.paths.length) return unknown;
32
+ if (entry.ref === context.currentRef) return { status: "applicable", applicablePaths: [...entry.paths] };
33
+ const diff = surveyObject(context.diff, ["repo", "base", "head", "complete", "paths"]);
34
+ if (diff.repo !== entry.repo || diff.base !== entry.ref || diff.head !== context.currentRef || diff.complete !== true) return unknown;
35
+ const paths = surveyArray(diff.paths, 1000).map(surveyPath);
36
+ if (new Set(paths).size !== paths.length) return unknown;
37
+ const applicablePaths = entry.paths.filter(path => !paths.some(changed => overlaps(path, changed)));
38
+ return { status: applicablePaths.length ? "applicable" : "changed", applicablePaths };
39
+ } catch { return unknown; }
40
+ }
41
+ /** Historical records remain immutable; this projection grants no rejection or admission authority. */
42
+ export function publicConsideredEntry(input: unknown, status: ConsideredMatch["status"]) {
43
+ const entry = parseConsideredEntry(input);
44
+ if (entry.withheld || entry.pass === "security") return { id: entry.id, status, rejectedBefore: true as const };
45
+ const { repo: _internalScope, ...publicEntry } = entry;
46
+ return { ...publicEntry, status, rejectedBefore: true as const };
47
+ }
@@ -22,7 +22,7 @@ export const PROTOCOL = 17;
22
22
  /** The descriptor's legacy protocol field remains this floor for previous published clients. */
23
23
  export const PROTOCOL_MIN = 16;
24
24
  // Literal metadata is read without executing a recovery target; consistency is pinned in tests.
25
- export const DAEMON_FEATURES = ["guidance_views", "guidance_variants", "guidance_probes", "guidance_probe_receipts", "execution_lineage", "model_overrides", "visuals", "project_autonomy", "conductor_recovery", "encrypted_rooms", "external_adapter_instances", "external_adapter_modules", "configured_acp", "native_hook_launch", "task_cancel", "invocation", "recovery_deferred_hub", "peer_instances", "role_stages", "task_planners", "release_trains", "reviewer_pool", "native_tui_launch", "terminal_owner", "cli_audit_delegated", "action_policy_floor", "calendar_schedules", "research_records", "research_dispatch", "research_dropped_offers", "research_experiments", "research_comparisons", "research_runners", "task_handoff", "session_identity", "schema_guard", "design_specs", "queue_discard_states", "tool_write_idempotency", "research_evidence", "review_comments", "questions", "accepted_delivery_settlement", "completions", "review_observer_input_state", "task_handoff_key", "task_handoff_seq", "peer_takeover"] as const;
25
+ export const DAEMON_FEATURES = ["guidance_views", "guidance_variants", "guidance_probes", "guidance_probe_receipts", "execution_lineage", "model_overrides", "visuals", "project_autonomy", "conductor_recovery", "encrypted_rooms", "external_adapter_instances", "external_adapter_modules", "configured_acp", "native_hook_launch", "task_cancel", "invocation", "recovery_deferred_hub", "peer_instances", "role_stages", "task_planners", "release_trains", "reviewer_pool", "reviewer_quota", "native_tui_launch", "terminal_owner", "cli_audit_delegated", "action_policy_floor", "calendar_schedules", "research_records", "research_dispatch", "research_dropped_offers", "research_experiments", "research_comparisons", "research_runners", "task_handoff", "session_identity", "schema_guard", "design_specs", "queue_discard_states", "tool_write_idempotency", "research_evidence", "research_synthesis", "research_evidence_withdrawal", "advisor_surveys", "review_comments", "questions", "accepted_delivery_settlement", "completions", "review_observer_input_state", "task_handoff_key", "task_handoff_seq", "peer_takeover"] as const;
26
26
  /** Protocols a current coordinator may authenticate while upgrading a running source. */
27
27
  export const RECOVERY_SOURCE_PROTOCOLS = [9, 10, 11, 12, 13, 14, 15, 16, PROTOCOL] as const;
28
28