@staix/agent-hub 0.49.1 → 0.51.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 (99) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +3 -3
  6. package/docs/agent-notes/daemon.md +1 -1
  7. package/docs/agent-notes/local-worker.md +3 -3
  8. package/docs/agent-notes/tasks.md +5 -1
  9. package/docs/design/adapters.md +17 -0
  10. package/docs/design/agent-hub.md +1 -1
  11. package/docs/design/cli-output-inventory.md +24 -19
  12. package/docs/design/cli-output.md +1 -1
  13. package/docs/design/roadmap.md +2 -2
  14. package/docs/design/task-board.md +34 -0
  15. package/docs/dogfood.md +8 -3
  16. package/docs/operations.md +53 -4
  17. package/docs/quickstart.md +26 -2
  18. package/docs/roadmap.json +20 -20
  19. package/docs/roadmap.md +2 -2
  20. package/docs/sdlc.md +3 -2
  21. package/docs/specs/2026-09-19-agent-hub-design.md +1 -0
  22. package/docs/verification/2026-11-29-0.50.0.md +54 -0
  23. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  24. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  25. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  26. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  27. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  28. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  29. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  30. package/docs/verified.json +31 -27
  31. package/package.json +1 -1
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +1329 -24629
  34. package/plugins/agent-hub/server.js +638 -414
  35. package/scripts/check-docs.mjs +1 -1
  36. package/src/adapters/acp.ts +13 -13
  37. package/src/adapters/agy/definition.ts +2 -2
  38. package/src/adapters/agy/entry.ts +2 -0
  39. package/src/adapters/claude-channel-evidence.ts +7 -3
  40. package/src/adapters/compat.ts +4 -3
  41. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  42. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -1
  43. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  44. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  45. package/src/adapters/definitions/native-cli-entry-jcode.ts +2 -0
  46. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  47. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  48. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  49. package/src/adapters/definitions/native-cli-entry-types.ts +3 -1
  50. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  51. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  52. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  53. package/src/adapters/jcode.ts +16 -0
  54. package/src/adapters/native-facts-hooks.ts +12 -0
  55. package/src/cli/autonomy-offline.ts +1 -1
  56. package/src/cli/bench.ts +1 -1
  57. package/src/cli/claude-profile-hook.ts +31 -11
  58. package/src/cli/commands/releases.ts +82 -0
  59. package/src/cli/conductor-recovery.ts +1 -1
  60. package/src/cli/facts-hook.ts +11 -4
  61. package/src/cli/help.ts +12 -10
  62. package/src/cli/identity.ts +5 -1
  63. package/src/cli/init-prompt.ts +1 -1
  64. package/src/cli/init-settings.ts +4 -35
  65. package/src/cli/init.ts +1 -1
  66. package/src/cli/json-text-spans.ts +57 -0
  67. package/src/cli/launch-check.ts +157 -0
  68. package/src/cli/launch.ts +19 -1
  69. package/src/cli/main.ts +63 -10
  70. package/src/cli/memory.ts +1 -1
  71. package/src/cli/output.ts +14 -1
  72. package/src/cli/preview.ts +1 -1
  73. package/src/cli/recovery-launch.ts +1 -1
  74. package/src/cli/setup-homes.ts +2 -2
  75. package/src/cli/start-agents-run.ts +85 -7
  76. package/src/cli/start-check.ts +28 -0
  77. package/src/cli/upgrade-runtime.ts +1 -1
  78. package/src/cli/warn-line.ts +1 -1
  79. package/src/hub/ci-watch.ts +311 -79
  80. package/src/hub/config-apply.ts +1 -1
  81. package/src/hub/config.ts +518 -0
  82. package/src/hub/control-client.ts +1 -1
  83. package/src/hub/daemon.ts +76 -513
  84. package/src/hub/delivery-public.ts +11 -0
  85. package/src/hub/hub-check.ts +125 -0
  86. package/src/hub/path-policy.ts +1 -1
  87. package/src/hub/permission-mode.ts +3 -40
  88. package/src/hub/permission-paths.ts +41 -0
  89. package/src/hub/recovery-policy.ts +1 -1
  90. package/src/hub/releases-inventory.ts +198 -0
  91. package/src/hub/runtime-capture-prune.ts +25 -3
  92. package/src/hub/runtime-prune-health.ts +8 -1
  93. package/src/hub/sdlc-release-authorization.ts +42 -21
  94. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  95. package/src/hub/sdlc-release-policy.ts +21 -7
  96. package/src/hub/sdlc-release.ts +80 -20
  97. package/src/hub/sdlc.ts +7 -3
  98. package/src/hub/tasks.ts +138 -36
  99. package/src/ui/plugin.ts +1 -1
package/src/hub/daemon.ts CHANGED
@@ -7,7 +7,7 @@ import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-varia
7
7
  import { GuidanceProbeStore } from "./guidance-probe-store.ts";
8
8
  import { GuidanceProbeError, probeSessionGeneration, probeSha256, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.ts";
9
9
  import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
10
- import { publicDeliveryBodies } from "./delivery-public.ts";
10
+ import { publicDeliveryBodies, publicDeliveryReason } from "./delivery-public.ts";
11
11
  import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
12
12
  import { RecordCapture, type RecordCapturePolicy } from "../memory/records.ts";
13
13
  import { VisualStore, validateVisualInput, validateVisualPayload, VISUAL_ID_PATTERN, type VisualRecord, type VisualSummary } from "./visual.ts";
@@ -22,7 +22,7 @@ import type { ActionMeta } from "@staix/agent-console/contract";
22
22
  import { isReviewObserverExcluded, reviewCaptureExcluded } from "./memory-policy.ts";
23
23
  import { RoomStoreError } from "../rooms/store.ts";
24
24
  import { RoomCommands, RoomRotationHoldError, type RoomPreview } from "../rooms/commands.ts";
25
- import { queueBackpressurePolicy, type QueueBackpressurePolicy } from "./queue-backpressure.ts";
25
+ import { queueBackpressurePolicy } from "./queue-backpressure.ts";
26
26
  import { RoomChat, type RoomInvocationIngress } from "../rooms/service.ts";
27
27
  import { RoomInvocations, roomInvocationHash } from "./room-invocations.ts";
28
28
  import { parseRemotePeerId, roomInvocationArgs, encodeRoomInvocationBody, type RoomReadInvocationRequest } from "../rooms/application.ts";
@@ -44,14 +44,14 @@ import { createClaudeFailureTrace, type ClaudeFailureTrace } from "./claude-fail
44
44
  import { buildNativePermissionProbe, NATIVE_PERMISSION_PROBE_MAX_PER_LAUNCH, validateNativePermissionRequest } from "./native-permission-request.ts";
45
45
  import { createClaudeLaunchProof, readClaudeLaunchProof } from "./claude-launch-proof.ts";
46
46
  import { InboxPolling } from "./inbox-polling.ts";
47
- import { ActionBudgets, actionPolicyConfig, floorEnforcement, floorReads, type ActionPolicyConfig } from "./action-policy.ts";
47
+ import { ActionBudgets, floorEnforcement, floorReads } from "./action-policy.ts";
48
48
  import { actionGate, claudeActionClasses } from "./action-enforce.ts";
49
49
  import type { FloorFacts } from "./action-class.ts";
50
50
  import { ReleaseAuthorizations, releaseAuthorizationError } from "./sdlc-release-authorization.ts";
51
51
  import { readCommittedReleasePolicy } from "./sdlc-release-policy.ts";
52
52
  import { parseReleaseGuardArgv, parseReleasePushUpdates } from "../cli/sdlc-release-guard.ts";
53
53
  import type { DocEvidence, ReleaseReportPolicy } from "./sdlc-release.ts";
54
- import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent, type AdapterModuleDeclaration } from "../adapters/external-modules.ts";
54
+ import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent } from "../adapters/external-modules.ts";
55
55
  import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
56
56
  import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
57
57
  import { NativeHookLaunches, type NativeHookLaunch } from "./native-hook-launch.ts";
@@ -60,7 +60,7 @@ import { Registry } from "./registry.ts";
60
60
  import { usedClaudeHomes } from "../cli/autonomy-homes.ts";
61
61
  import { readReleaseHostAdmission, type ReleaseHostAdmission } from "./release-admission.ts";
62
62
  import { MERGE_READBACK_INTERVAL_MS } from "./sdlc-merge.ts";
63
- import { ContainerRunner, RemoteRunner, remoteRunnerConfig, type RemoteRunnerConfig, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
63
+ import { ContainerRunner, RemoteRunner, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
64
64
  import { fetchSpec, specAvailable, specRefs } from "./spec-read.ts";
65
65
  import { readbackAcceptField } from "./spec-readback.ts";
66
66
  import { isDenied, sbplString } from "../local/deny.ts";
@@ -72,23 +72,23 @@ import { correctionInput, MemoryTelemetry } from "./memory-candidates.ts";
72
72
  import { MemoryObservations } from "./memory-observations.ts";
73
73
  import { createStalenessProbe } from "./memory-staleness.ts";
74
74
  import { matchingPlanFails, planGuardNodes, taskMemoryQueryNodes } from "./memory-plan-guard.ts";
75
- import { planningWipLimits } from "./planning.ts";
76
75
  import { ToolWriteRegistry, toolWriteOperation, toolWriteUnknownReply } from "./tool-request.ts";
77
76
  import { ControlWriteTelemetry, controlWriteMetadata, controlWriteSpan } from "./control-write-trace.ts";
78
77
  import { projectedDiff } from "./projected-diff.ts";
79
78
  import { listenWithoutPortCollision } from "./listen.ts";
80
79
  import { needs, type NeedsInput } from "../ui/needs.ts";
81
80
  import { overviewModel } from "../ui/overview-model.ts";
82
- import { loadPetConfig, PET_WINDOW_RETIRED_NOTICE, stripLegacyPetWindow } from "../pet/config.ts";
83
- import { projectionConfig, TextProjections, type ProjectionConfig } from "./text-projection.ts";
81
+ import { loadPetConfig } from "../pet/config.ts";
82
+ import { TextProjections } from "./text-projection.ts";
84
83
  import { policyPaths, policyRealPath, matchesPolicy } from "./path-policy.ts";
85
84
  import { CodeFacts, type CodeFactResult, type CodeSymbol } from "./code-facts.ts";
86
85
  import { gitAuditSource, checkoutAuditSource } from "./audit-source.ts";
87
86
  import { buildReviewBrief, withCodeSymbols } from "./review-brief.ts";
88
- import { profileName, projectProfile, resolveProfile, mergeProfileOverrides, type ProfileName } from "./profiles.ts";
87
+ import { profileName, projectProfile, resolveProfile } from "./profiles.ts";
89
88
  import { catalogAssignments, loadRoleCatalog, selectedRoles, roleIdentity } from "./roles.ts";
90
89
  import { ActivityRing } from "./activity.ts";
91
- import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer, jcodeDetachedNotice, jcodeToolCeilingCause, jcodeVersionAsync, type JcodePeer } from "../adapters/jcode.ts";
90
+ import { buildHubCheck, expectedHubLink } from "./hub-check.ts";
91
+ import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer, jcodeDetachedNotice, jcodeToolCeilingCause, jcodeVersionAsync, refusedHelloProcess, type JcodePeer } from "../adapters/jcode.ts";
92
92
  import { VERSION_REFUSAL, configuredCommands, describe, isCompatId } from "../adapters/compat.ts";
93
93
  import { agentVersionsAsync, type AgentVersionRow } from "../cli/agents.ts";
94
94
  import { driftedAgents, noticeDrift, type DriftedAgent } from "./agent-drift.ts";
@@ -99,12 +99,12 @@ import { peerRosterConfig, rosterAllows, staleInstanceKey, type PeerRoster } fro
99
99
  import { KNOWN_PEERS, OPTIONAL_PEERS, PLANNER_PEERS, SUPPORTED_PEERS, START_MODE_PEERS, isSupportedPeer, STARTABLE_PEERS, isStartablePeer } from "../adapters/registry.ts";
100
100
  import { RecoveryDeferredHubError } from "./deferred-hub.ts";
101
101
  import { databaseBusySite, isDatabaseBusy, RecoveryDatabaseBusy } from "./recovery-error.ts";
102
- import { ADAPTERS, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS, QUOTA_HANDOFF_PLATFORMS, NATIVE_CONFIG_BLOCKS, nativeConfigurationDefaults, mergeNativeConfiguration, retainNativeRouting, DAEMON_PORTS, definitionOf, createProjectAdapterCatalog, isFixedBuiltinDefinition } from "../adapters/registry.ts";
102
+ import { ADAPTERS, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS, QUOTA_HANDOFF_PLATFORMS, retainNativeRouting, DAEMON_PORTS, definitionOf, createProjectAdapterCatalog, isFixedBuiltinDefinition } from "../adapters/registry.ts";
103
103
  import { isSupportedPeer as registrySupportedPeer, definitionOf as builtinDefinitionOf, KNOWN_PEERS as BASE_KNOWN_PEERS, SUPPORTED_PEERS as BASE_SUPPORTED_PEERS, STARTABLE_PEERS as BASE_STARTABLE_PEERS } from "../adapters/registry.ts";
104
104
  import type { NativeFactsTranscript } from "../adapters/registry-types.ts";
105
105
  import type { ReviewScope } from "./review-scope.ts";
106
106
  import { checkJcodeInstanceHomes, instanceDefinitionOf, effectiveInstanceRoles, isPlannerOnly, instancePeerIds, validateInstances, type InstancesConfig } from "./instances.ts";
107
- import { INSTANCE_CONFIG_FILES, readInstanceConfig, withoutInertInstancePolicy, readInstanceConfigLayers, readInstanceRoleConfig } from "./instance-config.ts";
107
+ import { readInstanceConfig, readInstanceConfigLayers, readInstanceRoleConfig } from "./instance-config.ts";
108
108
  import { instanceBudgetHooks, projectBudgetHeadroom } from "./instance-budget.ts";
109
109
  import { resolveInstanceExecutionCwd } from "./instance-execution.ts";
110
110
  import { ProgressObserver, normalizeCodexObservation, normalizeClaudeObservation } from "./progress.ts";
@@ -116,14 +116,13 @@ import { homedir } from "node:os";
116
116
  import { spawn } from "node:child_process";
117
117
  import { childEnv, personEnv } from "./child-process.ts";
118
118
  import { runCheck } from "./checks.ts";
119
- import { DEFAULT_TASK_SWEEP, taskSweepConfig, type TaskSweepConfig } from "./task-sweep.ts";
120
- import { CONTRADICTION_WINDOW_SETTING, DEMOTE_AT_SETTING, DEMOTION_HALF_LIFE_SETTING, GROOM_FYI_WINDOW_SETTING, RESCREEN_MAX_SETTING, SPLIT_FAILURE_SHARE_SETTING, SPLIT_MIN_SETTING, taskOperationalReaders } from "./operational-settings.ts";
121
- import { CONSOLE_POLL_SETTING, CONSOLE_NOTICE_SETTING, CONSOLE_HISTORY_SETTING, CONSOLE_PENDING_STREAM_SETTING, CONSOLE_ATTENTION_SETTING, type ConsoleOperationalConfig } from "./operational-settings.ts";
122
- import { MODEL_COOLDOWN_FAILURES_SETTING, MODEL_COOLDOWN_SETTING, MODEL_COOLDOWN_CAP_SETTING, MODEL_TERMINAL_HISTORY_SETTING, modelOperationalReaders, type ModelOperationalConfig } from "./operational-settings.ts";
123
- import { ACP_TOOL_CEILING_SETTING, ACP_ACTIVITY_BATCH_SETTING, JCODE_STEER_TIMEOUT_SETTING, adapterOperationalReaders, type AdapterTimingConfig } from "./operational-settings.ts";
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";
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";
119
+ import { taskSweepConfig } from "./task-sweep.ts";
120
+ import { GROOM_FYI_WINDOW_SETTING, taskOperationalReaders } from "./operational-settings.ts";
121
+ import { modelOperationalReaders } from "./operational-settings.ts";
122
+ import { adapterOperationalReaders } from "./operational-settings.ts";
123
+ import { busOperationalReaders } from "./operational-settings.ts";
124
+ import { scheduleKeyOf, scheduleViews, ScheduleStore, type ScheduleEntry } from "./schedules.ts";
125
+ import { MEMORY_REVIEW_DEFAULTS, MEMORY_REVIEW_SCHEDULE_ID, memoryReviewCountLine, memoryReviewEntry, memoryReviewScope, memoryReviewTask, reviewBudgetNote, reviewBudgetStop, reviewCheckpointRequest, type ReviewSpend } from "./memory-review.ts";
127
126
  import { FolderStore, registerScanned, scanFolder, type FolderPolicy } from "./folder-trigger.ts";
128
127
  import { QuestionStore, QUESTION_SURFACES, questionView } from "./questions.ts";
129
128
  import { RunTracker, outcomeOf, settleVerdict, type Run } from "./completions.ts";
@@ -131,15 +130,13 @@ import { resultDetail, type ResultDetail } from "./completion-detail.ts";
131
130
  import { CompletionStore } from "./completions-store.ts";
132
131
  import { QuestionDesk } from "./question-desk.ts";
133
132
  import type { ScannedFile } from "./schedules.ts";
134
- import { corpusConfig } from "./corpus-config.ts";
135
- import { roadmapConfig, type MilestoneLinkKind, type MilestoneState, type RoadmapConfig } from "./roadmap.ts";
136
- import { mcpAllowNames } from "./instances.ts";
137
- import { ALL_MACHINE_LOCAL, configRefusal, configRepositoryPresent, configTracked, stripUntrusted } from "./config-trust.ts";
138
- import { instructedMode, parseExactInstruction, exactForm, instructedExecution, INSTRUCTION_CHILD_TIMEOUT_MS, type ExactForm, type InstructedExecution } from "./instructed-exact.ts";
133
+ import { roadmapConfig, type MilestoneLinkKind, type MilestoneState } from "./roadmap.ts";
134
+ import { ALL_MACHINE_LOCAL, configRefusal, configRepositoryPresent, configTracked } from "./config-trust.ts";
135
+ import { parseExactInstruction, exactForm, instructedExecution, INSTRUCTION_CHILD_TIMEOUT_MS, type ExactForm, type InstructedExecution } from "./instructed-exact.ts";
139
136
  import { intentForm, intentRefusal, literalInstructionIds } from "./instructed-intent.ts";
140
137
  import { instructedRuntimeAllowed } from "./instructed-runtime.ts";
141
138
  import { classifyPeerCommand, cliCommandLabel } from "../cli/identity.ts";
142
- import { authorizeConfigLeaf, configApply, configIdentityScope, configChanges, validateRawConfig, validateEffectiveConfig, validateOperationalConfig, validatePetConfig } from "./config-apply.ts";
139
+ import { authorizeConfigLeaf, configApply, configIdentityScope, configChanges, validateRawConfig, validateEffectiveConfig } from "./config-apply.ts";
143
140
  import { resolveSettledRoles } from "./settled-roles.ts";
144
141
  import { CONFIG_SOURCE_FILES, configFingerprint, configSourceTexts, parseConfigSources, type ConfigSourceTexts, type ConfigSources } from "./config-reload.ts";
145
142
  import { issueConductorRecoveryAuthority, authorizeConductorRecovery, assertConductorRecovery, RecoveryAuthorityError, type ConductorRecoveryBinding } from "./recovery-authority.ts";
@@ -165,7 +162,7 @@ import { isCodexPeer, type CodexPeer } from "../adapters/codex-appserver.ts";
165
162
  import { isPiPeer, PiVersionRefusal, type PiPeer } from "../adapters/pi.ts";
166
163
  import { isQwenDualPeer, qwenDualVersionAsync, type QwenDualPeer } from "../adapters/qwen-dual.ts";
167
164
  import { startModelRelay, type ModelRelay } from "../models/relay.ts";
168
- import { ensureMlx, type MlxOptions } from "../models/mlx.ts";
165
+ import { ensureMlx } from "../models/mlx.ts";
169
166
  import { PiToolReceipts, packPiShellResult } from "../pi/tool-receipts.ts";
170
167
  import { preparePiDependencies } from "../pi/task-dependencies.ts";
171
168
  import { publishPiDependencies } from "../pi/dependency-publish.ts";
@@ -193,16 +190,16 @@ import { isReviewerPrintPeer, reviewerNoVerdictLine, reviewerUnavailableReason,
193
190
  import type { OwnedInputContext } from "../adapters/claude-print-child.ts";
194
191
  import { createReviewerMcpSession, type ReviewerToolName } from "../adapters/reviewer-mcp.ts";
195
192
  import { reviewerPoolConfig } from "./reviewer-pool-config.ts";
196
- import { DEFAULT_REVIEW_GATE, DEFAULT_REVIEW_MAX_MINUTES, DEFAULT_REVIEW_UNKNOWN_QUOTA, reviewBudgetPolicyDescription, type ReviewGate, type ReviewUnknownQuota, reviewerAccountingIntegrity, reviewerAccountingRelevant } from "./review-budget.ts";
193
+ import { DEFAULT_REVIEW_GATE, DEFAULT_REVIEW_MAX_MINUTES, DEFAULT_REVIEW_UNKNOWN_QUOTA, reviewBudgetPolicyDescription, reviewerAccountingIntegrity, reviewerAccountingRelevant } from "./review-budget.ts";
197
194
  import { reviewDiff } from "../adapters/claude-print.ts";
198
195
  import { Capture } from "../memory/capture.ts";
199
- import { DEFAULT_OMNIROUTE, OmniRoute, type OmniRouteConfig } from "../omniroute/client.ts";
196
+ import { OmniRoute } from "../omniroute/client.ts";
200
197
  import { CorpusIndex } from "./corpus.ts";
201
198
  import { corpusEvidence } from "./corpus-evidence.ts";
202
199
  import { Briefs, preferRecordItems, type NativeItem, type BriefTask } from "../memory/brief.ts";
203
200
  import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type Task, type TaskClass } from "./board.ts";
204
201
  import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
205
- import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
202
+ import { Budget, readNativeQuota } from "./budget.ts";
206
203
  import { projectExhaustion, windowLeft, WINDOW_MINS, type ExhaustionProjection } from "./budget-projection.ts";
207
204
  import { remoteEnvelope, HUB } from "./envelope.ts";
208
205
  import { applyTurnAttribution, turnAttribution } from "./turn-attribution.ts";
@@ -214,7 +211,7 @@ import { canonicalPath, realPath, hubHome } from "./project.ts";
214
211
  import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, handoffStateGate, handoffTargetStopped, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
215
212
  import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
216
213
  import type { BusEvent, PublishResult } from "./bus.ts";
217
- import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, DEFAULT_ROLES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
214
+ import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
218
215
  import { effectiveClass, listedCapabilities, PublishRefusal, readShare, shareView, validatePublished, type CapabilityManifest } from "./capabilities.ts";
219
216
  import { invocationApproval, checkArgs, DEFAULT_TIMEOUT_S, InvocationLedger, invocationRefusal, refusedBy, renderInvocationResult, requestText, type InvocationOutcome, type InvocationRow } from "./invocations.ts";
220
217
  import { Conductor, ConductorHolds, conductorPeer, requireConductor, conductorProgressSink, publicConductorTask, publicPeerBudget, taskShowAllowed, type ConductEvent } from "./conductor.ts";
@@ -224,9 +221,9 @@ import { ProposalStore, SupervisionProposals, type SupervisionProposal } from ".
224
221
  import { drainCliAudits } from "../cli/identity-audit.ts";
225
222
  import { launcherPreview } from "../cli/preview.ts";
226
223
  import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
227
- import { DEFAULT_INFERENCE, DIGEST, Inference, SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii, type InferenceConfig, type PiiVerdict } from "./inference.ts";
224
+ import { DIGEST, Inference, SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii, type PiiVerdict } from "./inference.ts";
228
225
  import { taskEvidencePrivacy, type TaskEvidencePrivacy, ask, ASK_NOTE_TITLE, RUN_START } from "./ask.ts";
229
- import { currentRouting, loadRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
226
+ import { currentRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
230
227
  import { withChecklistLine, withoutChecklistLine } from "./learning.ts";
231
228
  import { FOLLOWUP_DEFAULTS } from "./learn-followup.ts";
232
229
  import { autonomyConsentStateDir, createAutonomyConsent, type AutonomyConsentValues } from "./autonomy-consent.ts";
@@ -250,36 +247,34 @@ import { negotiateProtocol, protocolWindow } from "./protocol-window.ts";
250
247
  import { attachEvent, originOf, type Origin } from "./provenance.ts";
251
248
  import { mintSessionId, sessionGate } from "./session-identity.ts";
252
249
  import { MAX_HOP, isInvocationKind, newEnvelope, parseMarker, replyParent, sanitize, USER, type Envelope, type PeerId, type Priority } from "./envelope.ts";
253
- import { BasePeer, DEFAULT_WATCHDOG_MS, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
250
+ import { BasePeer, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
254
251
  import { ClaudeTodoSource, DoingTracker, readAiTitle, DOING_STUB, SESSION_TITLE_HINT, sessionTitleText, sessionTitleBindings, unnamedSessionLabel, type DoingKind, type PeerDoing, type TitleCursor } from "./peer-doing.ts";
255
252
  import { MemoryClient } from "../memory/client.ts";
256
253
  import { VERSION, displayVersion } from "../version.ts";
257
254
  import { appendRecords, ResearchTail, taskRecords } from "./research.ts";
258
255
  import { readEvidence } from "./research-record.ts";
259
256
  import { memoryFigures, onlyTaskMemory, UNKNOWN_MEMORY_FIGURES, type MemoryFigures } from "./research-memory.ts";
260
- import { parseResearchRunners, type RegisteredRunnerV1 } from "./research-runner.ts";
257
+ import { parseResearchRunners } from "./research-runner.ts";
261
258
  import { benchReport, MIN_ATTEMPTS, readRuns, runSummary, type Measures, type RunSummary } from "./bench.ts";
262
259
  import { projectChain } from "@staix/agent-mem";
263
260
  import { recallFor } from "../memory/recall.ts";
264
261
  import { conflictsOf } from "./conflicts.ts";
265
262
  import { Facts, FACTS_PREFIX, type FactScope } from "./facts.ts";
266
- import { EditEvidence, editGuard, parseEditGovernance, type EditGuardArm } from "./edit-guard.ts";
263
+ import { EditEvidence, editGuard } from "./edit-guard.ts";
267
264
  import { crashPlan, lossNotice, openCrashNotices, readSessions, removeSessions, writeSessions, type CrashNotice, type SessionsFile } from "./crash.ts";
268
265
  import type { JournalDelivery } from "./delivery-journal.ts";
269
- import { DEFAULT_LIMITS, Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
266
+ import { Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
270
267
  import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, SnapshotCooldown, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
271
268
  import { archiveRestartSnapshot, compactRestartBus, readRecoveryWaivers, readRestartSnapshot, removeRestartSnapshot, restartPath, writeRestartSnapshot, type RecoveryPhase, type RestartPeerSnapshot, type RestartSnapshot } from "./restart.ts";
272
269
  import { consumeRecoveryContinuity, readRecoveryContinuity, retireRecoveryContinuity } from "./recovery-continuity.ts";
273
270
  import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf } from "../cli/terminal-recovery.ts";
274
271
  import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
275
272
 
276
- import { START_AGENTS_DEFAULT, checkStartAgents } from "./start-agents.ts";
277
- import { adapterCeiling, applyRoleCeiling } from "../adapters/role-eligibility.ts";
278
- import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, terminalTemplate, type PeerStartConfig, type StartMode } from "./start-mode.ts";
273
+ import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, type PeerStartConfig, type StartMode } from "./start-mode.ts";
279
274
  import { hasKimiHubMcp } from "../cli/kimi-mcp.ts";
280
275
  import type { TerminalOpener } from "./terminal-open.ts";
281
- import { isHubWritePath, grantablePath, instructionProtection, isPermissionMode, permissionBoundary, permissionDefaults, permissionGrant, PI_EDIT_TOOLS, type PermissionMode } from "./permission-mode.ts";
282
- import { ContextWindows, DEFAULT_CONTEXT, readNativeContext, type ContextConfig } from "./context-window.ts";
276
+ import { isHubWritePath, grantablePath, isPermissionMode, permissionBoundary, permissionDefaults, permissionGrant, PI_EDIT_TOOLS, type PermissionMode } from "./permission-mode.ts";
277
+ import { ContextWindows, readNativeContext } from "./context-window.ts";
283
278
  import { projectFileTool, scopedWriteBlocked } from "../cli/facts-hook.ts";
284
279
  import { detectTooling } from "./tooling.ts";
285
280
  import { CaptureStore, configuredPolicy, recordsEnabled, looksSecret, DEFAULT_LEASE_MS, memoryHome, SUGGESTED, taskKey, type CandidateStore, type MemoryStore, type GoalView, type Suggested, type View as MemoryView } from "@staix/agent-mem";
@@ -294,179 +289,10 @@ import { promotionScreen, withoutPii, mentionsPrivatePath } from "./memory-polic
294
289
  import { hostPlacementAttestation, memorySyncErrorText, writerRefusalOf, type WriterRefusal } from "./memory-sync-attestation.ts";
295
290
  import { classifyMemorySyncFailure, initialMemorySyncState, memorySyncDeclinedDetails, memorySyncFailureDetailHash, memorySyncView, memorySyncNextStep, memorySyncPlacementCounts, reduceMemorySync } from "./memory-sync-state.ts";
296
291
  import { createMemorySyncPolicy, inspectDeclinedMemoryRows } from "./memory-sync-policy.ts";
297
- import { DEFAULT_SPECS_CONFIG, parseSpecsConfig, type SpecsConfig } from "./specs-config.ts";
298
292
 
299
- export interface HubConfig {
300
- adapter_modules?: readonly AdapterModuleDeclaration[];
301
- adapters?: Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAdapterConfig>>;
302
- /** Person-owned declarations, read only from an untracked machine-local file. Bound for this daemon lifetime. */
303
- instances?: InstancesConfig;
304
- watchdog_ms: number;
305
- kimi_cmd: string[];
306
- qwen_cmd: string[];
307
- jcode_cmd: string[];
308
- jcode_home: string;
309
- /** Machine-local names of jcode MCP servers `ahub doctor` accepts for the hub-owned jcode (#1621). Names only; launch is unchanged. */
310
- jcode_mcp_allow?: string[];
311
- jcode_provider_profile: string;
312
- action_policy?: ActionPolicyConfig;
313
- permission_modes: Record<string, PermissionMode>;
314
- protect_instruction_files: boolean;
315
- instructed?: { mode: "off" | "exact" | "intent" };
316
- /** Loader-owned provenance of requested defaults, before machine-local filtering. */
317
- permission_default_sources?: Record<string, { mode: PermissionMode; source: string }>;
318
- codex_bin: string;
319
- batch_max: number;
320
- batch_ms: number;
321
- queue_cap: number;
322
- /** #489 H3: accepted delivery policy, read at the next delivery operation without rewriting queued work. */
323
- bus?: { max_attempts?: number; digest_max?: number; pull_budget_bytes?: number; notes_kept?: number; terminal_history_limit?: number; accepted_settle_ms?: number };
324
- /** #489 H5: accepted timing captured only when a new native adapter is constructed. */
325
- adapter_timing?: AdapterTimingConfig["adapter_timing"];
326
- /** #489 H6: relay policy is captured from restart-bound accepted configuration. */
327
- model_relay?: ModelOperationalConfig["model_relay"];
328
- /** #489 H7: accepted presentation preferences read by a new console through settings_get. */
329
- console?: ConsoleOperationalConfig["console"];
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). */
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 };
332
- roster: PeerRoster;
333
- roles: Record<string, string[]>;
334
- /** #455: the one peer that holds the planner role; unset, the `roles` planners stand, or the hub assigns one. */
335
- planner?: string | string[];
336
- profile?: ProfileName;
337
- profile_overrides?: Record<string, unknown>;
338
- pii?: { paths: string[] };
339
- data?: { readonly: string[] };
340
- text_projection?: ProjectionConfig;
341
- /** #510: machine-local folders of plain notes the hub may index, read-only; vault folders are refused when the index reads them. */
342
- corpus: { paths: string[] };
343
- roadmap?: RoadmapConfig;
344
- specs: SpecsConfig;
345
- catalog_roles?: Record<string, string[]>;
346
- conductor: { feed: "own" | "all" | "off"; approval_wait_s: number };
347
- /** #1221 T2: what the supervision queue may do. `off` evaluates nothing, `shadow` stores bounded proposals with no inbox row or notice, `advisory` may also show a pending one in the console inbox. Machine-local and off by default. */
348
- supervision: { mode: "off" | "shadow" | "advisory" };
349
- edit_governance?: { arm: EditGuardArm };
350
- budget: BudgetConfig;
351
- context: ContextConfig;
352
- inference: InferenceConfig;
353
- omniroute: OmniRouteConfig;
354
- pi: { enabled: boolean; auto_start: boolean; cmd: string[]; backend: "auto" | "dgx" | "mlx"; dgx_coding: string; dgx_fast: string; max_steps: number; max_continuations: number };
355
- mlx: { enabled: boolean } & Pick<MlxOptions, "provider" | "host" | "runtimeDir" | "modelPath" | "port" | "model" | "sourceModel" | "contextWindow" | "maxInputTokens" | "maxTokens" | "maxConcurrency">;
356
- /** `bash_network`: true is network through the egress proxy to `network_allow` (#65); "direct" is everything, until 0.13.0 (#83). */
357
- local: { deny: string[]; bash_network: boolean | "direct"; network_allow: string[]; max_steps: number; read_allow: string[]; /** #515: offer the local worker `doc_read` (PDF, DOCX, HWPX through `text_projection`); off by default, machine-local. */ doc_read: boolean; /** #515b: the hosts the local worker's `web_fetch` may read; empty (the default) means the tool does not exist. Machine-local. */ web_fetch: { allow: string[] } };
358
- /** Pending permission requests: how long they wait, and whether the desktop is told (issue #5). */
359
- approvals: { timeout_s: number; notify: boolean };
360
- /** An owner offline this long loses its open tasks back to routing; 0 turns it off (issue #6). */
361
- tasks: { release_after_min: number; wip_limits?: Record<string, number>; escalate_after: number; groom_fyi_window_min?: number; demote_at?: number; demotion_half_life_h?: number; contradiction_window_days?: number; rescreen_max?: number; split_min_observations?: number; split_max_failure_share?: number; /** #785 P1c: pull the top explicitly reserved ready card when a slot frees; machine-local, default off. */ auto_pull?: boolean; queue_backpressure?: Partial<QueueBackpressurePolicy> };
362
- /** Between-turn task escalation, disabled unless explicitly enabled (#186). */
363
- task_sweep: TaskSweepConfig;
364
- /** #512a: machine-local schedules; checked by `schedulesConfig`, never set from a committed file. */
365
- schedules: ScheduleEntry[];
366
- /** #512c: machine-local folder triggers, polled on the schedules timer; checked by `foldersConfig`, never set from a committed file. */
367
- folder_triggers: FolderEntry[];
368
- /** A command per task class run when the owner marks the task done, and its timeout (issue #7). */
369
- checks: { timeout_s: number; runner?: "container" | "remote"; remote?: RemoteRunnerConfig; [cls: string]: string | number | RemoteRunnerConfig | undefined };
370
- /** A git tree at each turn boundary for `ahub turns` and `ahub undo`, the last `keep` per peer (issue #33). */
371
- snapshots: { enabled: boolean; keep: number };
372
- /** Unbound visuals expire; task-bound records retain the task lifetime. */
373
- visuals: { retention_days: number };
374
- /** #1057: the worktree shelf. `quiet_days` shelves a worktree idle that long (0 = never); `alert_over` is the settled count that raises one inbox alert (0 = never). */
375
- worktrees: { quiet_days: number; alert_over: number };
376
- /** #1053: `ttl_s` expires an unanswered question (default 86400); `wait_ms` overrides an adapter definition's `questionWaitMs` per kind. */
377
- questions: { ttl_s: number; wait_ms: Record<string, number> };
378
- /** #247: opt-in research records of each approved task in ~/.agenthub/research (ids, counts and tokens only). */
379
- research: { enabled: boolean; runners?: Record<string, RegisteredRunnerV1> };
380
- /** #251: a project kept for benchmarks: `ahub bench run` resets its work tree between attempts. */
381
- bench: { enabled: boolean };
382
- /** #269: per peer, how a start comes up when nothing more specific was asked: `tui` (the default) or `headless`. Pi and Codex only. */
383
- peers: PeerStartConfig;
384
- /** #269: a machine-local argv that opens a terminal for a hub-made TUI start; `{command}` in one element is the command to run. */
385
- terminal: { open: string[] };
386
- /** #608: the peers `ahub up` asks the hub to start, machine-local. Read by the CLI at a person's `ahub up` and by the dashboard manager's start; the daemon itself never starts one from it. */
387
- start: { agents: string[] };
388
- /** Per-sender rate limits and repeat suppression for what agents send (issue #38). */
389
- limits: LimitsConfig;
390
- /** Reviewer choice from recorded review outcomes, once a reviewer has `min_reviews` of an implementer (issue #35). */
391
- review: { adaptive: boolean; min_reviews: number; pool?: string[]; rerotate?: boolean; same_family?: "fallback" | "never"; gate?: ReviewGate; unknown_quota?: ReviewUnknownQuota; max_minutes?: number };
392
- /** After an unplanned stop, start Kimi, Pi and the local worker again with their recorded sessions (issue #37). */
393
- /** #489 H4: the five waits the upgrade coordinator reads from this project's config at the start of each wait; the daemon itself only validates and carries them. */
394
- recovery: { auto_resume_after_crash: boolean; reconnect_wait_s?: number; unmanaged_reconnect_wait_s?: number; control_timeout_s?: number; shutdown_wait_s?: number; terminal_idle_wait_s?: number };
395
- /** Per peer, the hub-tool capabilities it has (issue #39); a peer not listed has all of them. */
396
- capabilities: Record<string, string[]>;
397
- /** #445 C1: machine-local invocation settings. `share` is the person's allowlist of native capabilities by peer id, each pinned by digest (`src/hub/capabilities.ts`). */
398
- invocation?: { share?: Record<string, Record<string, { digest: string; class?: string }>>; /** Seconds a request may wait for its result, 10 to 86400, default 600 (#445 C2). */ timeout_s?: number };
399
- /**
400
- * How owners of overlapping tasks coordinate (issue #107): "advisory" lets them message each other; "turn-free" has
401
- * them work without messages while the hub derives what they need to know. Anything else is advisory.
402
- */
403
- coordination: "advisory" | "turn-free";
404
- /** Switches for controlled ablations only (issue #110): `stale_notices: "deliver"` turns #106's dropping off. */
405
- experiments?: { stale_notices?: "drop" | "deliver" };
406
- /** Console-local terminal presentation (#280, #483); grants no authority. */
407
- pet?: false | Record<string, unknown>;
408
- /** Machine-local fields a config file set but git could not vouch for, and why (issue #17). */
409
- ignored?: string[];
410
- /** Reporting-only notice that machine-local release policy was ignored; never part of accepted policy authority. */
411
- releasePolicyNotices?: string[];
412
- /** Settings that were removed or are about to be (issue #83): what each does now, for `hub.log` and `ahub doctor`. */
413
- retired?: string[];
414
- }
415
- const nativeDefaults = nativeConfigurationDefaults({ home: homedir(), env: process.env, networkAllow: DEFAULT_NETWORK_ALLOW });
416
- export const DEFAULT_CONFIG: HubConfig = {
417
- watchdog_ms: DEFAULT_WATCHDOG_MS,
418
- ...nativeDefaults.commands,
419
- action_policy: actionPolicyConfig(),
420
- permission_modes: {},
421
- protect_instruction_files: false,
422
- instructed: { mode: "intent" },
423
- ...nativeDefaults.proxy,
424
- batch_max: 3,
425
- batch_ms: 15_000,
426
- queue_cap: 200,
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 },
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 },
429
- memory: { enabled: true, inject_tokens: 2000, brief_items: 8, preface_unused_after: 20, review: MEMORY_REVIEW_DEFAULTS },
430
- roster: {},
431
- roles: DEFAULT_ROLES,
432
- conductor: { feed: "own", approval_wait_s: 30 },
433
- supervision: { mode: "off" },
434
- edit_governance: { arm: "baseline" },
435
- budget: DEFAULT_BUDGET,
436
- context: DEFAULT_CONTEXT,
437
- model_relay: { cooldown_failures: MODEL_COOLDOWN_FAILURES_SETTING.defaultValue, cooldown_s: MODEL_COOLDOWN_SETTING.defaultValue, cooldown_cap_s: MODEL_COOLDOWN_CAP_SETTING.defaultValue, terminal_history_limit: MODEL_TERMINAL_HISTORY_SETTING.defaultValue },
438
- console: { poll_ms: CONSOLE_POLL_SETTING.defaultValue, notice_ms: CONSOLE_NOTICE_SETTING.defaultValue, history_limit: CONSOLE_HISTORY_SETTING.defaultValue, pending_stream_limit: CONSOLE_PENDING_STREAM_SETTING.defaultValue, attention_limit: CONSOLE_ATTENTION_SETTING.defaultValue },
439
- inference: DEFAULT_INFERENCE,
440
- omniroute: DEFAULT_OMNIROUTE,
441
- ...nativeDefaults.rpc,
442
- mlx: { enabled: true, provider: "ollama", model: "agenthub-fast-mlx:4b-8k", sourceModel: "qwen3.5:4b-mlx", contextWindow: 8192, maxInputTokens: 6000, maxTokens: 2048, maxConcurrency: 1 },
443
- ...nativeDefaults.sandbox,
444
- // Off here, so tests and a hub without a config file stay silent; a project's config defaults it on for macOS.
445
- approvals: { timeout_s: 120, notify: false },
446
- tasks: { release_after_min: 30, escalate_after: ESCALATE_AFTER, groom_fyi_window_min: GROOM_FYI_WINDOW_SETTING.defaultValue, demote_at: DEMOTE_AT_SETTING.defaultValue, demotion_half_life_h: DEMOTION_HALF_LIFE_SETTING.defaultValue, contradiction_window_days: CONTRADICTION_WINDOW_SETTING.defaultValue, rescreen_max: RESCREEN_MAX_SETTING.defaultValue, split_min_observations: SPLIT_MIN_SETTING.defaultValue, split_max_failure_share: SPLIT_FAILURE_SHARE_SETTING.defaultValue, auto_pull: false },
447
- task_sweep: DEFAULT_TASK_SWEEP,
448
- schedules: [],
449
- folder_triggers: [],
450
- corpus: { paths: [] },
451
- roadmap: roadmapConfig(undefined),
452
- specs: { ...DEFAULT_SPECS_CONFIG, roots: [] },
453
- checks: { timeout_s: 600 },
454
- // Off here like approvals.notify, so tests (whose cwd is this repository) write no objects; a project's config turns it on.
455
- snapshots: { enabled: false, keep: 20 },
456
- worktrees: { quiet_days: 7, alert_over: 10 },
457
- questions: { ttl_s: 86_400, wait_ms: {} },
458
- visuals: { retention_days: 30 },
459
- research: { enabled: false },
460
- bench: { enabled: false },
461
- peers: {},
462
- terminal: { open: [] },
463
- start: { agents: [...START_AGENTS_DEFAULT] },
464
- limits: DEFAULT_LIMITS,
465
- review: { adaptive: false, min_reviews: 5, gate: DEFAULT_REVIEW_GATE, unknown_quota: DEFAULT_REVIEW_UNKNOWN_QUOTA, max_minutes: DEFAULT_REVIEW_MAX_MINUTES },
466
- recovery: { auto_resume_after_crash: false, reconnect_wait_s: RECOVERY_RECONNECT_WAIT_SETTING.defaultValue, unmanaged_reconnect_wait_s: RECOVERY_UNMANAGED_RECONNECT_WAIT_SETTING.defaultValue, control_timeout_s: RECOVERY_CONTROL_TIMEOUT_SETTING.defaultValue, shutdown_wait_s: RECOVERY_SHUTDOWN_WAIT_SETTING.defaultValue, terminal_idle_wait_s: RECOVERY_TERMINAL_IDLE_WAIT_SETTING.defaultValue },
467
- capabilities: {},
468
- coordination: "advisory",
469
- };
293
+ import { CONFIG_FILES, DEFAULT_CONFIG, loadConfig, loadConductorPolicy, mlxLaunchProblem, type HubConfig } from "./config.ts";
294
+
295
+ export { DEFAULT_CONFIG, loadConfig, loadConductorPolicy, type ConfigLayer, type HubConfig } from "./config.ts";
470
296
 
471
297
  export { stateDirFor };
472
298
 
@@ -475,11 +301,6 @@ const READ_ONLY_HUB_TOOLS = new Set(["hub_roadmap_list", "hub_roadmap_show", "hu
475
301
  const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
476
302
  const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
477
303
 
478
- /** The shared project config, then the machine's own file, which overrides it block by block (issue #17). */
479
- const CONFIG_FILES = INSTANCE_CONFIG_FILES;
480
- export interface ConfigLayer { name: typeof CONFIG_FILES[number]; raw: Record<string, any> }
481
- const CONFIG_BLOCKS = ["instructed", "action_policy", "memory", "roster", "roles", "catalog_roles", "pii", "data", "conductor", "budget", "context", "inference", "omniroute", ...NATIVE_CONFIG_BLOCKS, "approvals", "tasks", "task_sweep", "bus", "adapter_timing", "model_relay", "console", "corpus", "specs", "checks", "snapshots", "worktrees", "visuals", "research", "bench", "limits", "review", "recovery", "capabilities", "mlx", "permission_modes", "peers", "terminal", "start", "pet", "questions"];
482
-
483
304
  /** Older targets parse raw keys before placement/trust checks, so even an empty or refused declaration needs the floor. */
484
305
  function rawResearchRunnersPresent(cwd: string): boolean {
485
306
  const texts = configSourceTexts(cwd);
@@ -507,294 +328,6 @@ function rawVisualsPresent(cwd: string): boolean {
507
328
  return false;
508
329
  }
509
330
 
510
- /** Connection-time policy refresh reads role/feed fields only, never launches or machine-local configuration. */
511
- export function loadConductorPolicy(cwd: string, layers?: readonly ConfigLayer[], scope: Pick<ReturnType<typeof readInstanceConfig>, "instances" | "catalog"> = readInstanceConfig(cwd, layers)): { roles: Record<string, string[]>; conductor: HubConfig["conductor"]; planner?: string | string[]; notices?: string[] } {
512
- const roles: Record<string, string[]> = { ...DEFAULT_ROLES };
513
- const conductor = { ...DEFAULT_CONFIG.conductor };
514
- const notices: string[] = [];
515
- // #1063: what the layers declare after the adapter ceiling and before the #1408 eligibility drop. At most one conductor is checked on this map (as on main), so an eligible-ceiling kind that cannot conduct is refused, never ignored, and a conductor the ceiling never allowed does not count.
516
- const declaredRoles: Record<string, string[]> = { ...DEFAULT_ROLES };
517
- let planner: string | string[] | undefined;
518
- // #1408 R2: the conductor role needs an interactive session, so the loader reads each peer's effective start mode (config.local.json wins per peer) before it reads roles.
519
- const startModes: Record<string, StartMode> = {};
520
- for (const name of CONFIG_FILES) {
521
- const raw = layers ? layers.find(layer => layer.name === name)?.raw : (() => { try { return JSON.parse(readFileSync(join(cwd, ".agenthub", name), "utf8")) as Record<string, unknown>; } catch { return undefined; } })();
522
- const peers = raw?.peers;
523
- if (peers && typeof peers === "object" && !Array.isArray(peers)) for (const [peer, block] of Object.entries(peers)) {
524
- const mode = block && typeof block === "object" ? (block as { start_mode?: unknown }).start_mode : undefined;
525
- if (mode === "tui" || mode === "headless") startModes[peer] = mode;
526
- }
527
- }
528
- for (const name of CONFIG_FILES) {
529
- let file: Record<string, unknown>;
530
- if (layers && !layers.some(layer => layer.name === name)) continue;
531
- try { file = layers ? structuredClone(layers.find(layer => layer.name === name)!.raw) : JSON.parse(readFileSync(join(cwd, ".agenthub", name), "utf8")); }
532
- catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
533
- if (file.roles !== undefined) {
534
- if (!file.roles || typeof file.roles !== "object" || Array.isArray(file.roles)) throw new Error("roles must be an object of peer role lists");
535
- for (const [peer, assigned] of Object.entries(file.roles)) {
536
- conductorPeer({ [peer]: assigned });
537
- const declared = assigned as string[];
538
- declaredRoles[peer] = adapterCeiling(peer, declared);
539
- // #525 R1: planner needs a kind that can plan; #1408 R2: conductor needs an eligible kind in an interactive form. Such an entry is dropped with a notice, never thrown, and nobody else gains it.
540
- // The builtin registry only, exactly as before: a project-configured ACP kind keeps the roles it is given (#525, #735).
541
- const kept = applyRoleCeiling(peer, declared, startModes[peer]);
542
- roles[peer] = kept.roles;
543
- notices.push(...kept.notices);
544
- }
545
- }
546
- if (file.planner !== undefined) {
547
- if (file.planner === null) throw new Error("planner takes a peer id or a nonempty list of up to eight ids");
548
- const def = instanceSettingDef("planner", scope.instances, scope.catalog);
549
- if (typeof def === "string") throw new Error(def);
550
- const normalized = checkSettingValue(def, file.planner) as string | string[];
551
- planner = Array.isArray(file.planner) ? [...file.planner] as string[] : normalized;
552
- }
553
- if (file.conductor !== undefined) {
554
- if (!file.conductor || typeof file.conductor !== "object" || Array.isArray(file.conductor)) throw new Error("conductor must be an object");
555
- const block = file.conductor as Record<string, unknown>;
556
- if (block.feed !== undefined) {
557
- if (!["own", "all", "off"].includes(String(block.feed))) throw new Error("conductor.feed must be own, all or off");
558
- conductor.feed = block.feed as "own" | "all" | "off";
559
- }
560
- if (block.approval_wait_s !== undefined) {
561
- if (typeof block.approval_wait_s !== "number" || !Number.isFinite(block.approval_wait_s) || block.approval_wait_s < 0) throw new Error("conductor.approval_wait_s must be a nonnegative number");
562
- conductor.approval_wait_s = block.approval_wait_s;
563
- }
564
- }
565
- }
566
- conductorPeer(declaredRoles);
567
- conductorPeer(roles);
568
- return { roles, conductor, ...(planner ? { planner } : {}), ...(notices.length ? { notices } : {}) };
569
- }
570
-
571
- /** `memory.short_ttl_days`: a whole number of days from 1 to 3650; anything else would make every short-term deadline invalid. */
572
- function ttlDays(v: unknown): number {
573
- if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 3650) throw new Error("memory.short_ttl_days must be a whole number of days from 1 to 3650");
574
- return v;
575
- }
576
- /** `memory.sync_interval_min`: 0 (off) or a whole number of minutes up to a day. */
577
- function syncMinutes(v: unknown): number {
578
- if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > 1440) throw new Error("memory.sync_interval_min must be 0 (off) or a whole number of minutes up to 1440");
579
- return v;
580
- }
581
-
582
- /** Routing diagnostics must not make independent config reads depend on valid routing. */
583
- function retiredRoutingSettings(cwd: string): readonly string[] {
584
- try { return loadRouting(cwd).retired ?? []; }
585
- catch { return []; } // Routing admission and reload report parse errors using their own last-good state.
586
- }
587
-
588
- /** #1057: a whole non-negative number of days or alert count; anything else (a negative, a fraction, a string) is the default, so a bad value never changes the shelf. The reload schema refuses it by name. */
589
- const wholeDays = (value: unknown, fallback: number): number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 100_000 ? value : fallback;
590
- /** #1053: `questions.ttl_s` (60 s to 30 days) and a per-kind `wait_ms` (1 s to 10 min); anything else keeps the default, so a bad value never changes what the person is asked. */
591
- const questionsConfig = (value: unknown): HubConfig["questions"] => {
592
- const raw = value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
593
- const ttl = typeof raw.ttl_s === "number" && Number.isSafeInteger(raw.ttl_s) && raw.ttl_s >= 60 && raw.ttl_s <= 2_592_000 ? raw.ttl_s : DEFAULT_CONFIG.questions.ttl_s;
594
- const wait: Record<string, number> = {};
595
- if (raw.wait_ms && typeof raw.wait_ms === "object" && !Array.isArray(raw.wait_ms)) for (const [kind, ms] of Object.entries(raw.wait_ms as Record<string, unknown>)) if (/^[a-z][a-z0-9-]{0,31}$/.test(kind) && typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 1000 && ms <= 600_000) wait[kind] = ms;
596
- return { ttl_s: ttl, wait_ms: wait };
597
- };
598
- export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routingRetired: readonly string[] = retiredRoutingSettings(cwd), externalDefinitions?: readonly import("../adapters/registry-types.ts").AdapterDefinition[]): HubConfig {
599
- const captured = layers ?? readInstanceConfigLayers(cwd);
600
- const instanceConfig = readInstanceConfig(cwd, captured, externalDefinitions);
601
- const instances = instanceConfig.instances;
602
- const adapterCatalog = instanceConfig.catalog;
603
- const ignored: string[] = [...instanceConfig.ignored];
604
- const releasePolicyNotices: string[] = [];
605
- const inertModuleRoster = !!instanceConfig.adapter_modules?.length;
606
- const appliedPermissionSources: NonNullable<HubConfig["permission_default_sources"]> = {};
607
- let retiredPetWindow = false;
608
- const files = CONFIG_FILES.flatMap((name) => {
609
- let file: Record<string, any>; // parsed JSON, checked field by field below
610
- if (!captured.some(layer => layer.name === name)) return [];
611
- try {
612
- file = withoutInertInstancePolicy(structuredClone(captured.find(layer => layer.name === name)!.raw), instanceConfig.declaredExternalInstances);
613
- } catch (error) {
614
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
615
- throw error;
616
- }
617
- delete file.adapter_modules; // Code provenance is captured separately and never evaluated by configuration reads.
618
- delete file.adapters; // Adapter provenance is compiled by the same project-local loader.
619
- delete file.instances; // Declaration authority was checked against its exact captured origin above.
620
- peerRosterConfig(file.roster, instances, adapterCatalog, inertModuleRoster);
621
- catalogAssignments(file.catalog_roles);
622
- profileName(file.profile);
623
- resolveProfile(file.profile, file.profile_overrides);
624
- projectionConfig(file.text_projection);
625
- corpusConfig(file.corpus);
626
- roadmapConfig(file.roadmap);
627
- if (file.specs !== undefined) parseSpecsConfig(file.specs);
628
- queueBackpressurePolicy(file.tasks?.queue_backpressure);
629
- validateOperationalConfig(file);
630
- for (const [block, key] of [["pii", "paths"], ["data", "readonly"]] as const) {
631
- const raw = file[block];
632
- if (raw !== undefined && (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).some(k => k !== key))) throw new Error(block + " must be a bounded path policy block");
633
- policyPaths(raw?.[key], block + "." + key);
634
- }
635
- if (file.jcode_cmd !== undefined && (!Array.isArray(file.jcode_cmd) || !file.jcode_cmd.length || file.jcode_cmd.some((word: unknown) => typeof word !== "string" || !word))) throw new Error("jcode_cmd must be a nonempty executable argv");
636
- if (file.jcode_home !== undefined && (typeof file.jcode_home !== "string" || !isAbsolute(file.jcode_home))) throw new Error("jcode_home must be an absolute path");
637
- if (file.jcode_mcp_allow !== undefined) mcpAllowNames(file.jcode_mcp_allow, "jcode_mcp_allow");
638
- for (const key of ["jcode_home", "jcode_provider_profile"]) if (file[key] !== undefined && typeof file[key] !== "string") throw new Error(`${key} must be a string`);
639
- if (file.qwen_cmd !== undefined && (!Array.isArray(file.qwen_cmd) || !file.qwen_cmd.length || file.qwen_cmd.some((word: unknown) => typeof word !== "string" || !word))) throw new Error("qwen_cmd must be a nonempty executable argv");
640
- actionPolicyConfig(file.action_policy);
641
- if (file.edit_governance !== undefined) parseEditGovernance(file.edit_governance);
642
- instructionProtection(file.protect_instruction_files);
643
- if (file.instructed !== undefined) {
644
- if (!file.instructed || typeof file.instructed !== "object" || Array.isArray(file.instructed) || Object.keys(file.instructed).some(key => key !== "mode")) throw new Error("instructed must contain only mode");
645
- instructedMode(file.instructed.mode);
646
- }
647
- permissionDefaults(file.permission_modes, instances, adapterCatalog); // malformed declarations fail even when trust would drop them
648
- peerStartConfig(file.peers, instances, adapterCatalog);
649
- if (file.terminal != null && (typeof file.terminal !== "object" || Array.isArray(file.terminal))) throw new Error("terminal must be an object");
650
- terminalTemplate(file.terminal?.open);
651
- if (file.start != null && (typeof file.start !== "object" || Array.isArray(file.start) || Object.keys(file.start).some((key: string) => key !== "agents"))) throw new Error("start must be an object with an agents list");
652
- if (file.start?.agents !== undefined) checkStartAgents(file.start.agents);
653
- const pet = stripLegacyPetWindow(file.pet);
654
- if (pet !== file.pet) { retiredPetWindow = true; if (pet && typeof pet === "object" && !Object.keys(pet).length) delete file.pet; else file.pet = pet; }
655
- if (file.pet !== undefined) validatePetConfig(file.pet, "config.pet");
656
- if (file.pet && typeof file.pet === "object" && !Object.keys(file.pet).length) delete file.pet;
657
- delete file.declaredExternalInstances; // host-derived refusal rows, never a file claim
658
- delete file.permission_default_sources; // provenance is loader-owned, never a file claim
659
- delete file._autonomy; // Inert restoration metadata, never policy or approval provenance.
660
- if (file.checks?.runner === "remote" || file.checks?.remote !== undefined) {
661
- if (name !== "config.local.json" || configTracked(cwd, name) !== false) throw new Error("remote checks require untracked config.local.json");
662
- if (file.checks.remote !== undefined) remoteRunnerConfig(file.checks.remote);
663
- }
664
- if (file.research !== undefined && (!file.research || typeof file.research !== "object" || Array.isArray(file.research))) throw new Error("research must be an object");
665
- const hasRunners = file.research && Object.hasOwn(file.research, "runners"), runnerDeclarations: unknown = hasRunners ? file.research.runners : undefined;
666
- const why = stripUntrusted(file, DEFAULT_CONFIG, cwd, name);
667
- if (why) {
668
- const notices = why.split("; ");
669
- releasePolicyNotices.push(...notices.filter(notice => notice.startsWith("release in .agenthub/config.local.json ignored:")));
670
- const existingNotices = notices.filter(notice => !notice.startsWith("release in .agenthub/config.local.json ignored:"));
671
- if (existingNotices.length) ignored.push(existingNotices.join("; "));
672
- }
673
- if (file.edit_governance && !Object.keys(file.edit_governance).length) delete file.edit_governance;
674
- // Release policy is read directly from the candidate commit by the S6 host reader, never runtime config.
675
- delete file.release;
676
- if (hasRunners) file.research.runners = parseResearchRunners(runnerDeclarations);
677
- for (const [peer, mode] of Object.entries(permissionDefaults(file.permission_modes, instances, adapterCatalog))) appliedPermissionSources[peer] = { mode, source: `.agenthub/${name}` };
678
- return [file];
679
- });
680
- if (!files.length) return routingRetired.length ? { ...DEFAULT_CONFIG, retired: [...routingRetired] } : DEFAULT_CONFIG;
681
- const file = files.reduce((a, b) => ({ ...a, ...b, ...Object.fromEntries(CONFIG_BLOCKS.filter((k) => a[k] !== undefined && b[k] !== undefined).map((k) => [k, { ...a[k], ...b[k] }])) }));
682
- const pressureLayers = files.filter(layer => layer.tasks?.queue_backpressure !== undefined);
683
- if (pressureLayers.length) file.tasks = { ...file.tasks, queue_backpressure: pressureLayers.reduce((prior, layer) => ({ ...prior, ...layer.tasks.queue_backpressure }), {}) };
684
- const wipLayers = files.filter(layer => layer.tasks?.wip_limits !== undefined);
685
- if (wipLayers.length) file.tasks = { ...file.tasks, wip_limits: wipLayers.reduce((prior, layer) => ({ ...prior, ...planningWipLimits(layer.tasks.wip_limits) }), {} as Record<string, number>) };
686
- const overrides = files.reduce<unknown>((prior, layer) => mergeProfileOverrides(prior, layer.profile_overrides), undefined);
687
- if (overrides !== undefined) file.profile_overrides = overrides;
688
- resolveProfile(file.profile, file.profile_overrides);
689
- delete file.ignored; // the hub's own record, never a file's
690
- delete file.retired;
691
- // Escape hatches with a stated end (issue #83). A removed one is ignored, never an error: an old config.local.json
692
- // must not stop a hub from starting.
693
- const retired: string[] = [...routingRetired];
694
- if (retiredPetWindow && !retired.includes(PET_WINDOW_RETIRED_NOTICE)) retired.push(PET_WINDOW_RETIRED_NOTICE);
695
- if (file.local?.sandbox !== undefined) {
696
- if (file.local.sandbox === "allow-default") retired.push('local.sandbox "allow-default" was removed in 0.12.0: the deny-default sandbox applies (local.read_allow adds paths)');
697
- file.local = { ...file.local };
698
- delete file.local.sandbox;
699
- }
700
- if (file.local?.bash_network === "direct") retired.push('local.bash_network "direct" (the open network) goes in 0.13.0: set it to true and list the hosts in local.network_allow');
701
- if (file.mlx != null && (typeof file.mlx !== "object" || Array.isArray(file.mlx))) throw new Error("mlx configuration must be an object");
702
- if (file.mlx?.enabled !== undefined && typeof file.mlx.enabled !== "boolean") throw new Error("mlx.enabled must be a boolean");
703
- if (file.mlx?.provider !== undefined && !["ollama", "legacy"].includes(file.mlx.provider)) throw new Error("mlx.provider must be ollama or legacy");
704
- if (file.mlx?.provider === undefined && (file.mlx?.modelPath || file.mlx?.runtimeDir || file.mlx?.bin || file.mlx?.port)) {
705
- throw new Error("legacy MLX configuration requires explicit mlx.provider=legacy; migrate to provider=ollama to avoid Python serving");
706
- }
707
- const mlx = { ...(file.mlx?.provider === "legacy" ? { enabled: true, provider: "legacy" as const, maxInputTokens: 16_000, maxTokens: 2048 } : DEFAULT_CONFIG.mlx), ...file.mlx };
708
- const conductorPolicy = loadConductorPolicy(cwd, captured, instanceConfig);
709
- retired.push(...conductorPolicy.notices ?? []);
710
- const configuredRoles = Object.fromEntries(adapterCatalog.definitions.filter(d => !definitionOf(d.kind)).map(d => [d.kind, [...d.roles]]));
711
- const extraRoles = Object.fromEntries(Object.keys(instances ?? {}).map(id => [id, effectiveInstanceRoles(id, instances, conductorPolicy.roles, adapterCatalog)]));
712
- const instancePermissions: Record<string, PermissionMode> = {};
713
- const instanceModes: PeerStartConfig = {};
714
- for (const [id, declaration] of Object.entries(instances ?? {})) {
715
- instanceModes[id] = { start_mode: declaration.start_mode ?? "headless" };
716
- if (declaration.permission_mode !== undefined) {
717
- instancePermissions[id] = declaration.permission_mode;
718
- appliedPermissionSources[id] = { mode: declaration.permission_mode, source: ".agenthub/config.local.json" };
719
- }
720
- }
721
- if (!mlx.enabled && file.pi?.backend === "mlx") throw new Error("Pi backend mlx conflicts with mlx.enabled=false");
722
- if (typeof mlx.runtimeDir === "string" && mlx.runtimeDir) mlx.runtimeDir = resolve(cwd, mlx.runtimeDir);
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);
728
- return {
729
- ...DEFAULT_CONFIG,
730
- ...file,
731
- ...(instanceConfig.adapters ? { adapters: instanceConfig.adapters } : {}),
732
- ...(instanceConfig.adapter_modules ? { adapter_modules: instanceConfig.adapter_modules } : {}),
733
- ...(instances ? { instances } : {}),
734
- ...(file.text_projection !== undefined ? { text_projection: projectionConfig(file.text_projection) } : {}),
735
- ...(file.pii !== undefined ? { pii: { paths: policyPaths(file.pii.paths, "pii.paths") } } : {}),
736
- ...(file.data !== undefined ? { data: { readonly: policyPaths(file.data.readonly, "data.readonly") } } : {}),
737
- action_policy: actionPolicyConfig(file.action_policy),
738
- ...(file.edit_governance !== undefined ? { edit_governance: parseEditGovernance(file.edit_governance) } : {}),
739
- permission_modes: { ...instancePermissions, ...permissionDefaults(file.permission_modes, instances, adapterCatalog) },
740
- protect_instruction_files: instructionProtection(file.protect_instruction_files),
741
- instructed: { mode: instructedMode(file.instructed?.mode) },
742
- permission_default_sources: appliedPermissionSources,
743
- memory: { ...DEFAULT_CONFIG.memory, native: true, ...file.memory, ...(file.memory?.short_ttl_days !== undefined ? { short_ttl_days: ttlDays(file.memory.short_ttl_days) } : {}),
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)
745
- roster: peerRosterConfig(file.roster, instances, adapterCatalog, inertModuleRoster),
746
- roles: Object.fromEntries(Object.entries({ ...configuredRoles, ...conductorPolicy.roles, ...extraRoles }).filter(([id]) => !instanceConfig.declaredExternalInstances?.some(row => row.id === id || row.kind === id))),
747
- planner: conductorPolicy.planner,
748
- conductor: conductorPolicy.conductor,
749
- budget: { ...DEFAULT_CONFIG.budget, wait_max_min: 30, ...file.budget }, // on with any project config (issue #36)
750
- context: { ...DEFAULT_CONTEXT, ...file.context },
751
- inference: { ...DEFAULT_CONFIG.inference, ...file.inference },
752
- omniroute: { ...DEFAULT_CONFIG.omniroute, ...file.omniroute },
753
- ...mergeNativeConfiguration(file, DEFAULT_CONFIG),
754
- approvals: {
755
- timeout_s: file.approvals?.timeout_s ?? DEFAULT_CONFIG.approvals.timeout_s,
756
- notify: typeof file.approvals?.notify === "boolean" ? file.approvals.notify : process.platform === "darwin",
757
- },
758
- tasks: { ...DEFAULT_CONFIG.tasks, ...file.tasks, ...(file.tasks?.wip_limits !== undefined ? { wip_limits: planningWipLimits(file.tasks.wip_limits) } : {}) },
759
- bus: { ...DEFAULT_CONFIG.bus, ...file.bus },
760
- adapter_timing: { ...DEFAULT_CONFIG.adapter_timing, ...file.adapter_timing },
761
- model_relay: { ...DEFAULT_CONFIG.model_relay, ...file.model_relay },
762
- console: { ...DEFAULT_CONFIG.console, ...file.console },
763
- task_sweep: taskSweepConfig(file.task_sweep),
764
- schedules: schedulesConfig(file.schedules),
765
- folder_triggers: foldersConfig(file.folder_triggers),
766
- corpus: corpusConfig(file.corpus),
767
- roadmap: roadmapConfig(file.roadmap),
768
- specs: parseSpecsConfig(file.specs),
769
- checks: { ...DEFAULT_CONFIG.checks, ...file.checks, runner: file.checks?.runner === "remote" ? "remote" : file.checks?.runner === "container" ? "container" : undefined,
770
- ...(file.checks?.remote !== undefined || file.checks?.runner === "remote" ? { remote: remoteRunnerConfig(file.checks?.remote) } : {}) },
771
- snapshots: { ...DEFAULT_CONFIG.snapshots, enabled: true, ...file.snapshots },
772
- worktrees: { quiet_days: wholeDays(file.worktrees?.quiet_days, DEFAULT_CONFIG.worktrees.quiet_days), alert_over: wholeDays(file.worktrees?.alert_over, DEFAULT_CONFIG.worktrees.alert_over) },
773
- questions: questionsConfig(file.questions),
774
- visuals: { retention_days: typeof file.visuals?.retention_days === "number" && Number.isSafeInteger(file.visuals.retention_days) && file.visuals.retention_days >= 1 && file.visuals.retention_days <= 3650 ? file.visuals.retention_days : DEFAULT_CONFIG.visuals.retention_days },
775
- research: { enabled: file.research?.enabled === true, ...(file.research?.runners !== undefined ? { runners: parseResearchRunners(file.research.runners) } : {}) }, // opt-in: anything but true is off
776
- bench: { enabled: file.bench?.enabled === true }, // opt-in: a run resets this project's work tree
777
- peers: { ...instanceModes, ...peerStartConfig(file.peers, instances, adapterCatalog) },
778
- terminal: { open: terminalTemplate(file.terminal?.open) },
779
- start: { agents: file.start?.agents === undefined ? [...START_AGENTS_DEFAULT] : checkStartAgents(file.start.agents) },
780
- limits: { ...PROJECT_LIMITS, ...file.limits }, // on with any project config (issue #38)
781
- review: { ...DEFAULT_CONFIG.review, ...file.review },
782
- recovery: { ...DEFAULT_CONFIG.recovery, ...file.recovery },
783
- capabilities: { ...file.capabilities },
784
- mlx,
785
- ...(ignored.length ? { ignored } : {}),
786
- ...(releasePolicyNotices.length ? { releasePolicyNotices } : {}),
787
- ...(retired.length ? { retired } : {}),
788
- };
789
- }
790
-
791
- /** Explicit launch choices are never replaced when the local capability is disabled. */
792
- export function mlxLaunchProblem(config: HubConfig, args: { backend?: unknown; model?: unknown }): string | undefined {
793
- if (config.mlx.enabled !== false) return undefined;
794
- if (args.backend === "mlx" || args.model === "mlx/fast") return "Pi MLX launch conflicts with mlx.enabled=false; select auto or a DGX alias";
795
- return undefined;
796
- }
797
-
798
331
  /** Shipped defaults remain capability-aware; operator-written MLX pins require an explicit migration. */
799
332
  function disabledMlxPolicyProblem(config: HubConfig, cwd: string): string | undefined {
800
333
  if (config.mlx.enabled !== false) return undefined;
@@ -2383,6 +1916,10 @@ export async function startDaemon(opts: DaemonOptions) {
2383
1916
  * hello is refused; a durable record would need a state file the refusal path does not own.
2384
1917
  */
2385
1918
  const jcodeDetached = new Map<string, { cause: string; command: string }>();
1919
+ /** #1795: the last hub-tools hello refused while that peer's owned launch was live and attached. One entry per peer, display only; it never marks the peer detached. */
1920
+ const jcodeRefusedHello = new Map<string, { at: number; pid?: number; command?: string }>();
1921
+ // #1795: the refused-hello record means "the owned launch is serving and a stray process was refused"; it is shown only while that holds.
1922
+ const ownedLaunchServing = (id: string): boolean => { const owner = jcodeLaunches.get(id); return !!owner && owner.ownedLaunchId !== undefined && bus.peers.get(id) === owner && ["idle", "busy", "paused"].includes(bus.stateOf(id)); };
2386
1923
  const globalModelRelay = (relay: ModelRelay) => { modelRelay = relay; };
2387
1924
  const nativeStateDir = (peer: string) => declarations[peer] ? join(opts.stateDir, "instances", peer) : opts.stateDir;
2388
1925
  const instanceAppPorts = new Map<string, number>();
@@ -8014,7 +7551,7 @@ export async function startDaemon(opts: DaemonOptions) {
8014
7551
  ...(dashboard ? { uiOrigin: dashboard.origin } : {}),
8015
7552
  codexProxyPort: opts.codexProxyPort,
8016
7553
  peers: Object.fromEntries(
8017
- 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 ?? [] } : {}) }]; }),
7554
+ 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 } : {}), ...(jcodeRefusedHello.has(id) && ownedLaunchServing(id) ? { refusedHello: jcodeRefusedHello.get(id) } : {}), ...(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 ?? [] } : {}) }]; }),
8018
7555
  ),
8019
7556
  peerVersions,
8020
7557
  taskWip: tasks.wipBreakdown(peerIds),
@@ -8078,7 +7615,21 @@ export async function startDaemon(opts: DaemonOptions) {
8078
7615
  budget: Object.fromEntries(Object.entries(budget.status()).map(([peer, row]) => [peer, row.paused ? { paused: { since: row.paused.since, resetsAt: row.paused.resetsAt } } : {}])),
8079
7616
  };
8080
7617
  const attention = needs(attentionInput, Date.now());
8081
- return { ...view, ...(includeAttentionInput ? { attentionInput } : {}), needs: { act: attention.act, watch: attention.watch, state: attention.state, ...(attention.items[0] ? { first: attention.items[0] } : {}) },
7618
+ // #1798: the one hub check, built from the finished peer rows; every surface renders this result.
7619
+ const hubCheck = buildHubCheck({ version: VERSION, controlPort: server.port ?? 0, peers: peerIds.map(id => {
7620
+ const row = view.peers[id] as Record<string, any> | undefined, def = definitionOf(id);
7621
+ const attached = !!bus.peers.get(id) && ["idle", "busy", "paused"].includes(bus.stateOf(id)) && row?.attached !== false;
7622
+ const detached = jcodeDetached.get(id);
7623
+ // The expected link comes from the adapter definition and the form the peer is started in, never from the observed link: a push peer that
7624
+ // drops to pull-only must still be expected to push. Pull-only by design: a ws-pull transport (agy), and a form the definition lists in
7625
+ // attach.pullOnlyForms (the Kimi TUI). The hub keeps no launch form for any other peer, so those are expected to push.
7626
+ const form = def?.attach?.admission ? (kimiSessionMode ?? startMode(id)) : startMode(id); // a definition with native admission keeps its pending launch form
7627
+ const expected = expectedHubLink(def, form);
7628
+ const nextStep = detached?.command ?? startCommand(id);
7629
+ return { id, expected, attached, starting: starting.has(id), pullOnly: row?.pullOnly === true,
7630
+ ...(typeof row?.attachEvidence === "string" ? { evidence: row.attachEvidence } : {}), detached: !!detached, queued: Number(row?.queued ?? 0), nextStep };
7631
+ }) });
7632
+ return { ...view, hubCheck, ...(includeAttentionInput ? { attentionInput } : {}), needs: { act: attention.act, watch: attention.watch, state: attention.state, ...(attention.items[0] ? { first: attention.items[0] } : {}) },
8082
7633
  ...(includeAttentionItems ? { attentionItems: attention.items } : {}) };
8083
7634
  };
8084
7635
  // #226: who owns this manifest, beyond a pid that a reboot can hand to another process. Only the file carries it
@@ -9233,7 +8784,8 @@ export async function startDaemon(opts: DaemonOptions) {
9233
8784
  try { startCurrent?.(); await jcode.start(); startCurrent?.(); registerModelOwner(jcode); bindRecordOwner(jcode, executionCwd, () => jcode.nativeSession); await reconcileNativeStart(peer, jcode, startCurrent); }
9234
8785
  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)"); }
9235
8786
  // #1668: this peer is under the hub again, so it is no longer detached. A start that failed above keeps the record.
9236
- if (jcodeDetached.delete(peer) && !stopping) writeStatus();
8787
+ const clearedDetached = jcodeDetached.delete(peer), clearedRefused = jcodeRefusedHello.delete(peer);
8788
+ if ((clearedDetached || clearedRefused) && !stopping) writeStatus();
9237
8789
  return { ok: true, policy: "unmanaged" };
9238
8790
  }
9239
8791
  if (adapter?.start.acpCommand) {
@@ -10199,6 +9751,8 @@ export async function startDaemon(opts: DaemonOptions) {
10199
9751
  return {
10200
9752
  id: row.id, peer: row.peer, state: row.state, revision: row.revision,
10201
9753
  ...(row.failureCause ? { failureCause: row.failureCause } : {}),
9754
+ // #1795: the stored reason of a failed or held delivery, through the same private and public rules as its bodies.
9755
+ ...(detail && row.reason ? { reason: publicDeliveryReason(originals, row.reason, { publicOnly, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); }, publicMetadataText: text => tasks.publicMetadataText(text) }) } : {}),
10202
9756
  ...roomChat.evidence(row.peer, row.id),
10203
9757
  ...(detail && bus.deliveryResolution(row.id) ? { resolvedBy: bus.deliveryResolution(row.id) } : {}),
10204
9758
  ...(!membershipAllowed(row.peer) ? { rostered: false, holdReason: "off roster" } : {}),
@@ -12410,7 +11964,10 @@ export async function startDaemon(opts: DaemonOptions) {
12410
11964
  if (!owner || !owner.ownsLaunch(msg.launchId)) {
12411
11965
  // #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
12412
11966
  // itself is unchanged and nothing new listens; the peer only gains the state `ahub status` reports until a hub-owned launch replaces it.
12413
- if (!stopping) { jcodeDetached.set(c.peer, jcodeDetachedNotice(c.peer)); writeStatus(); }
11967
+ // #1795: with the owned launch live and attached, the refused hello is a stray process, not a detached peer: name it and leave the peer's state alone.
11968
+ const live = !!owner && owner.ownedLaunchId !== undefined && bus.peers.get(c.peer) === owner && ["idle", "busy", "paused"].includes(bus.stateOf(c.peer));
11969
+ if (!stopping && live) { jcodeRefusedHello.set(c.peer, { at: Date.now(), ...refusedHelloProcess(msg.clientPid) }); writeStatus(); }
11970
+ else if (!stopping) { jcodeRefusedHello.delete(c.peer); jcodeDetached.set(c.peer, jcodeDetachedNotice(c.peer)); writeStatus(); }
12414
11971
  return sock.close(4403, "this process is not an owned launch of that peer; start it with ahub jcode");
12415
11972
  }
12416
11973
  }
@@ -13802,15 +13359,21 @@ export async function startDaemon(opts: DaemonOptions) {
13802
13359
  case "status": {
13803
13360
  const sendStatus = () => {
13804
13361
  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");
13362
+ // #1798 T3, display only: whether this tools connection runs under the launch the peer's current channel socket attached with. It labels a startup
13363
+ // notice and decides nothing: not admission, routing, delivery or permissions. Anyone holding the control token can send any launch id, so it is
13364
+ // a hint, never evidence. Per request, never cached or stored; the launch id itself is never returned, logged or recorded. Absent for every
13365
+ // other requester: a console, a minted session, a hub-owned tools child, a connection with no launch id, or a peer that is not a Claude channel.
13366
+ const thisLaunch = c.role === "tools" && !c.session && !c.toolsOwner && c.peer && c.launchId && definitionOf(c.peer)?.transport === "claude-channel"
13367
+ ? { thisLaunch: (bus.peers.get(c.peer) as { managedLaunchId?: unknown } | undefined)?.managedLaunchId === c.launchId } : {};
13805
13368
  if ((c.role === "console" || c.role === "tools") && msg.specs === true) {
13806
13369
  const summary = projectSpecs.status();
13807
13370
  if (summary) {
13808
13371
  const missingBlockHint = !specsMissingBlockHintShown && projectSpecs.missingBlock() === true;
13809
13372
  if (missingBlockHint) specsMissingBlockHintShown = true;
13810
- return void reply({ t: "status", status: { ...current, specs: { ...summary, ...(missingBlockHint ? { missingBlockHint: true } : {}) } } });
13373
+ return void reply({ t: "status", status: { ...current, ...thisLaunch, specs: { ...summary, ...(missingBlockHint ? { missingBlockHint: true } : {}) } } });
13811
13374
  }
13812
13375
  }
13813
- return void reply({ t: "status", status: current });
13376
+ return void reply({ t: "status", status: { ...current, ...thisLaunch } });
13814
13377
  };
13815
13378
  if (orphanChecks && !startupSpecPending()) return sendStatus();
13816
13379
  void Promise.all([orphanSweep, firstSpecProbe]).then(() => {