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
@@ -0,0 +1,351 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { mkdtemp, rm } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { Readable } from 'node:stream';
8
+ import type { IncomingMessage, ServerResponse } from 'node:http';
9
+ import type { ApprovalContinuation, ApprovalContinuationDecisionOptions } from '../core/contracts/approval-continuation';
10
+ import type { Job, ToolApproval } from '../core/contracts/types';
11
+ import type { ApprovalLedgerContract, ConfigStoreContract } from '../infrastructure/config/configstore';
12
+ import { JsonlStore } from '../infrastructure/state/state-jsonl';
13
+ import { ApprovalLedger } from '../infrastructure/config/config-approval-ledger';
14
+ import { handleApprovalDecisionFor, type ApprovalDecisionDeps } from '../routes/approvals';
15
+ import { handleAdminRuntimeApiFor } from '../routes/admin-runtime';
16
+ import { continueApprovalDecisionFor, reconcileApprovalContinuationsFor, approvalContinuationMaintenanceSnapshotFor, type ApprovalContinuationDeps } from './approval-continuations';
17
+
18
+ class Response {
19
+ statusCode = 0;
20
+ body: Record<string, any> = {};
21
+ writeHead(code: number): void { this.statusCode = code; }
22
+ setHeader(): void {}
23
+ end(raw: string | Buffer): void { this.body = JSON.parse(String(raw)); }
24
+ }
25
+
26
+ async function fixture(status: Job['status'] = 'done', direct = false) {
27
+ const directory = await mkdtemp(join(tmpdir(), 'approval-continuation-'));
28
+ const path = join(directory, 'state.jsonl');
29
+ const store = new JsonlStore(path);
30
+ await store.init();
31
+ const now = () => new Date().toISOString();
32
+ const job: Job = {
33
+ job_id: randomUUID(), request_id: `fixture-${randomUUID()}`, status, target: 'llm', profile: 'general',
34
+ project: '', source: 'synthetic', input_preview: '', metadata: { no_delivery: true }, created_at: now(), updated_at: now(),
35
+ };
36
+ if (direct) {
37
+ const runId = randomUUID();
38
+ job.request_id = `agent-tool:${'a'.repeat(64)}`;
39
+ job.target = 'agent-tool-v1'; job.source = 'agent-tool:synthetic-app'; job.client_app_id = 'synthetic-app';
40
+ job.agent_session_id = randomUUID(); job.on_behalf_of = 'synthetic-user'; job.session_id = runId;
41
+ job.dispatch = { route_key: 'orders' };
42
+ job.metadata = {
43
+ agent_tool_job_marker: 'bailing.agent-tool-job.v1', agent_tool_call_v1: true,
44
+ agent_invocation_id: 'a'.repeat(64), agent_run_id: runId, agent_route: 'orders', tool: 'refund_create',
45
+ agent_tool: 'refund_create', agent_args_hash: 'a'.repeat(64), agent_capability_revision: 'b'.repeat(64),
46
+ agent_execution_fingerprint: 'c'.repeat(64),
47
+ };
48
+ }
49
+ await store.createJob(job);
50
+ const approval: ToolApproval = {
51
+ id: 7, job_id: job.job_id, request_id: job.request_id, provider: 'synthetic', tool: 'refund_create',
52
+ scope: 'refund.create', risk: 'high', args_hash: 'a'.repeat(64), status: 'pending', created_at: now(),
53
+ };
54
+ let intent: ApprovalContinuation | null = null;
55
+ let kicks = 0;
56
+ const faults = { audit: false, queue: false, acknowledgement: false };
57
+ const originalAudit = store.appendAudit.bind(store);
58
+ const originalQueue = store.requeueApprovedJobOnce.bind(store);
59
+ store.appendAudit = async (entry) => {
60
+ if (faults.audit) throw new Error('synthetic audit unavailable');
61
+ await originalAudit(entry);
62
+ };
63
+ store.requeueApprovedJobOnce = async (input) => {
64
+ if (faults.queue) throw new Error('synthetic queue unavailable');
65
+ return await originalQueue(input);
66
+ };
67
+ const ledger = {
68
+ get: async () => ({ ...approval }), getByDecisionId: async () => null,
69
+ decideWithContinuation: async (_id: number, decision: 'approved' | 'denied', by: string, opts: ApprovalContinuationDecisionOptions) => {
70
+ if (approval.status !== 'pending') return approval.status === decision && approval.decision_id === opts.decision_id ? 'same' : 'conflict';
71
+ approval.status = decision; approval.decision_id = opts.decision_id;
72
+ intent = {
73
+ schema_version: 'bailing.approval-continuation.v1', approval_id: approval.id,
74
+ decision_key: opts.decision_id ?? `console:${approval.id}`, decision_id: opts.decision_id, decision,
75
+ job_id: approval.job_id, request_id: approval.request_id, args_hash: approval.args_hash,
76
+ tool: approval.tool, scope: approval.scope, by, ...opts, audit_recorded: false, completed: false,
77
+ };
78
+ return 'decided';
79
+ },
80
+ getContinuation: async () => intent && { ...intent },
81
+ pendingContinuations: async () => intent && !intent.completed ? [{ ...intent }] : [],
82
+ markContinuationAuditRecorded: async () => { intent!.audit_recorded = true; },
83
+ completeContinuation: async () => {
84
+ if (faults.acknowledgement) throw new Error('synthetic acknowledgement unavailable');
85
+ intent!.completed = true;
86
+ },
87
+ } as unknown as ApprovalLedgerContract;
88
+ const configStore = { approvals: ledger } as unknown as ConfigStoreContract;
89
+ const deps: ApprovalDecisionDeps = {
90
+ cfg: { server: { token: 'fixture-only' } } as ApprovalDecisionDeps['cfg'], configStore,
91
+ stateStore: store, now, sleep: async () => {}, secretForJob: async () => 'fixture-only',
92
+ engineRuntime: { kickInhubScheduler: () => { kicks++; } },
93
+ };
94
+ function body(decision: 'approved' | 'denied' = 'approved') {
95
+ return { kind: 'tool_approval_decision', schema_version: 'bailing.approval-decision.v1',
96
+ approval_id: approval.id, job_id: approval.job_id, request_id: approval.request_id,
97
+ args_hash: approval.args_hash, decision, decision_id: 'decision-fixture', approver: 'fixture-operator' };
98
+ }
99
+ async function call(decision: 'approved' | 'denied' = 'approved') {
100
+ const req = Object.assign(Readable.from([Buffer.from(JSON.stringify(body(decision)))]), {
101
+ method: 'POST', headers: { authorization: 'Bearer fixture-only' },
102
+ });
103
+ const res = new Response();
104
+ await handleApprovalDecisionFor(deps, req as IncomingMessage, res as unknown as ServerResponse, approval.id, new URL('http://fixture/approvals/7/decision'));
105
+ return res;
106
+ }
107
+ async function consoleCall(action: 'approve' | 'deny' = 'approve') {
108
+ const req = Object.assign(Readable.from([]), { method: 'POST', headers: {} });
109
+ const res = new Response();
110
+ await handleAdminRuntimeApiFor({ configStore, stateStore: store, now, isPaused: () => false,
111
+ queueStats: () => ({}), channelSend: async () => ({ ok: true }),
112
+ engineRuntime: { ...deps.engineRuntime, requeueForRerun: async () => { throw new Error('unfenced requeue forbidden'); } },
113
+ }, 'POST', `/admin/api/tool-approvals/7/${action}`, req as IncomingMessage, res as unknown as ServerResponse,
114
+ { kind: 'admin', via: 'session', role: 'admin', username: 'fixture-operator' });
115
+ return res;
116
+ }
117
+ return { directory, path, store, job, approval, ledger, deps, faults, call, consoleCall,
118
+ intent: () => intent, kicks: () => kicks,
119
+ close: () => rm(directory, { recursive: true, force: true }) };
120
+ }
121
+
122
+ test('approval maintenance snapshots report page failures and isolated run history without enumerating records', async () => {
123
+ const one = await fixture(), two = await fixture();
124
+ try {
125
+ one.faults.queue = true;
126
+ await one.call();
127
+ assert.equal(await reconcileApprovalContinuationsFor(one.deps), 0);
128
+ const snapshot = approvalContinuationMaintenanceSnapshotFor(one.deps)!;
129
+ assert.deepEqual(snapshot.progress, { scanned: 1, completed: 0, pending: 0, failed: 1 });
130
+ assert.equal(snapshot.work.kinds[0]!.completed, 1); // A completed pass can retain failed individual intents.
131
+ assert.equal(snapshot.work.kinds[0]!.failed, 0);
132
+ assert.equal(approvalContinuationMaintenanceSnapshotFor(two.deps)!.work.kinds[0]!.completed, 0);
133
+ snapshot.progress!.failed = 1000;
134
+ let reads = 0;
135
+ one.ledger.pendingContinuations = async () => { reads++; throw new Error('PRIVATE_LEDGER_TOKEN_JOB_ID'); };
136
+ assert.equal(approvalContinuationMaintenanceSnapshotFor(one.deps)!.progress!.failed, 1);
137
+ assert.equal(reads, 0);
138
+ await assert.rejects(reconcileApprovalContinuationsFor(one.deps));
139
+ const failed = approvalContinuationMaintenanceSnapshotFor(one.deps)!;
140
+ assert.equal(reads, 1);
141
+ assert.equal(failed.work.kinds[0]!.failed, 1);
142
+ assert.equal(failed.work.kinds[0]!.inFlight, 0);
143
+ assert(failed.work.kinds[0]!.lastFailedAt);
144
+ assert.doesNotMatch(JSON.stringify(failed), /PRIVATE_LEDGER|TOKEN|JOB_ID/);
145
+ } finally { await one.close(); await two.close(); }
146
+ });
147
+
148
+ for (const failure of ['audit', 'queue'] as const) test(`decision submitted then ${failure} fails: identical callback resumes only original job`, async () => {
149
+ const h = await fixture();
150
+ try {
151
+ h.faults[failure] = true;
152
+ const first = await h.call();
153
+ assert.equal(first.statusCode, 503);
154
+ assert.equal(first.body.decision_recorded, true);
155
+ assert.equal(h.approval.status, 'approved');
156
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
157
+ h.faults[failure] = false;
158
+ const retry = await h.call();
159
+ assert.equal(retry.statusCode, 200);
160
+ assert.equal(retry.body.idempotent, true);
161
+ assert.equal(retry.body.rerun, true);
162
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'queued');
163
+ assert.equal(h.intent()?.completed, true);
164
+ assert.equal(h.kicks(), 1);
165
+ } finally { await h.close(); }
166
+ });
167
+
168
+ test('queue succeeds but outbox ack is lost: new run completes and JSONL restart never requeues it again', async () => {
169
+ const h = await fixture();
170
+ try {
171
+ h.faults.acknowledgement = true;
172
+ assert.equal((await h.call()).statusCode, 503);
173
+ await h.store.updateJob(h.job.job_id, { status: 'done', result: { text: 'confirmed' }, metadata: {} });
174
+ const reopened = new JsonlStore(h.path); await reopened.init();
175
+ h.deps.stateStore = reopened;
176
+ h.faults.acknowledgement = false;
177
+ const retry = await h.call();
178
+ assert.equal(retry.statusCode, 200);
179
+ assert.equal(retry.body.rerun, false);
180
+ assert.equal((await reopened.getJob(h.job.job_id))?.status, 'done');
181
+ assert.equal((await reopened.getJob(h.job.job_id))?.approval_continuation_keys?.['7'], 'decision-fixture');
182
+ assert.equal(h.intent()?.completed, true);
183
+ } finally { await h.close(); }
184
+ });
185
+
186
+ test('lost queue reply after durable append is recoverable without another queue admission', async () => {
187
+ const h = await fixture();
188
+ try {
189
+ const queue = h.store.requeueApprovedJobOnce.bind(h.store);
190
+ let lost = false;
191
+ h.store.requeueApprovedJobOnce = async (input) => {
192
+ const result = await queue(input);
193
+ if (!lost) { lost = true; throw new Error('synthetic queue confirmation lost'); }
194
+ return result;
195
+ };
196
+ assert.equal((await h.call()).statusCode, 503);
197
+ await h.store.updateJob(h.job.job_id, { status: 'done' });
198
+ assert.equal((await h.call()).body.rerun, false);
199
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
200
+ } finally { await h.close(); }
201
+ });
202
+
203
+ test('concurrent original decision callbacks admit original job once', async () => {
204
+ const h = await fixture();
205
+ try {
206
+ const responses = await Promise.all(Array.from({ length: 12 }, () => h.call()));
207
+ assert(responses.every(res => res.statusCode === 200));
208
+ assert.equal(responses.filter(res => res.body.rerun).length, 1);
209
+ assert.equal((await h.store.getJob(h.job.job_id))?.approval_continuation_keys?.['7'], 'decision-fixture');
210
+ } finally { await h.close(); }
211
+ });
212
+
213
+ test('denied decision audit recovers from durable intent but never queues', async () => {
214
+ const h = await fixture();
215
+ try {
216
+ h.faults.audit = true; assert.equal((await h.call('denied')).statusCode, 503);
217
+ h.faults.audit = false;
218
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
219
+ assert.equal(h.intent()?.audit_recorded, true);
220
+ assert.equal(h.intent()?.completed, true);
221
+ assert.equal(h.kicks(), 0);
222
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
223
+ } finally { await h.close(); }
224
+ });
225
+
226
+ test('in-flight original job defers continuation until terminal, used approval does not rerun', async () => {
227
+ const h = await fixture('running');
228
+ try {
229
+ const first = await h.call();
230
+ assert.equal(first.body.continuation_pending, true);
231
+ assert.equal(h.intent()?.completed, false);
232
+ await h.store.updateJob(h.job.job_id, { status: 'done' });
233
+ h.approval.used_at = new Date().toISOString();
234
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
235
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
236
+ assert.equal(h.kicks(), 0);
237
+ } finally { await h.close(); }
238
+ });
239
+
240
+ test('in-flight unconsumed approval gets exactly one later terminal continuation', async () => {
241
+ const h = await fixture('running');
242
+ try {
243
+ assert.equal((await h.call()).body.continuation_pending, true);
244
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 0);
245
+ await h.store.updateJob(h.job.job_id, { status: 'done' });
246
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
247
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'queued');
248
+ } finally { await h.close(); }
249
+ });
250
+
251
+ test('console original approval is retryable after queue failure, conflicting reversal remains rejected', async () => {
252
+ const h = await fixture();
253
+ try {
254
+ h.faults.queue = true; assert.equal((await h.consoleCall()).statusCode, 503);
255
+ h.faults.queue = false;
256
+ const retry = await h.consoleCall();
257
+ assert.equal(retry.statusCode, 200); assert.equal(retry.body.idempotent, true); assert.equal(retry.body.rerun, true);
258
+ assert.equal((await h.consoleCall('deny')).statusCode, 409);
259
+ assert.equal((await h.consoleCall()).body.rerun, false);
260
+ } finally { await h.close(); }
261
+ });
262
+
263
+ test('Core-owned queue markers survive ordinary stale metadata and marker replacement patches', async () => {
264
+ const h = await fixture();
265
+ try {
266
+ await h.call();
267
+ await h.store.updateJob(h.job.job_id, { status: 'done', metadata: {}, approval_continuation_keys: {} });
268
+ assert.equal((await h.store.getJob(h.job.job_id))?.approval_continuation_keys?.['7'], 'decision-fixture');
269
+ assert.equal(await h.store.requeueApprovedJobOnce({ job_id: h.job.job_id, request_id: h.job.request_id, approval_id: 7, decision_key: 'decision-fixture' }), 'already_queued');
270
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
271
+ } finally { await h.close(); }
272
+ });
273
+
274
+ test('closing stops new recovery passes; pass is single flight and no detached timer is created', async () => {
275
+ const h = await fixture();
276
+ try {
277
+ h.faults.audit = true; await h.call(); h.faults.audit = false;
278
+ const closing: ApprovalContinuationDeps = { ...h.deps, isClosing: () => true };
279
+ assert.equal(await reconcileApprovalContinuationsFor(closing), 0);
280
+ assert.equal(h.intent()?.completed, false);
281
+ const original = h.ledger.pendingContinuations!;
282
+ let calls = 0;
283
+ h.ledger.pendingContinuations = async (limit) => { calls++; await Promise.resolve(); return original(limit); };
284
+ const results = await Promise.all([reconcileApprovalContinuationsFor(h.deps), reconcileApprovalContinuationsFor(h.deps)]);
285
+ assert.deepEqual(results, [1, 1]); assert.equal(calls, 1);
286
+ } finally { await h.close(); }
287
+ });
288
+
289
+ test('manual Agent continuation preserves original invocation without Core inference dispatch', async () => {
290
+ const h = await fixture('done', true);
291
+ try {
292
+ h.faults.audit = true; await h.call(); h.faults.audit = false;
293
+ assert.equal(h.intent()!.mode, 'manual');
294
+ await continueApprovalDecisionFor(h.deps, 7);
295
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
296
+ assert.equal(h.kicks(), 0);
297
+ } finally { await h.close(); }
298
+ });
299
+
300
+ test('missing state continuation port blocks a new decision rather than silently falling back', async () => {
301
+ const h = await fixture();
302
+ try {
303
+ h.deps.stateStore = { ...h.store, requeueApprovedJobOnce: undefined, getJob: h.store.getJob.bind(h.store) } as any;
304
+ const response = await h.call();
305
+ assert.equal(response.statusCode, 503);
306
+ assert.equal(h.approval.status, 'pending');
307
+ } finally { await h.close(); }
308
+ });
309
+
310
+ test('approval consumed between helper observation and atomic JSONL queue admission is not rerun', async () => {
311
+ const h = await fixture();
312
+ try {
313
+ const queue = h.store.requeueApprovedJobOnce.bind(h.store);
314
+ h.store.requeueApprovedJobOnce = async (input) => {
315
+ h.approval.used_at = new Date().toISOString();
316
+ return await queue(input);
317
+ };
318
+ const result = await h.call();
319
+ assert.equal(result.statusCode, 200); assert.equal(result.body.rerun, false);
320
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
321
+ assert.equal((await h.store.getJob(h.job.job_id))?.approval_continuation_keys, undefined);
322
+ assert.equal(h.intent()?.completed, true);
323
+ } finally { await h.close(); }
324
+ });
325
+
326
+ test('fair keyset pass reaches the 26th continuation after 25 unresolved records and wraps at the end', async () => {
327
+ const h = await fixture();
328
+ try {
329
+ h.approval.id = 26;
330
+ h.faults.audit = true; await h.call(); h.faults.audit = false;
331
+ const rows = Array.from({ length: 26 }, (_, index) => ({ approval_id: index + 1,
332
+ intent_json: { ...h.intent()!, approval_id: index + 1 }, audit_recorded_at: null, completed_at: null }));
333
+ const query = async (_sql: string, params: number[]) => [rows.filter(row => row.approval_id > (params[0] ?? 0)
334
+ && !(row.approval_id === 26 && h.intent()?.completed)).slice(0, 25)];
335
+ const paged = new ApprovalLedger(() => ({ query }));
336
+ h.ledger.pendingContinuations = paged.pendingContinuations.bind(paged);
337
+ const getApproval = h.ledger.get;
338
+ h.ledger.get = async (id) => id === 26 ? getApproval(id) : null;
339
+ const getIntent = h.ledger.getContinuation!;
340
+ h.ledger.getContinuation = async (id) => id === 26 ? getIntent(id) : { ...h.intent()!, approval_id: id };
341
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 0);
342
+ assert.equal(h.intent()?.completed, false);
343
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
344
+ assert.equal(h.intent()?.completed, true);
345
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'queued');
346
+ assert.equal((await paged.pendingContinuations()).length, 25);
347
+ const reopened = new ApprovalLedger(() => ({ query }));
348
+ const first = (await reopened.pendingContinuations())[0];
349
+ assert.ok(first); assert.equal(first.approval_id, 1);
350
+ } finally { await h.close(); }
351
+ });
@@ -0,0 +1,148 @@
1
+ import type { ApprovalContinuation } from '../core/contracts/approval-continuation';
2
+ import type { BackgroundWorkMetricsSnapshot } from '../core/observability/openmetrics';
3
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
4
+ import type { ApprovalLedgerContract, ConfigStoreContract } from '../infrastructure/config/configstore';
5
+ import type { EngineRuntime } from './engine';
6
+ import { isAgentToolInvocationJob } from './agent-tool-job';
7
+
8
+ export interface ApprovalContinuationDeps {
9
+ configStore: ConfigStoreContract | null;
10
+ stateStore: RuntimeStateStore;
11
+ engineRuntime: Pick<EngineRuntime, 'kickInhubScheduler'>;
12
+ now: () => string;
13
+ /** Host lifecycle owns stopping new maintenance and draining the awaited pass. */
14
+ isClosing?: () => boolean;
15
+ }
16
+
17
+ export function supportsApprovalContinuations(deps: Pick<ApprovalContinuationDeps, 'configStore' | 'stateStore'>): boolean {
18
+ const ledger = deps.configStore?.approvals;
19
+ return Boolean(ledger?.decideWithContinuation && ledger.getContinuation && ledger.pendingContinuations
20
+ && ledger.markContinuationAuditRecorded && ledger.completeContinuation && deps.stateStore.requeueApprovedJobOnce);
21
+ }
22
+
23
+ function checkedIntent(intent: ApprovalContinuation): void {
24
+ if (intent.schema_version !== 'bailing.approval-continuation.v1'
25
+ || !Number.isSafeInteger(intent.approval_id) || intent.approval_id <= 0
26
+ || typeof intent.decision_key !== 'string' || !intent.decision_key || intent.decision_key.length > 160
27
+ || !['approved', 'denied'].includes(intent.decision) || !['external', 'console'].includes(intent.source)
28
+ || !['rerun', 'manual'].includes(intent.mode)) throw new Error('approval_continuation_invalid');
29
+ }
30
+
31
+ export async function continueApprovalDecisionFor(deps: ApprovalContinuationDeps, approvalId: number): Promise<{ rerun: boolean; pending: boolean }> {
32
+ if (!supportsApprovalContinuations(deps)) throw new Error('approval_continuations_unavailable');
33
+ const ledger = deps.configStore!.approvals;
34
+ const intent = await ledger.getContinuation!(approvalId);
35
+ // A historical decision has no new durable intent. Never infer or manufacture one.
36
+ if (!intent || intent.completed) return { rerun: false, pending: false };
37
+ checkedIntent(intent);
38
+ const approval = await ledger.get(approvalId);
39
+ if (!approval || approval.id !== intent.approval_id || approval.status !== intent.decision || approval.job_id !== intent.job_id
40
+ || approval.request_id !== intent.request_id || approval.args_hash !== intent.args_hash
41
+ || (approval.decision_id ?? null) !== (intent.decision_id ?? null)) throw new Error('approval_continuation_conflict');
42
+ if (!intent.audit_recorded) {
43
+ // Fixed identity makes a crash between append and acknowledgement recognizable.
44
+ // Audit observations may repeat; original-job queue admission never does.
45
+ await deps.stateStore.appendAudit({
46
+ ts: deps.now(), job_id: intent.job_id, request_id: intent.request_id,
47
+ event: intent.source === 'external'
48
+ ? (intent.decision === 'approved' ? 'tool_approved_external' : 'tool_denied_external')
49
+ : (intent.decision === 'approved' ? 'tool_approved' : 'tool_denied'),
50
+ detail: {
51
+ continuation_id: `approval:${intent.approval_id}:${intent.decision_key}`,
52
+ approval_id: intent.approval_id, ...(intent.decision_id ? { decision_id: intent.decision_id } : {}),
53
+ tool: intent.tool, scope: intent.scope, by: intent.by, auth: intent.auth,
54
+ policy: intent.policy, reason: intent.reason, summary: intent.summary,
55
+ ...(intent.comment ? { comment: intent.comment } : {}),
56
+ },
57
+ });
58
+ await ledger.markContinuationAuditRecorded!(approvalId, intent.decision_key);
59
+ }
60
+ const latest = await ledger.get(approvalId);
61
+ let rerun = false;
62
+ if (intent.decision === 'approved' && intent.mode === 'rerun' && !latest?.used_at) {
63
+ const job = await deps.stateStore.getJob(intent.job_id);
64
+ if (!job || job.request_id !== intent.request_id || isAgentToolInvocationJob(job)) throw new Error('approval_continuation_job_conflict');
65
+ const outcome = await deps.stateStore.requeueApprovedJobOnce!({
66
+ job_id: intent.job_id, request_id: intent.request_id,
67
+ approval_id: intent.approval_id, decision_key: intent.decision_key,
68
+ decision_id: intent.decision_id,
69
+ isApprovedUnused: async () => {
70
+ const current = await ledger.get(approvalId);
71
+ if (!current || current.status !== 'approved' || current.job_id !== intent.job_id || current.request_id !== intent.request_id
72
+ || (current.decision_id ?? null) !== (intent.decision_id ?? null)) throw new Error('approval_continuation_conflict');
73
+ return !current.used_at;
74
+ },
75
+ });
76
+ if (outcome === 'in_flight') return { rerun: false, pending: true };
77
+ if (outcome === 'missing' || outcome === 'conflict') throw new Error('approval_continuation_job_conflict');
78
+ rerun = outcome === 'queued';
79
+ // The queue is durable before waking the scheduler. Recovery can wake it again safely.
80
+ if (outcome !== 'consumed') deps.engineRuntime.kickInhubScheduler();
81
+ }
82
+ await ledger.completeContinuation!(approvalId, intent.decision_key);
83
+ return { rerun, pending: false };
84
+ }
85
+
86
+ const passes = new WeakMap<ApprovalLedgerContract, Promise<number>>();
87
+ export interface ApprovalContinuationProgress { scanned: number; completed: number; pending: number; failed: number }
88
+ interface PassMetrics {
89
+ completed: number; failed: number; startedAt: string | null; completedAt: string | null; failedAt: string | null;
90
+ progress: ApprovalContinuationProgress;
91
+ }
92
+ const passMetrics = new WeakMap<ApprovalLedgerContract, PassMetrics>();
93
+
94
+ /** Read process-local maintenance state; never enumerate approval/job records. */
95
+ export function approvalContinuationMaintenanceSnapshotFor(
96
+ deps: Pick<ApprovalContinuationDeps, 'configStore' | 'stateStore'>,
97
+ nowMs = Date.now(),
98
+ ): { work: BackgroundWorkMetricsSnapshot; progress?: ApprovalContinuationProgress } | undefined {
99
+ if (!supportsApprovalContinuations(deps)) return undefined;
100
+ const ledger = deps.configStore!.approvals, value = passMetrics.get(ledger), running = passes.has(ledger);
101
+ const startedAt = value?.startedAt ?? null;
102
+ return {
103
+ work: { kinds: [{ kind: 'approval-continuation', inFlight: running ? 1 : 0,
104
+ completed: value?.completed ?? 0, failed: value?.failed ?? 0,
105
+ oldestPendingAgeMs: running && startedAt ? Math.max(0, nowMs - Date.parse(startedAt)) : 0,
106
+ lastStartedAt: startedAt, lastCompletedAt: value?.completedAt ?? null, lastFailedAt: value?.failedAt ?? null }] },
107
+ ...(value ? { progress: { ...value.progress } } : {}),
108
+ };
109
+ }
110
+
111
+ /** Await from boot/tick. One pass per owner; no detached timers or swallowed shutdown work. */
112
+ export async function reconcileApprovalContinuationsFor(deps: ApprovalContinuationDeps, limit = 25): Promise<number> {
113
+ if (deps.isClosing?.() || !supportsApprovalContinuations(deps)) return 0;
114
+ const ledger = deps.configStore!.approvals;
115
+ const active = passes.get(ledger);
116
+ if (active) return await active;
117
+ let metrics = passMetrics.get(ledger);
118
+ if (!metrics) {
119
+ metrics = { completed: 0, failed: 0, startedAt: null, completedAt: null, failedAt: null,
120
+ progress: { scanned: 0, completed: 0, pending: 0, failed: 0 } };
121
+ passMetrics.set(ledger, metrics);
122
+ }
123
+ const owner = metrics;
124
+ owner.startedAt = deps.now();
125
+ owner.progress = { scanned: 0, completed: 0, pending: 0, failed: 0 };
126
+ const work = (async () => {
127
+ const intents = await ledger.pendingContinuations!(limit);
128
+ let completed = 0;
129
+ for (const intent of intents) {
130
+ if (deps.isClosing?.()) break;
131
+ owner.progress.scanned++;
132
+ try {
133
+ const result = await continueApprovalDecisionFor(deps, intent.approval_id);
134
+ if (!result.pending) { completed++; owner.progress.completed++; } else owner.progress.pending++;
135
+ } catch { owner.progress.failed++; /* Durable intent remains pending; later explicit pass retries it. */ }
136
+ }
137
+ return completed;
138
+ })();
139
+ passes.set(ledger, work);
140
+ try {
141
+ const completed = await work;
142
+ owner.completed++; owner.completedAt = deps.now();
143
+ return completed;
144
+ } catch (error) {
145
+ owner.failed++; owner.failedAt = deps.now();
146
+ throw error;
147
+ } finally { if (passes.get(ledger) === work) passes.delete(ledger); }
148
+ }
@@ -0,0 +1,63 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { channelSendFor } from './channels';
4
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
5
+
6
+ const config = { channels: { get: async () => ({ kind: 'wecom', enabled: true,
7
+ config: { corpid: 'synthetic', secret: 'synthetic', agentid: '1' } }) } } as unknown as ConfigStoreContract;
8
+
9
+ test('channel attachments: oversized declared bodies cancel before upload or message dispatch', async (t) => {
10
+ let pulls = 0;
11
+ let cancels = 0;
12
+ let calls = 0;
13
+ t.mock.method(globalThis, 'fetch', async (input: unknown) => {
14
+ assert.equal(String(input), 'https://synthetic.invalid/a.txt');
15
+ calls++;
16
+ return new Response(new ReadableStream<Uint8Array>({
17
+ pull(controller) { pulls++; controller.enqueue(new Uint8Array(1)); },
18
+ cancel() { cancels++; },
19
+ }, { highWaterMark: 0 }), { headers: { 'content-length': String(20 * 1024 * 1024 + 1) } });
20
+ });
21
+ const result = await channelSendFor(config, 'synthetic', 'recipient', { text: 'synthetic', files: [{ url: 'https://synthetic.invalid/a.txt' }] });
22
+ assert.equal(result.ok, false);
23
+ assert.match(result.error ?? '', /超过 20MB 上限/);
24
+ assert.equal(result.mayHaveCommitted, undefined);
25
+ assert.equal(calls, 1);
26
+ assert.equal(pulls, 0);
27
+ assert.equal(cancels, 1);
28
+ });
29
+
30
+ test('channel attachments: low declared length cannot bypass body limit or upload partial media', async (t) => {
31
+ let pulls = 0;
32
+ let cancels = 0;
33
+ let calls = 0;
34
+ const chunk = new Uint8Array(1024 * 1024);
35
+ t.mock.method(globalThis, 'fetch', async (input: unknown) => {
36
+ assert.equal(String(input), 'https://synthetic.invalid/a.png');
37
+ calls++;
38
+ return new Response(new ReadableStream<Uint8Array>({
39
+ pull(controller) { pulls++; controller.enqueue(pulls <= 20 ? chunk : new Uint8Array(1)); },
40
+ cancel() { cancels++; },
41
+ }, { highWaterMark: 0 }), { headers: { 'content-length': '1' } });
42
+ });
43
+ const result = await channelSendFor(config, 'synthetic', 'recipient', { images: ['https://synthetic.invalid/a.png'] });
44
+ assert.equal(result.ok, false);
45
+ assert.match(result.error ?? '', /超过 20MB 上限/);
46
+ assert.equal(calls, 1);
47
+ assert.equal(pulls, 21);
48
+ assert.equal(cancels, 1);
49
+ });
50
+
51
+ test('channel attachments: HTTP errors cancel promptly and keep original status', async (t) => {
52
+ let pulls = 0;
53
+ let cancels = 0;
54
+ t.mock.method(globalThis, 'fetch', async () => new Response(new ReadableStream<Uint8Array>({
55
+ pull(controller) { pulls++; controller.enqueue(new Uint8Array(1)); },
56
+ cancel() { cancels++; return new Promise<void>(() => undefined); },
57
+ }, { highWaterMark: 0 }), { status: 403 }));
58
+ const result = await channelSendFor(config, 'synthetic', 'recipient', { files: [{ url: 'https://synthetic.invalid/a.txt' }] });
59
+ assert.equal(result.ok, false);
60
+ assert.match(result.error ?? '', /HTTP 403/);
61
+ assert.equal(pulls, 0);
62
+ assert.equal(cancels, 1);
63
+ });
@@ -4,6 +4,7 @@
4
4
  // 不建任何 job、不过 LLM、逐字送达——正式通知所见即所得;与「执行器拉取(wecom-notify)」那套解耦(内部告警不再走它)。
5
5
  import { sendWecomText, sendWecomMedia, sendWecomCard, uploadWecomMedia, type WecomAccessTokenCache } from '../adapters/channels/wecom-api';
6
6
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
+ import { cancelResponseBody, readResponseBody, ResponseBodyLimitError } from '../core/platform/http-body';
7
8
 
8
9
  export interface ChannelSendResult {
9
10
  ok: boolean;
@@ -23,13 +24,15 @@ async function fetchBinary(url: string, maxBytes = 20 * 1024 * 1024): Promise<{
23
24
  if (!/^https?:\/\//i.test(url)) return { error: 'URL 必须是 http(s)' };
24
25
  try {
25
26
  const r = await fetch(url, { signal: AbortSignal.timeout(20000) });
26
- if (!r.ok) return { error: `拉取失败 HTTP ${r.status}` };
27
- const ab = await r.arrayBuffer();
27
+ if (!r.ok) { cancelResponseBody(r); return { error: `拉取失败 HTTP ${r.status}` }; }
28
+ const ab = await readResponseBody(r, maxBytes);
28
29
  if (!ab.byteLength) return { error: '内容为空' };
29
- if (ab.byteLength > maxBytes) return { error: `超过 ${Math.round(maxBytes / 1048576)}MB 上限` };
30
30
  const mime = ((r.headers.get('content-type') || '').split(';')[0] || '').trim() || 'application/octet-stream';
31
31
  return { buf: Buffer.from(ab), mime };
32
- } catch (e) { return { error: `拉取异常 ${String(e instanceof Error ? e.message : e).slice(0, 80)}` }; }
32
+ } catch (e) {
33
+ if (e instanceof ResponseBodyLimitError) return { error: `超过 ${Math.round(maxBytes / 1048576)}MB 上限` };
34
+ return { error: `拉取异常 ${String(e instanceof Error ? e.message : e).slice(0, 80)}` };
35
+ }
33
36
  }
34
37
  /** 给上传素材取个带扩展名的文件名(企微 media/upload 需要):优先 URL 末段,其次按 mime/类型兜底。 */
35
38
  function fileNameFor(url: string, mime: string, kind: 'image' | 'file'): string {