@staix/agent-hub 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +2 -1
  3. package/docs/adding-an-ai-tool.md +2 -0
  4. package/docs/agent-notes/daemon.md +3 -3
  5. package/docs/agent-notes/local-worker.md +1 -0
  6. package/docs/agent-notes/tasks.md +3 -2
  7. package/docs/agent-notes/tests.md +2 -2
  8. package/docs/design/adapters.md +3 -0
  9. package/docs/design/agent-hub-architecture.md +2 -0
  10. package/docs/design/bus.md +2 -0
  11. package/docs/design/supervision.md +13 -1
  12. package/docs/design/task-board.md +13 -1
  13. package/docs/dogfood.md +13 -3
  14. package/docs/events.md +4 -2
  15. package/docs/memory.md +5 -3
  16. package/docs/operations.md +97 -17
  17. package/docs/quickstart.md +18 -2
  18. package/docs/research.md +2 -0
  19. package/docs/sdlc.md +6 -3
  20. package/docs/security.md +2 -2
  21. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  22. package/docs/verification/2026-11-18-0.43.0.md +56 -0
  23. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  24. package/docs/verified.json +25 -25
  25. package/package.json +2 -2
  26. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  27. package/plugins/agent-hub/kimi-hook.js +486 -218
  28. package/plugins/agent-hub/server.js +505 -234
  29. package/src/adapters/claude-implementer.ts +11 -1
  30. package/src/adapters/claude-print-child.ts +4 -1
  31. package/src/adapters/conformance/fakes/acp-server.ts +2 -1
  32. package/src/adapters/conformance/fakes/app-server.ts +1 -1
  33. package/src/adapters/local-worker.ts +7 -3
  34. package/src/adapters/reviewer-print.ts +3 -1
  35. package/src/cli/help.ts +3 -3
  36. package/src/cli/identity.ts +2 -0
  37. package/src/cli/main.ts +57 -5
  38. package/src/cli/output.ts +2 -2
  39. package/src/cli/sdlc-output.ts +7 -1
  40. package/src/cli/upgrade-output.ts +43 -2
  41. package/src/cli/upgrade-stopped.ts +162 -0
  42. package/src/cli/upgrade-wait.ts +37 -0
  43. package/src/cli/upgrade.ts +9 -3
  44. package/src/hub/board.ts +17 -2
  45. package/src/hub/bus.ts +4 -0
  46. package/src/hub/claude-shell-wrapper.ts +2 -1
  47. package/src/hub/config-apply.ts +1 -0
  48. package/src/hub/control-write-trace.ts +39 -2
  49. package/src/hub/daemon.ts +141 -37
  50. package/src/hub/envelope.ts +1 -0
  51. package/src/hub/facts.ts +30 -0
  52. package/src/hub/handoff.ts +14 -0
  53. package/src/hub/hub-tools.ts +1 -1
  54. package/src/hub/questions.ts +7 -0
  55. package/src/hub/quota-events.ts +40 -0
  56. package/src/hub/recovery-store.ts +57 -0
  57. package/src/hub/report.ts +1 -1
  58. package/src/hub/research-quality.ts +5 -1
  59. package/src/hub/research-record.ts +5 -3
  60. package/src/hub/restart.ts +49 -2
  61. package/src/hub/runtime-capture-prune.ts +123 -4
  62. package/src/hub/runtime-prune-health.ts +10 -2
  63. package/src/hub/sdlc-merge.ts +7 -3
  64. package/src/hub/sdlc-metrics.ts +17 -8
  65. package/src/hub/sdlc.ts +18 -6
  66. package/src/hub/settings.ts +2 -0
  67. package/src/hub/snapshots.ts +43 -0
  68. package/src/hub/supervision-rules.ts +2 -2
  69. package/src/hub/task-shell-command.ts +124 -0
  70. package/src/hub/task-sweep.ts +6 -2
  71. package/src/hub/tasks.ts +131 -22
  72. package/src/hub/turn-attribution.ts +46 -0
  73. package/src/hub/worktree-shelf.ts +2 -1
  74. package/src/local/sandbox.ts +2 -1
  75. package/src/local/shell-environment.ts +6 -0
  76. package/src/memory/brief.ts +10 -1
  77. package/templates/AGENTS.block.md +1 -1
package/src/hub/daemon.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { QuotaEventFilter } from "./quota-events.ts";
1
2
  import { piFailureText } from "./pi-failure.ts";
2
3
  import { nativeReviewerQuota } from "../adapters/definitions/native-quota.ts";
3
4
  import { parseGuidanceCreateInput, parseGuidanceIdQuery } from "./guidance-variants.ts";
@@ -52,6 +53,7 @@ import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
52
53
  import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
53
54
  import { NativeHookLaunches, type NativeHookLaunch } from "./native-hook-launch.ts";
54
55
  import { readReleaseHostAdmission, type ReleaseHostAdmission } from "./release-admission.ts";
56
+ import { MERGE_READBACK_INTERVAL_MS } from "./sdlc-merge.ts";
55
57
  import { ContainerRunner, RemoteRunner, remoteRunnerConfig, type RemoteRunnerConfig, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
56
58
  import { fetchSpec, specAvailable, specRefs } from "./spec-read.ts";
57
59
  import { isDenied, sbplString } from "../local/deny.ts";
@@ -112,7 +114,7 @@ import { CONSOLE_POLL_SETTING, CONSOLE_NOTICE_SETTING, CONSOLE_HISTORY_SETTING,
112
114
  import { MODEL_COOLDOWN_FAILURES_SETTING, MODEL_COOLDOWN_SETTING, MODEL_COOLDOWN_CAP_SETTING, MODEL_TERMINAL_HISTORY_SETTING, modelOperationalReaders, type ModelOperationalConfig } from "./operational-settings.ts";
113
115
  import { ACP_TOOL_CEILING_SETTING, ACP_ACTIVITY_BATCH_SETTING, JCODE_STEER_TIMEOUT_SETTING, adapterOperationalReaders, type AdapterTimingConfig } from "./operational-settings.ts";
114
116
  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";
115
- import { foldersConfig, scheduleViews, schedulesConfig, ScheduleStore, type FolderEntry, type ScheduleEntry } from "./schedules.ts";
117
+ import { foldersConfig, scheduleKeyOf, scheduleViews, schedulesConfig, ScheduleStore, type FolderEntry, type ScheduleEntry } from "./schedules.ts";
116
118
  import { FolderStore, registerScanned, scanFolder, type FolderPolicy } from "./folder-trigger.ts";
117
119
  import { QuestionStore, QUESTION_SURFACES, questionView } from "./questions.ts";
118
120
  import { RunTracker, outcomeOf, settleVerdict, type Run } from "./completions.ts";
@@ -157,6 +159,7 @@ import { CHECKPOINT_FIELDS, CHECKPOINT_FIELDS_SENTENCE, checkpointFieldCount, pa
157
159
  import { ModelOverrides, ModelOverrideLatches, type RuntimeModelStatus, type ModelSource } from "./model-overrides.ts";
158
160
  import { isNativeModelToken } from "../adapters/model-token.ts";
159
161
  import { processSignature, processLiveness } from "../pi/process-signature.ts";
162
+ import { processSignatureAsync } from "@staix/agent-mem/platform";
160
163
  import { PiSessionBookmarkMismatch, PiSessionUnresumable, recordPiReplacement, validatePiSession } from "../pi/session.ts";
161
164
  import { profile, proxyEnv, sandboxAvailable, type SandboxNetwork } from "../local/sandbox.ts";
162
165
  import { DEFAULT_NETWORK_ALLOW, startEgressProxy, type EgressProxy } from "../local/proxy.ts";
@@ -185,12 +188,13 @@ import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type
185
188
  import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
186
189
  import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
187
190
  import { remoteEnvelope, HUB } from "./envelope.ts";
191
+ import { applyTurnAttribution, turnAttribution } from "./turn-attribution.ts";
188
192
  import { recallMemoryLines, trimToTokens, aggregateUse, orderByUse } from "../memory/recall.ts";
189
193
  import { closeSync, constants as fsConstants, openSync, lstatSync, readSync, statSync } from "node:fs";
190
194
  import { basename, isAbsolute } from "node:path";
191
195
  import { fileURLToPath } from "node:url";
192
196
  import { canonicalPath, realPath, hubHome } from "./project.ts";
193
- import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
197
+ import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, handoffStateGate, handoffTargetStopped, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
194
198
  import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
195
199
  import type { BusEvent, PublishResult } from "./bus.ts";
196
200
  import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, DEFAULT_ROLES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
@@ -244,8 +248,8 @@ import { Facts, FACTS_PREFIX, type FactScope } from "./facts.ts";
244
248
  import { crashPlan, lossNotice, openCrashNotices, readSessions, removeSessions, writeSessions, type CrashNotice, type SessionsFile } from "./crash.ts";
245
249
  import type { JournalDelivery } from "./delivery-journal.ts";
246
250
  import { DEFAULT_LIMITS, Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
247
- import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
248
- import { archiveRestartSnapshot, readRecoveryWaivers, readRestartSnapshot, removeRestartSnapshot, restartPath, writeRestartSnapshot, type RecoveryPhase, type RestartPeerSnapshot, type RestartSnapshot } from "./restart.ts";
251
+ import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, SnapshotCooldown, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
252
+ import { archiveRestartSnapshot, compactRestartBus, readRecoveryWaivers, readRestartSnapshot, removeRestartSnapshot, restartPath, writeRestartSnapshot, type RecoveryPhase, type RestartPeerSnapshot, type RestartSnapshot } from "./restart.ts";
249
253
  import { consumeRecoveryContinuity, readRecoveryContinuity, retireRecoveryContinuity } from "./recovery-continuity.ts";
250
254
  import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf } from "../cli/terminal-recovery.ts";
251
255
  import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
@@ -765,6 +769,8 @@ function mlxPinProblem(routing: Routing, project: boolean): string | undefined {
765
769
  export interface DaemonOptions {
766
770
  /** Host-only fixture override; production reads the active memory home's and execution repository's public Record policy. */
767
771
  effectiveRecordPolicy?: (cwd: string) => { enabled: boolean; version: string } | undefined;
772
+ /** Host-only test trigger; production schedules its own unreferenced settlement interval. */
773
+ mergeReadbackTrigger?: (tick: () => void) => () => void;
768
774
  /** Host-only numeric startup reader observation; never read from config or control input. Observer failure changes no replay state. */
769
775
  startupSeedObserved?: (observation: { readPasses: number; readBytes: number }) => void;
770
776
  /** Host-only test/embedding port; never read from project configuration or a tool. */
@@ -2106,20 +2112,22 @@ export async function startDaemon(opts: DaemonOptions) {
2106
2112
  async function taskIntentBrief(task: import("../memory/brief.ts").BriefTask): Promise<import("../memory/brief.ts").IntentBriefContext> {
2107
2113
  checkMemory();
2108
2114
  const initial = task.id === undefined ? undefined : board.get(task.id), revision = configRevision;
2109
- const allowed = () => {
2115
+ let taskCurrent = false, contextPrivate = true;
2116
+ const refreshTask = () => {
2110
2117
  const current = task.id === undefined ? undefined : board.get(task.id);
2111
- return !stopping && configRevision === revision && !!initial && !!current && current.created === task.created && current.updated === initial.updated
2112
- && current.history.length === initial.history.length && current.owner === initial.owner && !tasks.isPii(current)
2113
- && !turns.get(current.owner ?? "")?.private && !contextPii(current.owner ?? "");
2118
+ taskCurrent = !!initial && !!current && current.created === task.created && current.updated === initial.updated
2119
+ && current.history.length === initial.history.length && current.owner === initial.owner && !tasks.isPii(current);
2120
+ contextPrivate = contextPii(initial?.owner ?? "");
2114
2121
  };
2115
- const assertCurrent = () => { checkMemory(); if (!allowed()) throw Error("memory brief context changed"); };
2122
+ const allowed = () => taskCurrent && !contextPrivate && !stopping && configRevision === revision && !turns.get(initial?.owner ?? "")?.private;
2123
+ const assertCurrent = () => { checkMemory(); refreshTask(); if (!allowed()) throw Error("memory brief context changed"); };
2116
2124
  assertCurrent();
2117
2125
  // Derived code neighbours are additional read-time selectors, never persisted memory or authority.
2118
2126
  const starts = taskNodes(task).filter(node => node.startsWith("symbol:"));
2119
2127
  let extra: string[] = [];
2120
2128
  if (starts.length && tasks.memoryCodeEligible(initial!)) {
2121
2129
  try {
2122
- const prepared = await memoryCode(starts, allowed);
2130
+ const prepared = await memoryCode(starts, () => { refreshTask(); return allowed(); });
2123
2131
  assertCurrent();
2124
2132
  extra = currentMemoryCode(prepared).nodes.map(node => node.id).filter(node => node.startsWith("symbol:")).map(node => node.slice(7));
2125
2133
  } catch { /* Optional code evidence never removes direct intent memory. */ }
@@ -2127,7 +2135,6 @@ export async function startDaemon(opts: DaemonOptions) {
2127
2135
  assertCurrent();
2128
2136
  const stale = staleness();
2129
2137
  const policy = createStandalonePolicy({ denyPaths: config.local.deny, host: { screen: async value => {
2130
- assertCurrent();
2131
2138
  if (value && typeof value === "object" && "id" in value) {
2132
2139
  const row = value as MemoryView;
2133
2140
  return screenMemory([row]).length === 1 && tasks.publicMetadataText(JSON.stringify(row));
@@ -2843,7 +2850,8 @@ export async function startDaemon(opts: DaemonOptions) {
2843
2850
  };
2844
2851
  const currentCheck = (receipt: { task: number; owner: string; updated: number | string; generation: number | string; revision?: number }) => {
2845
2852
  const task = board.get(receipt.task);
2846
- return !!task && task.owner === receipt.owner && task.state === "in_progress" && task.updated === receipt.updated && task.history.length === receipt.revision
2853
+ return !!task && task.owner === receipt.owner && task.state === "in_progress" && Number.isSafeInteger(receipt.revision) && receipt.revision! >= 0 && receipt.revision! <= task.history.length
2854
+ && task.history.slice(receipt.revision).every(entry => entry.event === "check run passed" || entry.event === "check run failed")
2847
2855
  && connectionGeneration(receipt.owner) === receipt.generation && may(receipt.owner, "check_run") && membershipAllowed(receipt.owner) && !tasks.isPii(task)
2848
2856
  && !turns.get(receipt.owner)?.private && !contextPii(receipt.owner);
2849
2857
  };
@@ -2892,6 +2900,7 @@ export async function startDaemon(opts: DaemonOptions) {
2892
2900
  while (checkBindings.size > 200) checkBindings.delete(checkBindings.keys().next().value!);
2893
2901
  if (stopping || !currentCheck(receipt)) { await checkRunner.markStale(receipt.run); return; }
2894
2902
  bus.publish(newEnvelope(HUB, sanitize(JSON.stringify(view)), { to: [receipt.owner], kind: "task", refs: { task: String(receipt.task), boundedCheck: receipt.run } }));
2903
+ if (currentCheck(receipt)) tasks.recordCheckResult(receipt);
2895
2904
  log(`check ${receipt.run}: exit ${receipt.exit ?? "unknown"}, bytes ${receipt.output_bytes}`);
2896
2905
  },
2897
2906
  };
@@ -3007,8 +3016,10 @@ export async function startDaemon(opts: DaemonOptions) {
3007
3016
  const projectSpecs = specInspectorAt(opts.cwd);
3008
3017
  let specsMissingBlockHintShown = false;
3009
3018
  let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
3019
+ let questionStore!: QuestionStore;
3010
3020
  startupTimings.mark("task_ports");
3011
3021
  const tasks: Tasks = new Tasks({
3022
+ ownerQuestionWait: (task, peer) => questionStore?.ownerWait(task, peer),
3012
3023
  guidanceProbes: { store: guidanceProbeStore, session: by => {
3013
3024
  const request = guidanceProbeRequestContext.getStore();
3014
3025
  return request?.actor === by ? { generation: request.generation, nativeSession: request.nativeSession,
@@ -3632,6 +3643,7 @@ export async function startDaemon(opts: DaemonOptions) {
3632
3643
  turnFreeNow = undefined;
3633
3644
  scopes = new Map();
3634
3645
  progress.prune();
3646
+ if (t.state === "approved" || t.state === "cancelled") { facts.closeTask(t.id); for (const store of worktreeFacts.values()) store.closeTask(t.id); } // #1556 T1: receipts end with the task
3635
3647
  factsOn(); // a PII task opening or closing switches tracking at once, not at the next boundary (issue #108)
3636
3648
  if (t.state !== "in_progress" || ownerWriteStarts.get(t.id)?.owner !== t.owner) ownerWriteStarts.delete(t.id);
3637
3649
  if ((h.event === "integration requested" || h.event === "integration unresolved") && /has not stopped/.test(h.note ?? "")) {
@@ -4022,6 +4034,7 @@ export async function startDaemon(opts: DaemonOptions) {
4022
4034
  }
4023
4035
  };
4024
4036
  const unsettledReviewerQuota = new Map<string, { account: string; peer: string }>();
4037
+ const quotaEvents = new QuotaEventFilter(event);
4025
4038
  const budget = new Budget(join(opts.stateDir, "hub.db"), config.budget, instanceBudgetHooks({
4026
4039
  definitionOf,
4027
4040
  pause: (peer) => bus.pause(peer),
@@ -4042,7 +4055,7 @@ export async function startDaemon(opts: DaemonOptions) {
4042
4055
  // A reading that arrived through a file carries the file's time; a stale one must not look fresh in the export.
4043
4056
  // #683 U1: pauses, resumes and derived resets go to the event log, ids and numbers only.
4044
4057
  ledger: entry => event(entry),
4045
- reading: (peer, windows, hard, at) => { queueMicrotask(() => tasks.refreshReviewerQuotaWaits()); return event({ type: "quota", peer, windows: windows.map((w) => ({ id: w.id, used: w.used, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) })), hard, ...(Math.abs(Date.now() - at) > 1000 ? { measuredAt: new Date(at).toISOString() } : {}) }) },
4058
+ reading: (peer, windows, hard, at) => { queueMicrotask(() => tasks.refreshReviewerQuotaWaits()); quotaEvents.record(peer, windows.map((w) => ({ id: w.id, used: w.used, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) })), hard, at); },
4046
4059
  handoff: (peer, context, urgentOnly) => tasks.reassignForPause(peer, context, urgentOnly),
4047
4060
  resumed: (record) => {
4048
4061
  // Coalesce unread notices without forgetting the public moves they carried.
@@ -4316,13 +4329,16 @@ export async function startDaemon(opts: DaemonOptions) {
4316
4329
  // Preserve real synchronous native boundaries, but never spend an unbounded sequence of Git waits
4317
4330
  // inside a single callback burst. Failed/slow captures are explicitly unknown, never stale baselines.
4318
4331
  let snapshotBudget: SnapshotBudget | undefined, snapshotBudgetNoticed = false;
4332
+ const snapshotCooldown = new SnapshotCooldown();
4333
+ type RoutineSnapshot = { repository: string; budget: SnapshotBudget; exhausted: boolean; skipped: boolean };
4319
4334
  const reserveSnapshotBudget = (): SnapshotBudget => {
4320
4335
  if (!snapshotBudget) {
4321
4336
  const requested = opts.snapshotBurstMs ?? 250;
4322
4337
  const ms = Number.isFinite(requested) ? Math.max(1, Math.min(250, requested)) : 250;
4323
4338
  const now = opts.snapshotClock;
4324
4339
  snapshotBudget = { deadline: (now ? now() : performance.now()) + ms, ...(now ? { now } : {}) };
4325
- setImmediate(() => { snapshotBudget = undefined; snapshotBudgetNoticed = false; });
4340
+ const burst = snapshotBudget;
4341
+ setImmediate(() => { snapshotCooldown.finish(burst); snapshotBudget = undefined; snapshotBudgetNoticed = false; });
4326
4342
  }
4327
4343
  return snapshotBudget;
4328
4344
  };
@@ -4334,16 +4350,25 @@ export async function startDaemon(opts: DaemonOptions) {
4334
4350
  return turnModelFields(bus.peers.get(peer)?.observedModel?.() ?? (hooked ? { model: hooked, evidence: "session" } : undefined));
4335
4351
  } catch { return {}; }
4336
4352
  };
4337
- const snapshotFailure = (what: string, error: unknown) => {
4353
+ const snapshotFailure = (what: string, error: unknown, routine?: RoutineSnapshot) => {
4338
4354
  if (error instanceof SnapshotBudgetExceeded) {
4355
+ if (routine) { routine.exhausted = true; return; }
4339
4356
  if (!snapshotBudgetNoticed) log(`snapshot unavailable: ${error.message}`);
4340
4357
  snapshotBudgetNoticed = true;
4341
4358
  } else log(`snapshot failed at ${what}: ${(error as Error).message}`);
4342
4359
  };
4343
- const snap = (what: string, capture = config.snapshots.enabled, peer?: string): { tree?: string; head?: string | null; commit?: string | null; reflog?: HeadMoveCursor; ms: number; budget?: SnapshotBudget; repo?: Repo } => {
4360
+ const finishRoutineSnapshot = (routine?: RoutineSnapshot) => {
4361
+ if (!routine || routine.skipped) return;
4362
+ if (routine.exhausted) {
4363
+ if (snapshotCooldown.exhausted(routine.repository, routine.budget)) log("snapshot unavailable: snapshot burst budget exhausted; boundary evidence is unknown; inspect snapshots.enabled");
4364
+ } else snapshotCooldown.success(routine.repository, routine.budget);
4365
+ };
4366
+ const snap = (what: string, capture = config.snapshots.enabled, peer?: string, routine = false): { tree?: string; head?: string | null; commit?: string | null; reflog?: HeadMoveCursor; ms: number; budget?: SnapshotBudget; repo?: Repo; routine?: RoutineSnapshot } => {
4344
4367
  if (!capture) return { ms: 0 };
4345
4368
  const captureSnapshot = () => {
4346
4369
  const t0 = performance.now(), budget = reserveSnapshotBudget();
4370
+ const boundary: RoutineSnapshot | undefined = routine ? { repository: peer ? executionRoot(peer) : opts.cwd, budget, exhausted: false, skipped: false } : undefined;
4371
+ if (boundary && snapshotCooldown.blocked(boundary.repository, budgetNow(budget))) { boundary.skipped = true; return { ms: 0, routine: boundary }; }
4347
4372
  let tree: string | undefined, head: string | null | undefined, commit: string | null | undefined, repo: Repo | undefined, reflog: HeadMoveCursor | undefined;
4348
4373
  try {
4349
4374
  repo = peer ? repoFor(peer, budget) : factsRepo;
@@ -4356,9 +4381,9 @@ export async function startDaemon(opts: DaemonOptions) {
4356
4381
  if (repo && !tree) log(`snapshot failed at ${what}`);
4357
4382
  } catch (error) {
4358
4383
  tree = undefined; head = undefined; commit = undefined; reflog = undefined;
4359
- snapshotFailure(what, error);
4384
+ snapshotFailure(what, error, boundary);
4360
4385
  }
4361
- return { tree, head, commit, reflog, budget, repo, ms: Math.round(performance.now() - t0) };
4386
+ return { tree, head, commit, reflog, budget, repo, ms: Math.round(performance.now() - t0), ...(boundary ? { routine: boundary } : {}) };
4362
4387
  };
4363
4388
  return controlWriteTelemetry ? controlWriteTelemetry.observe("snapshot", controlWritePrivacyGuard(true, true, peer as PeerId | undefined), captureSnapshot) : captureSnapshot();
4364
4389
  };
@@ -4488,6 +4513,14 @@ export async function startDaemon(opts: DaemonOptions) {
4488
4513
  const owned = board.list("in_progress").filter(task => task.owner === peer && !tasks.isPii(task));
4489
4514
  return owned.length === 1 ? owned[0]!.id : undefined;
4490
4515
  }
4516
+ /** Attribution only: the same board provenance check used by the schedule inventory. */
4517
+ function scheduledTask(taskId: number): boolean | undefined {
4518
+ try {
4519
+ const task = board.get(taskId);
4520
+ if (!task?.history[0]) return undefined;
4521
+ return task.history[0].by === HUB && scheduleKeyOf(task.detail) !== undefined;
4522
+ } catch { return undefined; }
4523
+ }
4491
4524
  type ImplementerFailureEntry = { launchId: string; generation: string; signal: AbortSignal; trace: ClaudeFailureTrace; probeCount: number; permissionAttempt: number };
4492
4525
  const implementerFailures = new WeakMap<PeerAdapter, ImplementerFailureEntry>();
4493
4526
  function currentImplementerTools(c: Client, verifyRoot = true): ReturnType<NonNullable<PeerAdapter["ownedTools"]>> {
@@ -4814,6 +4847,20 @@ export async function startDaemon(opts: DaemonOptions) {
4814
4847
  } catch { log(`accepted delivery timeout notice publication unconfirmed; inspect ahub queue list --peer ${sanitize(conductor)} and ahub queue show ${sanitize(row.id)}`); }
4815
4848
  }
4816
4849
  };
4850
+ let mergeReadbackPass: Promise<void> | undefined;
4851
+ const mergeReadbackTick = () => {
4852
+ if (!mergeReadbackPass) mergeReadbackPass = tasks.settleMergeReadbacks(Date.now()).catch(() => {}).finally(() => { mergeReadbackPass = undefined; });
4853
+ };
4854
+ const stopMergeReadbacks = opts.mergeReadbackTrigger?.(mergeReadbackTick);
4855
+ const mergeReadbackTimer = stopMergeReadbacks ? undefined : setInterval(mergeReadbackTick, MERGE_READBACK_INTERVAL_MS);
4856
+ mergeReadbackTimer?.unref();
4857
+ let mergeReadbackStopped = false;
4858
+ const stopMergeReadbackSchedule = () => {
4859
+ if (mergeReadbackStopped) return;
4860
+ mergeReadbackStopped = true; stopMergeReadbacks?.();
4861
+ if (mergeReadbackTimer) clearInterval(mergeReadbackTimer);
4862
+ };
4863
+ startupCleanup.push(async () => { stopMergeReadbackSchedule(); await mergeReadbackPass; });
4817
4864
  const intervals = [
4818
4865
  setInterval(() => {
4819
4866
  try { sweepInvocations(); } catch { log("invocation deadline sweep failed; the rows keep their state"); }
@@ -4923,6 +4970,26 @@ export async function startDaemon(opts: DaemonOptions) {
4923
4970
  };
4924
4971
  rescheduleSweep();
4925
4972
  startupCleanup.push(() => clearInterval(sweepTimer));
4973
+ let memorySyncFirst: ReturnType<typeof setTimeout> | undefined;
4974
+ let memorySyncTimer: ReturnType<typeof setInterval> | undefined;
4975
+ const clearMemorySyncTimers = () => {
4976
+ clearTimeout(memorySyncFirst);
4977
+ clearInterval(memorySyncTimer);
4978
+ memorySyncFirst = undefined;
4979
+ memorySyncTimer = undefined;
4980
+ };
4981
+ const rescheduleMemorySync = (firstPass: boolean) => {
4982
+ clearMemorySyncTimers();
4983
+ const every = config.memory.sync_interval_min ?? 10;
4984
+ if (!memoryStore || opts.memorySyncTrigger || every <= 0) return;
4985
+ if (firstPass) {
4986
+ memorySyncFirst = setTimeout(() => void syncNow(), 5_000);
4987
+ memorySyncFirst.unref?.();
4988
+ }
4989
+ memorySyncTimer = setInterval(() => void syncNow(), every * 60_000);
4990
+ memorySyncTimer.unref?.();
4991
+ };
4992
+ startupCleanup.push(clearMemorySyncTimers);
4926
4993
  // #512a: the schedules timer is its own interval, started whenever `schedules` is configured, whatever `task_sweep.enabled` says, and re-armed on reload.
4927
4994
  // It runs no task sweep. Held while stopping or recovering (inside `proposeFromSchedules`), where a due schedule counts the skip and coalesces.
4928
4995
  const schedulesStore = new ScheduleStore(join(opts.stateDir, "hub.db"));
@@ -5080,6 +5147,7 @@ export async function startDaemon(opts: DaemonOptions) {
5080
5147
  * target is unreachable without asking it again.
5081
5148
  */
5082
5149
  const handoffLogSeen = new Map<string, number>(), handoffFailures = new Map<string, { cause: string; at: number }>();
5150
+ const handoffCatchUpState = new Map<string, string>();
5083
5151
  const handoffLog = (target: string, cause: string, line: string): void => {
5084
5152
  handoffFailures.set(target, { cause, at: Date.now() });
5085
5153
  if (handoffLogGate(handoffLogSeen, `${target}|${cause}`, Date.now(), opts.handoffLogWindowMs ?? 15 * 60_000)) log(line);
@@ -5234,9 +5302,26 @@ export async function startDaemon(opts: DaemonOptions) {
5234
5302
  if (stopping) return;
5235
5303
  try {
5236
5304
  const project = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5237
- const descriptor = project && readControl(project.stateDir);
5238
- if (!project) { handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`); continue; }
5239
- if (!descriptor) { handoffLog(remote, "not running", `handoff catch-up of ${remote} skipped: its hub is not running`); continue; }
5305
+ if (!project) { handoffStateGate(handoffCatchUpState, remote, "moved"); handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`); continue; }
5306
+ const before = readControl(project.stateDir);
5307
+ const signature = before?.pidSignature && Number.isSafeInteger(before.pid) && before.pid! > 0
5308
+ ? await processSignatureAsync(before.pid!).catch(() => undefined) : undefined;
5309
+ if (stopping) return;
5310
+ const currentProject = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5311
+ if (!currentProject || currentProject.root !== project.root || currentProject.stateDir !== project.stateDir) {
5312
+ handoffStateGate(handoffCatchUpState, remote, "moved");
5313
+ handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`);
5314
+ continue;
5315
+ }
5316
+ const descriptor = readControl(project.stateDir);
5317
+ const sameIdentity = before?.pid === descriptor?.pid && before?.pidSignature === descriptor?.pidSignature;
5318
+ if (handoffTargetStopped(descriptor, (pid, expected) => processLiveness(pid, expected, () => sameIdentity ? signature : undefined))) {
5319
+ handoffFailures.set(remote, { cause: "not running", at: Date.now() });
5320
+ if (handoffStateGate(handoffCatchUpState, remote, "stopped")) log(`handoff catch-up of ${remote} skipped: its hub is not running`);
5321
+ continue;
5322
+ }
5323
+ handoffStateGate(handoffCatchUpState, remote, "available");
5324
+ if (!descriptor) continue; // handoffTargetStopped handles absence above
5240
5325
  if (!descriptor.features?.includes("task_handoff")) { handoffLog(remote, "too old for handoffs", `handoff catch-up of ${remote} skipped: its hub is too old for handoffs`); continue; }
5241
5326
  const client = await ControlClient.connect(project.stateDir, { role: "console", projectRoot: descriptor.cwd ?? project.root }, 3000);
5242
5327
  let answered = true;
@@ -5258,10 +5343,13 @@ export async function startDaemon(opts: DaemonOptions) {
5258
5343
  const handoffDescriptors = new Map<string, string>();
5259
5344
  const handoffWatch = (): void => {
5260
5345
  const changed = new Set<string>();
5261
- for (const remote of new Set(board.handoffOutboundOpen().filter(row => handoffCatchUpRow(row, Date.now())).map(row => row.remoteProject))) {
5346
+ const targets = new Set(board.handoffOutboundOpen().filter(row => handoffCatchUpRow(row, Date.now())).map(row => row.remoteProject));
5347
+ for (const target of handoffCatchUpState.keys()) if (!targets.has(target)) handoffCatchUpState.delete(target);
5348
+ for (const target of handoffDescriptors.keys()) if (!targets.has(target)) handoffDescriptors.delete(target);
5349
+ for (const remote of targets) {
5262
5350
  const project = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5263
5351
  const descriptor = project && readControl(project.stateDir);
5264
- const seen = descriptor ? `${descriptor.instanceId ?? ""}|${descriptor.url}` : "";
5352
+ const seen = descriptor ? `${descriptor.instanceId ?? ""}|${descriptor.url}|${descriptor.pid ?? ""}|${descriptor.pidSignature ?? ""}` : "";
5265
5353
  const before = handoffDescriptors.get(remote);
5266
5354
  handoffDescriptors.set(remote, seen);
5267
5355
  if (before !== undefined && before !== seen && seen) changed.add(remote);
@@ -6567,7 +6655,7 @@ export async function startDaemon(opts: DaemonOptions) {
6567
6655
  const nativeUnattended = (peer: string): boolean => startingUnattended.get(peer) ?? unattendedPeers.has(peer);
6568
6656
  // #1053: questions a peer asks the person. The store is the one record; the desk owns the waiting calls, supersede, cancel, expiry and the late-answer envelope.
6569
6657
  // Question text lives in hub.db and the envelope to the asking peer only: never a log line, an event, a notice or memory capture.
6570
- const questionStore = new QuestionStore(join(opts.stateDir, "hub.db"));
6658
+ questionStore = new QuestionStore(join(opts.stateDir, "hub.db"));
6571
6659
  startupCleanup.push(() => questionStore.close());
6572
6660
  const questionAttributions = new Map<string, TaskAttribution>();
6573
6661
  /**
@@ -6910,6 +6998,7 @@ export async function startDaemon(opts: DaemonOptions) {
6910
6998
  if (!recoveryActive() || releasing || taskOpsInFlight !== 0 || tasks.checksPending() !== 0 || piCallsInFlight() !== 0 || permissions.size !== 0 || starting.size !== 0 || requestedPeerStops.size !== 0 || rosterChanging !== undefined || !budget.recoverySettled || [...bus.peers.values()].filter(peer => !peer.id.includes("@")).some((peer) => peer.state === "busy" || ("recoveryReady" in peer && peer.recoveryReady !== true))) return false;
6911
6999
  if (tasks.guidanceProbesPending() !== 0) return false; // Active and uncertain fixture work retains its project lane.
6912
7000
  if (checkPending.size !== 0) return false;
7001
+ if (mergeReadbackPass) return false; // A host readback awaiting GitHub must settle before recovery commits.
6913
7002
  if (tasks.autoPullsPending() !== 0) return false; // #785 P1c: an automatic backlog pull mid-admission would write after the commit's digest; its own line keeps the line above exact for scripts/seeds.json
6914
7003
  if (tasks.queuePressureRechecksPending() !== 0) return false;
6915
7004
  if (tasks.schedulesPending() !== 0) return false; // #512a: a scheduled run mid-admission (its PII screen is awaited) would write after the commit's digest; the hold fence refuses its write, and this waits for it to end
@@ -7816,14 +7905,15 @@ export async function startDaemon(opts: DaemonOptions) {
7816
7905
  for (const id of turnTasks.keys()) if (!turnLog?.get(id)) turnTasks.delete(id);
7817
7906
  turnTasks.set(id, board.list().filter((t) => t.owner === e.peer && ["proposed", "in_progress", "changes_requested", "in_review"].includes(t.state)).map((t) => t.id));
7818
7907
  const capture = config.snapshots.enabled && !!turnLog;
7819
- const start = capture && !pii ? snap(`the start of ${id}`, config.snapshots.enabled, e.peer) : undefined; // before the peer is handed anything: the tap runs inside setState
7908
+ const start = capture && !pii ? snap(`the start of ${id}`, config.snapshots.enabled, e.peer, true) : undefined; // before the peer is handed anything: the tap runs inside setState
7820
7909
  try { if (capture) turnLog?.begin(id, e.peer, start?.tree, declarations[e.peer] ? executionRoot(e.peer) : undefined); } catch (error) { log(`turn record ${id}: ${(error as Error).message}`); }
7821
7910
  const writeTasks = tasks.ownerTurnTasks(e.peer);
7822
7911
  let branches: string | undefined, writeScope: boolean | undefined;
7823
7912
  if (writeTasks.length && start?.repo) try {
7824
7913
  branches = branchHeads(start.repo, start.budget);
7825
7914
  writeScope = ownerWriteRoot(e.peer) === opts.cwd ? canonicalWriteScope(start.repo, start.budget) : true;
7826
- } catch (error) { snapshotFailure(`the write scope of ${id}`, error); }
7915
+ } catch (error) { snapshotFailure(`the write scope of ${id}`, error, start?.routine); }
7916
+ finishRoutineSnapshot(start?.routine);
7827
7917
  const preparedRoles = preparedSessionRoleIdentities.get(e.peer)?.map(role => ({ ...role })) ?? null;
7828
7918
  turns.set(e.peer, { id, capture, start: startedAt, tokens: 0, writeTasks, branches, writeScope, deliveryTask: delivery, attribution, preparedRoles, ...(start ? { tree: start.tree, head: start.head, commit: start.commit, reflog: start.reflog, snapshotMs: start.ms } : {}), ...(pii ? { private: true } : {}) });
7829
7919
  const modelBoundary = modelBoundaries.get(e.peer);
@@ -7874,7 +7964,7 @@ export async function startDaemon(opts: DaemonOptions) {
7874
7964
  if (open.capture && turnLog && (open.private || holdsPii(e.peer))) {
7875
7965
  try { turnLog.end(open.id, undefined, [], Math.max(1, Number(config.snapshots.keep) || 20)); } catch (error) { log(`turn record ${open.id}: ${(error as Error).message}`); }
7876
7966
  } else if (open.capture && turnLog) {
7877
- const end = snap(`the end of ${open.id}`, true, e.peer);
7967
+ const end = snap(`the end of ${open.id}`, true, e.peer, true);
7878
7968
  let changed: string[] = [];
7879
7969
  if (open.tree && end.tree) {
7880
7970
  const turnRepo = end.repo!;
@@ -7914,7 +8004,7 @@ export async function startDaemon(opts: DaemonOptions) {
7914
8004
  }
7915
8005
  } catch (error) {
7916
8006
  end.tree = undefined; end.head = undefined; changed = [];
7917
- snapshotFailure(`the diff of ${open.id}`, error);
8007
+ snapshotFailure(`the diff of ${open.id}`, error, end.routine);
7918
8008
  }
7919
8009
  }
7920
8010
  if (open.tree && end.tree) files = changed.length; // unknown, not zero, when a snapshot failed
@@ -7930,14 +8020,15 @@ export async function startDaemon(opts: DaemonOptions) {
7930
8020
  if (scope === true) writeProgress = false;
7931
8021
  }
7932
8022
  }
7933
- } catch (error) { snapshotFailure(`the branch refs of ${open.id}`, error); }
8023
+ } catch (error) { snapshotFailure(`the branch refs of ${open.id}`, error, end.routine); }
7934
8024
  }
7935
8025
  }
7936
8026
  snapshotMs = (snapshotMs ?? 0) + end.ms;
7937
8027
  // #798 D2: a submodule's own edits never move the superproject's gitlink, so the diff above cannot see them. Name the dirty ones as unobserved (never as changed:
7938
8028
  // undo would try to restore them). Only for a turn whose trees are known; a read git cannot answer, or the budget cut short, records nothing, which stays unknown.
7939
8029
  let unobserved: string[] | undefined;
7940
- if (open.tree && end.tree && end.repo) try { unobserved = dirtySubmodules(end.repo, end.budget); } catch (error) { snapshotFailure(`the submodules of ${open.id}`, error); }
8030
+ if (open.tree && end.tree && end.repo) try { unobserved = dirtySubmodules(end.repo, end.budget); } catch (error) { snapshotFailure(`the submodules of ${open.id}`, error, end.routine); }
8031
+ finishRoutineSnapshot(end.routine);
7941
8032
  try { turnLog.end(open.id, end.tree, changed, Math.max(1, Number(config.snapshots.keep) || 20), unobserved); } catch (error) { log(`turn record ${open.id}: ${(error as Error).message}`); }
7942
8033
  // After the turn_end event: a notice delivered at once starts the peer's next turn, which must come after it.
7943
8034
  if (changed.length) afterTurn = () => detectConflicts(e.peer, open.id, open.start, changed);
@@ -8920,11 +9011,15 @@ export async function startDaemon(opts: DaemonOptions) {
8920
9011
  if (signal?.aborted) return "error: turn cancelled before tool effects";
8921
9012
  if (stopping || (recoveryActive() && recoveryPhase !== "preparing")) return "error: recovery is holding tool effects";
8922
9013
  const humanBash = context?.userBash === true && name === "bash";
9014
+ const attributionEnvs = humanBash ? [] : pi.budgetEnvelopes;
9015
+ let attributionTask: string | undefined;
9016
+ try { if (!humanBash) attributionTask = tasks.turnPolicy(attributionEnvs)?.task; } catch { /* Hints never block a tool. */ }
8923
9017
  let exitCode: number | null = null;
8924
9018
  const result = await piReceipts!.execute(sessionId ?? "", callId, name, humanBash ? { origin: "verified-user-bash", args: raw } : raw, async () => {
8925
9019
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "error: invalid tool arguments";
8926
9020
  const nativeTurn = pi.observationTurn;
8927
9021
  const output = TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name) ? await (name === "hub_ask" && signal ? invocationRequestSignal.run({ signal, current: () => !signal.aborted }, () => taskOp(peer, name, raw as Record<string, unknown>, true)) : taskOp(peer, name, raw as Record<string, unknown>, true)) : await runTool(name, JSON.stringify(raw), { ...ctx, signal,
9022
+ sandboxEnv: applyTurnAttribution(ctx.sandboxEnv ?? {}, humanBash ? { trigger: "manual" } : turnAttribution(attributionEnvs, { task: attributionTask === undefined ? undefined : Number(attributionTask), scheduled: scheduledTask })) as Record<string, string>,
8928
9023
  ...(humanBash ? { onProcessExit: (code: number | null) => { exitCode = code; } } : {}),
8929
9024
  shellExecutionCheck: input => signal?.aborted || context?.isCurrent?.() === false || bus.peers.get(peer) !== pi ? "aborted" : humanBash ? "valid" : shellProofs.check(input),
8930
9025
  permit: async (title, tool, toolSignal, path, _observe, originalPath, input, policy) => {
@@ -9166,6 +9261,7 @@ export async function startDaemon(opts: DaemonOptions) {
9166
9261
  beforeInput: (context, envs) => beforeOwnedObserverInput(peer, local, context, envs),
9167
9262
  inputReleased: (context, envs) => ownedObserverInputReleased(peer, local, context, envs),
9168
9263
  titlePreface: () => titlePreface(peer),
9264
+ scheduledTask,
9169
9265
  turnPolicy: (envs) => {
9170
9266
  const policy = tasks.turnPolicy(envs);
9171
9267
  if (!policy) return undefined;
@@ -9215,6 +9311,11 @@ export async function startDaemon(opts: DaemonOptions) {
9215
9311
  } catch { return false; }
9216
9312
  },
9217
9313
  chatTask: () => implementerChatTask(peer),
9314
+ scheduledTask,
9315
+ taskHintAllowed: taskId => {
9316
+ try { const task = board.get(taskId); return !!task && task.owner === peer && !tasks.isPii(task) && currentRoot(); }
9317
+ catch { return false; }
9318
+ },
9218
9319
  failureTrace: (launch, nativeVersion) => {
9219
9320
  const trace = createClaudeFailureTrace({ instanceId, nativeVersion, current: () => {
9220
9321
  const active = implementer.ownedTools?.(launch.launchId);
@@ -10162,6 +10263,8 @@ export async function startDaemon(opts: DaemonOptions) {
10162
10263
  refreshAutonomyConsent(prepared.fileConfig);
10163
10264
  for (const peer of changedPermissionDefaults) applyPendingPermissionDefault(peer);
10164
10265
  if (changes.some(change => change.key === "task_sweep" || change.key.startsWith("task_sweep."))) rescheduleSweep();
10266
+ const syncChange = changes.find(change => change.key === "memory.sync_interval_min");
10267
+ if (syncChange) rescheduleMemorySync((Number(syncChange.before ?? 10) <= 0) && Number(syncChange.after ?? 10) > 0);
10165
10268
  if (changes.some(change => change.key === "schedules" || change.key.startsWith("schedules.") || change.key === "folder_triggers" || change.key.startsWith("folder_triggers."))) rescheduleSchedules();
10166
10269
  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 });
10167
10270
  if (changes.some(change => change.key === "watchdog_ms")) for (const peer of bus.peers.values()) if (peer instanceof BasePeer) peer.configureWatchdog(config.watchdog_ms);
@@ -10845,6 +10948,7 @@ export async function startDaemon(opts: DaemonOptions) {
10845
10948
  ...(taskOpsInFlight !== 0 ? ["a task command in flight"] : []),
10846
10949
  ...(tasks.checksPending() !== 0 ? ["completion checks queued or running"] : []),
10847
10950
  ...(tasks.guidanceProbesPending() !== 0 ? ["guidance probe work in flight"] : []),
10951
+ ...(mergeReadbackPass ? ["an external merge readback in flight"] : []),
10848
10952
  ...(tasks.autoPullsPending() !== 0 ? ["an automatic backlog pull in flight"] : []),
10849
10953
  ...(tasks.queuePressureRechecksPending() !== 0 ? ["a queue-pressure assignment recheck in flight"] : []),
10850
10954
  ...(tasks.schedulesPending() !== 0 ? ["a scheduled task proposal in flight"] : []),
@@ -11130,7 +11234,7 @@ export async function startDaemon(opts: DaemonOptions) {
11130
11234
  sourceInstanceId: instanceId,
11131
11235
  operationId: op,
11132
11236
  committedAt: Date.now(),
11133
- bus: bus.snapshot(),
11237
+ bus: compactRestartBus(bus.snapshot()),
11134
11238
  manualPaused: [...manualPaused],
11135
11239
  peers,
11136
11240
  integrity: integrity(),
@@ -12605,7 +12709,7 @@ export async function startDaemon(opts: DaemonOptions) {
12605
12709
  const current = board.get(task.id) ?? task;
12606
12710
  rows.push({ id: task.id, title: tasks.publicTitle(current), ...(tasks.isPii(current) ? {} : { receipt: tasks.publicView(current).sdlc }), ...status });
12607
12711
  }
12608
- reply({ ok: true, mode: lifecycleConfig.mode, rows, truncated: selected.length > 100 });
12712
+ reply({ ok: true, mode: lifecycleConfig.mode, rows, ...(tasks.securityScanCounts() ? { securityScan: tasks.securityScanCounts() } : {}), truncated: selected.length > 100 });
12609
12713
  })().catch(() => reply({ ok: false, error: "lifecycle readback unavailable" }));
12610
12714
  return;
12611
12715
  }
@@ -13282,7 +13386,9 @@ export async function startDaemon(opts: DaemonOptions) {
13282
13386
  writeStatus();
13283
13387
  dashboard?.stop();
13284
13388
  stopConfigWatch();
13389
+ stopMergeReadbackSchedule();
13285
13390
  clearInterval(sweepTimer);
13391
+ clearMemorySyncTimers();
13286
13392
  clearInterval(schedulesTimer);
13287
13393
  tasks.stopCiWatchers(); // #785 P1b: no per-head CI watcher outlives the hub
13288
13394
  for (const i of intervals) clearInterval(i);
@@ -13314,11 +13420,13 @@ export async function startDaemon(opts: DaemonOptions) {
13314
13420
  // logged and shutdown finishes anyway, or the process ignores SIGTERM forever.
13315
13421
  for (const exit of exits) if (exit.status === "rejected") log(`peer stop failed during shutdown: ${(exit.reason as Error)?.message ?? exit.reason}`);
13316
13422
  await runnerStopped;
13423
+ await mergeReadbackPass;
13317
13424
  await Promise.all([...modelRelays.values()].map(relay => relay.close()));
13318
13425
  await egress?.close();
13319
13426
  await webEgress?.close();
13320
13427
  await Promise.all([...piReceiptLedgers.values()].map(ledger => ledger.close()));
13321
13428
  collectClaudeUsage();
13429
+ quotaEvents.flush();
13322
13430
  for (const id of [...researchPending.keys()]) writeResearch(id); // the peers have stopped, so their turns have ended
13323
13431
  budget.close();
13324
13432
  schedulesStore.close();
@@ -13404,11 +13512,7 @@ export async function startDaemon(opts: DaemonOptions) {
13404
13512
  catch (e) { log(`hub memory goals unreadable: ${(e as Error).message}`); }
13405
13513
  renewAllLeases();
13406
13514
  const leases = setInterval(renewAllLeases, 10 * 60_000); leases.unref?.(); intervals.push(leases);
13407
- const every = config.memory.sync_interval_min ?? 10;
13408
- if (every > 0 && !opts.memorySyncTrigger) {
13409
- const first = setTimeout(() => void syncNow(), 5_000); first.unref?.(); intervals.push(first);
13410
- const timer = setInterval(() => void syncNow(), every * 60_000); timer.unref?.(); intervals.push(timer);
13411
- }
13515
+ rescheduleMemorySync(true);
13412
13516
  }
13413
13517
  opts.memorySyncTrigger?.(syncNow);
13414
13518
  if (crashed) {
@@ -86,6 +86,7 @@ export const STANDING_INSTRUCTION =
86
86
  // burned a full turn writing "ack" because nothing told them a reply costs everyone else a turn. Same
87
87
  // wording as the channel's: an ack asked for "in one short line" is still the ack the issue is about.
88
88
  "Do not acknowledge a message that needs no answer; every reply costs the other agents a turn. " +
89
+ "When nothing in a delivery needs an answer from you, end your turn with exactly [FYI]; it sends nothing. Start progress notes with [FYI]. " +
89
90
  // Measured: told only not to acknowledge, Kimi still answers "Noted." The marker is the lever that actually
90
91
  // costs nobody a turn, and it was explained only in the Claude channel's instructions.
91
92
  "Start your own message with [FYI] when it needs nobody's turn (it goes to the console and the log only), " +
package/src/hub/facts.ts CHANGED
@@ -139,6 +139,9 @@ export interface Offered {
139
139
  coverage?: boolean;
140
140
  }
141
141
 
142
+ export const MAX_RECEIPTS_PER_PEER = 256;
143
+ export interface ReadReceipt { sha256: string; scope: "full" | "partial"; at: number; turnId: string }
144
+
142
145
  export class Facts {
143
146
  private readonly latest = new Map<string, Version>();
144
147
  private readonly transitions = new Map<string, Transition[]>();
@@ -185,6 +188,8 @@ export class Facts {
185
188
  private readonly covered = new Set<PeerId>();
186
189
  /** Each peer's native session or thread: a new one starts its views over. */
187
190
  private readonly sessions = new Map<PeerId, string>();
191
+ /** Read receipts, memory only (#1556 T1): peer -> "task\0path" -> receipt, insertion order is the LRU order. */
192
+ private readonly receipts = new Map<PeerId, Map<string, ReadReceipt>>();
188
193
  /** When tracking began: work on a task handed over before that is not covered. */
189
194
  private epoch = Date.now();
190
195
  private readonly root: string;
@@ -294,9 +299,29 @@ export class Facts {
294
299
  this.seenDropped.clear();
295
300
  this.unfollowed.clear(); // what was seen is forgotten: a notice about it would be stale
296
301
  this.writes.clear();
302
+ this.receipts.clear();
297
303
  this.epoch = Date.now();
298
304
  }
299
305
 
306
+ /** Record what `peer` read of `path` for `task`; bounded per peer, oldest evicted. Never persisted. */
307
+ recordRead(peer: PeerId, task: number, path: string, r: Omit<ReadReceipt, "at"> & { at?: number }): void {
308
+ let m = this.receipts.get(peer);
309
+ if (!m) this.receipts.set(peer, (m = new Map()));
310
+ const key = `${task}\0${path}`;
311
+ m.delete(key);
312
+ m.set(key, { ...r, at: r.at ?? Date.now() });
313
+ while (m.size > MAX_RECEIPTS_PER_PEER) m.delete(m.keys().next().value as string);
314
+ }
315
+
316
+ readReceipt(peer: PeerId, task: number, path: string): ReadReceipt | undefined {
317
+ return this.receipts.get(peer)?.get(`${task}\0${path}`);
318
+ }
319
+
320
+ /** The task closed: its receipts go. */
321
+ closeTask(task: number): void {
322
+ for (const m of this.receipts.values()) for (const k of [...m.keys()]) if (k.startsWith(`${task}\0`)) m.delete(k);
323
+ }
324
+
300
325
  /** A new native session or thread for `peer`: what the old one saw says nothing about the new one. */
301
326
  session(peer: PeerId, id: string | undefined): void {
302
327
  if (!id) return;
@@ -580,6 +605,11 @@ export class Facts {
580
605
  return this.observeAll();
581
606
  }
582
607
  if (tool === "Read") {
608
+ // #1556 T1: a read receipt per (peer, task, path), memory only. Unknown text (large or unreadable file) records nothing, never a guess.
609
+ const task = this.o.scope(peer)?.task?.id;
610
+ if (task !== undefined && pre.version.text !== undefined) {
611
+ this.recordRead(peer, task, file, { sha256: createHash("sha256").update(pre.version.text).digest("hex"), scope: input.offset === undefined && input.limit === undefined && readWhole(pre.version.text) ? "full" : "partial", turnId: toolUseId ?? "" });
612
+ }
583
613
  const version = this.observe(file);
584
614
  // Only a whole read of an unchanged file says what the peer saw: no offset or limit, and nothing Read cuts.
585
615
  if (!pre.version.projected && version.hash === pre.version.hash && input.offset === undefined && input.limit === undefined && readWhole(pre.version.text)) this.view(peer).set(file, version);
@@ -171,6 +171,20 @@ export function handoffLogGate(seen: Map<string, number>, key: string, now: numb
171
171
  return true;
172
172
  }
173
173
 
174
+ /** Missing descriptors or proven-gone processes are stopped; uncertain identity keeps the existing probe path. */
175
+ export function handoffTargetStopped(descriptor: { pid?: number; pidSignature?: string } | undefined, liveness: (pid: number, signature?: string) => "live" | "gone" | "unknown"): boolean {
176
+ if (!descriptor) return true;
177
+ if (!Number.isSafeInteger(descriptor.pid) || descriptor.pid! <= 0) return false;
178
+ try { return liveness(descriptor.pid!, descriptor.pidSignature) === "gone"; } catch { return false; }
179
+ }
180
+
181
+ /** Report only a change; the host prunes entries for targets no longer in its open handoffs. */
182
+ export function handoffStateGate(seen: Map<string, string>, target: string, state: string): boolean {
183
+ if (seen.get(target) === state) return false;
184
+ seen.set(target, state);
185
+ return true;
186
+ }
187
+
174
188
  /** What the target's own status descriptor says. A daemon that is not running, or does not know the handoff, is refused with the person's action. */
175
189
  export function checkTarget(project: RegisteredProject, descriptor: TargetDescriptor | undefined): void {
176
190
  if (!descriptor) throw new HandoffRefusal("not_running", `the hub of ${project.id} is not running; run \`ahub up\` in ${project.root}, then hand the task off again (handoffs are not queued)`);
@@ -263,7 +263,7 @@ export const TASK_TOOLS: HubTool[] = [
263
263
  tool("hub_delivery_resolve", "Confirm completion or discard your own needs_review delivery using the revision shown by hub_inbox. Requires a reason. Never replays the delivery or changes task state; another peer's row and stale revisions are refused.", { delivery_id: { type: "string", minLength: 1, maxLength: 256 }, revision: { type: "integer", minimum: 0 }, action: { type: "string", enum: ["completed", "discard"] }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["delivery_id", "revision", "action", "reason"]),
264
264
  tool("hub_backlog_list", "Read public backlog cards with planning revisions. Configured planners only; PII remains a stub.", {}),
265
265
  tool("hub_backlog_plan", "Plan an unpinned backlog item outside frozen releases with the revision you read and a bounded reason. Omit fields or give {} for a note-only revision. fields.sdlc accepts only repo/issue identity on unstarted backlog work; relinking clears old spec acceptance. A person's rank is retained. Actual dates cannot be set. fields.needsPerson (marking a leg only the person can run) is the person's: an agent that sends it, or plans a marked card, is refused.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", maxLength: 1000 }, fields: { type: "object", properties: { sdlc: { type: "object", minProperties: 1, properties: { repo: { type: ["string", "null"], maxLength: 400 }, issue: { type: ["integer", "null"], minimum: 1 } }, additionalProperties: false }, rank: { type: ["integer", "null"], minimum: 0 }, priority: { type: ["integer", "null"], minimum: 0, maximum: 3 }, release: { type: ["integer", "null"], minimum: 1 }, plannedStart: { type: ["integer", "null"], minimum: 1 }, due: { type: ["integer", "null"], minimum: 1 }, deps: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, reserved: { type: ["string", "null"], minLength: 1, maxLength: 32 }, needsPerson: { type: "boolean" } }, additionalProperties: false } }, ["id", "revision", "reason"]),
266
- tool("hub_backlog_pull", "Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
266
+ tool("hub_backlog_pull", "Configured planners only. Reserve a WIP slot and pull ready unpinned backlog work into To Do at its current revision. Preserves person order/reservations and frozen scope; pending unowned work can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 } }, ["id", "revision", "reason"]),
267
267
  tool("hub_backlog_split", "Split unstarted backlog work into two to eight staged parts. The original card retains integration/acceptance and depends on the children. Use after for existing prerequisite ids and afterParts for earlier zero-based part indexes. Latest unused unchanged children can be undone with hub_backlog_undo.", { id, revision: { type: "integer", minimum: 0 }, reason: { type: "string", minLength: 1, maxLength: 1000 }, parts: { type: "array", minItems: 2, maxItems: 8, items: { type: "object", properties: { title: { type: "string", minLength: 1, maxLength: 300 }, detail: { type: "string", maxLength: 8000 }, class: str, refs, plan, after: { type: "array", maxItems: 64, uniqueItems: true, items: { type: "integer", minimum: 1 } }, afterParts: { type: "array", maxItems: 8, uniqueItems: true, items: { type: "integer", minimum: 0 } } }, required: ["title"], additionalProperties: false } } }, ["id", "revision", "reason", "parts"]),
268
268
  tool("hub_backlog_undo", "Undo your latest planning change at its current revision. Refuses intervening changes and another actor's edit.", { id, revision: { type: "integer", minimum: 1 } }, ["id", "revision"]),
269
269
  tool("hub_study_draft", "Store a research campaign contract as a DRAFT revision 1 on an approved parent task. Configured planners only; it creates no task, dispatches nothing and never approves (only the person approves, with ahub study approve). The contract is data: question, scope, exclusions, sourceIds, units, deliverableSections, stopPolicy and an optional budget.", { parentTaskId: id, contract: { type: "object" } }, ["parentTaskId", "contract"]),