@staix/agent-hub 0.42.0 → 0.44.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 (77) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +2 -1
  3. package/docs/adding-an-ai-tool.md +2 -0
  4. package/docs/agent-notes/daemon.md +3 -3
  5. package/docs/agent-notes/local-worker.md +1 -0
  6. package/docs/agent-notes/tasks.md +3 -2
  7. package/docs/agent-notes/tests.md +2 -2
  8. package/docs/design/adapters.md +3 -0
  9. package/docs/design/agent-hub-architecture.md +2 -0
  10. package/docs/design/bus.md +2 -0
  11. package/docs/design/supervision.md +13 -1
  12. package/docs/design/task-board.md +13 -1
  13. package/docs/dogfood.md +13 -3
  14. package/docs/events.md +4 -2
  15. package/docs/memory.md +5 -3
  16. package/docs/operations.md +97 -17
  17. package/docs/quickstart.md +18 -2
  18. package/docs/research.md +2 -0
  19. package/docs/sdlc.md +6 -3
  20. package/docs/security.md +2 -2
  21. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  22. package/docs/verification/2026-11-18-0.43.0.md +56 -0
  23. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  24. package/docs/verified.json +25 -25
  25. package/package.json +2 -2
  26. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  27. package/plugins/agent-hub/kimi-hook.js +486 -218
  28. package/plugins/agent-hub/server.js +505 -234
  29. package/src/adapters/claude-implementer.ts +11 -1
  30. package/src/adapters/claude-print-child.ts +4 -1
  31. package/src/adapters/conformance/fakes/acp-server.ts +2 -1
  32. package/src/adapters/conformance/fakes/app-server.ts +1 -1
  33. package/src/adapters/local-worker.ts +7 -3
  34. package/src/adapters/reviewer-print.ts +3 -1
  35. package/src/cli/help.ts +3 -3
  36. package/src/cli/identity.ts +2 -0
  37. package/src/cli/main.ts +57 -5
  38. package/src/cli/output.ts +2 -2
  39. package/src/cli/sdlc-output.ts +7 -1
  40. package/src/cli/upgrade-output.ts +43 -2
  41. package/src/cli/upgrade-stopped.ts +162 -0
  42. package/src/cli/upgrade-wait.ts +37 -0
  43. package/src/cli/upgrade.ts +9 -3
  44. package/src/hub/board.ts +17 -2
  45. package/src/hub/bus.ts +4 -0
  46. package/src/hub/claude-shell-wrapper.ts +2 -1
  47. package/src/hub/config-apply.ts +1 -0
  48. package/src/hub/control-write-trace.ts +39 -2
  49. package/src/hub/daemon.ts +141 -37
  50. package/src/hub/envelope.ts +1 -0
  51. package/src/hub/facts.ts +30 -0
  52. package/src/hub/handoff.ts +14 -0
  53. package/src/hub/hub-tools.ts +1 -1
  54. package/src/hub/questions.ts +7 -0
  55. package/src/hub/quota-events.ts +40 -0
  56. package/src/hub/recovery-store.ts +57 -0
  57. package/src/hub/report.ts +1 -1
  58. package/src/hub/research-quality.ts +5 -1
  59. package/src/hub/research-record.ts +5 -3
  60. package/src/hub/restart.ts +49 -2
  61. package/src/hub/runtime-capture-prune.ts +123 -4
  62. package/src/hub/runtime-prune-health.ts +10 -2
  63. package/src/hub/sdlc-merge.ts +7 -3
  64. package/src/hub/sdlc-metrics.ts +17 -8
  65. package/src/hub/sdlc.ts +18 -6
  66. package/src/hub/settings.ts +2 -0
  67. package/src/hub/snapshots.ts +43 -0
  68. package/src/hub/supervision-rules.ts +2 -2
  69. package/src/hub/task-shell-command.ts +124 -0
  70. package/src/hub/task-sweep.ts +6 -2
  71. package/src/hub/tasks.ts +131 -22
  72. package/src/hub/turn-attribution.ts +46 -0
  73. package/src/hub/worktree-shelf.ts +2 -1
  74. package/src/local/sandbox.ts +2 -1
  75. package/src/local/shell-environment.ts +6 -0
  76. package/src/memory/brief.ts +10 -1
  77. package/templates/AGENTS.block.md +1 -1
@@ -0,0 +1,37 @@
1
+ import type { RecoveryOperation } from "./upgrade.ts";
2
+
3
+ export interface OperationWaitPorts {
4
+ read(id: string): RecoveryOperation;
5
+ /** The claimed runner: a pid, "unknown" when it cannot be told, undefined when none holds the claim. */
6
+ runner(id: string): number | "unknown" | undefined;
7
+ now(): number;
8
+ sleep(ms: number): Promise<void>;
9
+ }
10
+
11
+ /** A runner claims and writes within a moment of being spawned; this long without either reads as gone. */
12
+ export const RUNNER_APPEARS_MS = 10_000;
13
+ /**
14
+ * The longest `upgrade --yes` waits for an operation that is still running. A restart waits up to 10 minutes for a quiet hub and each peer restore can wait as long (docs/operations.md), so this is
15
+ * several of those; past it the command fails and names the status command, leaving the operation to its runner.
16
+ * ponytail: a fixed cap; read it from a recovery setting if a longer upgrade needs it.
17
+ */
18
+ export const OPERATION_WAIT_MS = 2 * 60 * 60 * 1000;
19
+
20
+ /**
21
+ * #1540 AC10: wait until a scheduled recovery operation is terminal (completed, cancelled or blocked), so `ahub upgrade --yes; ahub down` no longer races "recovery operation <id> is active".
22
+ * A runner that never shows, or is gone with the receipt still open, returns that open receipt: the caller reads it as a failure, never as success. The receipt is read once more after the runner
23
+ * lets go of its claim, because a runner writes its end state first.
24
+ */
25
+ export async function awaitOperationEnd(operation: Pick<RecoveryOperation, "id" | "updatedAt">, ports: OperationWaitPorts): Promise<RecoveryOperation> {
26
+ const started = ports.now();
27
+ let seen = false;
28
+ for (;;) {
29
+ const op = ports.read(operation.id);
30
+ if (op.phase === "completed" || op.phase === "cancelled" || op.phase === "blocked") return op;
31
+ const runner = ports.runner(operation.id);
32
+ if (runner !== undefined || op.updatedAt !== operation.updatedAt) seen = true;
33
+ if (runner === undefined && (seen || ports.now() - started > RUNNER_APPEARS_MS)) return ports.read(operation.id);
34
+ if (ports.now() - started > OPERATION_WAIT_MS) return op;
35
+ await ports.sleep(250);
36
+ }
37
+ }
@@ -1,3 +1,4 @@
1
+ import { scheduleRuntimeCapturePrune } from "../hub/runtime-capture-prune.ts";
1
2
  import { RecoveryLaunchError, type RecoveryLaunchFailure } from "./recovery-launch.ts";
2
3
  import { nativeRestoreGroup } from "../adapters/definitions/native-identity-defaults.ts";
3
4
  import { definitionOf } from "../adapters/registry.ts";
@@ -659,6 +660,11 @@ export function guardedRecoveryDriver(driver: RecoveryDriver, operation: () => R
659
660
  };
660
661
  }
661
662
 
663
+ /** #1546: a start that ran while this operation held its lock scheduled nothing; schedule runtime maintenance now that the lock is released. */
664
+ function pruneAfterRelease(home: string): void {
665
+ try { scheduleRuntimeCapturePrune(home); } catch { /* maintenance never changes a recovery outcome */ }
666
+ }
667
+
662
668
  /** Resumable state machine. Driver actions are preceded by receipts and followed by live readback. */
663
669
  export async function runRecovery(id: string, driver: RecoveryDriver, home = hubHome(), idleTimeoutMs = 600_000): Promise<RecoveryOperation> {
664
670
  // Read once to validate the selector, then claim the runner before trusting any
@@ -920,7 +926,7 @@ export async function runRecovery(id: string, driver: RecoveryDriver, home = hub
920
926
  if (scope === undefined && op.plan.kind === "upgrade" && !op.globalInstalled) {
921
927
  step("install-global"); await driver.installGlobal(op); op.globalInstalled = true; save();
922
928
  }
923
- releaseRecoveryLock(id, home, scope); op.phase = "completed"; step("completed");
929
+ releaseRecoveryLock(id, home, scope); pruneAfterRelease(home); op.phase = "completed"; step("completed");
924
930
  } catch (error) {
925
931
  // #215: every runner error ends with the choices status shows, read from every open source, never only this one.
926
932
  const presentationError = error instanceof RecoveryPresentationError ? error
@@ -1081,7 +1087,7 @@ export async function abortRecovery(id: string, driver: RecoveryDriver, home = h
1081
1087
  }
1082
1088
  delete op.error; delete op.failure; delete op.blockedReattachment; delete op.presentationCause;
1083
1089
  op.phase = "cancelled"; op.step = "cancelled"; op.updatedAt = driver.now();
1084
- writeOperation(id, op, home); releaseRecoveryLock(id, home, scope);
1090
+ writeOperation(id, op, home); releaseRecoveryLock(id, home, scope); pruneAfterRelease(home);
1085
1091
  } catch (error) {
1086
1092
  if (isDatabaseBusy(error)) throw new RecoveryDatabaseBusy();
1087
1093
  throw error;
@@ -1223,7 +1229,7 @@ export async function disposeRecovery(id: string, choice: { fresh: string } | {
1223
1229
  }
1224
1230
  delete op.error; delete op.failure;
1225
1231
  op.phase = "cancelled"; op.step = "disposed: stop-and-archive (abandoned, not completed)"; op.updatedAt = driver.now();
1226
- writeOperation(id, op, home); releaseRecoveryLock(id, home, scope);
1232
+ writeOperation(id, op, home); releaseRecoveryLock(id, home, scope); pruneAfterRelease(home);
1227
1233
  return op;
1228
1234
  } finally { releaseRunner(); }
1229
1235
  }
package/src/hub/board.ts CHANGED
@@ -296,6 +296,8 @@ export interface HistoryEntry {
296
296
  noWrites?: true;
297
297
  /** Host-recorded expected cost and exact review head, never narrative. */
298
298
  reviewCost?: ReviewCost;
299
+ /** Full commit submitted for review; independent of cost planning. */
300
+ requestHead?: string;
299
301
  /** #901: on the hub's own `check passed` / `check failed`: the check key (task class or profile class alias) whose command ran. Set by the hub from its own selection, never from output or an owner's words. */
300
302
  checkKey?: string;
301
303
  /** #901: on such an entry, the number of unresolved citation keys the example citation check printed (`citations: N declared keys, M missing`); absent when the check printed no such line. */
@@ -483,6 +485,7 @@ export interface Task extends PlanningFields {
483
485
 
484
486
  /** Structured execution evidence, including legacy rows whose owner was later cleared. */
485
487
  export function taskHasStarted(task: Pick<Task, "history">): boolean {
488
+ if (task.history.some(entry => entry.event === "check run passed" || entry.event === "check run failed")) return true;
486
489
  return task.history.some(entry => ["accepted", "done", "done (checking)", "check passed", "check failed", "changes_requested", "approved", "reopened", "integration requested", "integrated"].includes(entry.event));
487
490
  }
488
491
  /** S9 return eligibility never erases the historical acceptance used by cancellation and undo. */
@@ -2588,6 +2591,18 @@ export class Board {
2588
2591
  const rows = this.db.query(`SELECT id, at, total FROM security_scans WHERE repo=? AND sources=?${knownOnly ? " AND total IS NOT NULL" : ""} ORDER BY id DESC LIMIT ?`).all(repo.toLowerCase(), sources, Math.max(1, Math.min(1000, limit))) as { id: number; at: number; total: number | null }[];
2589
2592
  return rows.reverse();
2590
2593
  }
2594
+ /** The latest recorded per-source scan counts, with unreadable values kept unknown. */
2595
+ latestSecurityScanCounts(repo: string, sources: string): Record<string, number | null> | undefined {
2596
+ const row = this.db.query("SELECT counts FROM security_scans WHERE repo=? AND sources=? ORDER BY id DESC LIMIT 1").get(repo.toLowerCase(), sources) as { counts: string } | null;
2597
+ if (!row) return undefined;
2598
+ let counts: unknown;
2599
+ try { counts = JSON.parse(row.counts); } catch { counts = undefined; }
2600
+ const raw = counts && typeof counts === "object" && !Array.isArray(counts) ? counts as Record<string, unknown> : {};
2601
+ return Object.fromEntries(sources.split(",").filter(source => ["dependabot", "secret_scanning", "code_scanning"].includes(source)).map(source => {
2602
+ const value = raw[source];
2603
+ return [source, typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null];
2604
+ }));
2605
+ }
2591
2606
  recordSecurityScan(row: { repo: string; sources: string; counts: Record<string, number | null>; total: number | null }): number {
2592
2607
  if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(row.repo) || !/^[a-z_,]{1,80}$/.test(row.sources) || (row.total !== null && (!Number.isSafeInteger(row.total) || row.total < 0))) throw new Error("invalid security scan row");
2593
2608
  return Number(this.db.query("INSERT INTO security_scans(at, repo, sources, counts, total) VALUES(?,?,?,?,?)").run(Date.now(), row.repo.toLowerCase(), row.sources, JSON.stringify(row.counts), row.total).lastInsertRowid);
@@ -2685,7 +2700,7 @@ export class Board {
2685
2700
 
2686
2701
  /** The only way a task changes. Validates the move, records who did what, returns the new row. */
2687
2702
  /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */
2688
- update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2703
+ update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "requestHead" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2689
2704
  if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority));
2690
2705
  const task = this.get(id);
2691
2706
  if (!task) throw new Error(`no task #${id}`);
@@ -2783,7 +2798,7 @@ export class Board {
2783
2798
  && priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
2784
2799
  const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
2785
2800
  ? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history;
2786
- const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2801
+ const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(["done", "check run passed", "check run failed"].includes(event) && extra.requestHead && /^[a-f0-9]{40}$/.test(extra.requestHead) ? { requestHead: extra.requestHead } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed", "check run passed", "check run failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2787
2802
  this.taskWrite(() => {
2788
2803
  if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
2789
2804
  if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
package/src/hub/bus.ts CHANGED
@@ -209,6 +209,8 @@ export class Bus {
209
209
  * and is never corrected once the queue empties (measured: status.json kept `queued 4` on an empty queue).
210
210
  */
211
211
  onQueues?: () => void;
212
+ /** Host-only registration observation; never changes delivery or peer state. */
213
+ onPeerAdded?: (peer: PeerId) => void;
212
214
  /**
213
215
  * #445 C2: a peer's answer to a delivery, offered BEFORE anything is built from it. The host returns true when the answer belongs to an invocation it
214
216
  * took over: the bus then publishes nothing, stores nothing, emits no event and lets no tap, queue, digest or memory path see it. `answers` is what the
@@ -303,6 +305,7 @@ export class Bus {
303
305
  }
304
306
 
305
307
  add(peer: PeerAdapter): void {
308
+ const newAttachment = this.peers.get(peer.id) !== peer;
306
309
  if (peer.remoteRoom !== undefined && (!parseRemotePeerId(peer.id) || typeof peer.remoteRoom !== "string" || !peer.remoteRoom || peer.remoteRoom.length > 256 || !remoteFingerprint(peer.remoteMember))) throw new Error("invalid remote peer binding");
307
310
  const pendingRemote = peer.remoteRoom !== undefined && this.hasRemoteWork(peer.id);
308
311
  if (peer.remoteRoom !== undefined && pendingRemote) {
@@ -458,6 +461,7 @@ export class Bus {
458
461
  this.emit({ t: "state", peer: peer.id, state: this.stateOf(peer.id) });
459
462
  void this.drain(peer.id);
460
463
  };
464
+ if (newAttachment) try { this.onPeerAdded?.(peer.id); } catch { /* observers cannot undo a registered peer */ }
461
465
  }
462
466
 
463
467
  private persist(): void {
@@ -11,6 +11,7 @@ import { shellQuote } from "../cli/shell-quote.ts";
11
11
  import { readProcessTable, stopOwnedProcess, trackGroup } from "./child-process.ts";
12
12
  import { realPath } from "./project.ts";
13
13
  import { sbplString } from "../local/deny.ts";
14
+ import { sandboxCommandEnvironment } from "../local/shell-environment.ts";
14
15
 
15
16
  export interface ShellGrant {
16
17
  peer: string; task: number; generation: string; root: string; branch: string;
@@ -233,7 +234,7 @@ export class HostShellWrapper {
233
234
  try {
234
235
  if (!unchanged(ticket) || !this.stable(ticket.root.path) || !this.sandboxStable(grant, ticket.root.path) || !same(grant.root, ticket.root, true) || !same(grant.executable, ticket.executable)) throw fail();
235
236
  const temp = mkdtempSync(join(this.directory.path, "r-")); chmodSync(temp, 0o700); temporary = execution.temporary = stamp(temp, true);
236
- const env = { ...grant.env, TMPDIR: `${temporary.path}/` };
237
+ const env = grant.sandbox ? sandboxCommandEnvironment(grant.env, temporary.path) : { ...grant.env, TMPDIR: `${temporary.path}/` };
237
238
  // Identical own-temp allow suffix and data.readonly broad-write guard to sandboxedExec.
238
239
  if (grant.sandbox?.readOnlyData && /\(allow file-write\* \(subpath /.test(grant.sandbox.profile)) throw fail();
239
240
  const sandbox = grant.sandbox && `${grant.sandbox.profile}\n(allow file-read* ${grant.sandbox.readOnlyData ? "" : "file-write* "}process-exec (subpath ${sbplString(temporary.path)}))`;
@@ -308,6 +308,7 @@ export function configApply(key: string, scopes: readonly ConfigIdentityScope[]
308
308
  }
309
309
  const operational = operationalNumber(key);
310
310
  if (operational) return { applies: operational.applies, ...(operational.restartReason ? { reason: operational.restartReason } : {}) };
311
+ if (key === "memory.sync_interval_min") return { applies: "live" };
311
312
  if (nextMemory.has(key)) return { applies: "next use" };
312
313
  for (const [path, reason] of Object.entries(restart)) if (key === path || key.startsWith(`${path}.`)) return { applies: "restart", reason };
313
314
  if ([...live].some(path => key === path || key.startsWith(`${path}.`))) return { applies: "live" };
@@ -24,6 +24,8 @@ const MAX_ACTIVE_SPANS = 256;
24
24
  const MAX_RECENT_SPANS = 512;
25
25
  const MAX_LOOP_SPANS = 8;
26
26
  const MIN_SYNC_PREFIX_MS = 10;
27
+ /** Microtask hops one request may spend following its async spans after their first await, shared by all of them: bounds the loop work this telemetry adds (#1545). */
28
+ const MAX_REQUEST_HOPS = 16;
27
29
  const MAX_EMITS_PER_MINUTE = 60;
28
30
  const RATE_LIMIT_MS = 1_000;
29
31
  const RATE_KEYS = ["slow", "loop"] as const;
@@ -51,6 +53,7 @@ interface RequestTrace {
51
53
  phaseOrder: ControlWritePhase[];
52
54
  settled: boolean;
53
55
  privacySuppressed: boolean;
56
+ hopsLeft: number;
54
57
  }
55
58
  interface SpanTrace {
56
59
  id?: number;
@@ -60,6 +63,8 @@ interface SpanTrace {
60
63
  async: boolean;
61
64
  finished: boolean;
62
65
  prefixRecorded: boolean;
66
+ /** Loop turn the span began in (see turn): a span that finishes in the same turn never let the loop go idle. */
67
+ turn: number;
63
68
  }
64
69
  interface SpanInterval {
65
70
  kind: ControlWriteKind;
@@ -135,6 +140,7 @@ export function controlWriteSpan<T>(phase: ControlWritePhase, fn: () => T): T {
135
140
  if (!isThenable(result)) { request.telemetry.finishSpan(span); return result; }
136
141
  span.async = true;
137
142
  request.telemetry.recordSyncPrefix(span);
143
+ request.telemetry.followSpan(span);
138
144
  return Promise.resolve(result).then(
139
145
  value => { request.telemetry.finishSpan(span); return value; },
140
146
  error => { request.telemetry.finishSpan(span); throw error; },
@@ -158,6 +164,10 @@ export class ControlWriteTelemetry {
158
164
  private timer: ReturnType<typeof setInterval> | undefined;
159
165
  private nextSampleAt: number | undefined;
160
166
  private lastNow = 0;
167
+ private hops = 0;
168
+ /** Counts event-loop turns (one setImmediate marker, only while spans are being traced). */
169
+ private turn = 0;
170
+ private turnPending = false;
161
171
  private stopped = false;
162
172
  private completedRequests = 0;
163
173
  private expiredRequests = 0;
@@ -198,7 +208,7 @@ export class ControlWriteTelemetry {
198
208
  if (!inputVisible) return fn();
199
209
  const request: RequestTrace = {
200
210
  telemetry: this, metadata: safeMetadata, privacyCurrent,
201
- startedAt: now, phases: new Map(), phaseOrder: [], settled: false, privacySuppressed: false,
211
+ startedAt: now, phases: new Map(), phaseOrder: [], settled: false, privacySuppressed: false, hopsLeft: MAX_REQUEST_HOPS,
202
212
  logPrivacy: () => false,
203
213
  };
204
214
  request.logPrivacy = () => !request.privacySuppressed && this.privateNow(request.privacyCurrent);
@@ -298,7 +308,8 @@ export class ControlWriteTelemetry {
298
308
  }
299
309
 
300
310
  beginSpan(request: RequestTrace, phase: ControlWritePhase): SpanTrace {
301
- const span: SpanTrace = { request, phase, startedAt: this.readNow(), async: false, finished: false, prefixRecorded: false };
311
+ if (!this.turnPending && !this.stopped) { this.turnPending = true; setImmediate(() => { this.turn++; this.turnPending = false; }).unref?.(); }
312
+ const span: SpanTrace = { request, phase, startedAt: this.readNow(), async: false, finished: false, prefixRecorded: false, turn: this.turn };
302
313
  if (this.spans.size >= this.maxActiveSpans) { this.droppedSpans++; return span; }
303
314
  span.id = this.nextSpanId++;
304
315
  this.spans.set(span.id, span);
@@ -317,6 +328,9 @@ export class ControlWriteTelemetry {
317
328
  if (!request.phaseOrder.includes(span.phase)) request.phaseOrder.push(span.phase);
318
329
  request.phases.set(span.phase, prior + durationMs);
319
330
  if (!span.async && !span.prefixRecorded) this.rememberSyncInterval(span, endedAt);
331
+ // An async span that began and settled inside one loop turn never yielded: every ms of it was loop-busy time, so it is a synchronous
332
+ // slice (microtask chains). A span that yielded is a wait; overlap with a blocked window alone is presence, never cause.
333
+ else if (span.async && span.turn === this.turn && endedAt - span.startedAt >= MIN_SYNC_PREFIX_MS) this.rememberSyncInterval(span, endedAt);
320
334
  }
321
335
 
322
336
  /** Preserve a long synchronous prelude inside an async function for the delayed loop probe. */
@@ -328,6 +342,29 @@ export class ControlWriteTelemetry {
328
342
  this.rememberSyncInterval(span, endedAt);
329
343
  }
330
344
 
345
+ /** Hops spent following spans: the measured extra work, bounded per request. */
346
+ followedHops(): number { return this.hops; }
347
+
348
+ /**
349
+ * After a span's first await, look at the next few microtask turns of its request (a shared budget of MAX_REQUEST_HOPS, so the added
350
+ * loop work is bounded per request however many spans it has). A gap between two hops is time a continuation ran synchronously and is
351
+ * remembered as a synchronous slice. A block after a real I/O await is out of reach: the budget is spent by then, and Bun has no
352
+ * per-continuation hook, so such a slice is only a lower bound.
353
+ */
354
+ followSpan(span: SpanTrace): void {
355
+ let last = this.readNow();
356
+ const hop = (): void => {
357
+ const request = span.request;
358
+ if (span.finished || request.settled || this.stopped || request.hopsLeft <= 0) return;
359
+ request.hopsLeft--; this.hops++;
360
+ const now = this.readNow();
361
+ if (now - last >= MIN_SYNC_PREFIX_MS) this.rememberSyncInterval({ ...span, startedAt: last }, now);
362
+ last = now;
363
+ queueMicrotask(hop);
364
+ };
365
+ queueMicrotask(hop);
366
+ }
367
+
331
368
  private rememberSyncInterval(span: SpanTrace, endedAt: number): void {
332
369
  const request = span.request;
333
370
  this.recent.push({ kind: request.metadata.kind, ...(request.metadata.task === undefined ? {} : { task: request.metadata.task }), phase: span.phase, startedAt: span.startedAt, endedAt, async: false, privacyCurrent: request.logPrivacy });