bailinghub 0.9.0 → 0.9.2

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 (139) hide show
  1. package/.dockerignore +6 -0
  2. package/.npmignore +6 -0
  3. package/CONTRIBUTING.md +4 -0
  4. package/GOVERNANCE.md +9 -0
  5. package/README.en.md +7 -6
  6. package/README.md +7 -6
  7. package/SECURITY.md +8 -2
  8. package/THIRD_PARTY_NOTICES.md +17 -17
  9. package/docker-compose.images.yml +2 -2
  10. package/docs/CHANGELOG.en.md +22 -1
  11. package/docs/CHANGELOG.md +22 -1
  12. package/docs/COMPATIBILITY.en.md +4 -0
  13. package/docs/CORE_RELIABILITY.en.md +59 -0
  14. package/docs/CORE_RELIABILITY.md +59 -0
  15. package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
  16. package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
  17. package/docs/IMPLEMENTATION_STATUS.en.md +81 -0
  18. package/docs/IMPLEMENTATION_STATUS.md +81 -0
  19. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  20. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  21. package/docs/KERNEL_HOST_API.en.md +20 -0
  22. package/docs/KERNEL_HOST_API.md +20 -0
  23. package/docs/MODEL_BILLING.en.md +4 -0
  24. package/docs/MODEL_BILLING.md +4 -0
  25. package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
  26. package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
  27. package/docs/README.en.md +8 -0
  28. package/docs/README.md +8 -0
  29. package/docs/RELEASE_NOTES_NEXT.en.md +3 -3
  30. package/docs/RELEASE_NOTES_NEXT.md +3 -3
  31. package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
  32. package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
  33. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  34. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  35. package/docs/UPGRADE_v0.9.1.en.md +39 -0
  36. package/docs/UPGRADE_v0.9.1.md +39 -0
  37. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  38. package/docs/UPGRADE_v0.9.2.md +62 -0
  39. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
  40. package/package.json +10 -5
  41. package/scripts/check-doc-links.mjs +4 -0
  42. package/scripts/check-image-tags.sh +1 -1
  43. package/scripts/check-release-consistency.test.mjs +2 -2
  44. package/scripts/dependency-audit.mjs +134 -0
  45. package/scripts/dependency-audit.test.mjs +125 -0
  46. package/scripts/doctor-deployment.test.ts +419 -0
  47. package/scripts/doctor-deployment.ts +357 -0
  48. package/scripts/doctor.ts +8 -1
  49. package/scripts/install-secrets.test.mjs +185 -0
  50. package/scripts/install.sh +10 -6
  51. package/scripts/osps-results.py +114 -0
  52. package/scripts/publish-images.sh +1 -1
  53. package/scripts/release-audit.mjs +5 -0
  54. package/scripts/verify-github-repo.mjs +5 -0
  55. package/security/dependency-audit-exceptions.json +192 -0
  56. package/sql/065_usage_reconciliation_scan.sql +4 -0
  57. package/sql/066_approval_continuations.sql +15 -0
  58. package/sql/README.md +9 -0
  59. package/src/app/approval-continuations.mysql.test.ts +138 -0
  60. package/src/app/approval-continuations.test.ts +325 -0
  61. package/src/app/approval-continuations.ts +107 -0
  62. package/src/app/http-server.ts +3 -0
  63. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  64. package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
  65. package/src/app/kernel.ts +23 -0
  66. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  67. package/src/app/runtime-lifecycle-default.ts +7 -0
  68. package/src/app/runtime-lifecycle.ts +39 -0
  69. package/src/core/contracts/approval-continuation.ts +43 -0
  70. package/src/core/contracts/types.ts +2 -0
  71. package/src/core/state/approval-continuation.ts +22 -0
  72. package/src/core/state/state-codec.ts +1 -0
  73. package/src/core/state/state-contracts.ts +3 -0
  74. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  75. package/src/infrastructure/config/configstore.ts +2 -2
  76. package/src/infrastructure/state/state-jsonl.ts +41 -11
  77. package/src/infrastructure/state/state-mysql.ts +27 -0
  78. package/src/modules/usage/background-work.test.ts +144 -0
  79. package/src/modules/usage/background-work.ts +50 -0
  80. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  81. package/src/modules/usage/billing-reconciliation.test.ts +71 -0
  82. package/src/modules/usage/billing-repository.ts +60 -15
  83. package/src/modules/usage/maintenance.test.ts +62 -0
  84. package/src/modules/usage/maintenance.ts +31 -0
  85. package/src/modules/usage/model-gateway.ts +11 -3
  86. package/src/modules/usage/model-tool-gateway.mysql.test.ts +1 -1
  87. package/src/modules/usage/pricing.ts +3 -2
  88. package/src/modules/usage/repository.ts +2 -0
  89. package/src/modules/usage/test-harness.ts +2 -1
  90. package/src/routes/admin-default.ts +2 -2
  91. package/src/routes/admin-runtime-default.ts +2 -2
  92. package/src/routes/admin-runtime.test.ts +1 -1
  93. package/src/routes/admin-runtime.ts +25 -18
  94. package/src/routes/admin.ts +1 -1
  95. package/src/routes/approvals-default.ts +2 -2
  96. package/src/routes/approvals.ts +30 -33
  97. package/src/routes/critical-routes.test.ts +16 -3
  98. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  99. package/src/test-support/model-process-crash-child.ts +78 -0
  100. package/web/console/assets/{Accounts-DnddhY6t.js → Accounts-DKhw_QLr.js} +1 -1
  101. package/web/console/assets/{AgentClients-VInbD7JS.js → AgentClients-CM4_5HaA.js} +1 -1
  102. package/web/console/assets/{AgentTasks-B-1XklBg.js → AgentTasks-CkQgZTU5.js} +1 -1
  103. package/web/console/assets/{Approvals-34qUPHf0.js → Approvals-B9O9TkbO.js} +1 -1
  104. package/web/console/assets/{Audit-BbVgkSm2.js → Audit-2vDC1SPu.js} +1 -1
  105. package/web/console/assets/{BrandLockup-DgscF28e.js → BrandLockup-BgASiRSE.js} +1 -1
  106. package/web/console/assets/{Channels-Bp-yuk8d.js → Channels-A-GvkNBt.js} +1 -1
  107. package/web/console/assets/{ChatEntries-C9Ft60TS.js → ChatEntries-BLxymI67.js} +1 -1
  108. package/web/console/assets/{Clients-NPldD-DD.js → Clients-DeNlmvS6.js} +1 -1
  109. package/web/console/assets/{Cost-DZcuB-EB.js → Cost-CBq_L4Kz.js} +1 -1
  110. package/web/console/assets/{Credentials-RTT7N6zl.js → Credentials-DmtbctNj.js} +1 -1
  111. package/web/console/assets/{Diagnostics-_LeK8cce.js → Diagnostics-BbcRDiA-.js} +1 -1
  112. package/web/console/assets/{Executors-Bi7H8rIm.js → Executors-gGgmQrDt.js} +1 -1
  113. package/web/console/assets/{HelpTip-BfyWrxCE.js → HelpTip-Dtdt2tKR.js} +1 -1
  114. package/web/console/assets/{Kb-BHamz8NP.js → Kb-lgY6OXUz.js} +2 -2
  115. package/web/console/assets/{Login-C1rJR-6w.js → Login-DA6BASZd.js} +1 -1
  116. package/web/console/assets/{Projects-BRA4a48v.js → Projects-DEbmB_sT.js} +1 -1
  117. package/web/console/assets/{Routes-CTC7U-fQ.js → Routes-qS6LLoyS.js} +1 -1
  118. package/web/console/assets/{Runs-B_fa_BlD.js → Runs-DG-VLRSc.js} +1 -1
  119. package/web/console/assets/{Setup-C1_d0mFy.js → Setup-DEpVF5uw.js} +1 -1
  120. package/web/console/assets/{Shell-CHEV6RGC.js → Shell-DgoPgK1E.js} +1 -1
  121. package/web/console/assets/{StorageBuckets-DlG3ojhA.js → StorageBuckets-DJtNN769.js} +1 -1
  122. package/web/console/assets/{SystemSettings-DYo2gg6d.js → SystemSettings-0DEUgeTR.js} +1 -1
  123. package/web/console/assets/{SystemStatus-DKCoUZlq.js → SystemStatus-CR1phiPE.js} +1 -1
  124. package/web/console/assets/{Targets-CdkG6BPR.js → Targets-D65l-IMB.js} +1 -1
  125. package/web/console/assets/{Tools-DVpCt0ox.js → Tools-DqtrINrN.js} +1 -1
  126. package/web/console/assets/{Usage-DWCpLugC.js → Usage-B5njXNjx.js} +1 -1
  127. package/web/console/assets/{UsageAccess-B_Xq7ARW.js → UsageAccess-ChnB4pjb.js} +1 -1
  128. package/web/console/assets/{UsageHelp-t5ZG_f-e.js → UsageHelp-BBKIvbQ5.js} +1 -1
  129. package/web/console/assets/{index-C6W4LWVV.js → index-65JiiUr4.js} +1 -1
  130. package/web/console/assets/{index-H1kfa0Mj.js → index-sLKrJd_p.js} +2 -2
  131. package/web/console/assets/{request-DLsP1_ot.js → request-BpaimqEb.js} +1 -1
  132. package/web/console/assets/{schema-BLOHvAJQ.js → schema-D0Z4kFCZ.js} +1 -1
  133. package/web/console/assets/{util-CGVh2Jvr.js → util-DZYfJ5Zo.js} +1 -1
  134. package/web/console/assets/{vendor-element-BD089KxE.js → vendor-element-8cVcdt5T.js} +1 -1
  135. package/web/console/assets/{vendor-mammoth-Bv-CZhmH.js → vendor-mammoth-CnDA23N0.js} +1 -1
  136. package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
  137. package/web/console/index.html +3 -3
  138. package/web-admin/package-lock.json +83 -85
  139. package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
@@ -0,0 +1,325 @@
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, 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
+ for (const failure of ['audit', 'queue'] as const) test(`decision submitted then ${failure} fails: identical callback resumes only original job`, async () => {
123
+ const h = await fixture();
124
+ try {
125
+ h.faults[failure] = true;
126
+ const first = await h.call();
127
+ assert.equal(first.statusCode, 503);
128
+ assert.equal(first.body.decision_recorded, true);
129
+ assert.equal(h.approval.status, 'approved');
130
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
131
+ h.faults[failure] = false;
132
+ const retry = await h.call();
133
+ assert.equal(retry.statusCode, 200);
134
+ assert.equal(retry.body.idempotent, true);
135
+ assert.equal(retry.body.rerun, true);
136
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'queued');
137
+ assert.equal(h.intent()?.completed, true);
138
+ assert.equal(h.kicks(), 1);
139
+ } finally { await h.close(); }
140
+ });
141
+
142
+ test('queue succeeds but outbox ack is lost: new run completes and JSONL restart never requeues it again', async () => {
143
+ const h = await fixture();
144
+ try {
145
+ h.faults.acknowledgement = true;
146
+ assert.equal((await h.call()).statusCode, 503);
147
+ await h.store.updateJob(h.job.job_id, { status: 'done', result: { text: 'confirmed' }, metadata: {} });
148
+ const reopened = new JsonlStore(h.path); await reopened.init();
149
+ h.deps.stateStore = reopened;
150
+ h.faults.acknowledgement = false;
151
+ const retry = await h.call();
152
+ assert.equal(retry.statusCode, 200);
153
+ assert.equal(retry.body.rerun, false);
154
+ assert.equal((await reopened.getJob(h.job.job_id))?.status, 'done');
155
+ assert.equal((await reopened.getJob(h.job.job_id))?.approval_continuation_keys?.['7'], 'decision-fixture');
156
+ assert.equal(h.intent()?.completed, true);
157
+ } finally { await h.close(); }
158
+ });
159
+
160
+ test('lost queue reply after durable append is recoverable without another queue admission', async () => {
161
+ const h = await fixture();
162
+ try {
163
+ const queue = h.store.requeueApprovedJobOnce.bind(h.store);
164
+ let lost = false;
165
+ h.store.requeueApprovedJobOnce = async (input) => {
166
+ const result = await queue(input);
167
+ if (!lost) { lost = true; throw new Error('synthetic queue confirmation lost'); }
168
+ return result;
169
+ };
170
+ assert.equal((await h.call()).statusCode, 503);
171
+ await h.store.updateJob(h.job.job_id, { status: 'done' });
172
+ assert.equal((await h.call()).body.rerun, false);
173
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
174
+ } finally { await h.close(); }
175
+ });
176
+
177
+ test('concurrent original decision callbacks admit original job once', async () => {
178
+ const h = await fixture();
179
+ try {
180
+ const responses = await Promise.all(Array.from({ length: 12 }, () => h.call()));
181
+ assert(responses.every(res => res.statusCode === 200));
182
+ assert.equal(responses.filter(res => res.body.rerun).length, 1);
183
+ assert.equal((await h.store.getJob(h.job.job_id))?.approval_continuation_keys?.['7'], 'decision-fixture');
184
+ } finally { await h.close(); }
185
+ });
186
+
187
+ test('denied decision audit recovers from durable intent but never queues', async () => {
188
+ const h = await fixture();
189
+ try {
190
+ h.faults.audit = true; assert.equal((await h.call('denied')).statusCode, 503);
191
+ h.faults.audit = false;
192
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
193
+ assert.equal(h.intent()?.audit_recorded, true);
194
+ assert.equal(h.intent()?.completed, true);
195
+ assert.equal(h.kicks(), 0);
196
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
197
+ } finally { await h.close(); }
198
+ });
199
+
200
+ test('in-flight original job defers continuation until terminal, used approval does not rerun', async () => {
201
+ const h = await fixture('running');
202
+ try {
203
+ const first = await h.call();
204
+ assert.equal(first.body.continuation_pending, true);
205
+ assert.equal(h.intent()?.completed, false);
206
+ await h.store.updateJob(h.job.job_id, { status: 'done' });
207
+ h.approval.used_at = new Date().toISOString();
208
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
209
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
210
+ assert.equal(h.kicks(), 0);
211
+ } finally { await h.close(); }
212
+ });
213
+
214
+ test('in-flight unconsumed approval gets exactly one later terminal continuation', async () => {
215
+ const h = await fixture('running');
216
+ try {
217
+ assert.equal((await h.call()).body.continuation_pending, true);
218
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 0);
219
+ await h.store.updateJob(h.job.job_id, { status: 'done' });
220
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
221
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'queued');
222
+ } finally { await h.close(); }
223
+ });
224
+
225
+ test('console original approval is retryable after queue failure, conflicting reversal remains rejected', async () => {
226
+ const h = await fixture();
227
+ try {
228
+ h.faults.queue = true; assert.equal((await h.consoleCall()).statusCode, 503);
229
+ h.faults.queue = false;
230
+ const retry = await h.consoleCall();
231
+ assert.equal(retry.statusCode, 200); assert.equal(retry.body.idempotent, true); assert.equal(retry.body.rerun, true);
232
+ assert.equal((await h.consoleCall('deny')).statusCode, 409);
233
+ assert.equal((await h.consoleCall()).body.rerun, false);
234
+ } finally { await h.close(); }
235
+ });
236
+
237
+ test('Core-owned queue markers survive ordinary stale metadata and marker replacement patches', async () => {
238
+ const h = await fixture();
239
+ try {
240
+ await h.call();
241
+ await h.store.updateJob(h.job.job_id, { status: 'done', metadata: {}, approval_continuation_keys: {} });
242
+ assert.equal((await h.store.getJob(h.job.job_id))?.approval_continuation_keys?.['7'], 'decision-fixture');
243
+ 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');
244
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
245
+ } finally { await h.close(); }
246
+ });
247
+
248
+ test('closing stops new recovery passes; pass is single flight and no detached timer is created', async () => {
249
+ const h = await fixture();
250
+ try {
251
+ h.faults.audit = true; await h.call(); h.faults.audit = false;
252
+ const closing: ApprovalContinuationDeps = { ...h.deps, isClosing: () => true };
253
+ assert.equal(await reconcileApprovalContinuationsFor(closing), 0);
254
+ assert.equal(h.intent()?.completed, false);
255
+ const original = h.ledger.pendingContinuations!;
256
+ let calls = 0;
257
+ h.ledger.pendingContinuations = async (limit) => { calls++; await Promise.resolve(); return original(limit); };
258
+ const results = await Promise.all([reconcileApprovalContinuationsFor(h.deps), reconcileApprovalContinuationsFor(h.deps)]);
259
+ assert.deepEqual(results, [1, 1]); assert.equal(calls, 1);
260
+ } finally { await h.close(); }
261
+ });
262
+
263
+ test('manual Agent continuation preserves original invocation without Core inference dispatch', async () => {
264
+ const h = await fixture('done', true);
265
+ try {
266
+ h.faults.audit = true; await h.call(); h.faults.audit = false;
267
+ assert.equal(h.intent()!.mode, 'manual');
268
+ await continueApprovalDecisionFor(h.deps, 7);
269
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
270
+ assert.equal(h.kicks(), 0);
271
+ } finally { await h.close(); }
272
+ });
273
+
274
+ test('missing state continuation port blocks a new decision rather than silently falling back', async () => {
275
+ const h = await fixture();
276
+ try {
277
+ h.deps.stateStore = { ...h.store, requeueApprovedJobOnce: undefined, getJob: h.store.getJob.bind(h.store) } as any;
278
+ const response = await h.call();
279
+ assert.equal(response.statusCode, 503);
280
+ assert.equal(h.approval.status, 'pending');
281
+ } finally { await h.close(); }
282
+ });
283
+
284
+ test('approval consumed between helper observation and atomic JSONL queue admission is not rerun', async () => {
285
+ const h = await fixture();
286
+ try {
287
+ const queue = h.store.requeueApprovedJobOnce.bind(h.store);
288
+ h.store.requeueApprovedJobOnce = async (input) => {
289
+ h.approval.used_at = new Date().toISOString();
290
+ return await queue(input);
291
+ };
292
+ const result = await h.call();
293
+ assert.equal(result.statusCode, 200); assert.equal(result.body.rerun, false);
294
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
295
+ assert.equal((await h.store.getJob(h.job.job_id))?.approval_continuation_keys, undefined);
296
+ assert.equal(h.intent()?.completed, true);
297
+ } finally { await h.close(); }
298
+ });
299
+
300
+ test('fair keyset pass reaches the 26th continuation after 25 unresolved records and wraps at the end', async () => {
301
+ const h = await fixture();
302
+ try {
303
+ h.approval.id = 26;
304
+ h.faults.audit = true; await h.call(); h.faults.audit = false;
305
+ const rows = Array.from({ length: 26 }, (_, index) => ({ approval_id: index + 1,
306
+ intent_json: { ...h.intent()!, approval_id: index + 1 }, audit_recorded_at: null, completed_at: null }));
307
+ const query = async (_sql: string, params: number[]) => [rows.filter(row => row.approval_id > (params[0] ?? 0)
308
+ && !(row.approval_id === 26 && h.intent()?.completed)).slice(0, 25)];
309
+ const paged = new ApprovalLedger(() => ({ query }));
310
+ h.ledger.pendingContinuations = paged.pendingContinuations.bind(paged);
311
+ const getApproval = h.ledger.get;
312
+ h.ledger.get = async (id) => id === 26 ? getApproval(id) : null;
313
+ const getIntent = h.ledger.getContinuation!;
314
+ h.ledger.getContinuation = async (id) => id === 26 ? getIntent(id) : { ...h.intent()!, approval_id: id };
315
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 0);
316
+ assert.equal(h.intent()?.completed, false);
317
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
318
+ assert.equal(h.intent()?.completed, true);
319
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'queued');
320
+ assert.equal((await paged.pendingContinuations()).length, 25);
321
+ const reopened = new ApprovalLedger(() => ({ query }));
322
+ const first = (await reopened.pendingContinuations())[0];
323
+ assert.ok(first); assert.equal(first.approval_id, 1);
324
+ } finally { await h.close(); }
325
+ });
@@ -0,0 +1,107 @@
1
+ import type { ApprovalContinuation } from '../core/contracts/approval-continuation';
2
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
3
+ import type { ApprovalLedgerContract, ConfigStoreContract } from '../infrastructure/config/configstore';
4
+ import type { EngineRuntime } from './engine';
5
+ import { isAgentToolInvocationJob } from './agent-tool-job';
6
+
7
+ export interface ApprovalContinuationDeps {
8
+ configStore: ConfigStoreContract | null;
9
+ stateStore: RuntimeStateStore;
10
+ engineRuntime: Pick<EngineRuntime, 'kickInhubScheduler'>;
11
+ now: () => string;
12
+ /** Host lifecycle owns stopping new maintenance and draining the awaited pass. */
13
+ isClosing?: () => boolean;
14
+ }
15
+
16
+ export function supportsApprovalContinuations(deps: Pick<ApprovalContinuationDeps, 'configStore' | 'stateStore'>): boolean {
17
+ const ledger = deps.configStore?.approvals;
18
+ return Boolean(ledger?.decideWithContinuation && ledger.getContinuation && ledger.pendingContinuations
19
+ && ledger.markContinuationAuditRecorded && ledger.completeContinuation && deps.stateStore.requeueApprovedJobOnce);
20
+ }
21
+
22
+ function checkedIntent(intent: ApprovalContinuation): void {
23
+ if (intent.schema_version !== 'bailing.approval-continuation.v1'
24
+ || !Number.isSafeInteger(intent.approval_id) || intent.approval_id <= 0
25
+ || typeof intent.decision_key !== 'string' || !intent.decision_key || intent.decision_key.length > 160
26
+ || !['approved', 'denied'].includes(intent.decision) || !['external', 'console'].includes(intent.source)
27
+ || !['rerun', 'manual'].includes(intent.mode)) throw new Error('approval_continuation_invalid');
28
+ }
29
+
30
+ export async function continueApprovalDecisionFor(deps: ApprovalContinuationDeps, approvalId: number): Promise<{ rerun: boolean; pending: boolean }> {
31
+ if (!supportsApprovalContinuations(deps)) throw new Error('approval_continuations_unavailable');
32
+ const ledger = deps.configStore!.approvals;
33
+ const intent = await ledger.getContinuation!(approvalId);
34
+ // A historical decision has no new durable intent. Never infer or manufacture one.
35
+ if (!intent || intent.completed) return { rerun: false, pending: false };
36
+ checkedIntent(intent);
37
+ const approval = await ledger.get(approvalId);
38
+ if (!approval || approval.id !== intent.approval_id || approval.status !== intent.decision || approval.job_id !== intent.job_id
39
+ || approval.request_id !== intent.request_id || approval.args_hash !== intent.args_hash
40
+ || (approval.decision_id ?? null) !== (intent.decision_id ?? null)) throw new Error('approval_continuation_conflict');
41
+ if (!intent.audit_recorded) {
42
+ // Fixed identity makes a crash between append and acknowledgement recognizable.
43
+ // Audit observations may repeat; original-job queue admission never does.
44
+ await deps.stateStore.appendAudit({
45
+ ts: deps.now(), job_id: intent.job_id, request_id: intent.request_id,
46
+ event: intent.source === 'external'
47
+ ? (intent.decision === 'approved' ? 'tool_approved_external' : 'tool_denied_external')
48
+ : (intent.decision === 'approved' ? 'tool_approved' : 'tool_denied'),
49
+ detail: {
50
+ continuation_id: `approval:${intent.approval_id}:${intent.decision_key}`,
51
+ approval_id: intent.approval_id, ...(intent.decision_id ? { decision_id: intent.decision_id } : {}),
52
+ tool: intent.tool, scope: intent.scope, by: intent.by, auth: intent.auth,
53
+ policy: intent.policy, reason: intent.reason, summary: intent.summary,
54
+ ...(intent.comment ? { comment: intent.comment } : {}),
55
+ },
56
+ });
57
+ await ledger.markContinuationAuditRecorded!(approvalId, intent.decision_key);
58
+ }
59
+ const latest = await ledger.get(approvalId);
60
+ let rerun = false;
61
+ if (intent.decision === 'approved' && intent.mode === 'rerun' && !latest?.used_at) {
62
+ const job = await deps.stateStore.getJob(intent.job_id);
63
+ if (!job || job.request_id !== intent.request_id || isAgentToolInvocationJob(job)) throw new Error('approval_continuation_job_conflict');
64
+ const outcome = await deps.stateStore.requeueApprovedJobOnce!({
65
+ job_id: intent.job_id, request_id: intent.request_id,
66
+ approval_id: intent.approval_id, decision_key: intent.decision_key,
67
+ decision_id: intent.decision_id,
68
+ isApprovedUnused: async () => {
69
+ const current = await ledger.get(approvalId);
70
+ if (!current || current.status !== 'approved' || current.job_id !== intent.job_id || current.request_id !== intent.request_id
71
+ || (current.decision_id ?? null) !== (intent.decision_id ?? null)) throw new Error('approval_continuation_conflict');
72
+ return !current.used_at;
73
+ },
74
+ });
75
+ if (outcome === 'in_flight') return { rerun: false, pending: true };
76
+ if (outcome === 'missing' || outcome === 'conflict') throw new Error('approval_continuation_job_conflict');
77
+ rerun = outcome === 'queued';
78
+ // The queue is durable before waking the scheduler. Recovery can wake it again safely.
79
+ if (outcome !== 'consumed') deps.engineRuntime.kickInhubScheduler();
80
+ }
81
+ await ledger.completeContinuation!(approvalId, intent.decision_key);
82
+ return { rerun, pending: false };
83
+ }
84
+
85
+ const passes = new WeakMap<ApprovalLedgerContract, Promise<number>>();
86
+
87
+ /** Await from boot/tick. One pass per owner; no detached timers or swallowed shutdown work. */
88
+ export async function reconcileApprovalContinuationsFor(deps: ApprovalContinuationDeps, limit = 25): Promise<number> {
89
+ if (deps.isClosing?.() || !supportsApprovalContinuations(deps)) return 0;
90
+ const ledger = deps.configStore!.approvals;
91
+ const active = passes.get(ledger);
92
+ if (active) return await active;
93
+ const work = (async () => {
94
+ const intents = await ledger.pendingContinuations!(limit);
95
+ let completed = 0;
96
+ for (const intent of intents) {
97
+ if (deps.isClosing?.()) break;
98
+ try {
99
+ const result = await continueApprovalDecisionFor(deps, intent.approval_id);
100
+ if (!result.pending) completed++;
101
+ } catch { /* Durable intent remains pending; later explicit pass retries it. */ }
102
+ }
103
+ return completed;
104
+ })();
105
+ passes.set(ledger, work);
106
+ try { return await work; } finally { if (passes.get(ledger) === work) passes.delete(ledger); }
107
+ }
@@ -102,6 +102,9 @@ export function createBailingHttpServer(deps: BailingHttpServerDeps): BailingHtt
102
102
  const drained = await deps.queue.drain(shutdownDrainMs).catch(() => false);
103
103
  if (!drained) logger.warn(`[百灵中枢] 优雅停机等待 ${shutdownDrainMs}ms 后仍有在途任务,交由 DB lease/reaper 恢复`);
104
104
  await closed;
105
+ if (schedulers?.drain && !await schedulers.drain(shutdownDrainMs)) {
106
+ throw new Error('Persisted evidence maintenance drain timed out');
107
+ }
105
108
  await deps.closeRuntime?.();
106
109
  (deps.exit ?? process.exit)(0);
107
110
  }