@staix/agent-hub 0.46.0 → 0.47.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.
- package/CHANGELOG.md +85 -0
- package/README.md +8 -4
- package/docs/adding-an-ai-tool.md +20 -4
- package/docs/agent-notes/adapters.md +3 -3
- package/docs/agent-notes/benchmarks.md +7 -1
- package/docs/agent-notes/daemon.md +6 -5
- package/docs/agent-notes/tasks.md +4 -2
- package/docs/agent-notes/tests.md +3 -0
- package/docs/contracts/companion-cli-v1.json +3 -0
- package/docs/data-policy.md +9 -0
- package/docs/design/adapters.md +14 -0
- package/docs/design/cli-output-inventory.md +362 -0
- package/docs/design/cli-output.md +42 -1
- package/docs/design/execution-reference.md +5 -2
- package/docs/design/guidance-probes.md +2 -2
- package/docs/design/refusal-inventory.md +26 -0
- package/docs/design/roadmap.md +4 -0
- package/docs/design/task-board.md +17 -1
- package/docs/dogfood.md +26 -10
- package/docs/events.md +9 -0
- package/docs/friction.md +46 -0
- package/docs/memory.md +35 -3
- package/docs/operations.md +63 -15
- package/docs/profiles.md +1 -0
- package/docs/quickstart.md +14 -2
- package/docs/roles.md +6 -0
- package/docs/sdlc.md +44 -1
- package/docs/security.md +16 -7
- package/docs/specs/2026-09-19-agent-hub-design.md +17 -0
- package/docs/specs/2026-09-19-multi-project-design.md +7 -1
- package/docs/verification/2026-11-24-0.46.1.md +48 -0
- package/docs/verification/2026-11-25-agy-1.5.16.md +31 -0
- package/docs/verification/2026-11-25-claude-implementer-2.1.332.md +47 -0
- package/docs/verification/2026-11-25-codex-0172-reviewer-isolation.md +47 -0
- package/docs/verification/2026-11-25-kimi-272-reviewer-compat.md +38 -0
- package/docs/verification/2026-11-25-kimi-tui-272.md +14 -0
- package/docs/verification/2026-11-25-pi-160-compat.md +40 -0
- package/docs/verification/2026-11-26-0.47.0.md +43 -0
- package/docs/verification/2026-11-26-codex-0172-reviewer-tool-call.md +29 -0
- package/docs/verification/dogfood/2026-11-24.md +2829 -0
- package/docs/verification/pi-160-model-free.ts +57 -0
- package/docs/verification/pi-160-native.mjs +21 -0
- package/docs/verified.json +43 -31
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +679 -134
- package/plugins/agent-hub/server.js +776 -154
- package/src/adapters/acp.ts +5 -0
- package/src/adapters/channel-peer.ts +7 -0
- package/src/adapters/claude-print-child.ts +27 -5
- package/src/adapters/codex-appserver.ts +9 -0
- package/src/adapters/compat.ts +12 -11
- package/src/adapters/configured-acp.ts +45 -2
- package/src/adapters/configured-print.ts +163 -0
- package/src/adapters/conformance/index.ts +1 -0
- package/src/adapters/conformance/print.ts +57 -0
- package/src/adapters/definitions/native-activity.ts +57 -0
- package/src/adapters/definitions/native-factories.ts +4 -2
- package/src/adapters/jcode.ts +10 -2
- package/src/adapters/local-worker.ts +2 -0
- package/src/adapters/registry-types.ts +5 -3
- package/src/adapters/role-eligibility.ts +5 -0
- package/src/cli/bench.ts +2 -1
- package/src/cli/broker.ts +2 -1
- package/src/cli/capabilities-output.ts +10 -14
- package/src/cli/configured-acp-entry.ts +10 -2
- package/src/cli/console-state.ts +25 -5
- package/src/cli/error-format.ts +2 -0
- package/src/cli/guidance.ts +1 -1
- package/src/cli/handoff-output.ts +20 -17
- package/src/cli/help.ts +78 -40
- package/src/cli/init-settings.ts +15 -0
- package/src/cli/intake-output.ts +13 -13
- package/src/cli/launch.ts +3 -2
- package/src/cli/learn-output.ts +40 -21
- package/src/cli/main.ts +148 -77
- package/src/cli/memory.ts +47 -2
- package/src/cli/output.ts +54 -31
- package/src/cli/recovery-package.ts +6 -1
- package/src/cli/roadmap.ts +2 -2
- package/src/cli/room-output.ts +71 -0
- package/src/cli/room.ts +19 -33
- package/src/cli/schedule-output.ts +20 -19
- package/src/cli/sdlc-output.ts +188 -170
- package/src/cli/source-output.ts +17 -14
- package/src/cli/specs.ts +13 -13
- package/src/cli/study-output.ts +66 -69
- package/src/cli/task-output.ts +106 -158
- package/src/cli/terminal-recovery.ts +2 -1
- package/src/cli/upgrade-runtime.ts +2 -1
- package/src/cli/warn-line.ts +18 -0
- package/src/cli/worktrees-output.ts +25 -23
- package/src/hub/audit-source.ts +45 -0
- package/src/hub/board.ts +141 -5
- package/src/hub/bus.ts +13 -2
- package/src/hub/config-apply.ts +14 -1
- package/src/hub/config-trust.ts +1 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +371 -45
- package/src/hub/handoff.ts +5 -1
- package/src/hub/hub-tools.ts +23 -5
- package/src/hub/instance-config.ts +3 -3
- package/src/hub/learn-followup.ts +103 -0
- package/src/hub/learning.ts +63 -1
- package/src/hub/manager.ts +15 -1
- package/src/hub/memory-policy.ts +2 -1
- package/src/hub/memory-review.ts +217 -0
- package/src/hub/peer-activity.ts +37 -0
- package/src/hub/peers.ts +3 -0
- package/src/hub/project-move.ts +258 -0
- package/src/hub/registry.ts +16 -5
- package/src/hub/restart.ts +7 -0
- package/src/hub/review-brief.ts +8 -4
- package/src/hub/review-checkout.ts +26 -0
- package/src/hub/review-findings.ts +6 -3
- package/src/hub/risk-tier.ts +129 -0
- package/src/hub/roadmap-check.ts +1 -0
- package/src/hub/routing.ts +3 -1
- package/src/hub/sdlc-merge.ts +9 -0
- package/src/hub/sdlc-metrics.ts +24 -1
- package/src/hub/sdlc-queue.ts +1 -1
- package/src/hub/sdlc.ts +15 -6
- package/src/hub/settings.ts +2 -0
- package/src/hub/spec-readback.ts +136 -0
- package/src/hub/specs.ts +1 -1
- package/src/hub/task-list-page.ts +1 -1
- package/src/hub/tasks.ts +558 -65
- package/src/hub/ui.ts +4 -2
- package/src/ui/index.html +26 -2
- package/src/ui/overview-model.ts +138 -0
- package/src/ui/plugin.ts +30 -4
- package/templates/roles/ops/project-manager.md +1 -1
package/src/hub/daemon.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
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";
|
|
@@ -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";
|
|
@@ -221,7 +226,8 @@ import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
|
|
|
221
226
|
import { DEFAULT_INFERENCE, DIGEST, Inference, SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii, type InferenceConfig, type PiiVerdict } from "./inference.ts";
|
|
222
227
|
import { taskEvidencePrivacy, type TaskEvidencePrivacy, ask, ASK_NOTE_TITLE, RUN_START } from "./ask.ts";
|
|
223
228
|
import { currentRouting, loadRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
|
|
224
|
-
import { withChecklistLine } from "./learning.ts";
|
|
229
|
+
import { withChecklistLine, withoutChecklistLine } from "./learning.ts";
|
|
230
|
+
import { FOLLOWUP_DEFAULTS } from "./learn-followup.ts";
|
|
225
231
|
import { autonomyConsentStateDir, createAutonomyConsent, type AutonomyConsentValues } from "./autonomy-consent.ts";
|
|
226
232
|
import { insideRoot } from "./path-policy.ts";
|
|
227
233
|
import { autonomyPreset, autonomyEnvironment, planAutonomy, autonomyRemovalKeys, autonomyStatus, type AutonomyEnvironment, type AutonomyPeer } from "./autonomy.ts";
|
|
@@ -291,7 +297,7 @@ import { DEFAULT_SPECS_CONFIG, parseSpecsConfig, type SpecsConfig } from "./spec
|
|
|
291
297
|
|
|
292
298
|
export interface HubConfig {
|
|
293
299
|
adapter_modules?: readonly AdapterModuleDeclaration[];
|
|
294
|
-
adapters?: Readonly<Record<string, import("../adapters/configured-acp.ts").
|
|
300
|
+
adapters?: Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAdapterConfig>>;
|
|
295
301
|
/** Person-owned declarations, read only from an untracked machine-local file. Bound for this daemon lifetime. */
|
|
296
302
|
instances?: InstancesConfig;
|
|
297
303
|
watchdog_ms: number;
|
|
@@ -321,7 +327,7 @@ export interface HubConfig {
|
|
|
321
327
|
/** #489 H7: accepted presentation preferences read by a new console through settings_get. */
|
|
322
328
|
console?: ConsoleOperationalConfig["console"];
|
|
323
329
|
/** `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 };
|
|
330
|
+
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
331
|
roster: PeerRoster;
|
|
326
332
|
roles: Record<string, string[]>;
|
|
327
333
|
/** #455: the one peer that holds the planner role; unset, the `roles` planners stand, or the hub assigns one. */
|
|
@@ -419,7 +425,7 @@ export const DEFAULT_CONFIG: HubConfig = {
|
|
|
419
425
|
queue_cap: 200,
|
|
420
426
|
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
427
|
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 },
|
|
428
|
+
memory: { enabled: true, inject_tokens: 2000, brief_items: 8, preface_unused_after: 20, review: MEMORY_REVIEW_DEFAULTS },
|
|
423
429
|
roster: {},
|
|
424
430
|
roles: DEFAULT_ROLES,
|
|
425
431
|
conductor: { feed: "own", approval_wait_s: 30 },
|
|
@@ -464,7 +470,7 @@ export const DEFAULT_CONFIG: HubConfig = {
|
|
|
464
470
|
export { stateDirFor };
|
|
465
471
|
|
|
466
472
|
/** 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"]);
|
|
473
|
+
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
474
|
const BASE_RESERVED_IDS = new Set<string>([USER, ...SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.attach?.externalHello !== true), HUB, DIGEST]);
|
|
469
475
|
const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
|
|
470
476
|
|
|
@@ -714,6 +720,10 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
|
|
|
714
720
|
if (!mlx.enabled && file.pi?.backend === "mlx") throw new Error("Pi backend mlx conflicts with mlx.enabled=false");
|
|
715
721
|
if (typeof mlx.runtimeDir === "string" && mlx.runtimeDir) mlx.runtimeDir = resolve(cwd, mlx.runtimeDir);
|
|
716
722
|
if (typeof mlx.modelPath === "string" && mlx.modelPath) mlx.modelPath = resolve(cwd, mlx.modelPath);
|
|
723
|
+
// #1329 part 1: the scheduled memory review is derived from `memory.review` at every read (`scheduleEntries` below)
|
|
724
|
+
// rather than copied into `config.schedules`, because a config reload applies per-key deltas to this live object: a copy
|
|
725
|
+
// would go stale the moment a person flips the switch.
|
|
726
|
+
const memoryReview = memoryReviewConfig(file.memory?.review);
|
|
717
727
|
return {
|
|
718
728
|
...DEFAULT_CONFIG,
|
|
719
729
|
...file,
|
|
@@ -730,7 +740,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
|
|
|
730
740
|
instructed: { mode: instructedMode(file.instructed?.mode) },
|
|
731
741
|
permission_default_sources: appliedPermissionSources,
|
|
732
742
|
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)
|
|
743
|
+
...(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
744
|
roster: peerRosterConfig(file.roster, instances, adapterCatalog, inertModuleRoster),
|
|
735
745
|
roles: Object.fromEntries(Object.entries({ ...configuredRoles, ...conductorPolicy.roles, ...extraRoles }).filter(([id]) => !instanceConfig.declaredExternalInstances?.some(row => row.id === id || row.kind === id))),
|
|
736
746
|
planner: conductorPolicy.planner,
|
|
@@ -927,6 +937,8 @@ export interface DaemonOptions {
|
|
|
927
937
|
boundedTools?: {
|
|
928
938
|
specAvailable?: typeof specAvailable;
|
|
929
939
|
fetchSpec?: typeof fetchSpec;
|
|
940
|
+
/** Host-only seam for the issue edit-time reads a read-back grant and `ahub sdlc accept` make. */
|
|
941
|
+
specEdit?: SdlcGh;
|
|
930
942
|
runner?: (options: RunnerOptions) => Pick<ContainerRunner, "available" | "start" | "result" | "consumeOutput" | "cancel" | "sweep" | "stopAll" | "markStale"> & Partial<Pick<ContainerRunner, "unknownReceipts" | "maintenanceUnavailable" | "compactTask">>;
|
|
931
943
|
};
|
|
932
944
|
}
|
|
@@ -1890,6 +1902,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
1890
1902
|
const presenceOnlyDelivery = (envs: readonly Envelope[]): boolean => envs.length === 0 || envs.every(env => env.from === HUB && env.kind === "presence");
|
|
1891
1903
|
let remotePending = (_room: string): readonly string[] => [];
|
|
1892
1904
|
let remoteQueueChanged = () => {};
|
|
1905
|
+
const activities = new PeerActivityTracker();
|
|
1906
|
+
const activityPrivate = (peer: PeerId) => contextPii(peer) || reviewObserverHeld(peer)
|
|
1907
|
+
|| board.peerTaskSignals(peer).some(task => !isClosedTaskState(task.state)
|
|
1908
|
+
&& task.signals.some(signal => signal === "pii" || signal === "pii_path"))
|
|
1909
|
+
|| bus.lastDeliveredTo(peer).some(env => env.private || isReviewObserverExcluded(env)
|
|
1910
|
+
|| (env.refs?.task ? board.get(Number(env.refs.task))?.signals.some(signal => signal === "pii" || signal === "pii_path") : false));
|
|
1893
1911
|
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
1912
|
beforeReviewInputHandoff: (peer, envs) => {
|
|
1895
1913
|
const owner = bus.peers.get(peer);
|
|
@@ -1913,6 +1931,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
1913
1931
|
return sender === USER ? false : !bus.peers.has(sender) || !!turns.get(sender)?.private || contextPii(sender);
|
|
1914
1932
|
},
|
|
1915
1933
|
doing: (peer, kind, text) => observeDoing(peer, kind, text),
|
|
1934
|
+
activity: (peer, kind) => activities.observe(peer, kind, () => activityPrivate(peer)),
|
|
1916
1935
|
reviewObserverScope: peer => readReviewObserverScope ? readReviewObserverScope(peer) : "review-scope-unavailable",
|
|
1917
1936
|
reviewObserverInputExcluded: (peer, envs) => reviewInputHeld(peer, envs) || reviewObserverInput(peer),
|
|
1918
1937
|
onImportantQueued: (peer, counts) => { const p = bus.peers.get(peer); if (isWsPeer(p)) p.notifyQueued(counts); } });
|
|
@@ -2363,6 +2382,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
2363
2382
|
const modelRelays = new Map<string, ModelRelay>();
|
|
2364
2383
|
/** #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
2384
|
const jcodeLaunches = new Map<string, JcodePeer>();
|
|
2385
|
+
/**
|
|
2386
|
+
* #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
|
|
2387
|
+
* 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
|
|
2388
|
+
* hello is refused; a durable record would need a state file the refusal path does not own.
|
|
2389
|
+
*/
|
|
2390
|
+
const jcodeDetached = new Map<string, { cause: string; command: string }>();
|
|
2366
2391
|
const globalModelRelay = (relay: ModelRelay) => { modelRelay = relay; };
|
|
2367
2392
|
const nativeStateDir = (peer: string) => declarations[peer] ? join(opts.stateDir, "instances", peer) : opts.stateDir;
|
|
2368
2393
|
const instanceAppPorts = new Map<string, number>();
|
|
@@ -2462,6 +2487,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
2462
2487
|
} catch {
|
|
2463
2488
|
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
2489
|
}
|
|
2490
|
+
try {
|
|
2491
|
+
const retained = board.specReadbackIntegrity(), expected = restored?.integrity?.specReadbacks;
|
|
2492
|
+
if (restored && (expected ? expected.readbacks !== retained.readbacks || expected.digest !== retained.digest
|
|
2493
|
+
: retained.readbacks !== 0)) throw new Error("changed recovery binding");
|
|
2494
|
+
} catch {
|
|
2495
|
+
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");
|
|
2496
|
+
}
|
|
2465
2497
|
startupCleanup.push(() => guidanceProbeStore.close());
|
|
2466
2498
|
// #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
2499
|
// 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
|
|
@@ -3062,6 +3094,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3062
3094
|
let questionStore!: QuestionStore;
|
|
3063
3095
|
startupTimings.mark("task_ports");
|
|
3064
3096
|
const tasks: Tasks = new Tasks({
|
|
3097
|
+
taskTokens: () => Object.fromEntries(usageRollup.query({ by: "task" }).rows.flatMap(row => /^\d+$/.test(row.key) ? [[Number(row.key), row.counted.value]] : [])),
|
|
3065
3098
|
ownerQuestionWait: (task, peer) => questionStore?.ownerWait(task, peer),
|
|
3066
3099
|
guidanceProbes: { store: guidanceProbeStore, session: by => {
|
|
3067
3100
|
const request = guidanceProbeRequestContext.getStore();
|
|
@@ -3127,13 +3160,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3127
3160
|
catalog,
|
|
3128
3161
|
sessionRoles: peer => bus.peers.has(peer) && bus.stateOf(peer) !== "offline" ? preparedSessionRoles.get(peer) ?? [] : [],
|
|
3129
3162
|
projectedReview: task => reviewProjection(task),
|
|
3130
|
-
reviewMaterials
|
|
3163
|
+
reviewMaterials,
|
|
3131
3164
|
ownerWrites: (task, since) => ownerWriteEvidence(task, since),
|
|
3132
3165
|
ownerAccepted: task => captureOwnerWriteStart(task),
|
|
3133
3166
|
prepareReviewBrief: async task => {
|
|
3134
3167
|
if (tasks.isPii(task) || !task.refs.commit) return;
|
|
3135
3168
|
const root = executionRoot(task.owner ?? "");
|
|
3136
|
-
const brief = buildReviewBrief(root, task.refs.commit,
|
|
3169
|
+
const brief = buildReviewBrief(root, task.refs.commit, briefPolicy(root));
|
|
3137
3170
|
if ("unavailable" in brief) return;
|
|
3138
3171
|
const key = JSON.stringify([root, brief.head, brief.mergeBase]);
|
|
3139
3172
|
// prepareOnly and completion share one exact-tree pass, including an unknown result.
|
|
@@ -3156,7 +3189,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3156
3189
|
},
|
|
3157
3190
|
reviewBrief: task => {
|
|
3158
3191
|
const root = executionRoot(task.owner ?? "");
|
|
3159
|
-
const brief = buildReviewBrief(root, task.refs.commit,
|
|
3192
|
+
const brief = buildReviewBrief(root, task.refs.commit, briefPolicy(root));
|
|
3160
3193
|
return "unavailable" in brief ? brief : withCodeSymbols(brief, reviewSymbols.get(JSON.stringify([root, brief.head, brief.mergeBase])) ?? { state: "unknown" }, task.plan?.symbols, tasks.publicMetadataText);
|
|
3161
3194
|
},
|
|
3162
3195
|
specsConfig: () => config.specs,
|
|
@@ -3179,6 +3212,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3179
3212
|
// 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
3213
|
roadmapModel: (system, user, allowed) => inference ? inference.complete(system, user, 2000, { interactive: true, timeoutMs: 20_000, allowed }) : Promise.resolve(undefined),
|
|
3181
3214
|
auditSource: gitAuditSource(opts.cwd), // #1403 A4
|
|
3215
|
+
// #1646 T2: a verdict's evidence names the checkout its reviewer read. The reviewing session reports its own cwd at hello;
|
|
3216
|
+
// that path is read only when this host proves it a worktree of this repository, and it never proves isolation or grants any.
|
|
3217
|
+
reviewerCheckout: peer => {
|
|
3218
|
+
const attached = bus.peers.get(peer), root = attached && isWsPeer(attached) ? attached.sessionCwd : undefined;
|
|
3219
|
+
return root ? checkoutAuditSource(opts.cwd, root) : undefined;
|
|
3220
|
+
},
|
|
3182
3221
|
sdlc: {
|
|
3183
3222
|
config: () => lifecycleConfig,
|
|
3184
3223
|
gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
|
|
@@ -3292,7 +3331,10 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3292
3331
|
offerRead: (peer, envelopeId) => journal.offerRead(peer, envelopeId),
|
|
3293
3332
|
offerPullOnly: (id) => { const peer = bus.peers.get(id); return peer?.pullOnly === true; },
|
|
3294
3333
|
stallNotice: stall => { supervision.taskStalled(stall); },
|
|
3295
|
-
roles
|
|
3334
|
+
get roles() {
|
|
3335
|
+
if (!configuredIds.some(id => definitionOf(id)?.start.daemonPort === "configured-print")) return config.roles;
|
|
3336
|
+
return Object.fromEntries(Object.entries(config.roles).filter(([id]) => definitionOf(id)?.start.daemonPort !== "configured-print"));
|
|
3337
|
+
},
|
|
3296
3338
|
turnFree,
|
|
3297
3339
|
coordination: () => config.coordination === "turn-free",
|
|
3298
3340
|
capable: (peer) => capable.has(peer),
|
|
@@ -3507,6 +3549,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3507
3549
|
return executionRoots.get(peer) ?? opts.cwd;
|
|
3508
3550
|
};
|
|
3509
3551
|
const repoFor = (peer: string, budget?: SnapshotBudget) => executionRoot(peer) === opts.cwd ? factsRepo : repoOf(executionRoot(peer), budget);
|
|
3552
|
+
/** The screening every review brief of `root` is built with, so the stored brief, the prepare pass and a brief-scoped read agree. */
|
|
3553
|
+
const briefPolicy = (root: string) => ({
|
|
3554
|
+
privatePath: (path: string) => isDenied(path, config.local.deny) || matchesPolicy(root, path, config.pii?.paths ?? [], true),
|
|
3555
|
+
nameable: tasks.nameable,
|
|
3556
|
+
});
|
|
3510
3557
|
const projectionsFor = (peer: string): TextProjections => {
|
|
3511
3558
|
const root = executionRoot(peer);
|
|
3512
3559
|
if (root === opts.cwd) return projections;
|
|
@@ -4281,6 +4328,54 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4281
4328
|
// #683 U2: events.jsonl folded into hub.db, a bounded pass at a time, so `usage` never rescans the log.
|
|
4282
4329
|
const usageRollup = new UsageRollup(join(opts.stateDir, "hub.db"), join(opts.stateDir, "events.jsonl"));
|
|
4283
4330
|
startupCleanup.push(() => usageRollup.close());
|
|
4331
|
+
// #1329 part 2 (AC5, report): one memory-review card's counted spend and per-hub-run counts. The spend is read from the
|
|
4332
|
+
// hub's own roll-up, so it is what the hub counted, never an estimate; the counts are what this daemon observed on the
|
|
4333
|
+
// card's turns (memory entries read, proposals filed) and are written to the board as counts only when the card is done.
|
|
4334
|
+
const reviewCounts = new Map<number, { notes: number; corrections: number; remembered: number }>();
|
|
4335
|
+
const REVIEW_WEEK_MS = 7 * 86_400_000;
|
|
4336
|
+
const reviewCount = (task: number, field: "notes" | "corrections" | "remembered", by = 1): void => {
|
|
4337
|
+
const row = reviewCounts.get(task) ?? { notes: 0, corrections: 0, remembered: 0 };
|
|
4338
|
+
row[field] += by; reviewCounts.set(task, row);
|
|
4339
|
+
};
|
|
4340
|
+
const reviewCountedTokens = (ids: readonly number[]): number => {
|
|
4341
|
+
if (!ids.length) return 0;
|
|
4342
|
+
pollUsageRollup();
|
|
4343
|
+
const wanted = new Set(ids.map(String));
|
|
4344
|
+
return usageRollup.query({ by: "task" }).rows.filter(row => wanted.has(row.key)).reduce((sum, row) => sum + (row.counted.value ?? 0), 0);
|
|
4345
|
+
};
|
|
4346
|
+
const reviewSpend = (card: Task): ReviewSpend => {
|
|
4347
|
+
const week = board.list().filter(task => memoryReviewTask(task) && task.created >= Date.now() - REVIEW_WEEK_MS).map(task => task.id);
|
|
4348
|
+
return { run: reviewCountedTokens([card.id]), week: reviewCountedTokens(week) };
|
|
4349
|
+
};
|
|
4350
|
+
const reviewCountLine = (card: Task): string => memoryReviewCountLine({ ...(reviewCounts.get(card.id) ?? { notes: 0, corrections: 0, remembered: 0 }), tokens: reviewCountedTokens([card.id]) });
|
|
4351
|
+
/**
|
|
4352
|
+
* #1329 AC3: the review card the caller's current turn is bound to. The turn's own attribution names it: the card is
|
|
4353
|
+
* delivered to its owner, `Tasks.ownerTurnTasks` excludes a `review` card, and a call made outside that turn - the
|
|
4354
|
+
* reviewer's, or the owner's work on another task - is not in the review's scope.
|
|
4355
|
+
*/
|
|
4356
|
+
const reviewTurnCard = (by: PeerId): Task | undefined => tasks.reviewCardFor(by, turns.get(by)?.attribution.task);
|
|
4357
|
+
/**
|
|
4358
|
+
* The stop itself: a counted spend at either cap asks the owner for one checkpoint and then escalates the card with reason
|
|
4359
|
+
* `budget`, through the ordinary escalation path, so the board records who moved it and why. Each card stops once: the stop
|
|
4360
|
+
* is read from the card's own history, so it survives a daemon restart and a second turn cannot escalate it again.
|
|
4361
|
+
*/
|
|
4362
|
+
const reviewBudgetAfterTurn = async (peer: PeerId, taskIds: readonly number[]): Promise<void> => {
|
|
4363
|
+
const caps = config.memory.review;
|
|
4364
|
+
if (caps?.enabled !== true || !taskIds.length) return;
|
|
4365
|
+
// Only the run's own owner: a reviewer's turn that names the card spends the reviewer's tokens, not the review's.
|
|
4366
|
+
const cards = [...new Set(taskIds)].map(id => board.get(id)).filter((task): task is Task => !!task && task.owner === peer && memoryReviewTask(task) && !isClosedTaskState(task.state));
|
|
4367
|
+
if (!cards.length) return;
|
|
4368
|
+
for (const card of cards) {
|
|
4369
|
+
if (card.history.some(entry => entry.event === "escalated" && entry.reason === "budget")) continue;
|
|
4370
|
+
const spend = reviewSpend(card), stop = reviewBudgetStop(spend, caps);
|
|
4371
|
+
if (!stop) continue;
|
|
4372
|
+
if (card.owner) bus.publish(newEnvelope(HUB, reviewCheckpointRequest(card.id, stop), { to: [card.owner], kind: "task", priority: "important", refs: { task: String(card.id) } }));
|
|
4373
|
+
try { await tasks.escalate(HUB, card.id, reviewBudgetNote(card.id, stop, spend), "budget"); }
|
|
4374
|
+
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; }
|
|
4375
|
+
}
|
|
4376
|
+
};
|
|
4377
|
+
/** One advisory line for the stop that runs after a turn; it never fails the turn. */
|
|
4378
|
+
const reviewBudgetFailure = (error: Error): void => { log(`memory review budget: ${error.message.slice(0, 120)}`); };
|
|
4284
4379
|
// #1513 AC2: one window view feeds the `budget` reply, the dashboard snapshot and therefore `ahub budget` and the
|
|
4285
4380
|
// console, so the three cannot disagree. The burn series is hourly and an answer is kept for a minute per reading:
|
|
4286
4381
|
// the page polls every second and must not query the roll-up that often.
|
|
@@ -4870,7 +4965,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4870
4965
|
return false;
|
|
4871
4966
|
} catch { return undefined; } // Unknown is never evidence of no writes, including a missing/pruned tree.
|
|
4872
4967
|
}
|
|
4873
|
-
async function reviewMaterials(task: Task, requests: readonly ReviewReadRequest[]): Promise<ReviewMaterialBatch> {
|
|
4968
|
+
async function reviewMaterials(task: Task, requests: readonly ReviewReadRequest[], scope?: "brief"): Promise<ReviewMaterialBatch> {
|
|
4874
4969
|
const budget: SnapshotBudget = { deadline: Infinity };
|
|
4875
4970
|
budget.deadline = budgetNow(budget) + 8000;
|
|
4876
4971
|
const deadline = budget.deadline;
|
|
@@ -4903,6 +4998,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4903
4998
|
const canonical = relative(opts.cwd, resolve(root, path));
|
|
4904
4999
|
return canonical !== ".." && !canonical.startsWith("../") && !canonical.startsWith(".worktrees/") ? canonical : scoped;
|
|
4905
5000
|
});
|
|
5001
|
+
// #1646 T3: a reviewer reading its brief at the reviewed head is scoped to exactly the paths the brief lists, which the host
|
|
5002
|
+
// builds itself. The reader's caps (MAX_FILES per operation, PROJECTED_DIFF_BYTES) still bound every answer.
|
|
5003
|
+
if (scope === "brief") {
|
|
5004
|
+
const brief = buildReviewBrief(root, head, briefPolicy(root));
|
|
5005
|
+
if ("unavailable" in brief) return unavailable();
|
|
5006
|
+
scopes.push(...brief.reviewable.map(file => file.path));
|
|
5007
|
+
}
|
|
4906
5008
|
let base = "";
|
|
4907
5009
|
// Only complete PR metadata at this exact head expands scope. A declared PR link
|
|
4908
5010
|
// or a locally guessed merge base is never an inventory of its changed files.
|
|
@@ -5209,6 +5311,15 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
5209
5311
|
startupCleanup.push(() => folderStore.close());
|
|
5210
5312
|
let schedulesTimer: ReturnType<typeof setInterval> | undefined;
|
|
5211
5313
|
const scheduleNow = () => opts.schedulesNow?.() ?? Date.now();
|
|
5314
|
+
/**
|
|
5315
|
+
* #1329 part 1: the configured schedules plus the one the machine-local memory.review switch stands for. Read live from
|
|
5316
|
+
* 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
|
|
5317
|
+
* schedule path (`proposeFromSchedules`, `scheduleViews`, `setSchedulePaused`, `runScheduleNow`) takes its list from here.
|
|
5318
|
+
*/
|
|
5319
|
+
const scheduleEntries = (): ScheduleEntry[] => {
|
|
5320
|
+
const review = memoryReviewEntry(config.memory.review ?? MEMORY_REVIEW_DEFAULTS, opts.cwd);
|
|
5321
|
+
return review ? [...config.schedules, review] : config.schedules;
|
|
5322
|
+
};
|
|
5212
5323
|
/** The pass in flight, so a stop can wait for it before the board and the store close. */
|
|
5213
5324
|
let schedulesPass: Promise<void> | undefined;
|
|
5214
5325
|
/** #335: `ahub schedule run` calls in flight. They are not the timer's pass, but `stopOnce` waits for them just the same. */
|
|
@@ -5220,7 +5331,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
5220
5331
|
};
|
|
5221
5332
|
const runSchedulesOnce = async () => {
|
|
5222
5333
|
try {
|
|
5223
|
-
for (const run of await tasks.proposeFromSchedules(schedulesStore,
|
|
5334
|
+
for (const run of await tasks.proposeFromSchedules(schedulesStore, scheduleEntries(), scheduleNow(), () => opts.schedulesHeld?.() === true)) {
|
|
5224
5335
|
if (run.outcome === "ran") log(`schedule ${run.id}: proposed task #${run.task}`);
|
|
5225
5336
|
else if (run.outcome === "failed") log(`schedule ${run.id}: could not propose; see ahub status`);
|
|
5226
5337
|
}
|
|
@@ -5241,9 +5352,10 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
5241
5352
|
const rescheduleSchedules = () => {
|
|
5242
5353
|
if (schedulesTimer) clearInterval(schedulesTimer);
|
|
5243
5354
|
schedulesTimer = undefined;
|
|
5355
|
+
const entries = scheduleEntries();
|
|
5244
5356
|
if (!config.folder_triggers.length) { try { folderStore.prune([]); } catch { /* the store is closed while stopping */ } }
|
|
5245
|
-
if (!
|
|
5246
|
-
if (!
|
|
5357
|
+
if (!entries.length && !config.folder_triggers.length) { try { schedulesStore.prune([]); } catch { /* the store is closed while stopping */ } return; }
|
|
5358
|
+
if (!entries.length) { try { schedulesStore.prune([]); } catch { /* the store is closed while stopping */ } }
|
|
5247
5359
|
schedulesTimer = setInterval(() => { void runSchedules(); }, opts.schedulesEveryMs ?? 60_000);
|
|
5248
5360
|
schedulesTimer.unref?.();
|
|
5249
5361
|
};
|
|
@@ -5974,8 +6086,23 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
5974
6086
|
}
|
|
5975
6087
|
async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false): Promise<string> {
|
|
5976
6088
|
if (op === "hub_visual" || op === "hub_visual_show") return visualTool(by, op, a, piiTurn);
|
|
6089
|
+
// #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
|
|
6090
|
+
// may carry the PII, and the file body would be a second carrier of it.
|
|
6091
|
+
if (op === "hub_review_file") {
|
|
6092
|
+
// 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.
|
|
6093
|
+
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");
|
|
6094
|
+
return await tasks.reviewFile(by, a);
|
|
6095
|
+
}
|
|
5977
6096
|
const reviewTurn = reviewObserverHeld(by) || bus.lastDeliveredTo(by).some(isReviewObserverExcluded);
|
|
5978
6097
|
if (reviewTurn || op === "hub_review" && reviewCaptureExcluded(op, JSON.stringify(a))) progress.clearPeer(by);
|
|
6098
|
+
if (op === "hub_readback_report") {
|
|
6099
|
+
// #1658 T4: the report is the bound reader's; a private, PII or review-observer turn writes none.
|
|
6100
|
+
// 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.
|
|
6101
|
+
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");
|
|
6102
|
+
// 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.
|
|
6103
|
+
if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown holds read-back writes; wait for release and retry");
|
|
6104
|
+
return JSON.stringify(await tasks.specReadbackReport(by, a, () => stopping || recoveryActive() || bus.isRecoveryHeld ? "read-back write held by recovery or shutdown" : undefined));
|
|
6105
|
+
}
|
|
5979
6106
|
if (op === "hub_survey_report") {
|
|
5980
6107
|
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
6108
|
if (stopping || recoveryActive() || bus.isRecoveryHeld) throw new PreEffectToolRefusal("recovery or shutdown holds survey writes; wait for release and retry");
|
|
@@ -6053,6 +6180,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6053
6180
|
if (by !== USER && (piiTurn || turns.get(by)?.private || contextPii(by))) throw new PreEffectToolRefusal("bounded task tools unavailable during a PII turn");
|
|
6054
6181
|
}
|
|
6055
6182
|
if (op === "hub_specs" && (piiTurn || turns.get(by)?.private || contextPii(by))) throw new PreEffectToolRefusal("spec inspection unavailable during a private turn");
|
|
6183
|
+
// #1329 part 2 (AC3): while a turn is bound to a memory-review card its owner holds, the card's tool scope is enforced
|
|
6184
|
+
// here, on every call, before anything is written. The scope is a name rule in `memory-review.ts`; this only decides
|
|
6185
|
+
// whether this call runs in the review's turn, and an ordinary turn resolves no card at all.
|
|
6186
|
+
if (by !== USER) {
|
|
6187
|
+
const reviewCard = reviewTurnCard(by), refused = reviewCard && memoryReviewScope(op);
|
|
6188
|
+
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`);
|
|
6189
|
+
}
|
|
6056
6190
|
if (MEMORY_READ_TOOLS.has(op)) validateMemoryRead(op, a);
|
|
6057
6191
|
if (op === "hub_memory_correct") correctionInput(a);
|
|
6058
6192
|
if (op === "hub_task_propose" && by !== USER && (piiTurn || turns.get(by)?.private)) {
|
|
@@ -6117,9 +6251,19 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6117
6251
|
const code = symbolStarts.length ? await memoryCode(symbolStarts, valid).catch(() => unavailableMemoryCodeOverlay()) : undefined;
|
|
6118
6252
|
if (!valid()) throw new PreEffectToolRefusal("memory read unavailable");
|
|
6119
6253
|
checkMemory();
|
|
6120
|
-
|
|
6254
|
+
const read = memoryRead(memoryStore, memoryProject, screenMemory, op, a, staleness(), code ? currentMemoryCode(code) : undefined);
|
|
6255
|
+
// #1329: a review's done report counts the notes it checked, so a successful read on its card is counted here.
|
|
6256
|
+
const card = op === "hub_memory_show" ? (Array.isArray(a.ids) ? reviewTurnCard(by) : undefined) : undefined;
|
|
6257
|
+
if (card) reviewCount(card.id, "notes", (a.ids as unknown[]).length);
|
|
6258
|
+
return read;
|
|
6259
|
+
}
|
|
6260
|
+
if (op === "hub_memory_correct") {
|
|
6261
|
+
need("memory_correct", "propose memory corrections");
|
|
6262
|
+
const candidate = await tasks.correct(by, a);
|
|
6263
|
+
const card = reviewTurnCard(by);
|
|
6264
|
+
if (card) reviewCount(card.id, "corrections");
|
|
6265
|
+
return candidate;
|
|
6121
6266
|
}
|
|
6122
|
-
if (op === "hub_memory_correct") { need("memory_correct", "propose memory corrections"); return tasks.correct(by, a); }
|
|
6123
6267
|
if (op === "hub_remember") need("remember", "save notes to shared memory");
|
|
6124
6268
|
if (CAPABILITY_TOOLS.has(op)) {
|
|
6125
6269
|
// #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 +6291,24 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6147
6291
|
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
6292
|
}
|
|
6149
6293
|
if (op === "hub_task_spec") {
|
|
6150
|
-
|
|
6294
|
+
// #1658 T4: the person's ruling is one binding per read-back request, so the bound reader may state the spec back
|
|
6295
|
+
// without the standing spec_read capability, and only while its own request holds no report on the body it was filed for.
|
|
6296
|
+
const asked = board.get(Number(a.id)), specEditGh = opts.boundedTools?.specEdit;
|
|
6297
|
+
let grant = asked ? tasks.specReadbackGrant(asked.id, asked.created, by) : undefined;
|
|
6298
|
+
// #1658: a carried read fetches the request's own issue, so a receipt issue the task's text does not name is still read,
|
|
6299
|
+
// and a body that moved or another repository's issue ends the grant here.
|
|
6300
|
+
if (grant && (grant.repo.toLowerCase() !== memoryRepo.toLowerCase()
|
|
6301
|
+
|| !await tasks.specReadbackFresh(grant, specEditGh ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound))))) grant = undefined;
|
|
6302
|
+
const carried = (task: Task | undefined) => !!task && !!tasks.specReadbackGrant(task.id, task.created, by);
|
|
6303
|
+
if (!grant) need("spec_read", "read assigned specifications");
|
|
6151
6304
|
const authorized = () => {
|
|
6152
6305
|
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");
|
|
6306
|
+
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
6307
|
return task;
|
|
6155
6308
|
};
|
|
6156
6309
|
const task = authorized(), generation = connectionGeneration(by), updated = task.updated, revision = task.history.length;
|
|
6157
6310
|
const deadline = Date.now() + 25_000; // retain a response margin inside the control client's 30-second cap
|
|
6158
|
-
const issues = specRefs(task, memoryRepo);
|
|
6311
|
+
const issues = grant && !may(by, "spec_read") ? [grant.issue] : specRefs(task, memoryRepo);
|
|
6159
6312
|
if (!issues.length) throw new PreEffectToolRefusal("no assigned spec references");
|
|
6160
6313
|
await ensureSpec();
|
|
6161
6314
|
authorized();
|
|
@@ -6166,7 +6319,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6166
6319
|
if (remaining <= 0) throw new PreEffectToolRefusal("timeout");
|
|
6167
6320
|
specs.push(await (opts.boundedTools?.fetchSpec ?? fetchSpec)(memoryRepo, issue, { screen: boundedSafe, projectDir: opts.cwd, timeoutMs: Math.min(15_000, remaining) }));
|
|
6168
6321
|
const current = authorized();
|
|
6169
|
-
if (current.updated !== updated || current.history.length !== revision || connectionGeneration(by) !== generation || !may(by, "spec_read")) throw new PreEffectToolRefusal("spec unavailable");
|
|
6322
|
+
if (current.updated !== updated || current.history.length !== revision || connectionGeneration(by) !== generation || !may(by, "spec_read") && !carried(current)) throw new PreEffectToolRefusal("spec unavailable");
|
|
6170
6323
|
}
|
|
6171
6324
|
const result = JSON.stringify({ specs });
|
|
6172
6325
|
if (Buffer.byteLength(result) > 80 * 1024) throw new PreEffectToolRefusal("too large");
|
|
@@ -6445,6 +6598,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6445
6598
|
const doneLine = by === USER ? tasks.resultLine(t, by) : line(t);
|
|
6446
6599
|
const result = tasks.isChecking(t.id) ? `${doneLine}; its check is queued or running, and the result comes as a task message` : doneLine;
|
|
6447
6600
|
const specReport = by === USER ? "" : tasks.specReportText(t, by);
|
|
6601
|
+
// #1329 (report): a memory review's completion carries counts only, on the board and in the answer that reaches its
|
|
6602
|
+
// reviewer; no note text, no reviewed line. Counts this hub run did not observe read as unknown, never as zero.
|
|
6603
|
+
if (by !== USER && memoryReviewTask(t) && !tasks.isPii(t)) {
|
|
6604
|
+
const counts = reviewCountLine(t);
|
|
6605
|
+
board.update(t.id, HUB, "review counts", {}, counts);
|
|
6606
|
+
return [result, counts, specReport, extra].filter(Boolean).join("\n");
|
|
6607
|
+
}
|
|
6448
6608
|
return [result, specReport, extra].filter(Boolean).join("\n");
|
|
6449
6609
|
}
|
|
6450
6610
|
case "hub_sdlc_record":
|
|
@@ -6456,10 +6616,15 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6456
6616
|
if (!piiTurn && !reviewTurn && !tasks.isPii(reviewed) && verdict && !verdict.withheld && typeof a.note === "string" && a.note && verdict.note?.startsWith(a.note)) {
|
|
6457
6617
|
citeMemory(by, a.note, `review:${reviewed.id}:${reviewed.history.indexOf(verdict)}`, [newEnvelope(by, "", { refs: { task: String(reviewed.id) } })]);
|
|
6458
6618
|
}
|
|
6459
|
-
return
|
|
6619
|
+
return reviewed.reopenedWithoutReason?.length
|
|
6620
|
+
? line(reviewed) + "\nreopenedWithoutReason: " + JSON.stringify(reviewed.reopenedWithoutReason)
|
|
6621
|
+
: line(reviewed);
|
|
6460
6622
|
}
|
|
6461
6623
|
case "hub_remember": {
|
|
6462
|
-
const
|
|
6624
|
+
const reviewCard = reviewTurnCard(by);
|
|
6625
|
+
const { message: saved, outcome } = await tasks.rememberOutcome(by, a, reviewCard);
|
|
6626
|
+
// #1329 AC4: on a review card a note is a proposal, and the done report counts it by kind.
|
|
6627
|
+
if (reviewCard && outcome === "candidate") reviewCount(reviewCard.id, "remembered");
|
|
6463
6628
|
// #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
6629
|
// #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
6630
|
if (!piiTurn && !reviewTurn && typeof a.text === "string" && a.text && outcome !== "not_saved") {
|
|
@@ -6594,19 +6759,60 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6594
6759
|
// #335: the person's schedule commands; #933: the admitted conductor's too. Tasks refuses any other actor.
|
|
6595
6760
|
case "schedule_list":
|
|
6596
6761
|
if (by !== USER) throw new PreEffectToolRefusal("schedule list is a console command");
|
|
6597
|
-
return JSON.stringify(scheduleViews(
|
|
6762
|
+
return JSON.stringify(scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true));
|
|
6598
6763
|
case "schedule_run": {
|
|
6599
6764
|
// 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
6765
|
// 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,
|
|
6766
|
+
const run = tasks.runScheduleNow(by, schedulesStore, scheduleEntries(), a.id, scheduleNow(), () => opts.schedulesHeld?.() === true);
|
|
6602
6767
|
const drained = run.then(() => undefined, () => undefined);
|
|
6603
6768
|
manualSchedulePasses.add(drained); void drained.finally(() => manualSchedulePasses.delete(drained));
|
|
6604
6769
|
return JSON.stringify(await run);
|
|
6605
6770
|
}
|
|
6606
6771
|
case "schedule_pause":
|
|
6607
6772
|
case "schedule_resume":
|
|
6608
|
-
tasks.setSchedulePaused(by, schedulesStore,
|
|
6609
|
-
return JSON.stringify(scheduleViews(
|
|
6773
|
+
tasks.setSchedulePaused(by, schedulesStore, scheduleEntries(), a.id, op === "schedule_pause", scheduleNow());
|
|
6774
|
+
return JSON.stringify(scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true).filter(view => view.id === a.id));
|
|
6775
|
+
// #1329 part 1: `ahub memory review on|off|status`. Person only: it is deliberately absent from CONDUCTOR_TASK_OPS, so the
|
|
6776
|
+
// gate above refuses every other caller. The switch is the machine-local `memory.review.enabled` key, written through the
|
|
6777
|
+
// same writer and loader check as `ahub settings set`, so enabling without both caps is refused by the config, not here;
|
|
6778
|
+
// a store write beside it makes the change take effect now instead of at the next period, and `off` cancels the card the
|
|
6779
|
+
// last run left open through `Tasks.cancel`, the normal cancel path (AC2).
|
|
6780
|
+
case "memory_review": {
|
|
6781
|
+
const reviewView = () => scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true).find(candidate => candidate.id === MEMORY_REVIEW_SCHEDULE_ID);
|
|
6782
|
+
const action = a.action;
|
|
6783
|
+
if (action === "status") {
|
|
6784
|
+
const view = reviewView();
|
|
6785
|
+
// #1329 AC5: the spend is the hub's own counted tokens for the last card and, when one is open, for this week.
|
|
6786
|
+
const open = tasks.openScheduled().get(MEMORY_REVIEW_SCHEDULE_ID);
|
|
6787
|
+
const card = open === undefined ? undefined : board.get(open);
|
|
6788
|
+
const spend = card ? reviewSpend(card) : undefined;
|
|
6789
|
+
return JSON.stringify({ action: "status", enabled: config.memory.review?.enabled === true, review: config.memory.review ?? MEMORY_REVIEW_DEFAULTS,
|
|
6790
|
+
...(spend ? { spend, ...(card ? { task: card.id } : {}) } : {}), ...(view ? { schedule: view } : {}) });
|
|
6791
|
+
}
|
|
6792
|
+
if (action !== "on" && action !== "off") throw new PreEffectToolRefusal("memory review takes on, off or status; ahub memory review status shows the switch");
|
|
6793
|
+
const def = settingDef("memory.review.enabled");
|
|
6794
|
+
if (typeof def === "string") throw new PreEffectToolRefusal(`this hub has no memory.review setting; upgrade it, then run ahub memory review ${action}`);
|
|
6795
|
+
// The fence and the cancellation come before the config write: the write reloads the entries, and a pass already past its
|
|
6796
|
+
// hold check must meet the paused epoch rather than a schedule list that no longer explains why it is running.
|
|
6797
|
+
let cancelled: number | undefined;
|
|
6798
|
+
if (action === "off") {
|
|
6799
|
+
// #335's epoch, set before the write on purpose: the `tasks.cancel` below yields, so a timer pass can begin while the
|
|
6800
|
+
// config still says enabled, and that pass has to meet the paused epoch. Nothing has to undo it afterwards: the row
|
|
6801
|
+
// goes with the entry the reload drops (`Tasks.proposeFromSchedules` prunes a removed schedule).
|
|
6802
|
+
schedulesStore.setPaused(MEMORY_REVIEW_SCHEDULE_ID, true, scheduleNow());
|
|
6803
|
+
const open = tasks.openScheduled().get(MEMORY_REVIEW_SCHEDULE_ID);
|
|
6804
|
+
if (open !== undefined) { await tasks.cancel(open, by, { reason: "ahub memory review off stopped the schedule" }); cancelled = open; }
|
|
6805
|
+
}
|
|
6806
|
+
writeConfigSetting(opts.cwd, opts.stateDir, def, action === "on", scratch => configWriteCheck(scratch, "terminal", def.path.join(".")));
|
|
6807
|
+
const reloaded = await reloadConfig("terminal", def.key);
|
|
6808
|
+
// The write is on disk, so the switch survives a restart either way; only this daemon's view of it failed to catch up.
|
|
6809
|
+
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`);
|
|
6810
|
+
// `on` clears the pause here rather than leaving it to the reload: a key that is already `true` changes nothing, so
|
|
6811
|
+
// there is no reload to carry the fence, and this command must still resume a schedule a person paused by hand.
|
|
6812
|
+
if (action === "on") schedulesStore.setPaused(MEMORY_REVIEW_SCHEDULE_ID, false, scheduleNow());
|
|
6813
|
+
const view = reviewView();
|
|
6814
|
+
return JSON.stringify({ action, enabled: action === "on", review: config.memory.review ?? MEMORY_REVIEW_DEFAULTS, ...(cancelled === undefined ? {} : { cancelled }), ...(view ? { schedule: view } : {}) });
|
|
6815
|
+
}
|
|
6610
6816
|
// #334: natural-language intake. Person only, except approve for the admitted conductor (#933): Tasks refuses any other actor.
|
|
6611
6817
|
case "intake": {
|
|
6612
6818
|
const result = await tasks.intake(by, { text: a.text, sources: a.sources });
|
|
@@ -6618,8 +6824,14 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6618
6824
|
return JSON.stringify((await tasks.discardIntake(by, a.id)).map(task => tasks.publicView(task)));
|
|
6619
6825
|
// #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
6826
|
// 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
|
-
|
|
6622
|
-
|
|
6827
|
+
// #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.
|
|
6828
|
+
case "learn_list": {
|
|
6829
|
+
if (a.accepted !== true) return JSON.stringify(tasks.learnCandidates(by, { all: a.all === true }));
|
|
6830
|
+
const stored = storedConfig();
|
|
6831
|
+
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");
|
|
6832
|
+
const current = resolveProfile(stored.profile, stored.profile_overrides).review_checklist ?? [];
|
|
6833
|
+
return JSON.stringify({ view: "accepted", minReviewed: FOLLOWUP_DEFAULTS.minReviewed, ...tasks.learnFollowed(by, current) });
|
|
6834
|
+
}
|
|
6623
6835
|
// #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
6836
|
case "capabilities_list": {
|
|
6625
6837
|
const share = readShare(config.invocation?.share), peers: unknown[] = [];
|
|
@@ -6640,8 +6852,17 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6640
6852
|
if (!stored) throw new PreEffectToolRefusal("the config files do not load; fix them in your editor first: nothing was written");
|
|
6641
6853
|
const active = profileName(stored.profile);
|
|
6642
6854
|
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.
|
|
6855
|
+
// 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
6856
|
const current = resolveProfile(stored.profile, stored.profile_overrides).review_checklist ?? [];
|
|
6857
|
+
if ("marker" in plan) {
|
|
6858
|
+
// #1642 T3: exactly the one line the card's criterion names, and only while it is the checklist's own generated line.
|
|
6859
|
+
const removed = withoutChecklistLine(current, plan.marker);
|
|
6860
|
+
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`);
|
|
6861
|
+
const written = await settingsSet(LEARN_CHECKLIST.key, removed.list, "terminal", undefined, undefined, `ahub learn accept #${plan.id}: remove the checklist line`, LEARN_CHECKLIST);
|
|
6862
|
+
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`);
|
|
6863
|
+
const closed = await tasks.learnClose(by, a.id, "accepted");
|
|
6864
|
+
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" } });
|
|
6865
|
+
}
|
|
6645
6866
|
const next = withChecklistLine(current, plan.line);
|
|
6646
6867
|
if ("refused" in next) throw new PreEffectToolRefusal(next.refused);
|
|
6647
6868
|
const already = next.list.length === current.length;
|
|
@@ -6649,8 +6870,10 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6649
6870
|
const written = await settingsSet(LEARN_CHECKLIST.key, next.list, "terminal", undefined, undefined, `ahub learn accept #${plan.id}`, LEARN_CHECKLIST);
|
|
6650
6871
|
if (written.ok !== true) throw new PreEffectToolRefusal(String(written.error ?? "the checklist could not be written") + "; the candidate stays open");
|
|
6651
6872
|
}
|
|
6652
|
-
|
|
6653
|
-
|
|
6873
|
+
// #1642 T1: the before rate rides the closed card's own note, so the outcome view compares against what was true at acceptance.
|
|
6874
|
+
const before = tasks.learnBeforeRate(by, a.id);
|
|
6875
|
+
const closed = await tasks.learnClose(by, a.id, "accepted", before);
|
|
6876
|
+
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
6877
|
}
|
|
6655
6878
|
case "review_brief": {
|
|
6656
6879
|
const task = board.get(Number(a.id));
|
|
@@ -7615,6 +7838,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7615
7838
|
const researchEvidence = board.researchEvidenceIntegrity();
|
|
7616
7839
|
const reviewerQuota = reviewerQuotaIntegrity();
|
|
7617
7840
|
const advisorSurveys = board.surveyIntegrity();
|
|
7841
|
+
const specReadbacks = board.specReadbackIntegrity();
|
|
7618
7842
|
const guidanceVariants = board.guidanceVariantsIntegrity();
|
|
7619
7843
|
const guidanceProbes = guidanceProbeStore.integrity();
|
|
7620
7844
|
const executionReferences = board.executionReferencesIntegrity();
|
|
@@ -7623,7 +7847,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7623
7847
|
const visualIntegrity = visuals.integrity();
|
|
7624
7848
|
if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
|
|
7625
7849
|
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])) } : {}) };
|
|
7850
|
+
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
7851
|
};
|
|
7628
7852
|
/** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
|
|
7629
7853
|
const integrityAs = (expected: unknown) => {
|
|
@@ -7672,6 +7896,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7672
7896
|
const statusPeerIds = (open: ReturnType<Board["statusTasks"]>) => {
|
|
7673
7897
|
const reservations = board.statusReservations();
|
|
7674
7898
|
const ids = new Set([...bus.knownPeers(), ...extraIds, ...allExternalInstanceIds(), ...reservations].filter(id => !id.includes("@")));
|
|
7899
|
+
// #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.
|
|
7900
|
+
for (const peer of jcodeDetached.keys()) ids.add(peer);
|
|
7675
7901
|
for (const peer of configuredIds) if (onRoster(peer)) ids.add(peer);
|
|
7676
7902
|
if (!Object.keys(config.roster).some(peer => !membershipAllowed(peer))) return [...ids];
|
|
7677
7903
|
for (const task of open) for (const peer of [task.owner, task.reviewer]) if (peer && !membershipAllowed(peer)) ids.add(peer);
|
|
@@ -7697,7 +7923,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7697
7923
|
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
7924
|
return openCrashNotices(crashNotices, { attached, inFlight });
|
|
7699
7925
|
};
|
|
7700
|
-
const status = (includeAttentionItems = false, includeAttentionInput = false, includeDoing = false, includeIncomingLabels = false) => {
|
|
7926
|
+
const status = (includeAttentionItems = false, includeAttentionInput = false, includeDoing = false, includeIncomingLabels = false, includeActivity = false) => {
|
|
7701
7927
|
const taskNeeds = board.statusTasks();
|
|
7702
7928
|
const ownerIsolation = ownerIsolationProjection();
|
|
7703
7929
|
const taskStalls = tasks.stalled({ ownerIsolation });
|
|
@@ -7722,7 +7948,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7722
7948
|
pendingRestart: allPendingRestart(),
|
|
7723
7949
|
retainedConfig,
|
|
7724
7950
|
...(agentDrift.length ? { agentDrift } : {}),
|
|
7725
|
-
...(
|
|
7951
|
+
...(scheduleEntries().length ? { schedules: scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true) } : {}),
|
|
7726
7952
|
...(() => { const warning = mainCheckoutWarning(opts.cwd, tasks.publicMetadataText, checkoutBranch); return warning ? { mainCheckout: warning } : {}; })(),
|
|
7727
7953
|
startModes: Object.fromEntries([...START_MODE_PEERS, ...configuredIds].map(peer => [peer, startModeOf(config.peers, peer, declarations, adapterCatalog)])),
|
|
7728
7954
|
memoryProfile: memoryProfileStatus(includeAttentionItems),
|
|
@@ -7762,7 +7988,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7762
7988
|
...(dashboard ? { uiOrigin: dashboard.origin } : {}),
|
|
7763
7989
|
codexProxyPort: opts.codexProxyPort,
|
|
7764
7990
|
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 ?? [] } : {}) }]; }),
|
|
7991
|
+
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
7992
|
),
|
|
7767
7993
|
peerVersions,
|
|
7768
7994
|
taskWip: tasks.wipBreakdown(peerIds),
|
|
@@ -7801,6 +8027,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7801
8027
|
};
|
|
7802
8028
|
// #878: live readers only (the status reply, the dashboard); writeStatus never asks, so status.json never holds it.
|
|
7803
8029
|
if (includeDoing) for (const [id, doing] of Object.entries(doingRows(peerIds, includeIncomingLabels))) Object.assign(view.peers[id]!, { doing });
|
|
8030
|
+
if (includeActivity) for (const id of peerIds) {
|
|
8031
|
+
if (bus.stateOf(id) !== "busy") continue;
|
|
8032
|
+
const activity = activities.view(id, () => activityPrivate(id));
|
|
8033
|
+
if (activity) Object.assign(view.peers[id]!, { activity });
|
|
8034
|
+
}
|
|
7804
8035
|
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
8036
|
// Lazy legacy peer lists need not contain a persisted owner that is now offline.
|
|
7806
8037
|
for (const task of taskNeeds) if (task.owner && task.owner !== USER && task.owner !== HUB && !Object.hasOwn(peerNeeds, task.owner)) {
|
|
@@ -8335,6 +8566,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8335
8566
|
const nativeFactsTurn = nativeHookLaunches.current(e.peer) !== undefined && bus.peers.get(e.peer)?.pullOnly === true;
|
|
8336
8567
|
const edits = turnEditsFor(e.peer, open, files); // Discard the tally even when a native completion is unconfirmed.
|
|
8337
8568
|
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 });
|
|
8569
|
+
// #1329 AC5: the review's counted spend is checked after the turn that spent it. Only a card among this turn's tasks
|
|
8570
|
+
// reaches the stop, so an ordinary turn costs one lookup of the two live board states.
|
|
8571
|
+
if (open.tokens) {
|
|
8572
|
+
const reviewIds = [...new Set([...open.writeTasks.map(binding => binding.id), ...(open.attribution.task !== undefined ? [open.attribution.task] : [])])];
|
|
8573
|
+
void reviewBudgetAfterTurn(e.peer, reviewIds).catch(reviewBudgetFailure);
|
|
8574
|
+
}
|
|
8338
8575
|
if (!nativeFactsTurn && definitionOf(e.peer)?.turnEnd !== "native-hook") { // Claude's native turn end is its Stop hook
|
|
8339
8576
|
if ((bus.peers.get(e.peer)?.state ?? e.state) === "idle") queueMicrotask(() => finishSupervisionTurn(e.peer));
|
|
8340
8577
|
turnEnded.set(e.peer, Date.now());
|
|
@@ -8968,6 +9205,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8968
9205
|
recoveryTaskPreface(peer); await ensurePreface(peer); startCurrent?.();
|
|
8969
9206
|
try { startCurrent?.(); await jcode.start(); startCurrent?.(); registerModelOwner(jcode); bindRecordOwner(jcode, executionCwd, () => jcode.nativeSession); await reconcileNativeStart(peer, jcode, startCurrent); }
|
|
8970
9207
|
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)"); }
|
|
9208
|
+
// #1668: this peer is under the hub again, so it is no longer detached. A start that failed above keeps the record.
|
|
9209
|
+
if (jcodeDetached.delete(peer) && !stopping) writeStatus();
|
|
8971
9210
|
return { ok: true, policy: "unmanaged" };
|
|
8972
9211
|
}
|
|
8973
9212
|
if (adapter?.start.acpCommand) {
|
|
@@ -9026,6 +9265,30 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
9026
9265
|
} catch (error) { await kimi.stop().catch(stop => log(`kimi stop after a failed start: ${(stop as Error).message}`)); throw error; }
|
|
9027
9266
|
return { ok: true };
|
|
9028
9267
|
}
|
|
9268
|
+
if (adapter?.start.daemonPort === "configured-print" && adapter.start.create) {
|
|
9269
|
+
if (Object.entries(args).some(([key, value]) => key !== "mode" && value !== undefined))
|
|
9270
|
+
return { ok: false, error: "configured print accepts no launch overrides or resume options" };
|
|
9271
|
+
if (retainedOwner?.pendingOwnedProcess) return { ok: false, error: "configured print cleanup is unconfirmed; stop the peer before starting it again" };
|
|
9272
|
+
const print = adapter.start.create({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config,
|
|
9273
|
+
permission: "read-only", mcpServers: [], daemon: DAEMON_PORTS["configured-print"]({
|
|
9274
|
+
cwd: executionCwd, stateDir: opts.stateDir,
|
|
9275
|
+
deny: () => [...config.local.deny, ...(config.pii?.paths ?? [])],
|
|
9276
|
+
privateTurn: envs => contextPii(peer) || turns.get(peer)?.private === true || envs.some(env => {
|
|
9277
|
+
const task = env.refs?.task ? board.get(Number(env.refs.task)) : undefined;
|
|
9278
|
+
return task ? tasks.isPii(task) : false;
|
|
9279
|
+
}),
|
|
9280
|
+
publicText: boundedSafe,
|
|
9281
|
+
}) });
|
|
9282
|
+
try {
|
|
9283
|
+
startCurrent?.(); await print.start(); startCurrent?.();
|
|
9284
|
+
bus.add(print);
|
|
9285
|
+
print.onState?.(print.state);
|
|
9286
|
+
} catch (error) {
|
|
9287
|
+
await print.stop().catch(() => { bus.add(print); });
|
|
9288
|
+
throw error;
|
|
9289
|
+
}
|
|
9290
|
+
return { ok: true, policy: "unmanaged" };
|
|
9291
|
+
}
|
|
9029
9292
|
if (adapter?.transport === "acp" && adapter.start.create && adapter.start.launch) {
|
|
9030
9293
|
// Configured ACP definitions own immutable argv and policy; builtins retain their verified launch port.
|
|
9031
9294
|
const launch = adapter.start.launch({ instance: peer, form: "headless", projectRoot: opts.cwd, stateDir: opts.stateDir, entrypoint: CLI_ENTRY,
|
|
@@ -9107,6 +9370,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
9107
9370
|
actionBudgets.revoke(peer);
|
|
9108
9371
|
startCurrent?.();
|
|
9109
9372
|
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"]({
|
|
9373
|
+
activityServers: codexActivityServers(process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), executionCwd),
|
|
9110
9374
|
getModelOverride: () => modelSelection(peer),
|
|
9111
9375
|
onNativeModelApplied: model => { if (!stopping && bus.peers.get(peer) === codex && isNativeModelToken(model)) {
|
|
9112
9376
|
try { modelLatches.observeNative(peer, codex, model); } catch { modelLatches.forget(peer); }
|
|
@@ -10215,6 +10479,14 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10215
10479
|
if (tasks.milestoneShow(USER, cardId).order !== index) tasks.milestoneOrder(USER, cardId, index);
|
|
10216
10480
|
}
|
|
10217
10481
|
/** The dashboard's roadmap payload: the same public projection `ahub roadmap show` renders, plus who may act. */
|
|
10482
|
+
// #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.
|
|
10483
|
+
let overviewMemo: { key: string; view: ReturnType<typeof overviewModel> } | undefined;
|
|
10484
|
+
function overviewSnapshot() {
|
|
10485
|
+
const now = Date.now();
|
|
10486
|
+
const key = JSON.stringify([board.statusRevision(), Math.floor(now / 86_400_000), tasks.stalled().map(stall => [stall.task, stall.cause.kind])]);
|
|
10487
|
+
if (overviewMemo?.key !== key) overviewMemo = { key, view: overviewModel(tasks.overviewInput(now)) };
|
|
10488
|
+
return overviewMemo.view;
|
|
10489
|
+
}
|
|
10218
10490
|
function roadmapSnapshot(session?: DashboardSession) {
|
|
10219
10491
|
try { return { milestones: tasks.milestoneList(USER), person: session?.liveTest !== true }; }
|
|
10220
10492
|
catch { return { unavailable: true, person: false }; }
|
|
@@ -10334,11 +10606,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10334
10606
|
// #1483 R5: the roadmap block is the read that computes spec freshness, so it rides only the view that shows it and
|
|
10335
10607
|
// never another view's 1 s poll. The board's Milestone filter reads the same rows here, and its placement is the
|
|
10336
10608
|
// explicit task link only (the projection above also places a task through the issue it came from).
|
|
10609
|
+
// #1514: the Overview figures are computed only for the view that shows them, so no other view's 1 s poll pays for them.
|
|
10610
|
+
...(input?.view === "overview" ? { overview: overviewSnapshot() } : {}),
|
|
10337
10611
|
...(input?.view === "roadmap" ? { roadmap: { ...roadmapSnapshot(session), drift: roadmapDrift } } : {}),
|
|
10338
10612
|
milestones: board.milestones().map(row => ({ id: row.id, title: row.title, horizon: row.horizon, state: row.state, order: row.order })),
|
|
10339
10613
|
milestoneOfTask: Object.fromEntries(board.milestoneLinks().filter(link => link.kind === "task").map(link => [link.ref, link.milestone] as const)),
|
|
10340
10614
|
// #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
|
-
...(
|
|
10615
|
+
...(scheduleEntries().length ? { schedules: scheduleViews(scheduleEntries(), schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true) } : {}),
|
|
10342
10616
|
boardLegend: Object.entries(peerView).map(([id, peer]) => ({
|
|
10343
10617
|
peer: id, state: peer.state,
|
|
10344
10618
|
permissionMode: "permissionNote" in peer && peer.permissionNote ? "unmanaged" : permissionDisplay(id, bus.peers.get(id)),
|
|
@@ -10622,7 +10896,10 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10622
10896
|
if (changes.some(change => change.key === "task_sweep" || change.key.startsWith("task_sweep."))) rescheduleSweep();
|
|
10623
10897
|
const syncChange = changes.find(change => change.key === "memory.sync_interval_min");
|
|
10624
10898
|
if (syncChange) rescheduleMemorySync((Number(syncChange.before ?? 10) <= 0) && Number(syncChange.after ?? 10) > 0);
|
|
10625
|
-
|
|
10899
|
+
// #1329 part 1: no pause fence is synced here, and none is needed: a schedule's row is pruned as soon as its entry
|
|
10900
|
+
// disappears (`Tasks.proposeFromSchedules`), so `off` leaves no pause behind and `on` starts from a fresh period. The
|
|
10901
|
+
// one pause that outlives a config edit is a person's own `ahub schedule pause memory-review`, which `on` clears.
|
|
10902
|
+
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
10903
|
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
10904
|
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
10905
|
Object.assign(limits, config.limits);
|
|
@@ -11485,6 +11762,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11485
11762
|
// #1054: an older daemon ignores the completion tables, so an open run or a completion nobody has seen would be lost silently.
|
|
11486
11763
|
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
11764
|
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";
|
|
11765
|
+
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
11766
|
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
11767
|
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
11768
|
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 +11840,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11562
11840
|
return "target lacks research_evidence_withdrawal; choose a supporting daemon to preserve withdrawal revisions";
|
|
11563
11841
|
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("advisor_surveys")) && board.hasSurveyState())
|
|
11564
11842
|
return "target lacks advisor_surveys; persisted survey candidates and considered-finding history require a supporting daemon";
|
|
11843
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("spec_readbacks")) && board.hasSpecReadbacksState())
|
|
11844
|
+
return "target lacks spec_readbacks; stored spec read-back requests and reports require a supporting daemon";
|
|
11565
11845
|
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("project_autonomy")) {
|
|
11566
11846
|
let needsAutonomy = autonomyConfirmed.size > 0;
|
|
11567
11847
|
try {
|
|
@@ -12079,7 +12359,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
12079
12359
|
// 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
12360
|
if (definitionOf(c.peer)?.start.daemonPort === "owned-acp") {
|
|
12081
12361
|
const owner = jcodeLaunches.get(c.peer);
|
|
12082
|
-
if (!owner || !owner.ownsLaunch(msg.launchId))
|
|
12362
|
+
if (!owner || !owner.ownsLaunch(msg.launchId)) {
|
|
12363
|
+
// #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
|
|
12364
|
+
// itself is unchanged and nothing new listens; the peer only gains the state `ahub status` reports until a hub-owned launch replaces it.
|
|
12365
|
+
if (!stopping) { jcodeDetached.set(c.peer, jcodeDetachedNotice(c.peer)); writeStatus(); }
|
|
12366
|
+
return sock.close(4403, "this process is not an owned launch of that peer; start it with ahub jcode");
|
|
12367
|
+
}
|
|
12083
12368
|
}
|
|
12084
12369
|
} else {
|
|
12085
12370
|
c.peer = String(msg.peer ?? defaultChannelPeer(undefined));
|
|
@@ -13212,6 +13497,33 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13212
13497
|
(error: Error) => reply({ ok: false, error: sanitize(error.message).slice(0, 300) })).finally(() => { taskOpsInFlight--; });
|
|
13213
13498
|
return;
|
|
13214
13499
|
}
|
|
13500
|
+
if (msg.op === "readback-start" || msg.op === "readback-show") {
|
|
13501
|
+
// #1658: the person or the current conductor starts and reads a spec read-back; every request gets a reply.
|
|
13502
|
+
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" });
|
|
13503
|
+
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;
|
|
13504
|
+
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" });
|
|
13505
|
+
const externalOwner = c.externalOwner;
|
|
13506
|
+
const sessionCurrent = c.role === "console" ? () => { if (sock.data !== c || sock.readyState !== WebSocket.OPEN || c.role !== "console") throw new Error("person session changed"); } : operationalCurrent(sock);
|
|
13507
|
+
const fence = () => {
|
|
13508
|
+
try {
|
|
13509
|
+
sessionCurrent();
|
|
13510
|
+
if (externalOwner && !currentExternalTools(c, true)) return "read-back execution root changed; reconnect and retry";
|
|
13511
|
+
sessionCurrent();
|
|
13512
|
+
if (c.peer !== (asker === USER ? undefined : asker) || c.externalOwner !== externalOwner || c.toolsOwner) return "read-back actor changed; reconnect and retry";
|
|
13513
|
+
if (c.peer && (turns.get(c.peer)?.private || contextPii(c.peer))) return "read-back unavailable during private input";
|
|
13514
|
+
return recoveryActive() || stopping ? "recovery or shutdown holds read-back writes; retry after release" : undefined;
|
|
13515
|
+
} catch { return "read-back person or conductor session changed; reconnect and retry"; }
|
|
13516
|
+
};
|
|
13517
|
+
const refusal = fence(); if (refusal) return void reply({ ok: false, error: refusal });
|
|
13518
|
+
if (msg.op === "readback-show") {
|
|
13519
|
+
try { return void reply({ ok: true, readback: tasks.specReadbackShow(asker, msg.id) }); }
|
|
13520
|
+
catch (error) { return void reply({ ok: false, error: sanitize(error instanceof Error ? error.message : "read-back read unavailable").slice(0, 300) }); }
|
|
13521
|
+
}
|
|
13522
|
+
taskOpsInFlight++;
|
|
13523
|
+
void tasks.specReadbackStart(asker, msg.id, fence).then(result => reply({ ok: true, ...result }),
|
|
13524
|
+
(error: Error) => reply({ ok: false, error: sanitize(error.message).slice(0, 300) })).finally(() => { taskOpsInFlight--; });
|
|
13525
|
+
return;
|
|
13526
|
+
}
|
|
13215
13527
|
if (msg.op === "audit-start" || msg.op === "audit-show") {
|
|
13216
13528
|
// #1403 A4: the person or the one configured conductor starts and reads a security audit. Every request gets a reply, a refusal included.
|
|
13217
13529
|
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 +13645,22 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13333
13645
|
const repo = msg.repo ?? task?.sdlc?.repo;
|
|
13334
13646
|
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
13647
|
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 => {
|
|
13648
|
+
void readSpecEdit(repo, msg.issue, opts.boundedTools?.specEdit ?? ((args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound))).then(edit => {
|
|
13337
13649
|
if (!edit) return reply({ ok: false, error: "issue edit time unavailable; nothing was recorded" });
|
|
13338
13650
|
// The readback is for the receipt read before it; a relink meanwhile makes it someone else's evidence.
|
|
13339
13651
|
const now = board.get(msg.id)?.sdlc;
|
|
13340
13652
|
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 {
|
|
13342
|
-
|
|
13653
|
+
try {
|
|
13654
|
+
// #1658 AC6: the read-back line prints before the acceptance is recorded, and the acceptance proceeds in every state.
|
|
13655
|
+
const accepted = board.get(msg.id)!;
|
|
13656
|
+
// A read-back row whose bytes fail their hash is a storage defect, not a reason to refuse the person's
|
|
13657
|
+
// acceptance: the line then says the state is unknown, and the acceptance is recorded as in any other state.
|
|
13658
|
+
let readback: string | undefined;
|
|
13659
|
+
try { readback = readbackAcceptField(tasks.readbackView({ ...accepted, sdlc: { ...(accepted.sdlc ?? { stage: "spec" as const }), repo, issue: msg.issue } }, edit), msg.id).readback; }
|
|
13660
|
+
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)"; }
|
|
13661
|
+
const next = tasks.acceptSpec(USER, msg.id, { repo, issue: msg.issue, edit });
|
|
13662
|
+
reply({ ok: true, acceptance: next.sdlc?.acceptance, ...(readback ? { readback } : {}) });
|
|
13663
|
+
} catch (error) { reply({ ok: false, error: (error as Error).message }); }
|
|
13343
13664
|
}, () => reply({ ok: false, error: "issue edit time unavailable; nothing was recorded" }));
|
|
13344
13665
|
return;
|
|
13345
13666
|
}
|
|
@@ -13426,7 +13747,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13426
13747
|
return void reply({ ok: false, error: "unknown room operation" });
|
|
13427
13748
|
}
|
|
13428
13749
|
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));
|
|
13750
|
+
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
13751
|
if ((c.role === "console" || c.role === "tools") && msg.specs === true) {
|
|
13431
13752
|
const summary = projectSpecs.status();
|
|
13432
13753
|
if (summary) {
|
|
@@ -13920,6 +14241,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13920
14241
|
if (c.role !== "console") return void reply({ t: "questions", ok: false, error: "questions are shown to the person: use the console" });
|
|
13921
14242
|
return void reply({ t: "questions", ok: true, questions: questionStore.list(msg.state === "all" ? {} : { state: "open" }, 100).map(questionView), answeredQuestions: instructedQuestionViews() });
|
|
13922
14243
|
}
|
|
14244
|
+
// #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).
|
|
14245
|
+
case "board_revision": {
|
|
14246
|
+
if (c.role !== "console") return void reply({ t: "board_revision", ok: false, error: "the board revision is read by the console" });
|
|
14247
|
+
return void reply({ t: "board_revision", ok: true, boardRevision: board.statusRevision() });
|
|
14248
|
+
}
|
|
13923
14249
|
// #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
14250
|
// the store. A snapshot or a `results` read never writes one. Every message gets a reply (rid), a refusal included.
|
|
13925
14251
|
case "result_seen": {
|