@staix/agent-hub 0.42.0 → 0.43.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 (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -1
  3. package/docs/adding-an-ai-tool.md +2 -0
  4. package/docs/agent-notes/tasks.md +1 -1
  5. package/docs/agent-notes/tests.md +1 -1
  6. package/docs/design/adapters.md +3 -0
  7. package/docs/design/bus.md +2 -0
  8. package/docs/design/task-board.md +6 -0
  9. package/docs/dogfood.md +5 -1
  10. package/docs/memory.md +5 -3
  11. package/docs/operations.md +64 -4
  12. package/docs/quickstart.md +12 -2
  13. package/docs/sdlc.md +1 -1
  14. package/docs/security.md +1 -1
  15. package/docs/verification/2026-11-18-0.43.0.md +56 -0
  16. package/docs/verified.json +23 -23
  17. package/package.json +2 -2
  18. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  19. package/plugins/agent-hub/kimi-hook.js +307 -117
  20. package/plugins/agent-hub/server.js +307 -117
  21. package/src/adapters/claude-implementer.ts +11 -1
  22. package/src/adapters/claude-print-child.ts +4 -1
  23. package/src/adapters/conformance/fakes/acp-server.ts +2 -1
  24. package/src/adapters/conformance/fakes/app-server.ts +1 -1
  25. package/src/adapters/local-worker.ts +7 -3
  26. package/src/adapters/reviewer-print.ts +3 -1
  27. package/src/cli/help.ts +3 -3
  28. package/src/cli/identity.ts +2 -0
  29. package/src/cli/main.ts +56 -4
  30. package/src/cli/upgrade-output.ts +43 -2
  31. package/src/cli/upgrade-stopped.ts +162 -0
  32. package/src/cli/upgrade-wait.ts +37 -0
  33. package/src/hub/board.ts +4 -2
  34. package/src/hub/config-apply.ts +1 -0
  35. package/src/hub/daemon.ts +75 -13
  36. package/src/hub/envelope.ts +1 -0
  37. package/src/hub/handoff.ts +14 -0
  38. package/src/hub/questions.ts +7 -0
  39. package/src/hub/recovery-store.ts +39 -0
  40. package/src/hub/research-record.ts +2 -1
  41. package/src/hub/runtime-capture-prune.ts +114 -3
  42. package/src/hub/runtime-prune-health.ts +6 -2
  43. package/src/hub/sdlc-metrics.ts +2 -2
  44. package/src/hub/settings.ts +2 -0
  45. package/src/hub/task-sweep.ts +6 -2
  46. package/src/hub/tasks.ts +8 -3
  47. package/src/hub/turn-attribution.ts +46 -0
  48. package/templates/AGENTS.block.md +1 -1
package/src/hub/board.ts CHANGED
@@ -296,6 +296,8 @@ export interface HistoryEntry {
296
296
  noWrites?: true;
297
297
  /** Host-recorded expected cost and exact review head, never narrative. */
298
298
  reviewCost?: ReviewCost;
299
+ /** Full commit submitted for review; independent of cost planning. */
300
+ requestHead?: string;
299
301
  /** #901: on the hub's own `check passed` / `check failed`: the check key (task class or profile class alias) whose command ran. Set by the hub from its own selection, never from output or an owner's words. */
300
302
  checkKey?: string;
301
303
  /** #901: on such an entry, the number of unresolved citation keys the example citation check printed (`citations: N declared keys, M missing`); absent when the check printed no such line. */
@@ -2685,7 +2687,7 @@ export class Board {
2685
2687
 
2686
2688
  /** The only way a task changes. Validates the move, records who did what, returns the new row. */
2687
2689
  /** A `plan` in the patch replaces the old one whole: a new plan is the owner's current intent, not an addition. */
2688
- update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2690
+ update(id: number, by: PeerId, event: string, patch: Partial<Pick<Task, "state" | "owner" | "planner" | "reviewer" | "reserved" | "refs" | "plan" | "rejections" | "signals" | "sdlc" | "role" | "cancelled" | "codeSymbols">>, note?: string, extra: Pick<HistoryEntry, "invocation" | "plannerReason" | "planAuthor" | "selfReview" | "profile" | "sweep" | "wait" | "reason" | "from" | "capacity" | "conductorManual" | "withheld" | "noWrites" | "reviewCost" | "requestHead" | "reviewContext" | "reviewScope" | "evidenceOnly" | "reviewedHead" | "reviewFindings" | "unmetCriteria" | "deliverables" | "checkKey" | "missingKeys" | "claim" | "planObservation" | "planDeparture" | "planDepartureInvalidated" | "specReport" | "specRefBinding" | "resolvedReviewComments" | "securityPass" | keyof ReviewerHistory> = {}, expectedFlowRevision?: number, codeSymbolsAuthority?: typeof HOST_CODE_SYMBOLS, adoptionAuthority?: typeof HOST_MERGE_ADOPTION): Task {
2689
2691
  if (extra.resolvedReviewComments?.length && !this.db.inTransaction) return this.atomic(() => this.update(id, by, event, patch, note, extra, expectedFlowRevision, codeSymbolsAuthority, adoptionAuthority));
2690
2692
  const task = this.get(id);
2691
2693
  if (!task) throw new Error(`no task #${id}`);
@@ -2783,7 +2785,7 @@ export class Board {
2783
2785
  && priorHead !== undefined && /^[a-f0-9]{40}$/.test(priorHead);
2784
2786
  const previousHistory = backfill ? task.history.map((entry, index) => index === priorApproval && !entry.reviewedHead
2785
2787
  ? { ...entry, reviewedHead: entry.reviewFindings?.head ?? priorHead } : entry) : task.history;
2786
- const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2788
+ const history = [...previousHistory, { at: Date.now(), by, event, ...(resolvedReviewComments?.length ? { resolvedReviewComments } : {}), ...(returnPlanning ? { planning: returnPlanning } : {}), ...(extra.invocation ? { invocation: extra.invocation } : {}), ...plannerHistory, ...authorHistory, ...(extra.selfReview === true ? { selfReview: true as const } : {}), ...(planRevision ? { planRevision } : {}), ...(extra.planObservation ? { planObservation: extra.planObservation } : {}), ...(extra.planDeparture ? { planDeparture: extra.planDeparture } : {}), ...(departureInvalidated ? { planDepartureInvalidated: true as const } : {}), ...reviewMetadata, ...specMetadata, ...(note ? { note } : {}), ...(patch.cancelled?.supersededBy ? { supersededBy: patch.cancelled.supersededBy } : {}), ...("owner" in patch ? { owner: next.owner } : {}), ...(extra.profile ? { profile: extra.profile } : {}), ...(extra.sweep ? { sweep: extra.sweep } : {}), ...(event === "wait recorded" && extra.wait && Number.isSafeInteger(extra.wait.until) && extra.wait.until > 0 ? { wait: { until: extra.wait.until, owner: extra.wait.owner } } : {}), ...(extra.reason && TASK_MOVE_REASONS.includes(extra.reason) ? { reason: extra.reason } : {}), ...(extra.from ? { from: extra.from } : {}), ...(extra.capacity === true ? { capacity: true as const } : {}), ...(extra.conductorManual === true ? { conductorManual: true as const } : {}), ...(extra.withheld && (note || reviewFindings) ? { withheld: true as const } : {}), ...(reviewFindings ? { reviewFindings } : {}), ...(extra.reviewedHead ? { reviewedHead: extra.reviewedHead } : {}), ...(unmetCriteria?.length ? { unmetCriteria } : {}), ...(securityPass ? { securityPass } : {}), ...(deliverables ? { deliverables } : {}), ...(extra.reviewContext === "fresh" || extra.reviewContext === "continuing" ? { reviewContext: extra.reviewContext } : {}), ...(extra.reviewScope === "code" ? { reviewScope: "code" as const } : {}), ...(extra.evidenceOnly === true && event === "changes_requested" ? { evidenceOnly: true as const } : {}), ...(extra.reviewCost ? { reviewCost: extra.reviewCost } : {}), ...(event === "done" && extra.requestHead && /^[a-f0-9]{40}$/.test(extra.requestHead) ? { requestHead: extra.requestHead } : {}), ...(event === "done" && extra.noWrites === true ? { noWrites: true as const } : {}), ...(["check passed", "check failed"].includes(event) && typeof extra.checkKey === "string" && /^[a-z][a-z0-9_]{0,47}$/.test(extra.checkKey) ? { checkKey: extra.checkKey } : {}), ...(["check passed", "check failed"].includes(event) && Number.isSafeInteger(extra.missingKeys) && extra.missingKeys! >= 0 && extra.missingKeys! <= 100_000 ? { missingKeys: extra.missingKeys } : {}), ...(event === "claim verdict" && extra.claim ? { claim: extra.claim } : {}) }];
2787
2789
  this.taskWrite(() => {
2788
2790
  if (resolvedReviewComments?.length) for (const record of this.reviewComments(task.id, task.created)) {
2789
2791
  if (!resolvedReviewComments.includes(record.thread.id) || record.lifecycle !== "sent") continue;
@@ -308,6 +308,7 @@ export function configApply(key: string, scopes: readonly ConfigIdentityScope[]
308
308
  }
309
309
  const operational = operationalNumber(key);
310
310
  if (operational) return { applies: operational.applies, ...(operational.restartReason ? { reason: operational.restartReason } : {}) };
311
+ if (key === "memory.sync_interval_min") return { applies: "live" };
311
312
  if (nextMemory.has(key)) return { applies: "next use" };
312
313
  for (const [path, reason] of Object.entries(restart)) if (key === path || key.startsWith(`${path}.`)) return { applies: "restart", reason };
313
314
  if ([...live].some(path => key === path || key.startsWith(`${path}.`))) return { applies: "live" };
package/src/hub/daemon.ts CHANGED
@@ -112,7 +112,7 @@ import { CONSOLE_POLL_SETTING, CONSOLE_NOTICE_SETTING, CONSOLE_HISTORY_SETTING,
112
112
  import { MODEL_COOLDOWN_FAILURES_SETTING, MODEL_COOLDOWN_SETTING, MODEL_COOLDOWN_CAP_SETTING, MODEL_TERMINAL_HISTORY_SETTING, modelOperationalReaders, type ModelOperationalConfig } from "./operational-settings.ts";
113
113
  import { ACP_TOOL_CEILING_SETTING, ACP_ACTIVITY_BATCH_SETTING, JCODE_STEER_TIMEOUT_SETTING, adapterOperationalReaders, type AdapterTimingConfig } from "./operational-settings.ts";
114
114
  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";
115
+ import { foldersConfig, scheduleKeyOf, scheduleViews, schedulesConfig, ScheduleStore, type FolderEntry, type ScheduleEntry } from "./schedules.ts";
116
116
  import { FolderStore, registerScanned, scanFolder, type FolderPolicy } from "./folder-trigger.ts";
117
117
  import { QuestionStore, QUESTION_SURFACES, questionView } from "./questions.ts";
118
118
  import { RunTracker, outcomeOf, settleVerdict, type Run } from "./completions.ts";
@@ -157,6 +157,7 @@ import { CHECKPOINT_FIELDS, CHECKPOINT_FIELDS_SENTENCE, checkpointFieldCount, pa
157
157
  import { ModelOverrides, ModelOverrideLatches, type RuntimeModelStatus, type ModelSource } from "./model-overrides.ts";
158
158
  import { isNativeModelToken } from "../adapters/model-token.ts";
159
159
  import { processSignature, processLiveness } from "../pi/process-signature.ts";
160
+ import { processSignatureAsync } from "@staix/agent-mem/platform";
160
161
  import { PiSessionBookmarkMismatch, PiSessionUnresumable, recordPiReplacement, validatePiSession } from "../pi/session.ts";
161
162
  import { profile, proxyEnv, sandboxAvailable, type SandboxNetwork } from "../local/sandbox.ts";
162
163
  import { DEFAULT_NETWORK_ALLOW, startEgressProxy, type EgressProxy } from "../local/proxy.ts";
@@ -185,12 +186,13 @@ import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type
185
186
  import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
186
187
  import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
187
188
  import { remoteEnvelope, HUB } from "./envelope.ts";
189
+ import { applyTurnAttribution, turnAttribution } from "./turn-attribution.ts";
188
190
  import { recallMemoryLines, trimToTokens, aggregateUse, orderByUse } from "../memory/recall.ts";
189
191
  import { closeSync, constants as fsConstants, openSync, lstatSync, readSync, statSync } from "node:fs";
190
192
  import { basename, isAbsolute } from "node:path";
191
193
  import { fileURLToPath } from "node:url";
192
194
  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";
195
+ import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, handoffStateGate, handoffTargetStopped, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
194
196
  import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
195
197
  import type { BusEvent, PublishResult } from "./bus.ts";
196
198
  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";
@@ -3007,8 +3009,10 @@ export async function startDaemon(opts: DaemonOptions) {
3007
3009
  const projectSpecs = specInspectorAt(opts.cwd);
3008
3010
  let specsMissingBlockHintShown = false;
3009
3011
  let releaseReportPolicy: ((head: string, repo: string) => ReleaseReportPolicy | undefined) | undefined;
3012
+ let questionStore!: QuestionStore;
3010
3013
  startupTimings.mark("task_ports");
3011
3014
  const tasks: Tasks = new Tasks({
3015
+ ownerQuestionWait: (task, peer) => questionStore?.ownerWait(task, peer),
3012
3016
  guidanceProbes: { store: guidanceProbeStore, session: by => {
3013
3017
  const request = guidanceProbeRequestContext.getStore();
3014
3018
  return request?.actor === by ? { generation: request.generation, nativeSession: request.nativeSession,
@@ -4488,6 +4492,14 @@ export async function startDaemon(opts: DaemonOptions) {
4488
4492
  const owned = board.list("in_progress").filter(task => task.owner === peer && !tasks.isPii(task));
4489
4493
  return owned.length === 1 ? owned[0]!.id : undefined;
4490
4494
  }
4495
+ /** Attribution only: the same board provenance check used by the schedule inventory. */
4496
+ function scheduledTask(taskId: number): boolean | undefined {
4497
+ try {
4498
+ const task = board.get(taskId);
4499
+ if (!task?.history[0]) return undefined;
4500
+ return task.history[0].by === HUB && scheduleKeyOf(task.detail) !== undefined;
4501
+ } catch { return undefined; }
4502
+ }
4491
4503
  type ImplementerFailureEntry = { launchId: string; generation: string; signal: AbortSignal; trace: ClaudeFailureTrace; probeCount: number; permissionAttempt: number };
4492
4504
  const implementerFailures = new WeakMap<PeerAdapter, ImplementerFailureEntry>();
4493
4505
  function currentImplementerTools(c: Client, verifyRoot = true): ReturnType<NonNullable<PeerAdapter["ownedTools"]>> {
@@ -4923,6 +4935,26 @@ export async function startDaemon(opts: DaemonOptions) {
4923
4935
  };
4924
4936
  rescheduleSweep();
4925
4937
  startupCleanup.push(() => clearInterval(sweepTimer));
4938
+ let memorySyncFirst: ReturnType<typeof setTimeout> | undefined;
4939
+ let memorySyncTimer: ReturnType<typeof setInterval> | undefined;
4940
+ const clearMemorySyncTimers = () => {
4941
+ clearTimeout(memorySyncFirst);
4942
+ clearInterval(memorySyncTimer);
4943
+ memorySyncFirst = undefined;
4944
+ memorySyncTimer = undefined;
4945
+ };
4946
+ const rescheduleMemorySync = (firstPass: boolean) => {
4947
+ clearMemorySyncTimers();
4948
+ const every = config.memory.sync_interval_min ?? 10;
4949
+ if (!memoryStore || opts.memorySyncTrigger || every <= 0) return;
4950
+ if (firstPass) {
4951
+ memorySyncFirst = setTimeout(() => void syncNow(), 5_000);
4952
+ memorySyncFirst.unref?.();
4953
+ }
4954
+ memorySyncTimer = setInterval(() => void syncNow(), every * 60_000);
4955
+ memorySyncTimer.unref?.();
4956
+ };
4957
+ startupCleanup.push(clearMemorySyncTimers);
4926
4958
  // #512a: the schedules timer is its own interval, started whenever `schedules` is configured, whatever `task_sweep.enabled` says, and re-armed on reload.
4927
4959
  // It runs no task sweep. Held while stopping or recovering (inside `proposeFromSchedules`), where a due schedule counts the skip and coalesces.
4928
4960
  const schedulesStore = new ScheduleStore(join(opts.stateDir, "hub.db"));
@@ -5080,6 +5112,7 @@ export async function startDaemon(opts: DaemonOptions) {
5080
5112
  * target is unreachable without asking it again.
5081
5113
  */
5082
5114
  const handoffLogSeen = new Map<string, number>(), handoffFailures = new Map<string, { cause: string; at: number }>();
5115
+ const handoffCatchUpState = new Map<string, string>();
5083
5116
  const handoffLog = (target: string, cause: string, line: string): void => {
5084
5117
  handoffFailures.set(target, { cause, at: Date.now() });
5085
5118
  if (handoffLogGate(handoffLogSeen, `${target}|${cause}`, Date.now(), opts.handoffLogWindowMs ?? 15 * 60_000)) log(line);
@@ -5234,9 +5267,26 @@ export async function startDaemon(opts: DaemonOptions) {
5234
5267
  if (stopping) return;
5235
5268
  try {
5236
5269
  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; }
5270
+ if (!project) { handoffStateGate(handoffCatchUpState, remote, "moved"); handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`); continue; }
5271
+ const before = readControl(project.stateDir);
5272
+ const signature = before?.pidSignature && Number.isSafeInteger(before.pid) && before.pid! > 0
5273
+ ? await processSignatureAsync(before.pid!).catch(() => undefined) : undefined;
5274
+ if (stopping) return;
5275
+ const currentProject = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5276
+ if (!currentProject || currentProject.root !== project.root || currentProject.stateDir !== project.stateDir) {
5277
+ handoffStateGate(handoffCatchUpState, remote, "moved");
5278
+ handoffLog(remote, "project not registered (moved?)", `handoff catch-up of ${remote} skipped: project not registered (moved?)`);
5279
+ continue;
5280
+ }
5281
+ const descriptor = readControl(project.stateDir);
5282
+ const sameIdentity = before?.pid === descriptor?.pid && before?.pidSignature === descriptor?.pidSignature;
5283
+ if (handoffTargetStopped(descriptor, (pid, expected) => processLiveness(pid, expected, () => sameIdentity ? signature : undefined))) {
5284
+ handoffFailures.set(remote, { cause: "not running", at: Date.now() });
5285
+ if (handoffStateGate(handoffCatchUpState, remote, "stopped")) log(`handoff catch-up of ${remote} skipped: its hub is not running`);
5286
+ continue;
5287
+ }
5288
+ handoffStateGate(handoffCatchUpState, remote, "available");
5289
+ if (!descriptor) continue; // handoffTargetStopped handles absence above
5240
5290
  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
5291
  const client = await ControlClient.connect(project.stateDir, { role: "console", projectRoot: descriptor.cwd ?? project.root }, 3000);
5242
5292
  let answered = true;
@@ -5258,10 +5308,13 @@ export async function startDaemon(opts: DaemonOptions) {
5258
5308
  const handoffDescriptors = new Map<string, string>();
5259
5309
  const handoffWatch = (): void => {
5260
5310
  const changed = new Set<string>();
5261
- for (const remote of new Set(board.handoffOutboundOpen().filter(row => handoffCatchUpRow(row, Date.now())).map(row => row.remoteProject))) {
5311
+ const targets = new Set(board.handoffOutboundOpen().filter(row => handoffCatchUpRow(row, Date.now())).map(row => row.remoteProject));
5312
+ for (const target of handoffCatchUpState.keys()) if (!targets.has(target)) handoffCatchUpState.delete(target);
5313
+ for (const target of handoffDescriptors.keys()) if (!targets.has(target)) handoffDescriptors.delete(target);
5314
+ for (const remote of targets) {
5262
5315
  const project = registeredProjects(hubHome()).find(candidate => candidate.id === remote);
5263
5316
  const descriptor = project && readControl(project.stateDir);
5264
- const seen = descriptor ? `${descriptor.instanceId ?? ""}|${descriptor.url}` : "";
5317
+ const seen = descriptor ? `${descriptor.instanceId ?? ""}|${descriptor.url}|${descriptor.pid ?? ""}|${descriptor.pidSignature ?? ""}` : "";
5265
5318
  const before = handoffDescriptors.get(remote);
5266
5319
  handoffDescriptors.set(remote, seen);
5267
5320
  if (before !== undefined && before !== seen && seen) changed.add(remote);
@@ -6567,7 +6620,7 @@ export async function startDaemon(opts: DaemonOptions) {
6567
6620
  const nativeUnattended = (peer: string): boolean => startingUnattended.get(peer) ?? unattendedPeers.has(peer);
6568
6621
  // #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
6622
  // 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"));
6623
+ questionStore = new QuestionStore(join(opts.stateDir, "hub.db"));
6571
6624
  startupCleanup.push(() => questionStore.close());
6572
6625
  const questionAttributions = new Map<string, TaskAttribution>();
6573
6626
  /**
@@ -8920,11 +8973,15 @@ export async function startDaemon(opts: DaemonOptions) {
8920
8973
  if (signal?.aborted) return "error: turn cancelled before tool effects";
8921
8974
  if (stopping || (recoveryActive() && recoveryPhase !== "preparing")) return "error: recovery is holding tool effects";
8922
8975
  const humanBash = context?.userBash === true && name === "bash";
8976
+ const attributionEnvs = humanBash ? [] : pi.budgetEnvelopes;
8977
+ let attributionTask: string | undefined;
8978
+ try { if (!humanBash) attributionTask = tasks.turnPolicy(attributionEnvs)?.task; } catch { /* Hints never block a tool. */ }
8923
8979
  let exitCode: number | null = null;
8924
8980
  const result = await piReceipts!.execute(sessionId ?? "", callId, name, humanBash ? { origin: "verified-user-bash", args: raw } : raw, async () => {
8925
8981
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "error: invalid tool arguments";
8926
8982
  const nativeTurn = pi.observationTurn;
8927
8983
  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,
8984
+ sandboxEnv: applyTurnAttribution(ctx.sandboxEnv ?? {}, humanBash ? { trigger: "manual" } : turnAttribution(attributionEnvs, { task: attributionTask === undefined ? undefined : Number(attributionTask), scheduled: scheduledTask })) as Record<string, string>,
8928
8985
  ...(humanBash ? { onProcessExit: (code: number | null) => { exitCode = code; } } : {}),
8929
8986
  shellExecutionCheck: input => signal?.aborted || context?.isCurrent?.() === false || bus.peers.get(peer) !== pi ? "aborted" : humanBash ? "valid" : shellProofs.check(input),
8930
8987
  permit: async (title, tool, toolSignal, path, _observe, originalPath, input, policy) => {
@@ -9166,6 +9223,7 @@ export async function startDaemon(opts: DaemonOptions) {
9166
9223
  beforeInput: (context, envs) => beforeOwnedObserverInput(peer, local, context, envs),
9167
9224
  inputReleased: (context, envs) => ownedObserverInputReleased(peer, local, context, envs),
9168
9225
  titlePreface: () => titlePreface(peer),
9226
+ scheduledTask,
9169
9227
  turnPolicy: (envs) => {
9170
9228
  const policy = tasks.turnPolicy(envs);
9171
9229
  if (!policy) return undefined;
@@ -9215,6 +9273,11 @@ export async function startDaemon(opts: DaemonOptions) {
9215
9273
  } catch { return false; }
9216
9274
  },
9217
9275
  chatTask: () => implementerChatTask(peer),
9276
+ scheduledTask,
9277
+ taskHintAllowed: taskId => {
9278
+ try { const task = board.get(taskId); return !!task && task.owner === peer && !tasks.isPii(task) && currentRoot(); }
9279
+ catch { return false; }
9280
+ },
9218
9281
  failureTrace: (launch, nativeVersion) => {
9219
9282
  const trace = createClaudeFailureTrace({ instanceId, nativeVersion, current: () => {
9220
9283
  const active = implementer.ownedTools?.(launch.launchId);
@@ -10162,6 +10225,8 @@ export async function startDaemon(opts: DaemonOptions) {
10162
10225
  refreshAutonomyConsent(prepared.fileConfig);
10163
10226
  for (const peer of changedPermissionDefaults) applyPendingPermissionDefault(peer);
10164
10227
  if (changes.some(change => change.key === "task_sweep" || change.key.startsWith("task_sweep."))) rescheduleSweep();
10228
+ const syncChange = changes.find(change => change.key === "memory.sync_interval_min");
10229
+ if (syncChange) rescheduleMemorySync((Number(syncChange.before ?? 10) <= 0) && Number(syncChange.after ?? 10) > 0);
10165
10230
  if (changes.some(change => change.key === "schedules" || change.key.startsWith("schedules.") || change.key === "folder_triggers" || change.key.startsWith("folder_triggers."))) rescheduleSchedules();
10166
10231
  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
10232
  if (changes.some(change => change.key === "watchdog_ms")) for (const peer of bus.peers.values()) if (peer instanceof BasePeer) peer.configureWatchdog(config.watchdog_ms);
@@ -13283,6 +13348,7 @@ export async function startDaemon(opts: DaemonOptions) {
13283
13348
  dashboard?.stop();
13284
13349
  stopConfigWatch();
13285
13350
  clearInterval(sweepTimer);
13351
+ clearMemorySyncTimers();
13286
13352
  clearInterval(schedulesTimer);
13287
13353
  tasks.stopCiWatchers(); // #785 P1b: no per-head CI watcher outlives the hub
13288
13354
  for (const i of intervals) clearInterval(i);
@@ -13404,11 +13470,7 @@ export async function startDaemon(opts: DaemonOptions) {
13404
13470
  catch (e) { log(`hub memory goals unreadable: ${(e as Error).message}`); }
13405
13471
  renewAllLeases();
13406
13472
  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
- }
13473
+ rescheduleMemorySync(true);
13412
13474
  }
13413
13475
  opts.memorySyncTrigger?.(syncNow);
13414
13476
  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), " +
@@ -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)`);
@@ -204,6 +204,13 @@ export class QuestionStore {
204
204
  }
205
205
  close(): void { try { this.db.close(); } catch { /* already closed */ } }
206
206
 
207
+ /** Timing only: never hydrate question text for the idle-owner sweep.
208
+ * ponytail: QuestionDesk's KEEP_SETTLED_MS (7 days) is the anchor ceiling; after pruning the ladder falls back to its own state. A durable board marker is the upgrade path. */
209
+ ownerWait(task: number, peer: string): { open: boolean; settled?: number } {
210
+ const row = this.db.query("SELECT MAX(CASE WHEN state = 'open' THEN 1 ELSE 0 END) AS open, MAX(settled) AS settled FROM questions WHERE task = ? AND peer = ?").get(task, peer) as { open: number | null; settled: number | null };
211
+ return { open: row.open === 1, ...(row.settled === null ? {} : { settled: row.settled }) };
212
+ }
213
+
207
214
  get(set: string): QuestionRow | undefined {
208
215
  if (typeof set !== "string" || !QUESTION_SET.test(set)) return undefined;
209
216
  const raw = this.db.query("SELECT * FROM questions WHERE set_id = ?").get(set) as RawRow | null;
@@ -282,3 +282,42 @@ export function claimRunner(id: string, home = hubHome()): () => void {
282
282
  db.close();
283
283
  };
284
284
  }
285
+
286
+ /** True when any machine or project recovery hold exists, or the coordination state cannot be read: unknown is held. */
287
+ export function anyRecoveryHold(home = hubHome()): boolean {
288
+ try {
289
+ if (legacyRecoveryLock(home)) return true;
290
+ const db = projectLocks(home);
291
+ if (!db) return false;
292
+ try { return !!db.query("SELECT 1 FROM project_locks LIMIT 1").get(); } finally { db.close(); }
293
+ } catch { return true; }
294
+ }
295
+
296
+ /**
297
+ * #1541: remove one terminal receipt and its runner db. The exclusive runner claim is the only mutual exclusion: a live or
298
+ * unidentifiable runner keeps the receipt, a dead one is replaced by `claimRunner` in its own transaction, so two retirers
299
+ * on the same stale claim cannot both proceed. Under the claim `confirm` sees the receipt as it is now; the receipt leaves
300
+ * first, then the claim row is released, then the runner db. An interruption between them leaves only a runner db without
301
+ * a receipt, which the next call settles through the ENOENT branch (a later claimant re-reads the receipt, finds none and
302
+ * fails). A runner db whose receipt is gone is settled the same way (`settled`, `confirm` never called); only the call that
303
+ * removed the receipt answers `retired`.
304
+ */
305
+ export function retireOperation(id: string, home: string, confirm: (record: unknown) => boolean, hooks: { betweenPair?: () => void } = {}): "retired" | "settled" | "kept" {
306
+ const file = operationPath(id, home);
307
+ let release: () => void;
308
+ try { release = claimRunner(id, home); } catch { return "kept"; }
309
+ let result: "retired" | "settled" = "settled";
310
+ try {
311
+ let record: unknown, removed = false;
312
+ try { record = readOperation(id, home); }
313
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return "kept"; }
314
+ if (record !== undefined) {
315
+ if (!confirm(record)) return "kept";
316
+ rmSync(file); removed = true;
317
+ hooks.betweenPair?.();
318
+ }
319
+ result = removed ? "retired" : "settled";
320
+ } finally { release(); }
321
+ rmSync(`${file}.runner.db`, { force: true });
322
+ return result;
323
+ }
@@ -115,7 +115,8 @@ export function evidenceEntry(raw: unknown): EvidenceEntry | undefined {
115
115
  const family = closedId(e.reviewerFamily);
116
116
  if (family) out.reviewerFamily = family;
117
117
  const cost = text(e.reviewCost), findings = text(e.reviewFindings);
118
- if (typeof cost?.head === "string" && /^[0-9a-f]{40}$/.test(cost.head)) out.requestHead = cost.head;
118
+ const requestedHead = e.event === "done" ? e.requestHead ?? cost?.head ?? text(e.specReport)?.head : undefined;
119
+ if (typeof requestedHead === "string" && /^[0-9a-f]{40}$/.test(requestedHead)) out.requestHead = requestedHead;
119
120
  const planned = member(PLANNED_SCOPES, text(cost?.review)?.scope);
120
121
  if (planned) out.plannedScope = planned;
121
122
  if (typeof findings?.head === "string" && /^[0-9a-f]{40}$/.test(findings.head)) out.verdictHead = findings.head;
@@ -9,6 +9,7 @@ import { childEnv } from "./child-process.ts";
9
9
  import { hubHome, realPath } from "./project.ts";
10
10
  import { readProjectRuntimeReference, projectRuntimeFile } from "./project-runtime-state.ts";
11
11
  import { Registry, REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
12
+ import { anyRecoveryHold, retireOperation } from "./recovery-store.ts";
12
13
 
13
14
  export interface RuntimeCapturePrunePlan { remove: string[]; kept: string[]; deferred?: string }
14
15
  export interface RuntimeCapturePruneResult { removed: string[]; kept: string[]; quarantined?: string[]; deferred?: string }
@@ -24,6 +25,13 @@ const MAX_INVENTORY_BYTES = 16 * 1024 * 1024;
24
25
  // ponytail: larger inventories defer; upgrade to indexed/batched reference inventory, never larger lock/busy limits.
25
26
  const MAX_PROJECTS = 128, MAX_RECEIPTS = 128, MAX_CAPTURE_ENTRIES = 512, MAX_REFERENCE_FILES = 512;
26
27
  const LOCK_METADATA_MS = 250;
28
+ /** #1541: finished receipts the hub keeps (newest first), and the extra newest-per-selected-runtime ones; both stay far below MAX_RECEIPTS. */
29
+ export const RETAINED_TERMINAL_RECEIPTS = 32, RETAINED_SELECTED_RECEIPTS = 64;
30
+ // ponytail: one pass retires at most this many receipts and reads at most this many directory entries; a larger backlog drains over later passes.
31
+ const MAX_RETIRED_PER_PASS = 256, MAX_RECEIPT_SCAN_ENTRIES = 4096, MAX_RECEIPT_BYTES = 1024 * 1024, MAX_RECEIPT_SCAN_BYTES = 64 * 1024 * 1024;
32
+ const RUNNER_DB = /^[a-f0-9-]{36}\.json\.runner\.db$/;
33
+ /** What a deferral for the receipt ceiling starts with; doctor keys on it to add the retention rule. */
34
+ export const RECEIPT_CEILING_REASON = `recovery receipts exceed the ${MAX_RECEIPTS} receipt safety ceiling`;
27
35
  export const RUNTIME_PRUNE_MAX_BATCH = 3;
28
36
  export const RUNTIME_PRUNE_INTERVAL_MS = 60 * 60 * 1000;
29
37
  const RUNTIME_PRUNE_ADMISSION_BUSY_TIMEOUT_MS = 1;
@@ -166,14 +174,15 @@ function observeReferences(home: string, registry: Registry): Observation {
166
174
  observeDatabase(locks, observation, db => { if (db.query("SELECT 1 FROM project_locks LIMIT 1").get()) fail("project recovery coordination is present"); });
167
175
  }
168
176
  let receipts = 0;
169
- for (const entry of entries(recovery, observation)) {
177
+ const rows = entries(recovery, observation);
178
+ for (const entry of rows) {
170
179
  if (!entry.name.endsWith(".json")) continue;
171
- if (++receipts > MAX_RECEIPTS) fail("recovery receipt inventory exceeds its bound");
180
+ if (++receipts > MAX_RECEIPTS) fail(receiptCeilingRefusal(recovery, rows));
172
181
  if (OPERATION.exec(entry.name)?.[0] !== entry.name || !entry.isFile() || entry.isSymbolicLink()) fail("recovery receipt inventory is invalid");
173
182
  const record = metadata(join(recovery, entry.name), observation);
174
183
  if (!object(record) || ![1, 2, 3].includes(record.schema as number) || `${record.id}.json` !== entry.name
175
184
  || !["pending", "running", "blocked", "completed", "cancelled"].includes(record.phase as string)) fail("recovery receipt inventory is invalid");
176
- if (record.phase !== "completed" && record.phase !== "cancelled") fail("a retained recovery operation is not terminal");
185
+ if (record.phase !== "completed" && record.phase !== "cancelled") fail(`a retained recovery operation is not terminal: run ahub recovery status ${record.id}, then resume or abort it`);
177
186
  if (!object(record.plan) || !Array.isArray(record.plan.projects) || !Array.isArray(record.projects)
178
187
  || record.plan.projects.length !== record.projects.length || !["restart", "upgrade"].includes(record.plan.kind as string)
179
188
  || typeof record.plan.sourceDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.plan.sourceDigest)) fail("retained recovery runtime references are incomplete");
@@ -191,6 +200,21 @@ function observeReferences(home: string, registry: Registry): Observation {
191
200
  }
192
201
  return observation;
193
202
  }
203
+ /** AC4: the cause and a supported command. Only open receipts can hold the count above the ceiling, so name the first one found. */
204
+ function receiptCeilingRefusal(recovery: string, rows: Dirent[]): string {
205
+ const scratch: Observation = { files: new Map(), lists: new Map(), projects: "", roots: new Set(), bytes: 0 };
206
+ let first: string | undefined;
207
+ for (const row of rows) {
208
+ if (!row.name.endsWith(".json") || !OPERATION.test(row.name)) continue;
209
+ try {
210
+ const record = metadata(join(recovery, row.name), scratch);
211
+ if (object(record) && record.phase !== "completed" && record.phase !== "cancelled") { first = row.name.slice(0, -".json".length); break; }
212
+ } catch { /* an unreadable receipt is reported by the generic refusal below */ }
213
+ }
214
+ const next = first ? `run ahub recovery status ${first}, then ahub recovery resume ${first} or ahub recovery abort ${first}`
215
+ : "no open receipt was found, so the next maintenance pass (after a hub start, at most hourly) removes the finished ones; ahub recovery status <operation-id> shows one the hub keeps";
216
+ return `${RECEIPT_CEILING_REASON}: the hub keeps open receipts and removes finished ones itself; ${next}`;
217
+ }
194
218
  function validateObservation(registry: Registry, observation: Observation, budget: LockBudget): void {
195
219
  tick(budget);
196
220
  if (JSON.stringify(registry.list()) !== observation.projects) fail("project runtime registry changed before pruning");
@@ -269,6 +293,92 @@ function openRegistry(home: string): { home: string; registry: Registry } {
269
293
  const deferred = (error: unknown): string => `runtime capture pruning deferred: ${error instanceof Error ? error.message : "inventory unavailable"}`;
270
294
  function checkRetention(keepNewest: number): void { if (!Number.isSafeInteger(keepNewest) || keepNewest < 0) fail("runtime capture retention must be a nonnegative integer"); }
271
295
 
296
+ interface ReceiptRow { name: string; id: string; at: number; roots: string[] }
297
+ function receiptRoot(value: unknown): string | undefined {
298
+ if (typeof value !== "string" || !isAbsolute(value) || value.includes(String.fromCharCode(0))) return undefined;
299
+ try { return realPath(value); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; return resolve(value); }
300
+ }
301
+ function readReceipt(file: string, budget: { bytes: number }): unknown {
302
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
303
+ try {
304
+ const info = fstatSync(fd);
305
+ if (!info.isFile() || info.nlink !== 1 || info.size > MAX_RECEIPT_BYTES || budget.bytes + info.size > MAX_RECEIPT_SCAN_BYTES) return undefined;
306
+ const bytes = Buffer.alloc(info.size), count = readSync(fd, bytes, 0, info.size, 0);
307
+ if (count !== info.size) return undefined;
308
+ budget.bytes += count;
309
+ try { return JSON.parse(bytes.toString("utf8")); } catch { return undefined; }
310
+ } finally { closeSync(fd); }
311
+ }
312
+ const terminalReceipt = (record: unknown, name: string): record is Record<string, unknown> =>
313
+ object(record) && [1, 2, 3].includes(record.schema as number) && `${record.id}.json` === name && OPERATION.test(name) && (record.phase === "completed" || record.phase === "cancelled");
314
+ /** Runtime roots a registered project's runtime.json (or the live manager) selects, canonical; undefined when any of them cannot be read, which stops retention. */
315
+ function selectedRuntimeRoots(home: string, registry: Registry): string[] | undefined {
316
+ try {
317
+ const roots: string[] = [], projects = registry.list();
318
+ if (projects.length > MAX_PROJECTS) return undefined;
319
+ for (const project of projects) { const runtime = readProjectRuntimeReference(project); if (runtime) roots.push(realPath(runtime.root)); }
320
+ const manager = managerRuntimeRoot(home, { files: new Map(), lists: new Map(), projects: "", roots: new Set(), bytes: 0 });
321
+ if (manager) roots.push(manager);
322
+ return roots;
323
+ } catch { return undefined; }
324
+ }
325
+ /**
326
+ * #1541: the hub's own retention rule for finished recovery receipts. Keeps every receipt that is not terminal, the newest
327
+ * RETAINED_TERMINAL_RECEIPTS terminal ones, and the newest RETAINED_SELECTED_RECEIPTS terminal ones that name a runtime a
328
+ * registered project (or the live manager) still selects. The rest leave with their `.runner.db` through
329
+ * `retireOperation` (the exclusive runner claim, never check-then-unlink). The captures themselves stay protected by
330
+ * runtime.json, not by a receipt, so retention never releases one a project selects. Skips everything while any recovery hold exists.
331
+ */
332
+ export function retireTerminalReceipts(home: string, registry: Registry, hooks: { betweenPair?: () => void } = {}): number {
333
+ const recovery = join(home, "recovery");
334
+ if (!directory(recovery) || anyRecoveryHold(home)) return 0;
335
+ const selected = selectedRuntimeRoots(home, registry);
336
+ if (!selected) return 0;
337
+ const names: string[] = [], handle = opendirSync(recovery);
338
+ try {
339
+ for (;;) {
340
+ const entry = handle.readSync(); if (!entry) break;
341
+ if (names.length >= MAX_RECEIPT_SCAN_ENTRIES) return 0;
342
+ if (entry.isFile() && (entry.name.endsWith(".json") || RUNNER_DB.test(entry.name))) names.push(entry.name);
343
+ }
344
+ } finally { handle.closeSync(); }
345
+ const budget = { bytes: 0 }, terminal: ReceiptRow[] = [], receipts = new Set<string>();
346
+ for (const name of names) {
347
+ if (!name.endsWith(".json")) continue;
348
+ receipts.add(name);
349
+ let record: unknown;
350
+ try { record = readReceipt(join(recovery, name), budget); } catch { continue; }
351
+ if (!terminalReceipt(record, name)) continue; // open, unreadable or unknown receipts always stay
352
+ const roots: string[] = [];
353
+ try {
354
+ for (const value of [record.sourceRoot, object(record.plan) ? record.plan.sourceRoot : undefined, record.targetRoot]) { const root = receiptRoot(value); if (root) roots.push(root); }
355
+ } catch { continue; }
356
+ const at = Number.isFinite(record.updatedAt) ? record.updatedAt as number : Number.isFinite(record.createdAt) ? record.createdAt as number : 0;
357
+ terminal.push({ name, id: record.id as string, at, roots });
358
+ }
359
+ terminal.sort((a, b) => b.at - a.at || b.id.localeCompare(a.id));
360
+ const keep = new Set(terminal.slice(0, RETAINED_TERMINAL_RECEIPTS).map(row => row.name));
361
+ let extra = 0;
362
+ for (const row of terminal) {
363
+ if (extra >= RETAINED_SELECTED_RECEIPTS) break;
364
+ if (keep.has(row.name) || !selected.some(root => row.roots.some(own => contains(root, own) || contains(own, root)))) continue;
365
+ keep.add(row.name); extra++;
366
+ }
367
+ let retired = 0;
368
+ for (const row of terminal) {
369
+ if (keep.has(row.name)) continue;
370
+ if (retired >= MAX_RETIRED_PER_PASS) break;
371
+ const outcome = retireOperation(row.id, home, record => terminalReceipt(record, row.name), hooks);
372
+ if (outcome === "retired") retired++;
373
+ }
374
+ // A runner db whose receipt is gone (an interrupted earlier pass) is settled through the same claim; a live claim keeps it.
375
+ for (const name of names) {
376
+ const receipt = name.replace(/\.runner\.db$/, "");
377
+ if (RUNNER_DB.test(name) && !receipts.has(receipt) && retired < MAX_RETIRED_PER_PASS && retireOperation(receipt.slice(0, -".json".length), home, () => false, hooks) === "retired") retired++;
378
+ }
379
+ return retired;
380
+ }
381
+
272
382
  /** Metadata preview only; execution always refreshes reference observations before quarantining each candidate. */
273
383
  export function planRuntimeCapturePrune(home = hubHome(), keepNewest = 3): RuntimeCapturePrunePlan {
274
384
  let registry: Registry | undefined;
@@ -283,6 +393,7 @@ export function pruneRuntimeCaptures(home = hubHome(), keepNewest = 3): RuntimeC
283
393
  const removed: string[] = [], quarantined: string[] = []; let kept: string[] = [], registry: Registry | undefined;
284
394
  try {
285
395
  checkRetention(keepNewest); const opened = openRegistry(home); registry = opened.registry; home = opened.home;
396
+ retireTerminalReceipts(home, registry);
286
397
  const initial = lockedPlan(home, registry, observeReferences(home, registry), keepNewest); kept = initial.plan.kept;
287
398
  // Reject unknown layouts across the small batch before moving any entry; no package contents are hashed here.
288
399
  for (const root of initial.plan.remove) captureLayout(root);
@@ -4,12 +4,14 @@ import { isAbsolute, join, normalize } from "node:path";
4
4
  import { processLiveness } from "../pi/process-signature.ts";
5
5
  import { hubHome } from "./project.ts";
6
6
  import { REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
7
- import { RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
7
+ import { RETAINED_SELECTED_RECEIPTS, RETAINED_TERMINAL_RECEIPTS, RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
8
8
 
9
9
  export interface RuntimePruneHealthCheck { ok: boolean | undefined; name: string; detail: string }
10
10
  const MAX_LEDGER_BYTES = 1024 * 1024, MAX_OUTCOME_BYTES = 16 * 1024;
11
11
  const MAX_SCAN_ENTRIES = 1024, MAX_QUARANTINES = 64, SCAN_MS = 250;
12
12
  const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
13
+ /** #1541: the one retention rule, as docs/operations.md states it. */
14
+ export const RECEIPT_RETENTION_RULE = `Retention: maintenance keeps every open recovery receipt, the newest ${RETAINED_TERMINAL_RECEIPTS} finished ones and up to ${RETAINED_SELECTED_RECEIPTS} finished ones naming a runtime a project still selects, and removes older finished ones with their runner database itself`;
13
15
  const columns = "slot,id,admitted_at,phase,pid,outcome";
14
16
  const issue = (detail: string, ok: boolean | undefined = undefined): RuntimePruneHealthCheck => ({ ok, name: "runtime pruning", detail });
15
17
  const info = (file: string): Stats | undefined => {
@@ -63,7 +65,9 @@ function admissionHealth(file: string): LedgerHealth {
63
65
  || outcome.quarantined.some(value => typeof value !== "string" || value.length > 4096 || isAbsolute(value) || normalize(value) !== value || value.split(/[\\/]/).some(part => part === ".."))
64
66
  || outcome.deferred !== undefined && (typeof outcome.deferred !== "string" || Buffer.byteLength(outcome.deferred) > 512)) throw new Error("invalid completed outcome");
65
67
  if (outcome.deferred !== undefined || outcome.quarantined.length) {
66
- const detail = typeof outcome.deferred === "string" ? `maintenance deferred: ${outcome.deferred.replace(/[\x00-\x1f\x7f]/g, " ")}; inspect ${file}` : `maintenance retained quarantine paths; inspect ${file}`;
68
+ // #1541: a deferral that already names a supported command (the receipt ceiling, an open operation) is not sent to the ledger.
69
+ const text = typeof outcome.deferred === "string" ? outcome.deferred.replace(/[\x00-\x1f\x7f]/g, " ") : undefined;
70
+ const detail = text !== undefined ? `maintenance deferred: ${text}${text.includes("ahub recovery") ? `. ${RECEIPT_RETENTION_RULE}` : `; inspect ${file}`}` : `maintenance retained quarantine paths; inspect ${file}`;
67
71
  return { active: false, checks: [issue(detail, false)] };
68
72
  }
69
73
  return { checks: [], active: false };
@@ -14,7 +14,7 @@ export type BandTier = typeof BAND_TIERS[number];
14
14
  export interface MetricTask {
15
15
  id: number;
16
16
  private?: boolean;
17
- /** `evidenceOnly` marks a code-scope verdict with no open finding (#852): it is not a rework round. `requestHead` is the head a `done` asked review for (reviewCost.head); `verdictHead` the head a verdict was bound to (reviewFindings.head). Compared for equality only, never printed. */
17
+ /** `evidenceOnly` marks a code-scope verdict with no open finding (#852): it is not a rework round. `requestHead` is the head a `done` asked review for (requestHead, with historical fallbacks); `verdictHead` the head a verdict was bound to (reviewFindings.head). Compared for equality only, never printed. */
18
18
  history: { at: number; event: string; requestHead?: string; verdictHead?: string; evidenceOnly?: true }[];
19
19
  }
20
20
 
@@ -84,7 +84,7 @@ const VERDICTS = ["approved", "changes_requested"];
84
84
  * Review rounds whose verdict was bound to a different head than the review was requested for: the head moved while the review ran.
85
85
  * Known only for a round with both heads recorded; a task with no such round is unknown, never 0. (A `done` after an `approved` is not
86
86
  * evidence: the board cannot produce one.)
87
- * ponytail: the request head is `reviewCost.head` (the commit the done named first) while a verdict's head prefers the lifecycle receipt's
87
+ * ponytail: the request head is the commit recorded for the done while a verdict's head prefers the lifecycle receipt's
88
88
  * `head`/`localHead` over `refs.commit` (`findingHead`), so a receipt head that differs from the commit can read as stale. Ceiling: a
89
89
  * spurious stale round for a task whose receipt head and commit disagree; the upgrade is one shared head rule for both sides.
90
90
  */
@@ -58,6 +58,7 @@ const perClass = (name: TaskClass): SettingDef[] => [
58
58
  { key: `routing.classes.${name}.pi_backend`, group: "Routing", label: `${name}: Pi backend`, type: "enum", values: ["dgx", "mlx"], store: "routing", applies: "live", risk: "raises", path: ["classes", name, "pi_backend"] },
59
59
  ];
60
60
  export const SETTINGS: readonly SettingDef[] = [
61
+ { key: "memory.sync_interval_min", group: "Switches", label: "Memory sync interval in minutes (0 disables)", type: "integer", min: 0, max: 1440, store: "config", applies: "live", risk: "raises", path: ["memory", "sync_interval_min"] },
61
62
  ...["enabled", "auto_reassign"].map((key): SettingDef => ({ key: `task_sweep.${key}`, group: "Switches", label: `Task sweep: ${key}`, type: "boolean", store: "config", applies: "live", risk: "raises", floor: false, path: ["task_sweep", key] })),
62
63
  { key: "task_sweep.no_writes_turns", group: "Switches", label: "Consecutive owner turns without writes (0 disables)", type: "integer", min: 0, max: Number.MAX_SAFE_INTEGER, store: "config", applies: "live", risk: "raises", path: ["task_sweep", "no_writes_turns"] },
63
64
  ...["interval_s", "unaccepted_min", "idle_min", "review_min", "ready_min", "ladder_min"].map((key): SettingDef => ({ key: `task_sweep.${key}`, group: "Switches", label: `Task sweep: ${key}`, type: "number", min: 1, max: 2_147_483_647 / (key === "interval_s" ? 1000 : 60_000), store: "config", applies: "live", risk: "raises", path: ["task_sweep", key] })),
@@ -193,6 +194,7 @@ export function checkSettingValue(def: SettingDef, raw: unknown, routes: readonl
193
194
  if (def.store === "runtime") throw new Error(`${def.key} has no stored value to remove`);
194
195
  return null;
195
196
  }
197
+ if (def.key === "memory.sync_interval_min" && (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0 || raw > 1440)) throw new Error("memory.sync_interval_min must be 0 (off) or a whole number of minutes up to 1440");
196
198
  if (def.type === "number-or-off" && raw === "off") return raw;
197
199
  if (def.type === "integer" || def.type === "number" || def.type === "number-or-off") {
198
200
  if (typeof raw !== "number" || !(def.type === "integer" ? Number.isSafeInteger(raw) : Number.isFinite(raw)) || raw < (def.min ?? 0) || raw > (def.max ?? Number.MAX_SAFE_INTEGER)) throw new Error(`${def.key} takes ${def.type === "integer" ? "an integer" : def.type === "number-or-off" ? "off or a finite number" : "a number"} from ${def.min ?? 0} to ${def.max ?? Number.MAX_SAFE_INTEGER}`);