@staix/agent-hub 0.46.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +12 -6
  3. package/docs/adding-an-ai-tool.md +20 -4
  4. package/docs/agent-notes/adapters.md +3 -3
  5. package/docs/agent-notes/benchmarks.md +7 -1
  6. package/docs/agent-notes/daemon.md +5 -4
  7. package/docs/agent-notes/tasks.md +4 -2
  8. package/docs/agent-notes/tests.md +3 -0
  9. package/docs/contracts/companion-cli-v1.json +3 -0
  10. package/docs/data-policy.md +9 -0
  11. package/docs/design/adapters.md +14 -0
  12. package/docs/design/cli-output-inventory.md +362 -0
  13. package/docs/design/cli-output.md +42 -1
  14. package/docs/design/execution-reference.md +5 -2
  15. package/docs/design/guidance-probes.md +14 -2
  16. package/docs/design/refusal-inventory.md +26 -0
  17. package/docs/design/roadmap.md +4 -0
  18. package/docs/design/task-board.md +17 -1
  19. package/docs/dogfood.md +27 -11
  20. package/docs/events.md +9 -0
  21. package/docs/friction.md +46 -0
  22. package/docs/memory.md +35 -3
  23. package/docs/operations.md +95 -16
  24. package/docs/profiles.md +1 -0
  25. package/docs/quickstart.md +14 -2
  26. package/docs/roles.md +6 -0
  27. package/docs/sdlc.md +44 -1
  28. package/docs/security.md +29 -12
  29. package/docs/specs/2026-09-19-agent-hub-design.md +17 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +7 -1
  31. package/docs/verification/2026-11-25-agy-1.5.16.md +31 -0
  32. package/docs/verification/2026-11-25-claude-implementer-2.1.332.md +47 -0
  33. package/docs/verification/2026-11-25-codex-0172-reviewer-isolation.md +47 -0
  34. package/docs/verification/2026-11-25-kimi-272-reviewer-compat.md +38 -0
  35. package/docs/verification/2026-11-25-kimi-tui-272.md +14 -0
  36. package/docs/verification/2026-11-25-pi-160-compat.md +40 -0
  37. package/docs/verification/2026-11-26-0.47.0.md +43 -0
  38. package/docs/verification/2026-11-26-0.48.0.md +45 -0
  39. package/docs/verification/2026-11-26-codex-0172-reviewer-tool-call.md +29 -0
  40. package/docs/verification/dogfood/2026-11-24.md +2829 -0
  41. package/docs/verification/pi-160-model-free.ts +57 -0
  42. package/docs/verification/pi-160-native.mjs +21 -0
  43. package/docs/verified.json +44 -32
  44. package/package.json +2 -2
  45. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  46. package/plugins/agent-hub/kimi-hook.js +598 -131
  47. package/plugins/agent-hub/server.js +687 -143
  48. package/src/adapters/acp.ts +5 -0
  49. package/src/adapters/channel-peer.ts +7 -0
  50. package/src/adapters/claude-print-child.ts +27 -5
  51. package/src/adapters/codex-appserver.ts +9 -0
  52. package/src/adapters/compat.ts +12 -11
  53. package/src/adapters/configured-acp.ts +45 -2
  54. package/src/adapters/configured-print.ts +163 -0
  55. package/src/adapters/conformance/index.ts +1 -0
  56. package/src/adapters/conformance/print.ts +57 -0
  57. package/src/adapters/definitions/native-activity.ts +57 -0
  58. package/src/adapters/definitions/native-factories.ts +4 -2
  59. package/src/adapters/jcode.ts +10 -2
  60. package/src/adapters/local-probe.ts +59 -14
  61. package/src/adapters/local-worker.ts +20 -6
  62. package/src/adapters/registry-types.ts +5 -3
  63. package/src/adapters/role-eligibility.ts +5 -0
  64. package/src/cli/bench.ts +2 -1
  65. package/src/cli/broker.ts +2 -1
  66. package/src/cli/capabilities-output.ts +10 -14
  67. package/src/cli/configured-acp-entry.ts +10 -2
  68. package/src/cli/console-state.ts +25 -5
  69. package/src/cli/error-format.ts +2 -0
  70. package/src/cli/guidance.ts +1 -1
  71. package/src/cli/handoff-output.ts +20 -17
  72. package/src/cli/help.ts +79 -41
  73. package/src/cli/init-settings.ts +15 -0
  74. package/src/cli/intake-output.ts +13 -13
  75. package/src/cli/launch.ts +3 -2
  76. package/src/cli/learn-output.ts +40 -21
  77. package/src/cli/main.ts +150 -79
  78. package/src/cli/memory.ts +47 -2
  79. package/src/cli/output.ts +54 -31
  80. package/src/cli/roadmap.ts +2 -2
  81. package/src/cli/room-output.ts +71 -0
  82. package/src/cli/room.ts +19 -33
  83. package/src/cli/schedule-output.ts +20 -19
  84. package/src/cli/sdlc-output.ts +188 -170
  85. package/src/cli/source-output.ts +17 -14
  86. package/src/cli/specs.ts +13 -13
  87. package/src/cli/study-output.ts +66 -69
  88. package/src/cli/task-output.ts +106 -158
  89. package/src/cli/terminal-recovery.ts +2 -1
  90. package/src/cli/upgrade-runtime.ts +2 -1
  91. package/src/cli/warn-line.ts +18 -0
  92. package/src/cli/worktrees-output.ts +25 -23
  93. package/src/hub/audit-source.ts +45 -0
  94. package/src/hub/board.ts +141 -5
  95. package/src/hub/bus.ts +13 -2
  96. package/src/hub/config-apply.ts +14 -1
  97. package/src/hub/config-trust.ts +1 -0
  98. package/src/hub/control-client.ts +1 -1
  99. package/src/hub/daemon.ts +390 -47
  100. package/src/hub/guidance-probe-store.ts +51 -10
  101. package/src/hub/guidance-probes.ts +25 -7
  102. package/src/hub/handoff.ts +5 -1
  103. package/src/hub/hub-tools.ts +23 -5
  104. package/src/hub/instance-config.ts +3 -3
  105. package/src/hub/learn-followup.ts +103 -0
  106. package/src/hub/learning.ts +63 -1
  107. package/src/hub/manager.ts +15 -1
  108. package/src/hub/memory-policy.ts +2 -1
  109. package/src/hub/memory-review.ts +217 -0
  110. package/src/hub/peer-activity.ts +37 -0
  111. package/src/hub/peers.ts +3 -0
  112. package/src/hub/project-move.ts +258 -0
  113. package/src/hub/registry.ts +16 -5
  114. package/src/hub/restart.ts +7 -0
  115. package/src/hub/review-brief.ts +8 -4
  116. package/src/hub/review-checkout.ts +26 -0
  117. package/src/hub/review-findings.ts +6 -3
  118. package/src/hub/risk-tier.ts +129 -0
  119. package/src/hub/roadmap-check.ts +1 -0
  120. package/src/hub/routing.ts +3 -1
  121. package/src/hub/sdlc-merge.ts +9 -0
  122. package/src/hub/sdlc-metrics.ts +24 -1
  123. package/src/hub/sdlc-queue.ts +1 -1
  124. package/src/hub/sdlc.ts +15 -6
  125. package/src/hub/settings.ts +2 -0
  126. package/src/hub/spec-readback.ts +136 -0
  127. package/src/hub/specs.ts +1 -1
  128. package/src/hub/task-list-page.ts +1 -1
  129. package/src/hub/tasks.ts +586 -80
  130. package/src/hub/ui.ts +4 -2
  131. package/src/local/probe-types.ts +1 -0
  132. package/src/local/probe-workspace.ts +49 -0
  133. package/src/omniroute/client.ts +19 -3
  134. package/src/ui/guidance-panel.ts +2 -2
  135. package/src/ui/guidance-view.ts +4 -2
  136. package/src/ui/index.html +26 -2
  137. package/src/ui/overview-model.ts +138 -0
  138. package/src/ui/plugin.ts +30 -4
  139. package/templates/roles/ops/project-manager.md +1 -1
package/src/hub/daemon.ts CHANGED
@@ -1,9 +1,11 @@
1
+ import { PeerActivityTracker } from "./peer-activity.ts";
2
+ import { codexActivityServers } from "../adapters/definitions/native-activity.ts";
1
3
  import { QuotaEventFilter } from "./quota-events.ts";
2
4
  import { piFailureText } from "./pi-failure.ts";
3
5
  import { nativeReviewerQuota } from "../adapters/definitions/native-quota.ts";
4
6
  import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-variants.ts";
5
7
  import { GuidanceProbeStore } from "./guidance-probe-store.ts";
6
- import { GuidanceProbeError, probeSessionGeneration, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.ts";
8
+ import { GuidanceProbeError, probeSessionGeneration, probeSha256, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.ts";
7
9
  import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
8
10
  import { publicDeliveryBodies } from "./delivery-public.ts";
9
11
  import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
@@ -60,6 +62,7 @@ import { readReleaseHostAdmission, type ReleaseHostAdmission } from "./release-a
60
62
  import { MERGE_READBACK_INTERVAL_MS } from "./sdlc-merge.ts";
61
63
  import { ContainerRunner, RemoteRunner, remoteRunnerConfig, type RemoteRunnerConfig, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
62
64
  import { fetchSpec, specAvailable, specRefs } from "./spec-read.ts";
65
+ import { readbackAcceptField } from "./spec-readback.ts";
63
66
  import { isDenied, sbplString } from "../local/deny.ts";
64
67
  import { hostShellPath } from "./host-executable.ts";
65
68
  import { supersededDeliveryReason, deliveryTaskContext } from "./delivery-superseded.ts";
@@ -75,21 +78,22 @@ import { ControlWriteTelemetry, controlWriteMetadata, controlWriteSpan } from ".
75
78
  import { projectedDiff } from "./projected-diff.ts";
76
79
  import { listenWithoutPortCollision } from "./listen.ts";
77
80
  import { needs, type NeedsInput } from "../ui/needs.ts";
81
+ import { overviewModel } from "../ui/overview-model.ts";
78
82
  import { loadPetConfig, PET_WINDOW_RETIRED_NOTICE, stripLegacyPetWindow } from "../pet/config.ts";
79
83
  import { projectionConfig, TextProjections, type ProjectionConfig } from "./text-projection.ts";
80
84
  import { policyPaths, policyRealPath, matchesPolicy } from "./path-policy.ts";
81
85
  import { CodeFacts, type CodeFactResult, type CodeSymbol } from "./code-facts.ts";
82
- import { gitAuditSource } from "./audit-source.ts";
86
+ import { gitAuditSource, checkoutAuditSource } from "./audit-source.ts";
83
87
  import { buildReviewBrief, withCodeSymbols } from "./review-brief.ts";
84
88
  import { profileName, projectProfile, resolveProfile, mergeProfileOverrides, type ProfileName } from "./profiles.ts";
85
89
  import { catalogAssignments, loadRoleCatalog, selectedRoles, roleIdentity } from "./roles.ts";
86
90
  import { ActivityRing } from "./activity.ts";
87
- import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer, jcodeToolCeilingCause, jcodeVersionAsync, type JcodePeer } from "../adapters/jcode.ts";
91
+ import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer, jcodeDetachedNotice, jcodeToolCeilingCause, jcodeVersionAsync, type JcodePeer } from "../adapters/jcode.ts";
88
92
  import { VERSION_REFUSAL, configuredCommands, describe, isCompatId } from "../adapters/compat.ts";
89
93
  import { agentVersionsAsync, type AgentVersionRow } from "../cli/agents.ts";
90
94
  import { driftedAgents, noticeDrift, type DriftedAgent } from "./agent-drift.ts";
91
95
  import { jcodeMcpReady } from "../cli/jcode-mcp.ts";
92
- import { loadSdlc, readSpecEdit, sdlcGh, type SdlcConfig } from "./sdlc.ts";
96
+ import { loadSdlc, readSpecEdit, sdlcGh, type SdlcConfig, type SdlcGh } from "./sdlc.ts";
93
97
  import { claudePeer as defaultChannelPeer, claudeStateFile, ownTerminalRow, pathEvidence, transcriptPersisted } from "./claude-state.ts";
94
98
  import { peerRosterConfig, rosterAllows, staleInstanceKey, type PeerRoster } from "./roster.ts";
95
99
  import { KNOWN_PEERS, OPTIONAL_PEERS, PLANNER_PEERS, SUPPORTED_PEERS, START_MODE_PEERS, isSupportedPeer, STARTABLE_PEERS, isStartablePeer } from "../adapters/registry.ts";
@@ -119,6 +123,7 @@ import { MODEL_COOLDOWN_FAILURES_SETTING, MODEL_COOLDOWN_SETTING, MODEL_COOLDOWN
119
123
  import { ACP_TOOL_CEILING_SETTING, ACP_ACTIVITY_BATCH_SETTING, JCODE_STEER_TIMEOUT_SETTING, adapterOperationalReaders, type AdapterTimingConfig } from "./operational-settings.ts";
120
124
  import { BUS_ACCEPTED_SETTLE_MS_SETTING, BUS_DIGEST_MAX_SETTING, BUS_MAX_ATTEMPTS_SETTING, BUS_NOTES_KEPT_SETTING, BUS_PULL_BUDGET_BYTES_SETTING, BUS_TERMINAL_HISTORY_LIMIT_SETTING, busOperationalReaders, RECOVERY_CONTROL_TIMEOUT_SETTING, RECOVERY_RECONNECT_WAIT_SETTING, RECOVERY_SHUTDOWN_WAIT_SETTING, RECOVERY_TERMINAL_IDLE_WAIT_SETTING, RECOVERY_UNMANAGED_RECONNECT_WAIT_SETTING } from "./operational-settings.ts";
121
125
  import { foldersConfig, scheduleKeyOf, scheduleViews, schedulesConfig, ScheduleStore, type FolderEntry, type ScheduleEntry } from "./schedules.ts";
126
+ import { MEMORY_REVIEW_DEFAULTS, MEMORY_REVIEW_SCHEDULE_ID, memoryReviewConfig, memoryReviewCountLine, memoryReviewEntry, memoryReviewScope, memoryReviewTask, reviewBudgetNote, reviewBudgetStop, reviewCheckpointRequest, type MemoryReviewConfig, type ReviewSpend } from "./memory-review.ts";
122
127
  import { FolderStore, registerScanned, scanFolder, type FolderPolicy } from "./folder-trigger.ts";
123
128
  import { QuestionStore, QUESTION_SURFACES, questionView } from "./questions.ts";
124
129
  import { RunTracker, outcomeOf, settleVerdict, type Run } from "./completions.ts";
@@ -182,6 +187,7 @@ import { taskShellSandboxRestrictions } from "./task-shell-sandbox.ts";
182
187
  import { hostShellEnvironment } from "../local/shell-environment.ts";
183
188
  import { hubGitArgv, hubGitEnv, hubGitSync } from "./git.ts";
184
189
  import { isLocalPeer, type LocalPeer } from "../adapters/local-worker.ts";
190
+ import { createLiveGuidanceProbeLocalAdapter } from "../adapters/local-probe.ts";
185
191
  import { isClaudeImplementerPeer } from "../adapters/claude-implementer.ts";
186
192
  import { isReviewerPrintPeer, reviewerNoVerdictLine, reviewerUnavailableReason, ReviewerUnavailableError, REVIEWER_FALLBACK_UNCONFIRMED, type ReviewerPrintPeer } from "../adapters/reviewer-print.ts";
187
193
  import type { OwnedInputContext } from "../adapters/claude-print-child.ts";
@@ -221,7 +227,8 @@ import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
221
227
  import { DEFAULT_INFERENCE, DIGEST, Inference, SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii, type InferenceConfig, type PiiVerdict } from "./inference.ts";
222
228
  import { taskEvidencePrivacy, type TaskEvidencePrivacy, ask, ASK_NOTE_TITLE, RUN_START } from "./ask.ts";
223
229
  import { currentRouting, loadRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
224
- import { withChecklistLine } from "./learning.ts";
230
+ import { withChecklistLine, withoutChecklistLine } from "./learning.ts";
231
+ import { FOLLOWUP_DEFAULTS } from "./learn-followup.ts";
225
232
  import { autonomyConsentStateDir, createAutonomyConsent, type AutonomyConsentValues } from "./autonomy-consent.ts";
226
233
  import { insideRoot } from "./path-policy.ts";
227
234
  import { autonomyPreset, autonomyEnvironment, planAutonomy, autonomyRemovalKeys, autonomyStatus, type AutonomyEnvironment, type AutonomyPeer } from "./autonomy.ts";
@@ -291,7 +298,7 @@ import { DEFAULT_SPECS_CONFIG, parseSpecsConfig, type SpecsConfig } from "./spec
291
298
 
292
299
  export interface HubConfig {
293
300
  adapter_modules?: readonly AdapterModuleDeclaration[];
294
- adapters?: Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAcpAdapterConfig>>;
301
+ adapters?: Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAdapterConfig>>;
295
302
  /** Person-owned declarations, read only from an untracked machine-local file. Bound for this daemon lifetime. */
296
303
  instances?: InstancesConfig;
297
304
  watchdog_ms: number;
@@ -321,7 +328,7 @@ export interface HubConfig {
321
328
  /** #489 H7: accepted presentation preferences read by a new console through settings_get. */
322
329
  console?: ConsoleOperationalConfig["console"];
323
330
  /** `native` (#258): the hub's own store in ~/.agenthub/memory, on with any project config; `short_ttl_days`: short-term lifetime after approval; `sync_interval_min`: machine sync while a remote is set (default 10, 0 off); `preface_unused_after` (#1330): a long-term preface line delivered at least this many times and never cited moves to the end of its section, so the cap cuts it first (default 20, 0 keeps the store order). */
324
- memory: { enabled: boolean; worker_url?: string; inject_tokens: number; brief_items: number; native?: boolean; short_ttl_days?: number; sync_interval_min?: number; suggest_edges?: boolean; preface_unused_after?: number };
331
+ memory: { enabled: boolean; worker_url?: string; inject_tokens: number; brief_items: number; native?: boolean; short_ttl_days?: number; sync_interval_min?: number; suggest_edges?: boolean; preface_unused_after?: number; review?: MemoryReviewConfig };
325
332
  roster: PeerRoster;
326
333
  roles: Record<string, string[]>;
327
334
  /** #455: the one peer that holds the planner role; unset, the `roles` planners stand, or the hub assigns one. */
@@ -419,7 +426,7 @@ export const DEFAULT_CONFIG: HubConfig = {
419
426
  queue_cap: 200,
420
427
  bus: { max_attempts: BUS_MAX_ATTEMPTS_SETTING.defaultValue, digest_max: BUS_DIGEST_MAX_SETTING.defaultValue, pull_budget_bytes: BUS_PULL_BUDGET_BYTES_SETTING.defaultValue, notes_kept: BUS_NOTES_KEPT_SETTING.defaultValue, terminal_history_limit: BUS_TERMINAL_HISTORY_LIMIT_SETTING.defaultValue, accepted_settle_ms: BUS_ACCEPTED_SETTLE_MS_SETTING.defaultValue },
421
428
  adapter_timing: { acp_tool_ceiling_min: ACP_TOOL_CEILING_SETTING.defaultValue, acp_activity_batch_ms: ACP_ACTIVITY_BATCH_SETTING.defaultValue, jcode_steer_timeout_s: JCODE_STEER_TIMEOUT_SETTING.defaultValue },
422
- memory: { enabled: true, inject_tokens: 2000, brief_items: 8, preface_unused_after: 20 },
429
+ memory: { enabled: true, inject_tokens: 2000, brief_items: 8, preface_unused_after: 20, review: MEMORY_REVIEW_DEFAULTS },
423
430
  roster: {},
424
431
  roles: DEFAULT_ROLES,
425
432
  conductor: { feed: "own", approval_wait_s: 30 },
@@ -464,7 +471,7 @@ export const DEFAULT_CONFIG: HubConfig = {
464
471
  export { stateDirFor };
465
472
 
466
473
  /** Ids an external process may not claim: the console user and the adapters the daemon runs itself. */
467
- const READ_ONLY_HUB_TOOLS = new Set(["hub_roadmap_list", "hub_roadmap_show", "hub_roadmap_check", "hub_roadmap_unplaced", "roadmap_sync", "roadmap_export", "hub_guidance_list", "hub_guidance_show", "hub_lineage_show", "hub_visual_show", "hub_capabilities", "hub_inbox", "hub_send", "hub_delivery_done", "hub_review", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_evidence_read", "hub_status", "hub_specs", "hub_supervision_list"]);
474
+ const READ_ONLY_HUB_TOOLS = new Set(["hub_roadmap_list", "hub_roadmap_show", "hub_roadmap_check", "hub_roadmap_unplaced", "roadmap_sync", "roadmap_export", "hub_guidance_list", "hub_guidance_show", "hub_lineage_show", "hub_visual_show", "hub_capabilities", "hub_inbox", "hub_send", "hub_delivery_done", "hub_review", "hub_review_file", "hub_task_show", "hub_task_list", "hub_study_show", "hub_experiment_show", "hub_memory_search", "hub_memory_show", "hub_memory_graph", "hub_source_read", "hub_evidence_read", "hub_status", "hub_specs", "hub_supervision_list"]);
468
475
  const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
469
476
  const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
470
477
 
@@ -714,6 +721,10 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
714
721
  if (!mlx.enabled && file.pi?.backend === "mlx") throw new Error("Pi backend mlx conflicts with mlx.enabled=false");
715
722
  if (typeof mlx.runtimeDir === "string" && mlx.runtimeDir) mlx.runtimeDir = resolve(cwd, mlx.runtimeDir);
716
723
  if (typeof mlx.modelPath === "string" && mlx.modelPath) mlx.modelPath = resolve(cwd, mlx.modelPath);
724
+ // #1329 part 1: the scheduled memory review is derived from `memory.review` at every read (`scheduleEntries` below)
725
+ // rather than copied into `config.schedules`, because a config reload applies per-key deltas to this live object: a copy
726
+ // would go stale the moment a person flips the switch.
727
+ const memoryReview = memoryReviewConfig(file.memory?.review);
717
728
  return {
718
729
  ...DEFAULT_CONFIG,
719
730
  ...file,
@@ -730,7 +741,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
730
741
  instructed: { mode: instructedMode(file.instructed?.mode) },
731
742
  permission_default_sources: appliedPermissionSources,
732
743
  memory: { ...DEFAULT_CONFIG.memory, native: true, ...file.memory, ...(file.memory?.short_ttl_days !== undefined ? { short_ttl_days: ttlDays(file.memory.short_ttl_days) } : {}),
733
- ...(file.memory?.sync_interval_min !== undefined ? { sync_interval_min: syncMinutes(file.memory.sync_interval_min) } : {}) }, // the native store is on with any project config (#258)
744
+ ...(file.memory?.sync_interval_min !== undefined ? { sync_interval_min: syncMinutes(file.memory.sync_interval_min) } : {}), review: memoryReview }, // the native store is on with any project config (#258)
734
745
  roster: peerRosterConfig(file.roster, instances, adapterCatalog, inertModuleRoster),
735
746
  roles: Object.fromEntries(Object.entries({ ...configuredRoles, ...conductorPolicy.roles, ...extraRoles }).filter(([id]) => !instanceConfig.declaredExternalInstances?.some(row => row.id === id || row.kind === id))),
736
747
  planner: conductorPolicy.planner,
@@ -927,6 +938,8 @@ export interface DaemonOptions {
927
938
  boundedTools?: {
928
939
  specAvailable?: typeof specAvailable;
929
940
  fetchSpec?: typeof fetchSpec;
941
+ /** Host-only seam for the issue edit-time reads a read-back grant and `ahub sdlc accept` make. */
942
+ specEdit?: SdlcGh;
930
943
  runner?: (options: RunnerOptions) => Pick<ContainerRunner, "available" | "start" | "result" | "consumeOutput" | "cancel" | "sweep" | "stopAll" | "markStale"> & Partial<Pick<ContainerRunner, "unknownReceipts" | "maintenanceUnavailable" | "compactTask">>;
931
944
  };
932
945
  }
@@ -1890,6 +1903,12 @@ export async function startDaemon(opts: DaemonOptions) {
1890
1903
  const presenceOnlyDelivery = (envs: readonly Envelope[]): boolean => envs.length === 0 || envs.every(env => env.from === HUB && env.kind === "presence");
1891
1904
  let remotePending = (_room: string): readonly string[] => [];
1892
1905
  let remoteQueueChanged = () => {};
1906
+ const activities = new PeerActivityTracker();
1907
+ const activityPrivate = (peer: PeerId) => contextPii(peer) || reviewObserverHeld(peer)
1908
+ || board.peerTaskSignals(peer).some(task => !isClosedTaskState(task.state)
1909
+ && task.signals.some(signal => signal === "pii" || signal === "pii_path"))
1910
+ || bus.lastDeliveredTo(peer).some(env => env.private || isReviewObserverExcluded(env)
1911
+ || (env.refs?.task ? board.get(Number(env.refs.task))?.signals.some(signal => signal === "pii" || signal === "pii_path") : false));
1893
1912
  const bus: Bus = new Bus({ rostered: membershipAllowed, ...busReaders, trackQueuePressure: () => { const policy = queuePolicy(); return policy.max_queued > 0 || policy.max_oldest_s > 0; }, deliveryHeld: peer => requestedPeerStops.has(peer) || rosterChanging === peer, journal, batchMax: config.batch_max, batchMs: config.batch_ms, queueCap: config.queue_cap, condense: (envs) => inference?.condense(envs) ?? Promise.resolve(envs), admit, relevant: (peer, env) => reviewOnlyPeer(peer) && !reviewOnlyItem(peer, env) ? `not for ${peer}: a review-only instance receives review requests only` : env.refs?.boundedCheck || env.refs?.supervision || env.refs?.backlog ? relevantNotice(peer, env) : staleOff() || relevantNotice(peer, env), silence,
1894
1913
  beforeReviewInputHandoff: (peer, envs) => {
1895
1914
  const owner = bus.peers.get(peer);
@@ -1913,6 +1932,7 @@ export async function startDaemon(opts: DaemonOptions) {
1913
1932
  return sender === USER ? false : !bus.peers.has(sender) || !!turns.get(sender)?.private || contextPii(sender);
1914
1933
  },
1915
1934
  doing: (peer, kind, text) => observeDoing(peer, kind, text),
1935
+ activity: (peer, kind) => activities.observe(peer, kind, () => activityPrivate(peer)),
1916
1936
  reviewObserverScope: peer => readReviewObserverScope ? readReviewObserverScope(peer) : "review-scope-unavailable",
1917
1937
  reviewObserverInputExcluded: (peer, envs) => reviewInputHeld(peer, envs) || reviewObserverInput(peer),
1918
1938
  onImportantQueued: (peer, counts) => { const p = bus.peers.get(peer); if (isWsPeer(p)) p.notifyQueued(counts); } });
@@ -2363,6 +2383,12 @@ export async function startDaemon(opts: DaemonOptions) {
2363
2383
  const modelRelays = new Map<string, ModelRelay>();
2364
2384
  /** #368: the owned Jcode launch of each Jcode peer, from creation (its MCP child connects while `start()` runs, before the bus has the peer). */
2365
2385
  const jcodeLaunches = new Map<string, JcodePeer>();
2386
+ /**
2387
+ * #1668: a rostered Jcode peer whose socket a server the hub did not start is serving, written from the tools hello that admission refused and
2388
+ * read by `ahub status`. A hub-owned launch of that peer clears it. ponytail: this daemon's memory, so a restart forgets it until that server's next
2389
+ * hello is refused; a durable record would need a state file the refusal path does not own.
2390
+ */
2391
+ const jcodeDetached = new Map<string, { cause: string; command: string }>();
2366
2392
  const globalModelRelay = (relay: ModelRelay) => { modelRelay = relay; };
2367
2393
  const nativeStateDir = (peer: string) => declarations[peer] ? join(opts.stateDir, "instances", peer) : opts.stateDir;
2368
2394
  const instanceAppPorts = new Map<string, number>();
@@ -2462,6 +2488,13 @@ export async function startDaemon(opts: DaemonOptions) {
2462
2488
  } catch {
2463
2489
  guidanceProbeStore.close(); board.close(); throw new Error("advisor survey state or recovery binding is unavailable; restore trusted project state and choose a supporting target before retrying");
2464
2490
  }
2491
+ try {
2492
+ const retained = board.specReadbackIntegrity(), expected = restored?.integrity?.specReadbacks;
2493
+ if (restored && (expected ? expected.readbacks !== retained.readbacks || expected.digest !== retained.digest
2494
+ : retained.readbacks !== 0)) throw new Error("changed recovery binding");
2495
+ } catch {
2496
+ guidanceProbeStore.close(); board.close(); throw new Error("spec read-back state or recovery binding is unavailable; restore trusted project state and choose a supporting target before retrying");
2497
+ }
2465
2498
  startupCleanup.push(() => guidanceProbeStore.close());
2466
2499
  // #1226 T3: the one explicit crash reconcile. A fresh process has no probe in flight, so a session still `reserved` or `running` belongs to a previous process
2467
2500
  // and is recorded as unknown with an unknown receipt (never launched, retried or turned into a success). It runs after the integrity comparison above, never
@@ -3061,9 +3094,22 @@ export async function startDaemon(opts: DaemonOptions) {
3061
3094
  let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
3062
3095
  let questionStore!: QuestionStore;
3063
3096
  startupTimings.mark("task_ports");
3097
+ const liveProbeId = process.env.AGENTHUB_LIVE_GUIDANCE_PROBE_ID;
3098
+ const liveProbe = probeSha256(liveProbeId) ? {
3099
+ id: liveProbeId,
3100
+ adapter: createLiveGuidanceProbeLocalAdapter({
3101
+ cwd: opts.cwd, omni: new OmniRoute(config.omniroute), permit: async () => false,
3102
+ current: () => {
3103
+ if (process.env.AGENTHUB_LIVE_GUIDANCE_PROBE_ID !== liveProbeId)
3104
+ // refusal:by-design human-authority: only the host operator can restore the startup selection
3105
+ throw new PreEffectToolRefusal("live guidance probe selection changed");
3106
+ },
3107
+ }),
3108
+ } : undefined;
3064
3109
  const tasks: Tasks = new Tasks({
3110
+ taskTokens: () => Object.fromEntries(usageRollup.query({ by: "task" }).rows.flatMap(row => /^\d+$/.test(row.key) ? [[Number(row.key), row.counted.value]] : [])),
3065
3111
  ownerQuestionWait: (task, peer) => questionStore?.ownerWait(task, peer),
3066
- guidanceProbes: { store: guidanceProbeStore, session: by => {
3112
+ guidanceProbes: { store: guidanceProbeStore, ...(liveProbe ? { live: liveProbe } : {}), session: by => {
3067
3113
  const request = guidanceProbeRequestContext.getStore();
3068
3114
  return request?.actor === by ? { generation: request.generation, nativeSession: request.nativeSession,
3069
3115
  requestConnectionId: request.requestConnectionId, current: request.current } : undefined;
@@ -3127,13 +3173,13 @@ export async function startDaemon(opts: DaemonOptions) {
3127
3173
  catalog,
3128
3174
  sessionRoles: peer => bus.peers.has(peer) && bus.stateOf(peer) !== "offline" ? preparedSessionRoles.get(peer) ?? [] : [],
3129
3175
  projectedReview: task => reviewProjection(task),
3130
- reviewMaterials: (task, requests) => reviewMaterials(task, requests),
3176
+ reviewMaterials,
3131
3177
  ownerWrites: (task, since) => ownerWriteEvidence(task, since),
3132
3178
  ownerAccepted: task => captureOwnerWriteStart(task),
3133
3179
  prepareReviewBrief: async task => {
3134
3180
  if (tasks.isPii(task) || !task.refs.commit) return;
3135
3181
  const root = executionRoot(task.owner ?? "");
3136
- const brief = buildReviewBrief(root, task.refs.commit, { privatePath: path => isDenied(path, config.local.deny) || matchesPolicy(root, path, config.pii?.paths ?? [], true), nameable: tasks.nameable });
3182
+ const brief = buildReviewBrief(root, task.refs.commit, briefPolicy(root));
3137
3183
  if ("unavailable" in brief) return;
3138
3184
  const key = JSON.stringify([root, brief.head, brief.mergeBase]);
3139
3185
  // prepareOnly and completion share one exact-tree pass, including an unknown result.
@@ -3156,7 +3202,7 @@ export async function startDaemon(opts: DaemonOptions) {
3156
3202
  },
3157
3203
  reviewBrief: task => {
3158
3204
  const root = executionRoot(task.owner ?? "");
3159
- const brief = buildReviewBrief(root, task.refs.commit, { privatePath: path => isDenied(path, config.local.deny) || matchesPolicy(root, path, config.pii?.paths ?? [], true), nameable: tasks.nameable });
3205
+ const brief = buildReviewBrief(root, task.refs.commit, briefPolicy(root));
3160
3206
  return "unavailable" in brief ? brief : withCodeSymbols(brief, reviewSymbols.get(JSON.stringify([root, brief.head, brief.mergeBase])) ?? { state: "unknown" }, task.plan?.symbols, tasks.publicMetadataText);
3161
3207
  },
3162
3208
  specsConfig: () => config.specs,
@@ -3179,6 +3225,12 @@ export async function startDaemon(opts: DaemonOptions) {
3179
3225
  // R3 (#1481): the hub's own model, public text only (the caller screened it), never PII and never trusted: Tasks parses and checks the answer.
3180
3226
  roadmapModel: (system, user, allowed) => inference ? inference.complete(system, user, 2000, { interactive: true, timeoutMs: 20_000, allowed }) : Promise.resolve(undefined),
3181
3227
  auditSource: gitAuditSource(opts.cwd), // #1403 A4
3228
+ // #1646 T2: a verdict's evidence names the checkout its reviewer read. The reviewing session reports its own cwd at hello;
3229
+ // that path is read only when this host proves it a worktree of this repository, and it never proves isolation or grants any.
3230
+ reviewerCheckout: peer => {
3231
+ const attached = bus.peers.get(peer), root = attached && isWsPeer(attached) ? attached.sessionCwd : undefined;
3232
+ return root ? checkoutAuditSource(opts.cwd, root) : undefined;
3233
+ },
3182
3234
  sdlc: {
3183
3235
  config: () => lifecycleConfig,
3184
3236
  gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
@@ -3292,7 +3344,10 @@ export async function startDaemon(opts: DaemonOptions) {
3292
3344
  offerRead: (peer, envelopeId) => journal.offerRead(peer, envelopeId),
3293
3345
  offerPullOnly: (id) => { const peer = bus.peers.get(id); return peer?.pullOnly === true; },
3294
3346
  stallNotice: stall => { supervision.taskStalled(stall); },
3295
- roles: config.roles,
3347
+ get roles() {
3348
+ if (!configuredIds.some(id => definitionOf(id)?.start.daemonPort === "configured-print")) return config.roles;
3349
+ return Object.fromEntries(Object.entries(config.roles).filter(([id]) => definitionOf(id)?.start.daemonPort !== "configured-print"));
3350
+ },
3296
3351
  turnFree,
3297
3352
  coordination: () => config.coordination === "turn-free",
3298
3353
  capable: (peer) => capable.has(peer),
@@ -3507,6 +3562,11 @@ export async function startDaemon(opts: DaemonOptions) {
3507
3562
  return executionRoots.get(peer) ?? opts.cwd;
3508
3563
  };
3509
3564
  const repoFor = (peer: string, budget?: SnapshotBudget) => executionRoot(peer) === opts.cwd ? factsRepo : repoOf(executionRoot(peer), budget);
3565
+ /** The screening every review brief of `root` is built with, so the stored brief, the prepare pass and a brief-scoped read agree. */
3566
+ const briefPolicy = (root: string) => ({
3567
+ privatePath: (path: string) => isDenied(path, config.local.deny) || matchesPolicy(root, path, config.pii?.paths ?? [], true),
3568
+ nameable: tasks.nameable,
3569
+ });
3510
3570
  const projectionsFor = (peer: string): TextProjections => {
3511
3571
  const root = executionRoot(peer);
3512
3572
  if (root === opts.cwd) return projections;
@@ -4281,6 +4341,54 @@ export async function startDaemon(opts: DaemonOptions) {
4281
4341
  // #683 U2: events.jsonl folded into hub.db, a bounded pass at a time, so `usage` never rescans the log.
4282
4342
  const usageRollup = new UsageRollup(join(opts.stateDir, "hub.db"), join(opts.stateDir, "events.jsonl"));
4283
4343
  startupCleanup.push(() => usageRollup.close());
4344
+ // #1329 part 2 (AC5, report): one memory-review card's counted spend and per-hub-run counts. The spend is read from the
4345
+ // hub's own roll-up, so it is what the hub counted, never an estimate; the counts are what this daemon observed on the
4346
+ // card's turns (memory entries read, proposals filed) and are written to the board as counts only when the card is done.
4347
+ const reviewCounts = new Map<number, { notes: number; corrections: number; remembered: number }>();
4348
+ const REVIEW_WEEK_MS = 7 * 86_400_000;
4349
+ const reviewCount = (task: number, field: "notes" | "corrections" | "remembered", by = 1): void => {
4350
+ const row = reviewCounts.get(task) ?? { notes: 0, corrections: 0, remembered: 0 };
4351
+ row[field] += by; reviewCounts.set(task, row);
4352
+ };
4353
+ const reviewCountedTokens = (ids: readonly number[]): number => {
4354
+ if (!ids.length) return 0;
4355
+ pollUsageRollup();
4356
+ const wanted = new Set(ids.map(String));
4357
+ return usageRollup.query({ by: "task" }).rows.filter(row => wanted.has(row.key)).reduce((sum, row) => sum + (row.counted.value ?? 0), 0);
4358
+ };
4359
+ const reviewSpend = (card: Task): ReviewSpend => {
4360
+ const week = board.list().filter(task => memoryReviewTask(task) && task.created >= Date.now() - REVIEW_WEEK_MS).map(task => task.id);
4361
+ return { run: reviewCountedTokens([card.id]), week: reviewCountedTokens(week) };
4362
+ };
4363
+ const reviewCountLine = (card: Task): string => memoryReviewCountLine({ ...(reviewCounts.get(card.id) ?? { notes: 0, corrections: 0, remembered: 0 }), tokens: reviewCountedTokens([card.id]) });
4364
+ /**
4365
+ * #1329 AC3: the review card the caller's current turn is bound to. The turn's own attribution names it: the card is
4366
+ * delivered to its owner, `Tasks.ownerTurnTasks` excludes a `review` card, and a call made outside that turn - the
4367
+ * reviewer's, or the owner's work on another task - is not in the review's scope.
4368
+ */
4369
+ const reviewTurnCard = (by: PeerId): Task | undefined => tasks.reviewCardFor(by, turns.get(by)?.attribution.task);
4370
+ /**
4371
+ * The stop itself: a counted spend at either cap asks the owner for one checkpoint and then escalates the card with reason
4372
+ * `budget`, through the ordinary escalation path, so the board records who moved it and why. Each card stops once: the stop
4373
+ * is read from the card's own history, so it survives a daemon restart and a second turn cannot escalate it again.
4374
+ */
4375
+ const reviewBudgetAfterTurn = async (peer: PeerId, taskIds: readonly number[]): Promise<void> => {
4376
+ const caps = config.memory.review;
4377
+ if (caps?.enabled !== true || !taskIds.length) return;
4378
+ // Only the run's own owner: a reviewer's turn that names the card spends the reviewer's tokens, not the review's.
4379
+ const cards = [...new Set(taskIds)].map(id => board.get(id)).filter((task): task is Task => !!task && task.owner === peer && memoryReviewTask(task) && !isClosedTaskState(task.state));
4380
+ if (!cards.length) return;
4381
+ for (const card of cards) {
4382
+ if (card.history.some(entry => entry.event === "escalated" && entry.reason === "budget")) continue;
4383
+ const spend = reviewSpend(card), stop = reviewBudgetStop(spend, caps);
4384
+ if (!stop) continue;
4385
+ if (card.owner) bus.publish(newEnvelope(HUB, reviewCheckpointRequest(card.id, stop), { to: [card.owner], kind: "task", priority: "important", refs: { task: String(card.id) } }));
4386
+ try { await tasks.escalate(HUB, card.id, reviewBudgetNote(card.id, stop, spend), "budget"); }
4387
+ catch (error) { if (!(error instanceof AssignmentUndeliveredError)) notify(`memory review task #${card.id} reached its ${stop.cap} token cap but could not be escalated; inspect it with ahub task show`); return; }
4388
+ }
4389
+ };
4390
+ /** One advisory line for the stop that runs after a turn; it never fails the turn. */
4391
+ const reviewBudgetFailure = (error: Error): void => { log(`memory review budget: ${error.message.slice(0, 120)}`); };
4284
4392
  // #1513 AC2: one window view feeds the `budget` reply, the dashboard snapshot and therefore `ahub budget` and the
4285
4393
  // console, so the three cannot disagree. The burn series is hourly and an answer is kept for a minute per reading:
4286
4394
  // the page polls every second and must not query the roll-up that often.
@@ -4870,7 +4978,7 @@ export async function startDaemon(opts: DaemonOptions) {
4870
4978
  return false;
4871
4979
  } catch { return undefined; } // Unknown is never evidence of no writes, including a missing/pruned tree.
4872
4980
  }
4873
- async function reviewMaterials(task: Task, requests: readonly ReviewReadRequest[]): Promise<ReviewMaterialBatch> {
4981
+ async function reviewMaterials(task: Task, requests: readonly ReviewReadRequest[], scope?: "brief"): Promise<ReviewMaterialBatch> {
4874
4982
  const budget: SnapshotBudget = { deadline: Infinity };
4875
4983
  budget.deadline = budgetNow(budget) + 8000;
4876
4984
  const deadline = budget.deadline;
@@ -4903,6 +5011,13 @@ export async function startDaemon(opts: DaemonOptions) {
4903
5011
  const canonical = relative(opts.cwd, resolve(root, path));
4904
5012
  return canonical !== ".." && !canonical.startsWith("../") && !canonical.startsWith(".worktrees/") ? canonical : scoped;
4905
5013
  });
5014
+ // #1646 T3: a reviewer reading its brief at the reviewed head is scoped to exactly the paths the brief lists, which the host
5015
+ // builds itself. The reader's caps (MAX_FILES per operation, PROJECTED_DIFF_BYTES) still bound every answer.
5016
+ if (scope === "brief") {
5017
+ const brief = buildReviewBrief(root, head, briefPolicy(root));
5018
+ if ("unavailable" in brief) return unavailable();
5019
+ scopes.push(...brief.reviewable.map(file => file.path));
5020
+ }
4906
5021
  let base = "";
4907
5022
  // Only complete PR metadata at this exact head expands scope. A declared PR link
4908
5023
  // or a locally guessed merge base is never an inventory of its changed files.
@@ -5209,6 +5324,15 @@ export async function startDaemon(opts: DaemonOptions) {
5209
5324
  startupCleanup.push(() => folderStore.close());
5210
5325
  let schedulesTimer: ReturnType<typeof setInterval> | undefined;
5211
5326
  const scheduleNow = () => opts.schedulesNow?.() ?? Date.now();
5327
+ /**
5328
+ * #1329 part 1: the configured schedules plus the one the machine-local memory.review switch stands for. Read live from
5329
+ * the config at every call, so a reload that flips the switch adds or drops the entry with no copy to re-derive, and every
5330
+ * schedule path (`proposeFromSchedules`, `scheduleViews`, `setSchedulePaused`, `runScheduleNow`) takes its list from here.
5331
+ */
5332
+ const scheduleEntries = (): ScheduleEntry[] => {
5333
+ const review = memoryReviewEntry(config.memory.review ?? MEMORY_REVIEW_DEFAULTS, opts.cwd);
5334
+ return review ? [...config.schedules, review] : config.schedules;
5335
+ };
5212
5336
  /** The pass in flight, so a stop can wait for it before the board and the store close. */
5213
5337
  let schedulesPass: Promise<void> | undefined;
5214
5338
  /** #335: `ahub schedule run` calls in flight. They are not the timer's pass, but `stopOnce` waits for them just the same. */
@@ -5220,7 +5344,7 @@ export async function startDaemon(opts: DaemonOptions) {
5220
5344
  };
5221
5345
  const runSchedulesOnce = async () => {
5222
5346
  try {
5223
- for (const run of await tasks.proposeFromSchedules(schedulesStore, config.schedules, scheduleNow(), () => opts.schedulesHeld?.() === true)) {
5347
+ for (const run of await tasks.proposeFromSchedules(schedulesStore, scheduleEntries(), scheduleNow(), () => opts.schedulesHeld?.() === true)) {
5224
5348
  if (run.outcome === "ran") log(`schedule ${run.id}: proposed task #${run.task}`);
5225
5349
  else if (run.outcome === "failed") log(`schedule ${run.id}: could not propose; see ahub status`);
5226
5350
  }
@@ -5241,9 +5365,10 @@ export async function startDaemon(opts: DaemonOptions) {
5241
5365
  const rescheduleSchedules = () => {
5242
5366
  if (schedulesTimer) clearInterval(schedulesTimer);
5243
5367
  schedulesTimer = undefined;
5368
+ const entries = scheduleEntries();
5244
5369
  if (!config.folder_triggers.length) { try { folderStore.prune([]); } catch { /* the store is closed while stopping */ } }
5245
- if (!config.schedules.length && !config.folder_triggers.length) { try { schedulesStore.prune([]); } catch { /* the store is closed while stopping */ } return; }
5246
- if (!config.schedules.length) { try { schedulesStore.prune([]); } catch { /* the store is closed while stopping */ } }
5370
+ if (!entries.length && !config.folder_triggers.length) { try { schedulesStore.prune([]); } catch { /* the store is closed while stopping */ } return; }
5371
+ if (!entries.length) { try { schedulesStore.prune([]); } catch { /* the store is closed while stopping */ } }
5247
5372
  schedulesTimer = setInterval(() => { void runSchedules(); }, opts.schedulesEveryMs ?? 60_000);
5248
5373
  schedulesTimer.unref?.();
5249
5374
  };
@@ -5974,8 +6099,23 @@ export async function startDaemon(opts: DaemonOptions) {
5974
6099
  }
5975
6100
  async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false): Promise<string> {
5976
6101
  if (op === "hub_visual" || op === "hub_visual_show") return visualTool(by, op, a, piiTurn);
6102
+ // #1646 T3: a brief file read is the reviewer's read of the commit it approves. A PII or private turn reads none: its words
6103
+ // may carry the PII, and the file body would be a second carrier of it.
6104
+ if (op === "hub_review_file") {
6105
+ // refusal:by-design operator-knowledge: whether this turn is private or PII is the console operator's setting, so no command the caller runs lifts it.
6106
+ if (piiTurn || turns.get(by)?.private || contextPii(by)) throw new PreEffectToolRefusal("review brief files are unavailable during a PII or private turn; read them in a turn without the private task");
6107
+ return await tasks.reviewFile(by, a);
6108
+ }
5977
6109
  const reviewTurn = reviewObserverHeld(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
5978
6110
  if (reviewTurn || op === "hub_review" && reviewCaptureExcluded(op, JSON.stringify(a))) progress.clearPeer(by);
6111
+ if (op === "hub_readback_report") {
6112
+ // #1658 T4: the report is the bound reader's; a private, PII or review-observer turn writes none.
6113
+ // refusal:by-design operator-knowledge: whether a turn is private, PII or a review observer's is the console operator's setting, so no command the caller runs lifts it.
6114
+ if (piiTurn || turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by)) throw new PreEffectToolRefusal("read-back reports are unavailable in private or review input; retry in a public reader turn");
6115
+ // refusal:by-design world-action: recovery and shutdown are the hub's own state, released by the hub, so the write waits for that release rather than a caller command.
6116
+ if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown holds read-back writes; wait for release and retry");
6117
+ return JSON.stringify(await tasks.specReadbackReport(by, a, () => stopping || recoveryActive() || bus.isRecoveryHeld ? "read-back write held by recovery or shutdown" : undefined));
6118
+ }
5979
6119
  if (op === "hub_survey_report") {
5980
6120
  if (piiTurn || turns.get(by)?.private || contextPii(by) || reviewTurn || reviewObserverInput(by)) throw new PreEffectToolRefusal("survey reports are unavailable in private or review input; retry in a public current-owner context");
5981
6121
  if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown holds survey writes; wait for release and retry");
@@ -6053,6 +6193,13 @@ export async function startDaemon(opts: DaemonOptions) {
6053
6193
  if (by !== USER && (piiTurn || turns.get(by)?.private || contextPii(by))) throw new PreEffectToolRefusal("bounded task tools unavailable during a PII turn");
6054
6194
  }
6055
6195
  if (op === "hub_specs" && (piiTurn || turns.get(by)?.private || contextPii(by))) throw new PreEffectToolRefusal("spec inspection unavailable during a private turn");
6196
+ // #1329 part 2 (AC3): while a turn is bound to a memory-review card its owner holds, the card's tool scope is enforced
6197
+ // here, on every call, before anything is written. The scope is a name rule in `memory-review.ts`; this only decides
6198
+ // whether this call runs in the review's turn, and an ordinary turn resolves no card at all.
6199
+ if (by !== USER) {
6200
+ const reviewCard = reviewTurnCard(by), refused = reviewCard && memoryReviewScope(op);
6201
+ if (reviewCard && refused) throw new PreEffectToolRefusal(`task #${reviewCard.id}: ${refused}; read the card with ahub task show ${reviewCard.id}, and run that work in a turn outside this review`);
6202
+ }
6056
6203
  if (MEMORY_READ_TOOLS.has(op)) validateMemoryRead(op, a);
6057
6204
  if (op === "hub_memory_correct") correctionInput(a);
6058
6205
  if (op === "hub_task_propose" && by !== USER && (piiTurn || turns.get(by)?.private)) {
@@ -6117,9 +6264,19 @@ export async function startDaemon(opts: DaemonOptions) {
6117
6264
  const code = symbolStarts.length ? await memoryCode(symbolStarts, valid).catch(() => unavailableMemoryCodeOverlay()) : undefined;
6118
6265
  if (!valid()) throw new PreEffectToolRefusal("memory read unavailable");
6119
6266
  checkMemory();
6120
- return memoryRead(memoryStore, memoryProject, screenMemory, op, a, staleness(), code ? currentMemoryCode(code) : undefined);
6267
+ const read = memoryRead(memoryStore, memoryProject, screenMemory, op, a, staleness(), code ? currentMemoryCode(code) : undefined);
6268
+ // #1329: a review's done report counts the notes it checked, so a successful read on its card is counted here.
6269
+ const card = op === "hub_memory_show" ? (Array.isArray(a.ids) ? reviewTurnCard(by) : undefined) : undefined;
6270
+ if (card) reviewCount(card.id, "notes", (a.ids as unknown[]).length);
6271
+ return read;
6272
+ }
6273
+ if (op === "hub_memory_correct") {
6274
+ need("memory_correct", "propose memory corrections");
6275
+ const candidate = await tasks.correct(by, a);
6276
+ const card = reviewTurnCard(by);
6277
+ if (card) reviewCount(card.id, "corrections");
6278
+ return candidate;
6121
6279
  }
6122
- if (op === "hub_memory_correct") { need("memory_correct", "propose memory corrections"); return tasks.correct(by, a); }
6123
6280
  if (op === "hub_remember") need("remember", "save notes to shared memory");
6124
6281
  if (CAPABILITY_TOOLS.has(op)) {
6125
6282
  // #445 C1: both calls carry a peer's words (a description, a name), so neither runs in a PII turn or for a peer holding PII, and neither reaches memory.
@@ -6147,15 +6304,24 @@ export async function startDaemon(opts: DaemonOptions) {
6147
6304
  return JSON.stringify({ published: manifest.capabilities.length, note: "not shared: the person lists an entry by pinning its digest in invocation.share (ahub capabilities shows each digest)" });
6148
6305
  }
6149
6306
  if (op === "hub_task_spec") {
6150
- need("spec_read", "read assigned specifications");
6307
+ // #1658 T4: the person's ruling is one binding per read-back request, so the bound reader may state the spec back
6308
+ // without the standing spec_read capability, and only while its own request holds no report on the body it was filed for.
6309
+ const asked = board.get(Number(a.id)), specEditGh = opts.boundedTools?.specEdit;
6310
+ let grant = asked ? tasks.specReadbackGrant(asked.id, asked.created, by) : undefined;
6311
+ // #1658: a carried read fetches the request's own issue, so a receipt issue the task's text does not name is still read,
6312
+ // and a body that moved or another repository's issue ends the grant here.
6313
+ if (grant && (grant.repo.toLowerCase() !== memoryRepo.toLowerCase()
6314
+ || !await tasks.specReadbackFresh(grant, specEditGh ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound))))) grant = undefined;
6315
+ const carried = (task: Task | undefined) => !!task && !!tasks.specReadbackGrant(task.id, task.created, by);
6316
+ if (!grant) need("spec_read", "read assigned specifications");
6151
6317
  const authorized = () => {
6152
6318
  const task = board.get(a.id);
6153
- if (!task || task.state === "backlog" || task.owner !== by && task.reviewer !== by || tasks.isPii(task) || turns.get(by)?.private || contextPii(by)) throw new PreEffectToolRefusal("spec unavailable");
6319
+ if (!task || task.state === "backlog" || task.owner !== by && task.reviewer !== by && !carried(task) || tasks.isPii(task) || turns.get(by)?.private || contextPii(by)) throw new PreEffectToolRefusal("spec unavailable");
6154
6320
  return task;
6155
6321
  };
6156
6322
  const task = authorized(), generation = connectionGeneration(by), updated = task.updated, revision = task.history.length;
6157
6323
  const deadline = Date.now() + 25_000; // retain a response margin inside the control client's 30-second cap
6158
- const issues = specRefs(task, memoryRepo);
6324
+ const issues = grant && !may(by, "spec_read") ? [grant.issue] : specRefs(task, memoryRepo);
6159
6325
  if (!issues.length) throw new PreEffectToolRefusal("no assigned spec references");
6160
6326
  await ensureSpec();
6161
6327
  authorized();
@@ -6166,7 +6332,7 @@ export async function startDaemon(opts: DaemonOptions) {
6166
6332
  if (remaining <= 0) throw new PreEffectToolRefusal("timeout");
6167
6333
  specs.push(await (opts.boundedTools?.fetchSpec ?? fetchSpec)(memoryRepo, issue, { screen: boundedSafe, projectDir: opts.cwd, timeoutMs: Math.min(15_000, remaining) }));
6168
6334
  const current = authorized();
6169
- if (current.updated !== updated || current.history.length !== revision || connectionGeneration(by) !== generation || !may(by, "spec_read")) throw new PreEffectToolRefusal("spec unavailable");
6335
+ if (current.updated !== updated || current.history.length !== revision || connectionGeneration(by) !== generation || !may(by, "spec_read") && !carried(current)) throw new PreEffectToolRefusal("spec unavailable");
6170
6336
  }
6171
6337
  const result = JSON.stringify({ specs });
6172
6338
  if (Buffer.byteLength(result) > 80 * 1024) throw new PreEffectToolRefusal("too large");
@@ -6445,6 +6611,13 @@ export async function startDaemon(opts: DaemonOptions) {
6445
6611
  const doneLine = by === USER ? tasks.resultLine(t, by) : line(t);
6446
6612
  const result = tasks.isChecking(t.id) ? `${doneLine}; its check is queued or running, and the result comes as a task message` : doneLine;
6447
6613
  const specReport = by === USER ? "" : tasks.specReportText(t, by);
6614
+ // #1329 (report): a memory review's completion carries counts only, on the board and in the answer that reaches its
6615
+ // reviewer; no note text, no reviewed line. Counts this hub run did not observe read as unknown, never as zero.
6616
+ if (by !== USER && memoryReviewTask(t) && !tasks.isPii(t)) {
6617
+ const counts = reviewCountLine(t);
6618
+ board.update(t.id, HUB, "review counts", {}, counts);
6619
+ return [result, counts, specReport, extra].filter(Boolean).join("\n");
6620
+ }
6448
6621
  return [result, specReport, extra].filter(Boolean).join("\n");
6449
6622
  }
6450
6623
  case "hub_sdlc_record":
@@ -6456,10 +6629,15 @@ export async function startDaemon(opts: DaemonOptions) {
6456
6629
  if (!piiTurn && !reviewTurn && !tasks.isPii(reviewed) && verdict && !verdict.withheld && typeof a.note === "string" && a.note && verdict.note?.startsWith(a.note)) {
6457
6630
  citeMemory(by, a.note, `review:${reviewed.id}:${reviewed.history.indexOf(verdict)}`, [newEnvelope(by, "", { refs: { task: String(reviewed.id) } })]);
6458
6631
  }
6459
- return line(reviewed);
6632
+ return reviewed.reopenedWithoutReason?.length
6633
+ ? line(reviewed) + "\nreopenedWithoutReason: " + JSON.stringify(reviewed.reopenedWithoutReason)
6634
+ : line(reviewed);
6460
6635
  }
6461
6636
  case "hub_remember": {
6462
- const { message: saved, outcome } = await tasks.rememberOutcome(by, a);
6637
+ const reviewCard = reviewTurnCard(by);
6638
+ const { message: saved, outcome } = await tasks.rememberOutcome(by, a, reviewCard);
6639
+ // #1329 AC4: on a review card a note is a proposal, and the done report counts it by kind.
6640
+ if (reviewCard && outcome === "candidate") reviewCount(reviewCard.id, "remembered");
6463
6641
  // #1279: a saved note that names another entry cites it. `tasks.remember` already refused a PII task, a private path and a secret, so only a note it saved gets here.
6464
6642
  // #802: the structured outcome decides, never the reply wording. Only `not_saved` skips the citation: a candidate note held for a person's review was cited under the old wording test too, and stays so.
6465
6643
  if (!piiTurn && !reviewTurn && typeof a.text === "string" && a.text && outcome !== "not_saved") {
@@ -6594,19 +6772,60 @@ export async function startDaemon(opts: DaemonOptions) {
6594
6772
  // #335: the person's schedule commands; #933: the admitted conductor's too. Tasks refuses any other actor.
6595
6773
  case "schedule_list":
6596
6774
  if (by !== USER) throw new PreEffectToolRefusal("schedule list is a console command");
6597
- return JSON.stringify(scheduleViews(config.schedules, schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true));
6775
+ return JSON.stringify(scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true));
6598
6776
  case "schedule_run": {
6599
6777
  // The run is registered with the shutdown drain, so `stopOnce` waits for it, as for a timer pass, before the board and the store close (#335). A run that arrives
6600
6778
  // once stop has begun is refused earlier still, by the control layer ("hub is stopping"); the test below holds that, so nothing here repeats it.
6601
- const run = tasks.runScheduleNow(by, schedulesStore, config.schedules, a.id, scheduleNow(), () => opts.schedulesHeld?.() === true);
6779
+ const run = tasks.runScheduleNow(by, schedulesStore, scheduleEntries(), a.id, scheduleNow(), () => opts.schedulesHeld?.() === true);
6602
6780
  const drained = run.then(() => undefined, () => undefined);
6603
6781
  manualSchedulePasses.add(drained); void drained.finally(() => manualSchedulePasses.delete(drained));
6604
6782
  return JSON.stringify(await run);
6605
6783
  }
6606
6784
  case "schedule_pause":
6607
6785
  case "schedule_resume":
6608
- tasks.setSchedulePaused(by, schedulesStore, config.schedules, a.id, op === "schedule_pause", scheduleNow());
6609
- return JSON.stringify(scheduleViews(config.schedules, schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true).filter(view => view.id === a.id));
6786
+ tasks.setSchedulePaused(by, schedulesStore, scheduleEntries(), a.id, op === "schedule_pause", scheduleNow());
6787
+ return JSON.stringify(scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true).filter(view => view.id === a.id));
6788
+ // #1329 part 1: `ahub memory review on|off|status`. Person only: it is deliberately absent from CONDUCTOR_TASK_OPS, so the
6789
+ // gate above refuses every other caller. The switch is the machine-local `memory.review.enabled` key, written through the
6790
+ // same writer and loader check as `ahub settings set`, so enabling without both caps is refused by the config, not here;
6791
+ // a store write beside it makes the change take effect now instead of at the next period, and `off` cancels the card the
6792
+ // last run left open through `Tasks.cancel`, the normal cancel path (AC2).
6793
+ case "memory_review": {
6794
+ const reviewView = () => scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true).find(candidate => candidate.id === MEMORY_REVIEW_SCHEDULE_ID);
6795
+ const action = a.action;
6796
+ if (action === "status") {
6797
+ const view = reviewView();
6798
+ // #1329 AC5: the spend is the hub's own counted tokens for the last card and, when one is open, for this week.
6799
+ const open = tasks.openScheduled().get(MEMORY_REVIEW_SCHEDULE_ID);
6800
+ const card = open === undefined ? undefined : board.get(open);
6801
+ const spend = card ? reviewSpend(card) : undefined;
6802
+ return JSON.stringify({ action: "status", enabled: config.memory.review?.enabled === true, review: config.memory.review ?? MEMORY_REVIEW_DEFAULTS,
6803
+ ...(spend ? { spend, ...(card ? { task: card.id } : {}) } : {}), ...(view ? { schedule: view } : {}) });
6804
+ }
6805
+ if (action !== "on" && action !== "off") throw new PreEffectToolRefusal("memory review takes on, off or status; ahub memory review status shows the switch");
6806
+ const def = settingDef("memory.review.enabled");
6807
+ if (typeof def === "string") throw new PreEffectToolRefusal(`this hub has no memory.review setting; upgrade it, then run ahub memory review ${action}`);
6808
+ // The fence and the cancellation come before the config write: the write reloads the entries, and a pass already past its
6809
+ // hold check must meet the paused epoch rather than a schedule list that no longer explains why it is running.
6810
+ let cancelled: number | undefined;
6811
+ if (action === "off") {
6812
+ // #335's epoch, set before the write on purpose: the `tasks.cancel` below yields, so a timer pass can begin while the
6813
+ // config still says enabled, and that pass has to meet the paused epoch. Nothing has to undo it afterwards: the row
6814
+ // goes with the entry the reload drops (`Tasks.proposeFromSchedules` prunes a removed schedule).
6815
+ schedulesStore.setPaused(MEMORY_REVIEW_SCHEDULE_ID, true, scheduleNow());
6816
+ const open = tasks.openScheduled().get(MEMORY_REVIEW_SCHEDULE_ID);
6817
+ if (open !== undefined) { await tasks.cancel(open, by, { reason: "ahub memory review off stopped the schedule" }); cancelled = open; }
6818
+ }
6819
+ writeConfigSetting(opts.cwd, opts.stateDir, def, action === "on", scratch => configWriteCheck(scratch, "terminal", def.path.join(".")));
6820
+ const reloaded = await reloadConfig("terminal", def.key);
6821
+ // The write is on disk, so the switch survives a restart either way; only this daemon's view of it failed to catch up.
6822
+ if (reloaded.ok !== true) throw new Error(`memory.review.enabled was ${action === "on" ? "set" : "cleared"} in .agenthub/config.local.json but this hub did not apply it: ${sanitize(typeof reloaded.error === "string" ? reloaded.error : "the reload failed")}; fix the config and run ahub memory review status`);
6823
+ // `on` clears the pause here rather than leaving it to the reload: a key that is already `true` changes nothing, so
6824
+ // there is no reload to carry the fence, and this command must still resume a schedule a person paused by hand.
6825
+ if (action === "on") schedulesStore.setPaused(MEMORY_REVIEW_SCHEDULE_ID, false, scheduleNow());
6826
+ const view = reviewView();
6827
+ return JSON.stringify({ action, enabled: action === "on", review: config.memory.review ?? MEMORY_REVIEW_DEFAULTS, ...(cancelled === undefined ? {} : { cancelled }), ...(view ? { schedule: view } : {}) });
6828
+ }
6610
6829
  // #334: natural-language intake. Person only, except approve for the admitted conductor (#933): Tasks refuses any other actor.
6611
6830
  case "intake": {
6612
6831
  const result = await tasks.intake(by, { text: a.text, sources: a.sources });
@@ -6618,8 +6837,14 @@ export async function startDaemon(opts: DaemonOptions) {
6618
6837
  return JSON.stringify((await tasks.discardIntake(by, a.id)).map(task => tasks.publicView(task)));
6619
6838
  // #514b: the person's verdict on a recurring-criterion candidate. Person only (Tasks refuses any other `by`, and the generic gate above already refuses every non-person caller, the configured
6620
6839
  // conductor included: none of these is in CONDUCTOR_TASK_OPS). Accept writes ONE key, derived from the card's key line, through the settings writer.
6621
- case "learn_list":
6622
- return JSON.stringify(tasks.learnCandidates(by, { all: a.all === true }));
6840
+ // #1642 T2: `--accepted` reads what each followed line did, against the checklist this project uses now. A config that does not load reads no checklist: refused, never an empty one.
6841
+ case "learn_list": {
6842
+ if (a.accepted !== true) return JSON.stringify(tasks.learnCandidates(by, { all: a.all === true }));
6843
+ const stored = storedConfig();
6844
+ if (!stored) throw new PreEffectToolRefusal("the config files do not load; no checklist was read. Fix .agenthub/config.json or config.local.json in your editor, then run ahub learn list --accepted again");
6845
+ const current = resolveProfile(stored.profile, stored.profile_overrides).review_checklist ?? [];
6846
+ return JSON.stringify({ view: "accepted", minReviewed: FOLLOWUP_DEFAULTS.minReviewed, ...tasks.learnFollowed(by, current) });
6847
+ }
6623
6848
  // #445 C1: the person's view of every peer's capabilities, shared or not. Person only (not in CONDUCTOR_TASK_OPS); it shows what a peer offers, never calls it.
6624
6849
  case "capabilities_list": {
6625
6850
  const share = readShare(config.invocation?.share), peers: unknown[] = [];
@@ -6640,8 +6865,17 @@ export async function startDaemon(opts: DaemonOptions) {
6640
6865
  if (!stored) throw new PreEffectToolRefusal("the config files do not load; fix them in your editor first: nothing was written");
6641
6866
  const active = profileName(stored.profile);
6642
6867
  if (plan.profile !== active) throw new PreEffectToolRefusal(`this card is for the ${plan.profile} profile and the project's profile is ${active}: nothing was written; reject the card, or switch profile first`);
6643
- // review_checklist replaces as a unit: extend the checklist the profile uses now (the person's, else the shipped one), never start from one line.
6868
+ // review_checklist replaces as a unit: extend, or for a removal card shorten, the checklist the profile uses now (the person's, else the shipped one), never start from one line.
6644
6869
  const current = resolveProfile(stored.profile, stored.profile_overrides).review_checklist ?? [];
6870
+ if ("marker" in plan) {
6871
+ // #1642 T3: exactly the one line the card's criterion names, and only while it is the checklist's own generated line.
6872
+ const removed = withoutChecklistLine(current, plan.marker);
6873
+ if ("refused" in removed) throw new PreEffectToolRefusal(`${removed.refused}. ahub learn reject ${plan.id} closes this card; ahub learn list --all shows the removal cards and their windows`);
6874
+ const written = await settingsSet(LEARN_CHECKLIST.key, removed.list, "terminal", undefined, undefined, `ahub learn accept #${plan.id}: remove the checklist line`, LEARN_CHECKLIST);
6875
+ if (written.ok !== true) throw new PreEffectToolRefusal(`${written.error ?? "the checklist could not be written"}; the removal card stays open: fix what the error names, then run ahub learn accept on it again`);
6876
+ const closed = await tasks.learnClose(by, a.id, "accepted");
6877
+ return JSON.stringify({ card: tasks.publicView(closed), accepted: { kind: "removal", profile: plan.profile, class: plan.class, criterion: plan.criterion, removed: true, lines: removed.list.length, file: ".agenthub/config.local.json", applies: "after a restart (profile contracts are bound at startup)", undo: "ahub settings undo" } });
6878
+ }
6645
6879
  const next = withChecklistLine(current, plan.line);
6646
6880
  if ("refused" in next) throw new PreEffectToolRefusal(next.refused);
6647
6881
  const already = next.list.length === current.length;
@@ -6649,8 +6883,10 @@ export async function startDaemon(opts: DaemonOptions) {
6649
6883
  const written = await settingsSet(LEARN_CHECKLIST.key, next.list, "terminal", undefined, undefined, `ahub learn accept #${plan.id}`, LEARN_CHECKLIST);
6650
6884
  if (written.ok !== true) throw new PreEffectToolRefusal(String(written.error ?? "the checklist could not be written") + "; the candidate stays open");
6651
6885
  }
6652
- const closed = await tasks.learnClose(by, a.id, "accepted");
6653
- return JSON.stringify({ card: tasks.publicView(closed), accepted: { profile: plan.profile, class: plan.class, criterion: plan.criterion, line: plan.line, tasks: plan.tasks, lines: next.list.length, alreadyPresent: already, file: ".agenthub/config.local.json", applies: "after a restart (profile contracts are bound at startup)", undo: already ? undefined : "ahub settings undo" } });
6886
+ // #1642 T1: the before rate rides the closed card's own note, so the outcome view compares against what was true at acceptance.
6887
+ const before = tasks.learnBeforeRate(by, a.id);
6888
+ const closed = await tasks.learnClose(by, a.id, "accepted", before);
6889
+ return JSON.stringify({ card: tasks.publicView(closed), accepted: { kind: "addition", profile: plan.profile, class: plan.class, criterion: plan.criterion, line: plan.line, tasks: plan.tasks, before, lines: next.list.length, alreadyPresent: already, file: ".agenthub/config.local.json", applies: "after a restart (profile contracts are bound at startup)", undo: already ? undefined : "ahub settings undo" } });
6654
6890
  }
6655
6891
  case "review_brief": {
6656
6892
  const task = board.get(Number(a.id));
@@ -7615,6 +7851,7 @@ export async function startDaemon(opts: DaemonOptions) {
7615
7851
  const researchEvidence = board.researchEvidenceIntegrity();
7616
7852
  const reviewerQuota = reviewerQuotaIntegrity();
7617
7853
  const advisorSurveys = board.surveyIntegrity();
7854
+ const specReadbacks = board.specReadbackIntegrity();
7618
7855
  const guidanceVariants = board.guidanceVariantsIntegrity();
7619
7856
  const guidanceProbes = guidanceProbeStore.integrity();
7620
7857
  const executionReferences = board.executionReferencesIntegrity();
@@ -7623,7 +7860,7 @@ export async function startDaemon(opts: DaemonOptions) {
7623
7860
  const visualIntegrity = visuals.integrity();
7624
7861
  if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
7625
7862
  throw new Error("visual recovery integrity unavailable; inspect the retained store before recovery");
7626
- return { ...(roadmap.milestones || roadmap.links ? { roadmap } : {}), ...(reviewerQuota.rows || !reviewerQuota.complete || reviewerQuota.waits ? { reviewerQuota } : {}), queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(advisorSurveys.surveys || advisorSurveys.findings || advisorSurveys.considered ? { advisorSurveys } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(guidanceProbes.experiments || guidanceProbes.sessions ? { guidanceProbes } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
7863
+ return { ...(roadmap.milestones || roadmap.links ? { roadmap } : {}), ...(reviewerQuota.rows || !reviewerQuota.complete || reviewerQuota.waits ? { reviewerQuota } : {}), queues, manualPaused: [...manualPaused].sort(), boardDigest: digest(boardState), budgetDigest: digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(advisorSurveys.surveys || advisorSurveys.findings || advisorSurveys.considered ? { advisorSurveys } : {}), ...(specReadbacks.readbacks ? { specReadbacks } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(guidanceProbes.experiments || guidanceProbes.sessions ? { guidanceProbes } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(allExternalInstanceIds().length ? { externalBindingsDigest: digest(allExternalInstanceIds().sort().map(id => [id, (externalRefusedRows.has(id) ? externalBindings.get(id) : retainedExternalBinding(id)) ?? null])) } : {}) };
7627
7864
  };
7628
7865
  /** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
7629
7866
  const integrityAs = (expected: unknown) => {
@@ -7672,6 +7909,8 @@ export async function startDaemon(opts: DaemonOptions) {
7672
7909
  const statusPeerIds = (open: ReturnType<Board["statusTasks"]>) => {
7673
7910
  const reservations = board.statusReservations();
7674
7911
  const ids = new Set([...bus.knownPeers(), ...extraIds, ...allExternalInstanceIds(), ...reservations].filter(id => !id.includes("@")));
7912
+ // #1668: a peer whose socket a server the hub did not start is serving stays on the report until a hub-owned launch clears the record.
7913
+ for (const peer of jcodeDetached.keys()) ids.add(peer);
7675
7914
  for (const peer of configuredIds) if (onRoster(peer)) ids.add(peer);
7676
7915
  if (!Object.keys(config.roster).some(peer => !membershipAllowed(peer))) return [...ids];
7677
7916
  for (const task of open) for (const peer of [task.owner, task.reviewer]) if (peer && !membershipAllowed(peer)) ids.add(peer);
@@ -7697,7 +7936,7 @@ export async function startDaemon(opts: DaemonOptions) {
7697
7936
  if (crashLostIds.size) { try { for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && crashLostIds.has(row.id)) inFlight++; } catch { inFlight = crashLostIds.size; } }
7698
7937
  return openCrashNotices(crashNotices, { attached, inFlight });
7699
7938
  };
7700
- const status = (includeAttentionItems = false, includeAttentionInput = false, includeDoing = false, includeIncomingLabels = false) => {
7939
+ const status = (includeAttentionItems = false, includeAttentionInput = false, includeDoing = false, includeIncomingLabels = false, includeActivity = false) => {
7701
7940
  const taskNeeds = board.statusTasks();
7702
7941
  const ownerIsolation = ownerIsolationProjection();
7703
7942
  const taskStalls = tasks.stalled({ ownerIsolation });
@@ -7722,7 +7961,7 @@ export async function startDaemon(opts: DaemonOptions) {
7722
7961
  pendingRestart: allPendingRestart(),
7723
7962
  retainedConfig,
7724
7963
  ...(agentDrift.length ? { agentDrift } : {}),
7725
- ...(config.schedules.length ? { schedules: scheduleViews(config.schedules, schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true) } : {}),
7964
+ ...(scheduleEntries().length ? { schedules: scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true) } : {}),
7726
7965
  ...(() => { const warning = mainCheckoutWarning(opts.cwd, tasks.publicMetadataText, checkoutBranch); return warning ? { mainCheckout: warning } : {}; })(),
7727
7966
  startModes: Object.fromEntries([...START_MODE_PEERS, ...configuredIds].map(peer => [peer, startModeOf(config.peers, peer, declarations, adapterCatalog)])),
7728
7967
  memoryProfile: memoryProfileStatus(includeAttentionItems),
@@ -7762,7 +8001,7 @@ export async function startDaemon(opts: DaemonOptions) {
7762
8001
  ...(dashboard ? { uiOrigin: dashboard.origin } : {}),
7763
8002
  codexProxyPort: opts.codexProxyPort,
7764
8003
  peers: Object.fromEntries(
7765
- peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
8004
+ peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); const detached = jcodeDetached.get(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(detached ? { detached } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
7766
8005
  ),
7767
8006
  peerVersions,
7768
8007
  taskWip: tasks.wipBreakdown(peerIds),
@@ -7801,6 +8040,11 @@ export async function startDaemon(opts: DaemonOptions) {
7801
8040
  };
7802
8041
  // #878: live readers only (the status reply, the dashboard); writeStatus never asks, so status.json never holds it.
7803
8042
  if (includeDoing) for (const [id, doing] of Object.entries(doingRows(peerIds, includeIncomingLabels))) Object.assign(view.peers[id]!, { doing });
8043
+ if (includeActivity) for (const id of peerIds) {
8044
+ if (bus.stateOf(id) !== "busy") continue;
8045
+ const activity = activities.view(id, () => activityPrivate(id));
8046
+ if (activity) Object.assign(view.peers[id]!, { activity });
8047
+ }
7804
8048
  const peerNeeds: Record<string, NonNullable<NeedsInput["peers"]>[string]> = Object.fromEntries(Object.entries(view.peers).map(([peer, row]) => [peer, { state: row.state, attached: row.attached, needsReview: row.needsReview, heldBy: row.heldBy }]));
7805
8049
  // Lazy legacy peer lists need not contain a persisted owner that is now offline.
7806
8050
  for (const task of taskNeeds) if (task.owner && task.owner !== USER && task.owner !== HUB && !Object.hasOwn(peerNeeds, task.owner)) {
@@ -8335,6 +8579,12 @@ export async function startDaemon(opts: DaemonOptions) {
8335
8579
  const nativeFactsTurn = nativeHookLaunches.current(e.peer) !== undefined && bus.peers.get(e.peer)?.pullOnly === true;
8336
8580
  const edits = turnEditsFor(e.peer, open, files); // Discard the tally even when a native completion is unconfirmed.
8337
8581
  if (nativeFactsTurn ? (nativeCompletedAt.get(e.peer) ?? -1) >= open.start : definitionOf(e.peer)?.turnEnd !== "native-hook" || (nativeCompletedAt.get(e.peer) ?? -1) >= open.start) event({ type: "turn_end", peer: e.peer, turn: open.id, ms: Date.now() - open.start, ...open.attribution, preparedRoles: open.preparedRoles, ...(open.tokens ? { tokens: open.tokens } : {}), ...(files !== undefined ? { files, snapshotMs } : {}), ...noteObservedModel(e.peer, observedTurnModel(e.peer)), ...edits });
8582
+ // #1329 AC5: the review's counted spend is checked after the turn that spent it. Only a card among this turn's tasks
8583
+ // reaches the stop, so an ordinary turn costs one lookup of the two live board states.
8584
+ if (open.tokens) {
8585
+ const reviewIds = [...new Set([...open.writeTasks.map(binding => binding.id), ...(open.attribution.task !== undefined ? [open.attribution.task] : [])])];
8586
+ void reviewBudgetAfterTurn(e.peer, reviewIds).catch(reviewBudgetFailure);
8587
+ }
8338
8588
  if (!nativeFactsTurn && definitionOf(e.peer)?.turnEnd !== "native-hook") { // Claude's native turn end is its Stop hook
8339
8589
  if ((bus.peers.get(e.peer)?.state ?? e.state) === "idle") queueMicrotask(() => finishSupervisionTurn(e.peer));
8340
8590
  turnEnded.set(e.peer, Date.now());
@@ -8968,6 +9218,8 @@ export async function startDaemon(opts: DaemonOptions) {
8968
9218
  recoveryTaskPreface(peer); await ensurePreface(peer); startCurrent?.();
8969
9219
  try { startCurrent?.(); await jcode.start(); startCurrent?.(); registerModelOwner(jcode); bindRecordOwner(jcode, executionCwd, () => jcode.nativeSession); await reconcileNativeStart(peer, jcode, startCurrent); }
8970
9220
  catch { await jcode.stop().catch(() => {}); if (jcodeLaunches.get(peer) === jcode) jcodeLaunches.delete(peer); throw new Error("Jcode startup not verified; check native version, provider profile, MCP store and owned daemon (details withheld)"); }
9221
+ // #1668: this peer is under the hub again, so it is no longer detached. A start that failed above keeps the record.
9222
+ if (jcodeDetached.delete(peer) && !stopping) writeStatus();
8971
9223
  return { ok: true, policy: "unmanaged" };
8972
9224
  }
8973
9225
  if (adapter?.start.acpCommand) {
@@ -9026,6 +9278,30 @@ export async function startDaemon(opts: DaemonOptions) {
9026
9278
  } catch (error) { await kimi.stop().catch(stop => log(`kimi stop after a failed start: ${(stop as Error).message}`)); throw error; }
9027
9279
  return { ok: true };
9028
9280
  }
9281
+ if (adapter?.start.daemonPort === "configured-print" && adapter.start.create) {
9282
+ if (Object.entries(args).some(([key, value]) => key !== "mode" && value !== undefined))
9283
+ return { ok: false, error: "configured print accepts no launch overrides or resume options" };
9284
+ if (retainedOwner?.pendingOwnedProcess) return { ok: false, error: "configured print cleanup is unconfirmed; stop the peer before starting it again" };
9285
+ const print = adapter.start.create({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config,
9286
+ permission: "read-only", mcpServers: [], daemon: DAEMON_PORTS["configured-print"]({
9287
+ cwd: executionCwd, stateDir: opts.stateDir,
9288
+ deny: () => [...config.local.deny, ...(config.pii?.paths ?? [])],
9289
+ privateTurn: envs => contextPii(peer) || turns.get(peer)?.private === true || envs.some(env => {
9290
+ const task = env.refs?.task ? board.get(Number(env.refs.task)) : undefined;
9291
+ return task ? tasks.isPii(task) : false;
9292
+ }),
9293
+ publicText: boundedSafe,
9294
+ }) });
9295
+ try {
9296
+ startCurrent?.(); await print.start(); startCurrent?.();
9297
+ bus.add(print);
9298
+ print.onState?.(print.state);
9299
+ } catch (error) {
9300
+ await print.stop().catch(() => { bus.add(print); });
9301
+ throw error;
9302
+ }
9303
+ return { ok: true, policy: "unmanaged" };
9304
+ }
9029
9305
  if (adapter?.transport === "acp" && adapter.start.create && adapter.start.launch) {
9030
9306
  // Configured ACP definitions own immutable argv and policy; builtins retain their verified launch port.
9031
9307
  const launch = adapter.start.launch({ instance: peer, form: "headless", projectRoot: opts.cwd, stateDir: opts.stateDir, entrypoint: CLI_ENTRY,
@@ -9107,6 +9383,7 @@ export async function startDaemon(opts: DaemonOptions) {
9107
9383
  actionBudgets.revoke(peer);
9108
9384
  startCurrent?.();
9109
9385
  const codex: CodexPeer = adapter!.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["codex-appserver"]({
9386
+ activityServers: codexActivityServers(process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), executionCwd),
9110
9387
  getModelOverride: () => modelSelection(peer),
9111
9388
  onNativeModelApplied: model => { if (!stopping && bus.peers.get(peer) === codex && isNativeModelToken(model)) {
9112
9389
  try { modelLatches.observeNative(peer, codex, model); } catch { modelLatches.forget(peer); }
@@ -10215,6 +10492,14 @@ export async function startDaemon(opts: DaemonOptions) {
10215
10492
  if (tasks.milestoneShow(USER, cardId).order !== index) tasks.milestoneOrder(USER, cardId, index);
10216
10493
  }
10217
10494
  /** The dashboard's roadmap payload: the same public projection `ahub roadmap show` renders, plus who may act. */
10495
+ // #1514: the Overview figures are reused until the board, the UTC day or the open stalls change, so a quiet board costs nothing per poll.
10496
+ let overviewMemo: { key: string; view: ReturnType<typeof overviewModel> } | undefined;
10497
+ function overviewSnapshot() {
10498
+ const now = Date.now();
10499
+ const key = JSON.stringify([board.statusRevision(), Math.floor(now / 86_400_000), tasks.stalled().map(stall => [stall.task, stall.cause.kind])]);
10500
+ if (overviewMemo?.key !== key) overviewMemo = { key, view: overviewModel(tasks.overviewInput(now)) };
10501
+ return overviewMemo.view;
10502
+ }
10218
10503
  function roadmapSnapshot(session?: DashboardSession) {
10219
10504
  try { return { milestones: tasks.milestoneList(USER), person: session?.liveTest !== true }; }
10220
10505
  catch { return { unavailable: true, person: false }; }
@@ -10334,11 +10619,13 @@ export async function startDaemon(opts: DaemonOptions) {
10334
10619
  // #1483 R5: the roadmap block is the read that computes spec freshness, so it rides only the view that shows it and
10335
10620
  // never another view's 1 s poll. The board's Milestone filter reads the same rows here, and its placement is the
10336
10621
  // explicit task link only (the projection above also places a task through the issue it came from).
10622
+ // #1514: the Overview figures are computed only for the view that shows them, so no other view's 1 s poll pays for them.
10623
+ ...(input?.view === "overview" ? { overview: overviewSnapshot() } : {}),
10337
10624
  ...(input?.view === "roadmap" ? { roadmap: { ...roadmapSnapshot(session), drift: roadmapDrift } } : {}),
10338
10625
  milestones: board.milestones().map(row => ({ id: row.id, title: row.title, horizon: row.horizon, state: row.state, order: row.order })),
10339
10626
  milestoneOfTask: Object.fromEntries(board.milestoneLinks().filter(link => link.kind === "task").map(link => [link.ref, link.milestone] as const)),
10340
10627
  // #335: each schedule's next run, ids and times only (a title or detail is task text). Absent when none is configured, so an older page and an unconfigured project see no change.
10341
- ...(config.schedules.length ? { schedules: scheduleViews(config.schedules, schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true) } : {}),
10628
+ ...(scheduleEntries().length ? { schedules: scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true) } : {}),
10342
10629
  boardLegend: Object.entries(peerView).map(([id, peer]) => ({
10343
10630
  peer: id, state: peer.state,
10344
10631
  permissionMode: "permissionNote" in peer && peer.permissionNote ? "unmanaged" : permissionDisplay(id, bus.peers.get(id)),
@@ -10622,7 +10909,10 @@ export async function startDaemon(opts: DaemonOptions) {
10622
10909
  if (changes.some(change => change.key === "task_sweep" || change.key.startsWith("task_sweep."))) rescheduleSweep();
10623
10910
  const syncChange = changes.find(change => change.key === "memory.sync_interval_min");
10624
10911
  if (syncChange) rescheduleMemorySync((Number(syncChange.before ?? 10) <= 0) && Number(syncChange.after ?? 10) > 0);
10625
- if (changes.some(change => change.key === "schedules" || change.key.startsWith("schedules.") || change.key === "folder_triggers" || change.key.startsWith("folder_triggers."))) rescheduleSchedules();
10912
+ // #1329 part 1: no pause fence is synced here, and none is needed: a schedule's row is pruned as soon as its entry
10913
+ // disappears (`Tasks.proposeFromSchedules`), so `off` leaves no pause behind and `on` starts from a fresh period. The
10914
+ // one pause that outlives a config edit is a person's own `ahub schedule pause memory-review`, which `on` clears.
10915
+ if (changes.some(change => change.key === "schedules" || change.key.startsWith("schedules.") || change.key === "folder_triggers" || change.key.startsWith("folder_triggers.") || change.key === "memory.review" || change.key.startsWith("memory.review."))) rescheduleSchedules();
10626
10916
  if (changes.some(change => ["batch_max", "batch_ms", "queue_cap"].includes(change.key))) bus.configureScheduling({ batchMax: config.batch_max, batchMs: config.batch_ms, queueCap: config.queue_cap });
10627
10917
  if (changes.some(change => change.key === "watchdog_ms")) for (const peer of bus.peers.values()) if (peer instanceof BasePeer) peer.configureWatchdog(config.watchdog_ms);
10628
10918
  Object.assign(limits, config.limits);
@@ -11454,6 +11744,10 @@ export async function startDaemon(opts: DaemonOptions) {
11454
11744
  }
11455
11745
  catch { return "instructed mode compatibility is unknown; choose a supporting daemon"; }
11456
11746
  }
11747
+ if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probe_live")) {
11748
+ try { if (guidanceProbeStore.hasLiveRecords()) return "target lacks guidance_probe_live; retained live guidance probe state requires a supporting daemon"; }
11749
+ catch { return "live guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
11750
+ }
11457
11751
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probes")) {
11458
11752
  try { if (guidanceProbeStore.hasRecords()) return "target lacks guidance_probes; retained probe declarations or held work require a supporting daemon; choose a target advertising guidance_probes"; }
11459
11753
  catch { return "guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
@@ -11485,6 +11779,7 @@ export async function startDaemon(opts: DaemonOptions) {
11485
11779
  // #1054: an older daemon ignores the completion tables, so an open run or a completion nobody has seen would be lost silently.
11486
11780
  if (completionStore.hasPending() && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("completions"))) return `target lacks completions; ${completionStore.openRuns().length ? "open runs cannot be kept by that daemon: let them settle (ahub status), then retry; " : ""}unread results cannot be kept by that daemon: read them (ahub results --read-all), or use a supporting release`;
11487
11781
  if (externalIds.size && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("external_adapter_modules"))) return "target lacks external_adapter_modules; verified external definitions cannot be preserved by that daemon";
11782
+ if (configuredIds.some(id => definitionOf(id)?.start.daemonPort === "configured-print") && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("configured_print"))) return "target lacks configured_print; print adapter declarations cannot be preserved by that daemon";
11488
11783
  if (configuredIds.length && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("configured_acp"))) return "target lacks configured_acp; project adapter definitions cannot be preserved by that daemon";
11489
11784
  if (extraIds.length && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("peer_instances"))) return "target lacks peer_instances; declared instance identities cannot be restored by that daemon";
11490
11785
  if (extraIds.some(id => adapterCatalog.definitionOf(declarations[id]!.kind)?.transport === "claude-channel" && declarations[id]!.roles?.includes("implementer")) && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("role_stages"))) return "target lacks role_stages; declared Claude implementer authority cannot be restored by that daemon";
@@ -11562,6 +11857,8 @@ export async function startDaemon(opts: DaemonOptions) {
11562
11857
  return "target lacks research_evidence_withdrawal; choose a supporting daemon to preserve withdrawal revisions";
11563
11858
  if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("advisor_surveys")) && board.hasSurveyState())
11564
11859
  return "target lacks advisor_surveys; persisted survey candidates and considered-finding history require a supporting daemon";
11860
+ if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("spec_readbacks")) && board.hasSpecReadbacksState())
11861
+ return "target lacks spec_readbacks; stored spec read-back requests and reports require a supporting daemon";
11565
11862
  if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("project_autonomy")) {
11566
11863
  let needsAutonomy = autonomyConfirmed.size > 0;
11567
11864
  try {
@@ -12079,7 +12376,12 @@ export async function startDaemon(opts: DaemonOptions) {
12079
12376
  // peer's current owned launch. A forged AGENTHUB_PEER_ID in some other process has no such id, so it never acts as that peer.
12080
12377
  if (definitionOf(c.peer)?.start.daemonPort === "owned-acp") {
12081
12378
  const owner = jcodeLaunches.get(c.peer);
12082
- if (!owner || !owner.ownsLaunch(msg.launchId)) return sock.close(4403, "this process is not an owned launch of that peer; start it with ahub jcode");
12379
+ if (!owner || !owner.ownsLaunch(msg.launchId)) {
12380
+ // #1668: this peer's socket is served by a server the hub did not start, so the peer is offline here while that work goes on. The refusal
12381
+ // itself is unchanged and nothing new listens; the peer only gains the state `ahub status` reports until a hub-owned launch replaces it.
12382
+ if (!stopping) { jcodeDetached.set(c.peer, jcodeDetachedNotice(c.peer)); writeStatus(); }
12383
+ return sock.close(4403, "this process is not an owned launch of that peer; start it with ahub jcode");
12384
+ }
12083
12385
  }
12084
12386
  } else {
12085
12387
  c.peer = String(msg.peer ?? defaultChannelPeer(undefined));
@@ -13212,6 +13514,33 @@ export async function startDaemon(opts: DaemonOptions) {
13212
13514
  (error: Error) => reply({ ok: false, error: sanitize(error.message).slice(0, 300) })).finally(() => { taskOpsInFlight--; });
13213
13515
  return;
13214
13516
  }
13517
+ if (msg.op === "readback-start" || msg.op === "readback-show") {
13518
+ // #1658: the person or the current conductor starts and reads a spec read-back; every request gets a reply.
13519
+ if (Object.keys(msg).some(key => !["t", "rid", "op", "id"].includes(key))) return void reply({ ok: false, error: "a read-back accepts only its task id; remove unknown fields" });
13520
+ const asker = c.role === "console" ? USER : c.role === "tools" && c.peer && conductorPeer(config.roles) === c.peer && !c.toolsOwner && !turns.get(c.peer)?.private && !contextPii(c.peer) ? c.peer : undefined;
13521
+ if (!asker) return void reply({ ok: false, error: "only the person or the current configured conductor may use spec read-backs; ask the person to run ahub sdlc readback start" });
13522
+ const externalOwner = c.externalOwner;
13523
+ const sessionCurrent = c.role === "console" ? () => { if (sock.data !== c || sock.readyState !== WebSocket.OPEN || c.role !== "console") throw new Error("person session changed"); } : operationalCurrent(sock);
13524
+ const fence = () => {
13525
+ try {
13526
+ sessionCurrent();
13527
+ if (externalOwner && !currentExternalTools(c, true)) return "read-back execution root changed; reconnect and retry";
13528
+ sessionCurrent();
13529
+ if (c.peer !== (asker === USER ? undefined : asker) || c.externalOwner !== externalOwner || c.toolsOwner) return "read-back actor changed; reconnect and retry";
13530
+ if (c.peer && (turns.get(c.peer)?.private || contextPii(c.peer))) return "read-back unavailable during private input";
13531
+ return recoveryActive() || stopping ? "recovery or shutdown holds read-back writes; retry after release" : undefined;
13532
+ } catch { return "read-back person or conductor session changed; reconnect and retry"; }
13533
+ };
13534
+ const refusal = fence(); if (refusal) return void reply({ ok: false, error: refusal });
13535
+ if (msg.op === "readback-show") {
13536
+ try { return void reply({ ok: true, readback: tasks.specReadbackShow(asker, msg.id) }); }
13537
+ catch (error) { return void reply({ ok: false, error: sanitize(error instanceof Error ? error.message : "read-back read unavailable").slice(0, 300) }); }
13538
+ }
13539
+ taskOpsInFlight++;
13540
+ void tasks.specReadbackStart(asker, msg.id, fence).then(result => reply({ ok: true, ...result }),
13541
+ (error: Error) => reply({ ok: false, error: sanitize(error.message).slice(0, 300) })).finally(() => { taskOpsInFlight--; });
13542
+ return;
13543
+ }
13215
13544
  if (msg.op === "audit-start" || msg.op === "audit-show") {
13216
13545
  // #1403 A4: the person or the one configured conductor starts and reads a security audit. Every request gets a reply, a refusal included.
13217
13546
  const asker = c.role === "console" ? USER : c.role === "tools" && c.peer && conductorPeer(config.roles) === c.peer && !c.toolsOwner && !turns.get(c.peer)?.private && !contextPii(c.peer) ? c.peer : undefined;
@@ -13333,13 +13662,22 @@ export async function startDaemon(opts: DaemonOptions) {
13333
13662
  const repo = msg.repo ?? task?.sdlc?.repo;
13334
13663
  if (!task || typeof repo !== "string") return void reply({ ok: false, error: task ? "spec acceptance needs --repo owner/repository (the task's receipt names none)" : "invalid lifecycle task id" });
13335
13664
  const linked = `${task.sdlc?.repo ?? ""}#${task.sdlc?.issue ?? ""}`;
13336
- void readSpecEdit(repo, msg.issue, (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound)).then(edit => {
13665
+ void readSpecEdit(repo, msg.issue, opts.boundedTools?.specEdit ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound))).then(edit => {
13337
13666
  if (!edit) return reply({ ok: false, error: "issue edit time unavailable; nothing was recorded" });
13338
13667
  // The readback is for the receipt read before it; a relink meanwhile makes it someone else's evidence.
13339
13668
  const now = board.get(msg.id)?.sdlc;
13340
13669
  if (`${now?.repo ?? ""}#${now?.issue ?? ""}` !== linked) return reply({ ok: false, error: "the task's spec link changed during the readback; nothing was recorded, run ahub sdlc accept again" });
13341
- try { const next = tasks.acceptSpec(USER, msg.id, { repo, issue: msg.issue, edit }); reply({ ok: true, acceptance: next.sdlc?.acceptance }); }
13342
- catch (error) { reply({ ok: false, error: (error as Error).message }); }
13670
+ try {
13671
+ // #1658 AC6: the read-back line prints before the acceptance is recorded, and the acceptance proceeds in every state.
13672
+ const accepted = board.get(msg.id)!;
13673
+ // A read-back row whose bytes fail their hash is a storage defect, not a reason to refuse the person's
13674
+ // acceptance: the line then says the state is unknown, and the acceptance is recorded as in any other state.
13675
+ let readback: string | undefined;
13676
+ try { readback = readbackAcceptField(tasks.readbackView({ ...accepted, sdlc: { ...(accepted.sdlc ?? { stage: "spec" as const }), repo, issue: msg.issue } }, edit), msg.id).readback; }
13677
+ catch { readback = "spec read-back: storage unreadable (the acceptance is recorded and no state is known; restore a trusted hub.db backup to read it)"; }
13678
+ const next = tasks.acceptSpec(USER, msg.id, { repo, issue: msg.issue, edit });
13679
+ reply({ ok: true, acceptance: next.sdlc?.acceptance, ...(readback ? { readback } : {}) });
13680
+ } catch (error) { reply({ ok: false, error: (error as Error).message }); }
13343
13681
  }, () => reply({ ok: false, error: "issue edit time unavailable; nothing was recorded" }));
13344
13682
  return;
13345
13683
  }
@@ -13426,7 +13764,7 @@ export async function startDaemon(opts: DaemonOptions) {
13426
13764
  return void reply({ ok: false, error: "unknown room operation" });
13427
13765
  }
13428
13766
  case "status": {
13429
- const current = status(c.role === "console", false, true, c.role === "console" || (c.role === "tools" || c.role === "peer") && c.peer === conductorPeer(config.roles));
13767
+ const current = status(c.role === "console", false, true, c.role === "console" || (c.role === "tools" || c.role === "peer") && c.peer === conductorPeer(config.roles), c.role === "console");
13430
13768
  if ((c.role === "console" || c.role === "tools") && msg.specs === true) {
13431
13769
  const summary = projectSpecs.status();
13432
13770
  if (summary) {
@@ -13920,6 +14258,11 @@ export async function startDaemon(opts: DaemonOptions) {
13920
14258
  if (c.role !== "console") return void reply({ t: "questions", ok: false, error: "questions are shown to the person: use the console" });
13921
14259
  return void reply({ t: "questions", ok: true, questions: questionStore.list(msg.state === "all" ? {} : { state: "open" }, 100).map(questionView), answeredQuestions: instructedQuestionViews() });
13922
14260
  }
14261
+ // #1635: the board's write counter alone, for acon's revision polling. A console-role read of one bare number: no task, title or text, and no board write. An older hub answers an unknown message with ok:false, which the plugin maps to "0" (always fetch).
14262
+ case "board_revision": {
14263
+ if (c.role !== "console") return void reply({ t: "board_revision", ok: false, error: "the board revision is read by the console" });
14264
+ return void reply({ t: "board_revision", ok: true, boardRevision: board.statusRevision() });
14265
+ }
13923
14266
  // #1054: a person's receipt for a result. Console role ONLY, like `permit`: a peer's connection, a `hub_send` body or a tool result that quotes a receipt is text and never reaches
13924
14267
  // the store. A snapshot or a `results` read never writes one. Every message gets a reply (rid), a refusal included.
13925
14268
  case "result_seen": {