bailinghub 0.9.1 → 0.9.3

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 (115) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/CHANGELOG.en.md +23 -1
  5. package/docs/CHANGELOG.md +23 -1
  6. package/docs/CORE_RELIABILITY.en.md +79 -0
  7. package/docs/CORE_RELIABILITY.md +79 -0
  8. package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
  9. package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
  10. package/docs/IMPLEMENTATION_STATUS.en.md +27 -15
  11. package/docs/IMPLEMENTATION_STATUS.md +27 -15
  12. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  13. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  14. package/docs/KERNEL_HOST_API.en.md +2 -0
  15. package/docs/KERNEL_HOST_API.md +2 -0
  16. package/docs/MODEL_BILLING.en.md +4 -0
  17. package/docs/MODEL_BILLING.md +4 -0
  18. package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
  19. package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
  20. package/docs/OPERATIONS.en.md +13 -0
  21. package/docs/OPERATIONS.md +12 -0
  22. package/docs/README.en.md +7 -0
  23. package/docs/README.md +7 -0
  24. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  25. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  26. package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
  27. package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
  28. package/docs/TOOLS_DESIGN.md +1 -0
  29. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  30. package/docs/UPGRADE_v0.9.2.md +62 -0
  31. package/docs/UPGRADE_v0.9.3.en.md +63 -0
  32. package/docs/UPGRADE_v0.9.3.md +63 -0
  33. package/package.json +7 -3
  34. package/scripts/check-doc-links.mjs +4 -0
  35. package/scripts/check-image-tags.sh +1 -1
  36. package/scripts/check-release-consistency.test.mjs +2 -2
  37. package/scripts/doctor-deployment.test.ts +419 -0
  38. package/scripts/doctor-deployment.ts +357 -0
  39. package/scripts/doctor.ts +8 -1
  40. package/scripts/install-secrets.test.mjs +185 -0
  41. package/scripts/install.sh +10 -6
  42. package/scripts/publish-images.sh +1 -1
  43. package/scripts/release-audit.mjs +8 -0
  44. package/scripts/verify-github-repo.mjs +8 -0
  45. package/security/dependency-audit-exceptions.json +1 -1
  46. package/sql/065_usage_reconciliation_scan.sql +4 -0
  47. package/sql/066_approval_continuations.sql +15 -0
  48. package/sql/067_delivery_dlq_replay.sql +10 -0
  49. package/sql/README.en.md +6 -0
  50. package/sql/README.md +15 -0
  51. package/src/adapters/llm/file.test.ts +59 -0
  52. package/src/adapters/llm/file.ts +11 -4
  53. package/src/app/agent-tool-invocations.test.ts +3 -1
  54. package/src/app/approval-continuations.mysql.test.ts +138 -0
  55. package/src/app/approval-continuations.test.ts +351 -0
  56. package/src/app/approval-continuations.ts +148 -0
  57. package/src/app/channels-attachments.test.ts +63 -0
  58. package/src/app/channels.ts +7 -4
  59. package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
  60. package/src/app/delivery-dlq-replay.test.ts +75 -0
  61. package/src/app/delivery-dlq-replay.ts +41 -0
  62. package/src/app/delivery.ts +3 -2
  63. package/src/app/http-server.ts +3 -0
  64. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  65. package/src/app/kernel-notification-lifecycle.test.ts +49 -0
  66. package/src/app/kernel.ts +22 -0
  67. package/src/app/notification-outbound.test.ts +53 -0
  68. package/src/app/operational-metrics.test.ts +37 -1
  69. package/src/app/operational-metrics.ts +25 -2
  70. package/src/app/outbound.ts +13 -2
  71. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  72. package/src/app/runtime-lifecycle-default.ts +7 -0
  73. package/src/app/runtime-lifecycle.test.ts +89 -0
  74. package/src/app/runtime-lifecycle.ts +52 -11
  75. package/src/app/tool-approvals.ts +2 -1
  76. package/src/core/contracts/approval-continuation.ts +43 -0
  77. package/src/core/contracts/delivery-replay.ts +41 -0
  78. package/src/core/contracts/tools-idempotency.test.ts +121 -5
  79. package/src/core/contracts/tools.ts +21 -11
  80. package/src/core/contracts/types.ts +4 -0
  81. package/src/core/observability/openmetrics.test.ts +28 -0
  82. package/src/core/observability/openmetrics.ts +91 -0
  83. package/src/core/platform/http-body.test.ts +185 -0
  84. package/src/core/platform/http-body.ts +58 -0
  85. package/src/core/runtime/finish-runtime.test.ts +2 -0
  86. package/src/core/runtime/finish-runtime.ts +10 -7
  87. package/src/core/runtime/notification-background-work.test.ts +50 -0
  88. package/src/core/runtime/notification-background-work.ts +101 -0
  89. package/src/core/state/approval-continuation.ts +22 -0
  90. package/src/core/state/delivery-replay.ts +19 -0
  91. package/src/core/state/state-codec.ts +2 -0
  92. package/src/core/state/state-contracts.ts +6 -0
  93. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  94. package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
  95. package/src/infrastructure/config/configstore.ts +4 -3
  96. package/src/infrastructure/state/state-jsonl.ts +56 -11
  97. package/src/infrastructure/state/state-mysql.ts +54 -0
  98. package/src/modules/usage/background-work.test.ts +28 -0
  99. package/src/modules/usage/background-work.ts +43 -7
  100. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  101. package/src/modules/usage/billing-reconciliation.test.ts +85 -0
  102. package/src/modules/usage/billing-repository.ts +63 -11
  103. package/src/modules/usage/maintenance.test.ts +78 -0
  104. package/src/modules/usage/maintenance.ts +39 -0
  105. package/src/modules/usage/model-gateway.ts +2 -1
  106. package/src/routes/admin-default.ts +2 -2
  107. package/src/routes/admin-runtime-default.ts +2 -2
  108. package/src/routes/admin-runtime.test.ts +1 -1
  109. package/src/routes/admin-runtime.ts +39 -18
  110. package/src/routes/admin.ts +1 -1
  111. package/src/routes/approvals-default.ts +2 -2
  112. package/src/routes/approvals.ts +30 -33
  113. package/src/routes/critical-routes.test.ts +16 -3
  114. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  115. package/src/test-support/model-process-crash-child.ts +78 -0
@@ -4,11 +4,16 @@ import {
4
4
  renderOperationalMetrics,
5
5
  type CollectorResult,
6
6
  type ControlPlaneOperationalMetricsSnapshot,
7
+ type BackgroundWorkMetricsSnapshot,
8
+ type RuntimeMaintenanceMetricsSnapshot,
7
9
  } from '../core/observability/openmetrics';
8
10
  import { buildVersionInfo } from '../core/platform/version';
9
11
  import type { AuditFailureTracker } from '../core/state/audit-observability';
10
12
  import type { JobOperationalMetricsSnapshot, RuntimeStateStore } from '../core/state/state-contracts';
11
13
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
14
+ import { usageReconciliationSnapshotFor } from '../modules/usage/billing-repository';
15
+ import { usageMaintenanceSnapshotFor } from '../modules/usage/maintenance';
16
+ import { approvalContinuationMaintenanceSnapshotFor } from './approval-continuations';
12
17
 
13
18
  export interface OperationalMetricsEndpoint {
14
19
  readonly enabled: boolean;
@@ -23,6 +28,7 @@ export interface OperationalMetricsDeps {
23
28
  queue: { stats(): { running: number; waiting: number } };
24
29
  isPaused(): boolean;
25
30
  auditFailures: Pick<AuditFailureTracker, 'snapshot'>;
31
+ notificationWork?: { snapshot(nowMs?: number): BackgroundWorkMetricsSnapshot };
26
32
  logger?: Pick<Console, 'error'>;
27
33
  now?: () => number;
28
34
  build?: { version: string; commit: string };
@@ -51,7 +57,7 @@ function buildIdentity(root: string): { version: string; commit: string } {
51
57
  }
52
58
 
53
59
  async function collect<T>(
54
- collector: 'state' | 'control_plane',
60
+ collector: 'state' | 'control_plane' | 'maintenance',
55
61
  action: (() => Promise<T>) | undefined,
56
62
  timeoutMs: number,
57
63
  logger: Pick<Console, 'error'>,
@@ -96,7 +102,7 @@ export function createOperationalMetricsEndpointFor(deps: OperationalMetricsDeps
96
102
  async scrape(): Promise<string> {
97
103
  const startedAt = now();
98
104
  const snapshotAt = now();
99
- const [state, controlPlane] = await Promise.all([
105
+ const [state, controlPlane, maintenance] = await Promise.all([
100
106
  collect<JobOperationalMetricsSnapshot>(
101
107
  'state',
102
108
  stateCollector ? () => stateCollector(snapshotAt) : undefined,
@@ -109,6 +115,22 @@ export function createOperationalMetricsEndpointFor(deps: OperationalMetricsDeps
109
115
  deps.cfg.metrics.scrapeTimeoutMs,
110
116
  logger,
111
117
  ),
118
+ collect<RuntimeMaintenanceMetricsSnapshot>(
119
+ 'maintenance',
120
+ async () => {
121
+ const usage = deps.configStore?.usage;
122
+ const approval = approvalContinuationMaintenanceSnapshotFor({ configStore: deps.configStore, stateStore: deps.store }, snapshotAt);
123
+ return {
124
+ capturedAtMs: snapshotAt,
125
+ ...(usage ? { usage: usage.backgroundWork.snapshot(snapshotAt), usageReconciliation: usageReconciliationSnapshotFor(usage),
126
+ usageRetry: usageMaintenanceSnapshotFor(usage) } : {}),
127
+ ...(deps.notificationWork ? { notification: deps.notificationWork.snapshot(snapshotAt) } : {}),
128
+ ...(approval ? { approval: approval.work, approvalReconciliation: approval.progress } : {}),
129
+ };
130
+ },
131
+ deps.cfg.metrics.scrapeTimeoutMs,
132
+ logger,
133
+ ),
112
134
  ]);
113
135
  return renderOperationalMetrics({
114
136
  ...build,
@@ -116,6 +138,7 @@ export function createOperationalMetricsEndpointFor(deps: OperationalMetricsDeps
116
138
  queue: deps.queue.stats(),
117
139
  state,
118
140
  controlPlane,
141
+ maintenance,
119
142
  auditWriteFailuresTotal: deps.auditFailures.snapshot().total,
120
143
  scrapeDurationSeconds: Math.max((now() - startedAt) / 1000, 0),
121
144
  });
@@ -9,6 +9,7 @@ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
9
  import type { RuntimeStateStore } from '../core/state/state-contracts';
10
10
  import type { AppConfig } from '../core/config/config';
11
11
  import { requireServerToken } from '../core/platform/server-token';
12
+ import { notificationBackgroundWorkFor, type NotificationBackgroundKind } from '../core/runtime/notification-background-work';
12
13
 
13
14
  export { signBody };
14
15
 
@@ -63,7 +64,13 @@ export async function secretForJobWithDeps(deps: Pick<OutboundRuntimeDeps, 'cfg'
63
64
  }
64
65
 
65
66
  const OUTBOUND_BACKOFF_MS = [0, 2000, 10_000]; // 共 3 次尝试
66
- export async function postSignedWithDeps(deps: Pick<OutboundRuntimeDeps, 'stateStore' | 'now' | 'sleep' | 'fetch'>, url: string, payload: unknown, secret: string, audit: { job_id: string; request_id: string; event: string }): Promise<boolean> {
67
+ export function postSignedWithDeps(deps: Pick<OutboundRuntimeDeps, 'stateStore' | 'now' | 'sleep' | 'fetch'>, url: string, payload: unknown, secret: string, audit: { job_id: string; request_id: string; event: string }): Promise<boolean> {
68
+ const kind: NotificationBackgroundKind = audit.event.startsWith('approval_') ? 'approval-notification'
69
+ : audit.event.startsWith('alert') ? 'alert' : audit.event === 'callback' ? 'callback' : 'delivery';
70
+ return notificationBackgroundWorkFor(deps.stateStore).track(kind, () => postSignedInner(deps, url, payload, secret, audit), sent => !sent);
71
+ }
72
+
73
+ async function postSignedInner(deps: Pick<OutboundRuntimeDeps, 'stateStore' | 'now' | 'sleep' | 'fetch'>, url: string, payload: unknown, secret: string, audit: { job_id: string; request_id: string; event: string }): Promise<boolean> {
67
74
  const body = JSON.stringify(payload);
68
75
  for (let i = 0; i < OUTBOUND_BACKOFF_MS.length; i++) {
69
76
  if (OUTBOUND_BACKOFF_MS[i]! > 0) await deps.sleep(OUTBOUND_BACKOFF_MS[i]!);
@@ -101,7 +108,11 @@ export async function fireCallbackWithDeps(deps: OutboundRuntimeDeps, url: strin
101
108
  // 渠道规则使用 channelSend 直推(复用渠道凭证),通用 webhook 使用签名 HTTP 直发;
102
109
  // 两种出口都不创建需要执行器认领的任务,避免告警链路因执行器离线而积压。
103
110
  const alertSentAtByStore = new WeakMap<RuntimeStateStore, Map<string, number>>();
104
- export async function sendAlertWithDeps(deps: OutboundRuntimeDeps, key: string, text: string): Promise<void> {
111
+ export function sendAlertWithDeps(deps: OutboundRuntimeDeps, key: string, text: string): Promise<void> {
112
+ return notificationBackgroundWorkFor(deps.stateStore).track('alert', () => sendAlertInner(deps, key, text));
113
+ }
114
+
115
+ async function sendAlertInner(deps: OutboundRuntimeDeps, key: string, text: string): Promise<void> {
105
116
  const rules = deps.configStore ? await deps.configStore.alertRules.matching(key).catch(() => []) : [];
106
117
  const a = deps.cfg.alerts;
107
118
  const webhookUrl = (a && a.type === 'webhook' && a.url) ? a.url : '';
@@ -0,0 +1,55 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import type { AppConfig } from '../core/config/config';
4
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
5
+ import { startRuntimeSchedulersFor, type RuntimeLifecycleDeps } from './runtime-lifecycle';
6
+
7
+ function deps(reconcileApprovalContinuations: () => Promise<void>): RuntimeLifecycleDeps {
8
+ return {
9
+ cfg: { auditRetentionDays: 0 } as AppConfig,
10
+ configStore: null, stateStore: {} as RuntimeStateStore,
11
+ kbService: null, kbSync: null, toolIndex: null,
12
+ isPaused: () => false, refreshTargets: async () => {},
13
+ kickInhubScheduler() {}, drainInhubScheduler: async () => 0,
14
+ recoverInhubJobs: async () => 0,
15
+ now: () => new Date(0).toISOString(), sleep: async () => {},
16
+ reconcileApprovalContinuations,
17
+ };
18
+ }
19
+
20
+ test('standalone stop preserves unfinished evidence writes across drain timeout and retry', async (t) => {
21
+ let release!: () => void;
22
+ const gate = new Promise<void>(resolve => { release = resolve; });
23
+ let started!: () => void;
24
+ const firstPass = new Promise<void>(resolve => { started = resolve; });
25
+ let calls = 0;
26
+ let completed = false;
27
+ const schedulers = startRuntimeSchedulersFor(deps(async () => {
28
+ calls++; started(); await gate; completed = true;
29
+ }));
30
+ t.after(() => { schedulers.stop(); release(); });
31
+ // The scheduler's timer is unref'ed; a bounded guard keeps this test alive.
32
+ let guard: ReturnType<typeof setTimeout> | undefined;
33
+ try {
34
+ await Promise.race([firstPass, new Promise<never>((_, reject) => {
35
+ guard = setTimeout(() => reject(new Error('first evidence pass did not start')), 1_000);
36
+ })]);
37
+ } finally { if (guard) clearTimeout(guard); }
38
+ schedulers.stop();
39
+ assert.equal(await schedulers.drain!(1), false);
40
+ assert.equal(completed, false, 'a timeout must not treat a pending write as drained');
41
+ assert.equal(await schedulers.drain!(1), false, 'a retry still observes the original pending write');
42
+ release();
43
+ assert.equal(await schedulers.drain!(1_000), true);
44
+ assert.equal(completed, true);
45
+ assert.equal(calls, 1);
46
+ });
47
+
48
+ test('standalone stop before the first timer admits no persisted evidence work', async () => {
49
+ let calls = 0;
50
+ const schedulers = startRuntimeSchedulersFor(deps(async () => { calls++; }));
51
+ schedulers.stop();
52
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
53
+ assert.equal(calls, 0);
54
+ assert.equal(await schedulers.drain!(1), true);
55
+ });
@@ -12,6 +12,7 @@ import {
12
12
  type RuntimeSchedulers,
13
13
  } from './runtime-lifecycle';
14
14
  import { bootstrapInitialAdmin } from './admin-bootstrap';
15
+ import { reconcileApprovalContinuationsFor } from './approval-continuations';
15
16
 
16
17
  export function defaultRuntimeLifecycleDeps(): RuntimeLifecycleDeps {
17
18
  return {
@@ -29,6 +30,12 @@ export function defaultRuntimeLifecycleDeps(): RuntimeLifecycleDeps {
29
30
  now,
30
31
  sleep,
31
32
  targetRegistry,
33
+ reconcileApprovalContinuations: async () => {
34
+ await reconcileApprovalContinuationsFor({
35
+ configStore: cfgStore, stateStore: store,
36
+ engineRuntime: { kickInhubScheduler }, now,
37
+ });
38
+ },
32
39
  afterStoresInitialized: async () => {
33
40
  await bootstrapInitialAdmin(cfg.bootstrapAdmin, { admins: cfgStore?.admins ?? null });
34
41
  },
@@ -5,6 +5,7 @@ import type { ToolProvider } from '../core/contracts/types';
5
5
  import type { RuntimeStateStore } from '../core/state/state-contracts';
6
6
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
7
  import type { ToolIndexService } from '../services/tools-index';
8
+ import { notificationBackgroundWorkFor } from '../core/runtime/notification-background-work';
8
9
  import {
9
10
  createManagedRuntimeMaintenanceFor,
10
11
  createManagedRuntimeMaintenanceStateV1,
@@ -32,6 +33,94 @@ function toolProvider(name: string, input: Partial<ToolProvider> = {}): ToolProv
32
33
  };
33
34
  }
34
35
 
36
+ interface CapturedTimer { fire(): void; ms: number; interval: boolean; unref(): void }
37
+ async function withCapturedTimers<T>(action: (timers: CapturedTimer[]) => Promise<T>): Promise<T> {
38
+ const timers: CapturedTimer[] = [];
39
+ const originalTimeout = globalThis.setTimeout, originalInterval = globalThis.setInterval, originalClear = globalThis.clearTimeout;
40
+ const register = (interval: boolean) => ((fn: () => void, ms: number) => {
41
+ const timer: CapturedTimer = { fire: fn, ms, interval, unref() {} };
42
+ timers.push(timer); return timer;
43
+ });
44
+ globalThis.setTimeout = register(false) as unknown as typeof setTimeout;
45
+ globalThis.setInterval = register(true) as unknown as typeof setInterval;
46
+ globalThis.clearTimeout = (() => {}) as typeof clearTimeout;
47
+ try { return await action(timers); } finally {
48
+ globalThis.setTimeout = originalTimeout; globalThis.setInterval = originalInterval; globalThis.clearTimeout = originalClear;
49
+ }
50
+ }
51
+
52
+ test('standalone stop waits for a monitor producer before notification drain can release resources', async () => {
53
+ let releaseMonitor!: () => void, enteredMonitor!: () => void, enteredFetch!: () => void, releaseFetch!: () => void;
54
+ const monitorGate = new Promise<void>(resolve => { releaseMonitor = resolve; });
55
+ const monitorEntered = new Promise<void>(resolve => { enteredMonitor = resolve; });
56
+ const sendEntered = new Promise<void>(resolve => { enteredFetch = resolve; });
57
+ const sendGate = new Promise<void>(resolve => { releaseFetch = resolve; });
58
+ const stateStore = { async listJobsByStatus() { return []; }, async appendAudit() {} } as unknown as RuntimeStateStore;
59
+ const notifications = notificationBackgroundWorkFor(stateStore);
60
+ const originalFetch = globalThis.fetch;
61
+ globalThis.fetch = async () => { enteredFetch(); await sendGate; return new Response('', { status: 200 }); };
62
+ let resourcesClosed = false;
63
+ const schedulers = await withCapturedTimers(async timers => {
64
+ const target = startRuntimeSchedulersFor({
65
+ cfg: { auditRetentionDays: 0, server: { token: 'synthetic-only' }, brand: { name: 'Synthetic' },
66
+ alerts: { type: 'webhook', url: 'https://synthetic.invalid/alert', cooldown_min: 0 } } as AppConfig,
67
+ configStore: { executors: { async list() { return []; } }, alertRules: { async matching() { return []; } },
68
+ observability: { async monitorSnapshot() { enteredMonitor(); await monitorGate; return { errors_15m: 5, oldest_queued_min: 0 }; } },
69
+ } as unknown as ConfigStoreContract,
70
+ stateStore, kbService: null, kbSync: null, toolIndex: null, isPaused: () => false,
71
+ async refreshTargets() {}, kickInhubScheduler() {}, async drainInhubScheduler() { return 0; },
72
+ async recoverInhubJobs() { return 0; }, now: () => new Date().toISOString(), async sleep() {},
73
+ });
74
+ timers.find(timer => !timer.interval && timer.ms === 60000)!.fire();
75
+ await monitorEntered;
76
+ return target;
77
+ });
78
+ const closeResources = async (budget: number) => {
79
+ if (!await schedulers.drain!(budget)) return false;
80
+ notifications.beginDrain();
81
+ if (!await notifications.drain(budget)) return false;
82
+ resourcesClosed = true;
83
+ return true;
84
+ };
85
+ try {
86
+ schedulers.stop();
87
+ assert.equal(await closeResources(1), false);
88
+ assert.equal(resourcesClosed, false);
89
+ assert.equal(notifications.snapshot().draining, false, 'the producer must drain before the child tracker starts draining');
90
+ releaseMonitor(); await sendEntered;
91
+ assert.equal(await schedulers.drain!(100), true);
92
+ assert.equal(await closeResources(1), false);
93
+ assert.equal(resourcesClosed, false);
94
+ assert.ok(notifications.snapshot().kinds.find(value => value.kind === 'alert')!.inFlight > 0);
95
+ releaseFetch();
96
+ assert.equal(await closeResources(100), true);
97
+ assert.equal(resourcesClosed, true);
98
+ } finally {
99
+ releaseMonitor(); releaseFetch(); schedulers.stop();
100
+ await schedulers.drain!(100); await notifications.drain(100); globalThis.fetch = originalFetch;
101
+ }
102
+ });
103
+
104
+ test('standalone stopped callbacks cannot admit maintenance or create the recurring monitor timer', async () => {
105
+ let targetRefreshes = 0, drains = 0;
106
+ await withCapturedTimers(async timers => {
107
+ const schedulers = startRuntimeSchedulersFor({
108
+ cfg: { auditRetentionDays: 0 } as AppConfig, configStore: null,
109
+ stateStore: {} as RuntimeStateStore, kbService: null, kbSync: null, toolIndex: null,
110
+ isPaused: () => false, async refreshTargets() { targetRefreshes++; }, kickInhubScheduler() {},
111
+ async drainInhubScheduler() { drains++; return 0; }, async recoverInhubJobs() { return 0; },
112
+ now: () => new Date().toISOString(), async sleep() {},
113
+ });
114
+ const registered = timers.length;
115
+ schedulers.stop();
116
+ for (const timer of [...timers]) timer.fire();
117
+ await new Promise<void>(resolve => setImmediate(resolve));
118
+ assert.equal(timers.length, registered);
119
+ assert.equal(targetRefreshes, 0); assert.equal(drains, 0);
120
+ assert.equal(await schedulers.drain!(0), true);
121
+ });
122
+ });
123
+
35
124
  test('initializeRuntimeLifecycleFor: Store 初始化后、目标刷新前执行启动契约', async () => {
36
125
  const events: string[] = [];
37
126
  const stateStore = {
@@ -12,6 +12,7 @@ import type { KbService } from '../services/kb';
12
12
  import type { KbSyncService } from '../services/kbsync';
13
13
  import type { ToolIndexService } from '../services/tools-index';
14
14
  import { embedConfigOf } from './tool-context';
15
+ import { runUsageMaintenanceFor } from '../modules/usage/maintenance';
15
16
 
16
17
  const TARGET_REFRESH_MS = 60_000;
17
18
  const INHUB_DRAIN_MS = 500;
@@ -23,6 +24,8 @@ const REAPER_INTERVAL_MS = 60_000;
23
24
  const TOOL_CALL_CLEANUP_MS = 60 * 60 * 1000;
24
25
  const AUDIT_RETENTION_CLEANUP_MS = 6 * 60 * 60 * 1000;
25
26
  const TOOL_INDEX_PREWARM_DELAY_MS = 0;
27
+ const USAGE_MAINTENANCE_MS = 60_000;
28
+ const APPROVAL_CONTINUATION_MS = 60_000;
26
29
 
27
30
  // 兜底:定期把派发后长时间未回报的 dispatched 任务重排回队列(执行器/网络异常时不至于卡死)。
28
31
  // 阈值需大于最长任务耗时(出厂能力档上限 6min),这里取 20min。
@@ -36,6 +39,8 @@ const TOOL_CALL_RETENTION_MS = 3 * 24 * 60 * 60 * 1000;
36
39
 
37
40
  export interface RuntimeSchedulers {
38
41
  stop(): void;
42
+ /** Accepted scheduler producers must finish registering children before resources close. */
43
+ drain?(drainMs?: number): Promise<boolean>;
39
44
  }
40
45
 
41
46
  export interface RuntimeLifecycleDeps {
@@ -53,6 +58,8 @@ export interface RuntimeLifecycleDeps {
53
58
  now: () => string;
54
59
  sleep: (ms: number) => Promise<void>;
55
60
  afterStoresInitialized?: () => Promise<void>;
61
+ /** Reconcile already-decided approvals; never creates a new user decision. */
62
+ reconcileApprovalContinuations?: () => Promise<void>;
56
63
  /** 可嵌入宿主必须注入 Kernel 自己的 registry;默认实例仅服务旧 OSS 包装。 */
57
64
  targetRegistry?: TargetRegistry;
58
65
  }
@@ -117,6 +124,8 @@ async function runToolIndexPrewarmFor(deps: RuntimeLifecycleDeps): Promise<void>
117
124
  }
118
125
 
119
126
  interface RuntimeMaintenanceActions {
127
+ reconcileUsage(): Promise<void>;
128
+ reconcileApprovals(): Promise<void>;
120
129
  prewarmToolIndexes(): Promise<void>;
121
130
  refreshTargets(): Promise<void>;
122
131
  drainInhub(maxClaims?: number): Promise<number>;
@@ -135,6 +144,8 @@ interface RuntimeMaintenanceActions {
135
144
  */
136
145
  function runtimeMaintenanceActionsFor(deps: RuntimeLifecycleDeps): RuntimeMaintenanceActions {
137
146
  return {
147
+ reconcileUsage: () => runUsageMaintenanceFor(deps.configStore?.usage ?? null),
148
+ reconcileApprovals: () => deps.reconcileApprovalContinuations?.() ?? Promise.resolve(),
138
149
  prewarmToolIndexes: () => runToolIndexPrewarmFor(deps),
139
150
  async refreshTargets() {
140
151
  await deps.refreshTargets();
@@ -298,6 +309,10 @@ export function createManagedRuntimeMaintenanceFor(
298
309
  const tasks: ManagedMaintenanceTask[] = [
299
310
  // Prewarm is per Kernel cache, so it must run again after an eviction.
300
311
  scheduled('tool-index-prewarm', 0, null, actions.prewarmToolIndexes, false),
312
+ // New Kernel owners reconcile saved evidence on their first existing tick.
313
+ // Neither task sends provider requests or restores client orchestration.
314
+ scheduled('usage-maintenance', 0, USAGE_MAINTENANCE_MS, actions.reconcileUsage, false),
315
+ scheduled('approval-continuations', 0, APPROVAL_CONTINUATION_MS, actions.reconcileApprovals, false),
301
316
  scheduled('boot-recovery', 2_000, null, actions.recoverBoot),
302
317
  scheduled('target-refresh', TARGET_REFRESH_MS, TARGET_REFRESH_MS, actions.refreshTargets),
303
318
  scheduled('monitor', MONITOR_DELAY_MS, MONITOR_INTERVAL_MS, actions.monitor),
@@ -378,54 +393,80 @@ export function createManagedRuntimeMaintenanceFor(
378
393
  export function startRuntimeSchedulersFor(deps: RuntimeLifecycleDeps): RuntimeSchedulers {
379
394
  const actions = runtimeMaintenanceActionsFor(deps);
380
395
  const timers: Array<ReturnType<typeof setInterval> | ReturnType<typeof setTimeout>> = [];
396
+ const acceptedWork = new Set<Promise<unknown>>();
397
+ let stopped = false;
398
+ function reconcile(action: () => Promise<unknown>): void {
399
+ if (stopped) return;
400
+ const work = Promise.resolve().then(action);
401
+ acceptedWork.add(work);
402
+ void work.finally(() => acceptedWork.delete(work)).catch(() => undefined);
403
+ }
381
404
  const every = (fn: () => void, ms: number): void => {
405
+ if (stopped) return;
382
406
  const timer = setInterval(fn, ms);
383
407
  timer.unref();
384
408
  timers.push(timer);
385
409
  };
386
410
  const later = (fn: () => void, ms: number): void => {
411
+ if (stopped) return;
387
412
  const timer = setTimeout(fn, ms);
388
413
  timer.unref();
389
414
  timers.push(timer);
390
415
  };
391
416
 
392
417
  // 服务先启动,索引随后在后台预热;任何数据库/索引异常都不阻塞 HTTP 就绪。
393
- later(() => void actions.prewarmToolIndexes(), TOOL_INDEX_PREWARM_DELAY_MS);
418
+ later(() => reconcile(actions.prewarmToolIndexes), TOOL_INDEX_PREWARM_DELAY_MS);
419
+ later(() => reconcile(actions.reconcileUsage), 0);
420
+ later(() => reconcile(actions.reconcileApprovals), 0);
421
+ every(() => reconcile(actions.reconcileUsage), USAGE_MAINTENANCE_MS);
422
+ every(() => reconcile(actions.reconcileApprovals), APPROVAL_CONTINUATION_MS);
394
423
 
395
- every(() => void actions.refreshTargets().catch(() => undefined), TARGET_REFRESH_MS);
424
+ every(() => reconcile(actions.refreshTargets), TARGET_REFRESH_MS);
396
425
 
397
426
  // inhub DB 调度器:llm 等中枢内目标也从 bz_jobs 队列认领,避免依赖建单进程的内存 promise。
398
427
  // kick 提供低延迟,tick 提供兜底与多实例拾取;认领本身在 DB 里原子化。
399
- every(() => void actions.drainInhub(1).catch(() => undefined), INHUB_DRAIN_MS);
428
+ every(() => reconcile(() => actions.drainInhub(1)), INHUB_DRAIN_MS);
400
429
 
401
430
  // 自监控:启动 1 分钟后首跑,避开冷启动误报。
402
431
  later(() => {
403
- void actions.monitor();
404
- every(() => void actions.monitor(), MONITOR_INTERVAL_MS);
432
+ reconcile(actions.monitor);
433
+ every(() => reconcile(actions.monitor), MONITOR_INTERVAL_MS);
405
434
  }, MONITOR_DELAY_MS);
406
435
 
407
436
  // 工具源 spec 自动刷新:每分钟扫一遍,按各源 auto_refresh_min 节流。
408
- every(() => void actions.refreshSpecs().catch(() => undefined), SPEC_REFRESH_MS);
437
+ every(() => reconcile(actions.refreshSpecs), SPEC_REFRESH_MS);
409
438
 
410
439
  // 知识库数据源连接器:每分钟扫一遍到点的(变更/出错记审计,平稳无事不刷流水)。
411
440
  if (deps.kbSync) {
412
- every(() => void actions.syncKnowledgeBases().catch(() => undefined), KB_SYNC_MS);
441
+ every(() => reconcile(actions.syncKnowledgeBases), KB_SYNC_MS);
413
442
  }
414
443
 
415
- every(() => void actions.reapStaleWork(), REAPER_INTERVAL_MS);
444
+ every(() => reconcile(actions.reapStaleWork), REAPER_INTERVAL_MS);
416
445
 
417
446
  // 执行日志清理:只删除超龄且已确认 completed 的行;未决状态必须保留给人工对账。
418
- every(() => void actions.cleanupToolCalls(), TOOL_CALL_CLEANUP_MS);
447
+ every(() => reconcile(actions.cleanupToolCalls), TOOL_CALL_CLEANUP_MS);
419
448
 
420
449
  if (deps.cfg.auditRetentionDays > 0) {
421
- later(() => void actions.cleanupAudit(), 60_000);
422
- every(() => void actions.cleanupAudit(), AUDIT_RETENTION_CLEANUP_MS);
450
+ later(() => reconcile(actions.cleanupAudit), 60_000);
451
+ every(() => reconcile(actions.cleanupAudit), AUDIT_RETENTION_CLEANUP_MS);
423
452
  }
424
453
 
425
454
  return {
426
455
  stop() {
456
+ stopped = true;
427
457
  for (const timer of timers.splice(0)) clearTimeout(timer);
428
458
  },
459
+ async drain(drainMs = 30_000) {
460
+ if (acceptedWork.size === 0) return true;
461
+ const bounded = Number.isFinite(drainMs) ? Math.max(0, Math.floor(drainMs)) : 0;
462
+ let timer: ReturnType<typeof setTimeout> | undefined;
463
+ try {
464
+ return await Promise.race([
465
+ Promise.allSettled([...acceptedWork]).then(() => true),
466
+ new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), bounded); }),
467
+ ]);
468
+ } finally { if (timer) clearTimeout(timer); }
469
+ },
429
470
  };
430
471
  }
431
472
 
@@ -9,6 +9,7 @@ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
9
  import type { RuntimeStateStore } from '../core/state/state-contracts';
10
10
  import type { AppConfig } from '../core/config/config';
11
11
  import { isAgentToolInvocationJob } from './agent-tool-job';
12
+ import { notificationBackgroundWorkFor } from '../core/runtime/notification-background-work';
12
13
 
13
14
  /** 重跑时的"已批准调用清单"提示:审批车道 B 的另一半。 */
14
15
  export async function approvedNoteForJobFor(config: ConfigStoreContract | null, jobId: string): Promise<string | undefined> {
@@ -67,7 +68,7 @@ export function approvalDepsForStores(
67
68
  });
68
69
  },
69
70
  async notify(id, snap) {
70
- await notifyApprovalFor(config, state, job, provider, toolsCfg, sourceCfg, id, snap, appConfig, nowFn, sleepFn, targetRegistry);
71
+ await notificationBackgroundWorkFor(state).track('approval-notification', () => notifyApprovalFor(config, state, job, provider, toolsCfg, sourceCfg, id, snap, appConfig, nowFn, sleepFn, targetRegistry));
71
72
  },
72
73
  };
73
74
  }
@@ -0,0 +1,43 @@
1
+ /** Trusted decision coordinates, independent of business metadata and model input. */
2
+ export interface ApprovalContinuation {
3
+ schema_version: 'bailing.approval-continuation.v1';
4
+ approval_id: number;
5
+ decision_key: string;
6
+ decision_id?: string;
7
+ decision: 'approved' | 'denied';
8
+ job_id: string;
9
+ request_id: string;
10
+ args_hash: string;
11
+ tool: string;
12
+ scope: string;
13
+ by: string;
14
+ source: 'external' | 'console';
15
+ auth: string;
16
+ mode: 'rerun' | 'manual';
17
+ policy?: string;
18
+ reason?: string;
19
+ summary?: string;
20
+ comment?: string;
21
+ audit_recorded: boolean;
22
+ completed: boolean;
23
+ }
24
+
25
+ export interface ApprovalContinuationDecisionOptions {
26
+ decision_id?: string;
27
+ comment?: string;
28
+ source: 'external' | 'console';
29
+ auth: string;
30
+ mode: 'rerun' | 'manual';
31
+ }
32
+
33
+ export interface ApprovalRequeueInput {
34
+ job_id: string;
35
+ request_id: string;
36
+ approval_id: number;
37
+ decision_key: string;
38
+ decision_id?: string;
39
+ /** JSONL adapter rechecks this after seeing a terminal job under its single-writer lock. */
40
+ isApprovedUnused?: () => Promise<boolean>;
41
+ }
42
+
43
+ export type ApprovalRequeueOutcome = 'queued' | 'already_queued' | 'in_flight' | 'consumed' | 'missing' | 'conflict';
@@ -0,0 +1,41 @@
1
+ import type { Job } from './types';
2
+ import { truncateUtf8 } from '../platform/http-body';
3
+
4
+ export type DeliveryKind = 'native_channel' | 'executor_target';
5
+ export interface DeliveryDlqRecord {
6
+ id: number;
7
+ parent_job_id?: string;
8
+ channel: string;
9
+ recipient: string;
10
+ content: string;
11
+ resolved: boolean;
12
+ delivery_kind?: DeliveryKind | null;
13
+ notification_job_id?: string | null;
14
+ executor_replay_key?: string | null;
15
+ }
16
+
17
+ export interface DeliveryRequeueInput {
18
+ dlq_id: number;
19
+ replay_key: string;
20
+ job_id: string;
21
+ request_id: string;
22
+ target: string;
23
+ /** Non-SQL adapters recheck the original DLQ under their single-writer lock. */
24
+ isOriginalDelivery?: () => Promise<boolean>;
25
+ }
26
+ export type DeliveryRequeueOutcome = 'queued' | 'already_queued' | 'in_flight' | 'missing' | 'conflict';
27
+
28
+ export function deliveryReplayKey(dlqId: number): string {
29
+ if (!Number.isSafeInteger(dlqId) || dlqId <= 0) throw new Error('delivery_dlq_invalid_id');
30
+ return `delivery-dlq:${dlqId}`;
31
+ }
32
+
33
+ /** A DLQ may only replay the original notification child, never its business parent. */
34
+ export function isOriginalExecutorDelivery(d: DeliveryDlqRecord, job: Job | null): boolean {
35
+ if (!job || job.source !== 'delivery' || !job.target?.endsWith('-notify') || d.channel !== job.target
36
+ || d.parent_job_id !== job.job_id || (d.notification_job_id && d.notification_job_id !== job.job_id)
37
+ || (d.delivery_kind && d.delivery_kind !== 'executor_target')) return false;
38
+ const recipient = String(job.metadata?.recipient ?? job.metadata?.to ?? '?').slice(0, 512);
39
+ const content = String(job.input ?? '');
40
+ return d.recipient === recipient && (d.content === truncateUtf8(content, 60000) || d.content === content.slice(0, 60000));
41
+ }