bailinghub 0.9.1 → 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 (74) 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 +12 -1
  5. package/docs/CHANGELOG.md +12 -1
  6. package/docs/CORE_RELIABILITY.en.md +59 -0
  7. package/docs/CORE_RELIABILITY.md +59 -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 +22 -14
  11. package/docs/IMPLEMENTATION_STATUS.md +23 -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/README.en.md +5 -0
  21. package/docs/README.md +5 -0
  22. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  23. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  24. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  25. package/docs/UPGRADE_v0.9.2.md +62 -0
  26. package/package.json +7 -3
  27. package/scripts/check-doc-links.mjs +2 -0
  28. package/scripts/check-image-tags.sh +1 -1
  29. package/scripts/check-release-consistency.test.mjs +2 -2
  30. package/scripts/doctor-deployment.test.ts +419 -0
  31. package/scripts/doctor-deployment.ts +357 -0
  32. package/scripts/doctor.ts +8 -1
  33. package/scripts/install-secrets.test.mjs +185 -0
  34. package/scripts/install.sh +10 -6
  35. package/scripts/publish-images.sh +1 -1
  36. package/scripts/release-audit.mjs +4 -0
  37. package/scripts/verify-github-repo.mjs +4 -0
  38. package/sql/065_usage_reconciliation_scan.sql +4 -0
  39. package/sql/066_approval_continuations.sql +15 -0
  40. package/sql/README.md +9 -0
  41. package/src/app/approval-continuations.mysql.test.ts +138 -0
  42. package/src/app/approval-continuations.test.ts +325 -0
  43. package/src/app/approval-continuations.ts +107 -0
  44. package/src/app/http-server.ts +3 -0
  45. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  46. package/src/app/kernel.ts +13 -0
  47. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  48. package/src/app/runtime-lifecycle-default.ts +7 -0
  49. package/src/app/runtime-lifecycle.ts +39 -0
  50. package/src/core/contracts/approval-continuation.ts +43 -0
  51. package/src/core/contracts/types.ts +2 -0
  52. package/src/core/state/approval-continuation.ts +22 -0
  53. package/src/core/state/state-codec.ts +1 -0
  54. package/src/core/state/state-contracts.ts +3 -0
  55. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  56. package/src/infrastructure/config/configstore.ts +2 -2
  57. package/src/infrastructure/state/state-jsonl.ts +41 -11
  58. package/src/infrastructure/state/state-mysql.ts +27 -0
  59. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  60. package/src/modules/usage/billing-reconciliation.test.ts +71 -0
  61. package/src/modules/usage/billing-repository.ts +54 -11
  62. package/src/modules/usage/maintenance.test.ts +62 -0
  63. package/src/modules/usage/maintenance.ts +31 -0
  64. package/src/modules/usage/model-gateway.ts +2 -1
  65. package/src/routes/admin-default.ts +2 -2
  66. package/src/routes/admin-runtime-default.ts +2 -2
  67. package/src/routes/admin-runtime.test.ts +1 -1
  68. package/src/routes/admin-runtime.ts +25 -18
  69. package/src/routes/admin.ts +1 -1
  70. package/src/routes/approvals-default.ts +2 -2
  71. package/src/routes/approvals.ts +30 -33
  72. package/src/routes/critical-routes.test.ts +16 -3
  73. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  74. package/src/test-support/model-process-crash-child.ts +78 -0
@@ -0,0 +1,15 @@
1
+ -- Decision and continuation intent commit together. Job queue admission uses its
2
+ -- own durable marker so an outbox acknowledgement loss cannot requeue it twice.
3
+ CREATE TABLE IF NOT EXISTS `bz_approval_continuations` (
4
+ `approval_id` BIGINT UNSIGNED NOT NULL,
5
+ `intent_json` JSON NOT NULL,
6
+ `audit_recorded_at` DATETIME DEFAULT NULL,
7
+ `completed_at` DATETIME DEFAULT NULL,
8
+ `created_at` DATETIME NOT NULL,
9
+ PRIMARY KEY (`approval_id`),
10
+ KEY `idx_approval_continuation_pending` (`completed_at`, `approval_id`)
11
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
12
+
13
+ ALTER TABLE `bz_jobs`
14
+ ADD COLUMN `approval_continuation_keys` JSON DEFAULT NULL
15
+ COMMENT 'Core-owned approval decision queue markers, never business metadata';
package/sql/README.md CHANGED
@@ -24,6 +24,15 @@ npm run db:init # 按文件名顺序应用所有未应用的结构文件
24
24
  - **错误码容错兜底**:`IF NOT EXISTS` 自身幂等;加列/索引遇到 1060/1061 时,只有实际列/索引结构与官方语句一致才按已完成处理,跑完即记账,此后走账本快路径。
25
25
  - **失败关闭**:账本出现既不属于活动序列、也不属于固化退役证据的文件,或者任一已记账摘要不匹配时,会在补录摘要或执行新迁移前拒绝继续。
26
26
 
27
+ ## Core 0.9.2:065/066 可靠性修复
28
+
29
+ 以下新增结构从 Core 0.9.2 提供,历史 v0.9.1 Tag 不包含它们:
30
+
31
+ - `065_usage_reconciliation_scan.sql` 新增 `(billing_state, updated_at, id)` 索引,供待结算记录公平分页,不修改历史计量或费用。
32
+ - `066_approval_continuations.sql` 新增审批补续表与 `bz_jobs.approval_continuation_keys`,配合决策事务和原任务入队去重,不回填历史决策。
33
+
34
+ 使用新审批入口前显式应用 066,并配套更新 Core state/config 仓储;缺少表时决策事务失败关闭。运行时不自动迁移,回退代码不删除补续表或标记。完整行为、升级与回退边界见[Core 可靠性修复](../docs/CORE_RELIABILITY.md)。
35
+
27
36
  ## 058 跨系统归档成员绑定
28
37
 
29
38
  `058_agent_conversation_member_bindings.sql` 在 Core 0.7.0 引入,只给已有归档增加
@@ -0,0 +1,138 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { fork } from 'node:child_process';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { createPool } from 'mysql2/promise';
7
+ import type { Job } from '../core/contracts/types';
8
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
+ import { ApprovalLedger } from '../infrastructure/config/config-approval-ledger';
10
+ import { MysqlStore } from '../infrastructure/state/state-mysql';
11
+ import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
12
+ import { continueApprovalDecisionFor, reconcileApprovalContinuationsFor, type ApprovalContinuationDeps } from './approval-continuations';
13
+
14
+ const enabled = process.env.BAILING_APPROVAL_CONTINUATION_TEST_MYSQL === '1';
15
+
16
+ async function fixture() {
17
+ const database = `approval_acceptance_${randomUUID().replaceAll('-', '')}`;
18
+ const mysql = { host: '127.0.0.1', port: 16307, user: 'root', password: '', database, connectionLimit: 8 };
19
+ const admin = createPool({ ...mysql, database: undefined });
20
+ await admin.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
21
+ const pool = createPool({ ...mysql, timezone: 'Z' });
22
+ try {
23
+ await migrateBailingHubCoreSchema({ mysql, logger: { log() {}, warn() {} } });
24
+ const ledger = new ApprovalLedger(() => pool);
25
+ const owner = { get: async () => pool, close: async () => {} };
26
+ const store = new MysqlStore(mysql, owner); await store.init();
27
+ const now = () => new Date().toISOString();
28
+ const job: Job = { job_id: randomUUID(), request_id: `fixture-${randomUUID()}`, status: 'done', target: 'llm',
29
+ profile: 'synthetic', project: '', source: 'synthetic', input_preview: '', metadata: {}, created_at: now(), updated_at: now() };
30
+ await store.createJob(job);
31
+ const approvalId = await ledger.create({ job_id: job.job_id, request_id: job.request_id, provider: 'synthetic', tool: 'refund_create',
32
+ scope: 'refund.create', risk: 'high', args_hash: 'a'.repeat(64), args_json: '{"synthetic":true}' });
33
+ const decisionId = `decision-${randomUUID()}`;
34
+ let kicks = 0;
35
+ const deps: ApprovalContinuationDeps = { configStore: { approvals: ledger } as unknown as ConfigStoreContract,
36
+ stateStore: store, now, engineRuntime: { kickInhubScheduler: () => { kicks++; } } };
37
+ const decide = () => ledger.decideWithContinuation(approvalId, 'approved', 'synthetic-operator', {
38
+ decision_id: decisionId, source: 'external', auth: 'fixture', mode: 'rerun' });
39
+ return { mysql, pool, store, ledger, deps, job, approvalId, decisionId, decide, kicks: () => kicks,
40
+ close: async () => { await pool.end(); await admin.query(`DROP DATABASE \`${database}\``); await admin.end(); } };
41
+ } catch (error) {
42
+ await pool.end(); await admin.query(`DROP DATABASE \`${database}\``); await admin.end(); throw error;
43
+ }
44
+ }
45
+
46
+ for (const stage of ['after-decision', 'after-queue'] as const) test(`MySQL original approval survives actual SIGKILL ${stage}`, { skip: !enabled }, async () => {
47
+ const h = await fixture();
48
+ try {
49
+ const child = fork(fileURLToPath(new URL('../test-support/approval-continuation-crash-child.ts', import.meta.url)), [], {
50
+ execArgv: ['--import', 'tsx'], env: { PATH: process.env.PATH }, stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
51
+ });
52
+ const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve, reject) => {
53
+ const timeout = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('synthetic crash worker timeout')); }, 10_000);
54
+ child.once('error', reject);
55
+ child.once('exit', (code, signal) => { clearTimeout(timeout); resolve({ code, signal }); });
56
+ });
57
+ const checkpoint = new Promise<any>((resolve, reject) => {
58
+ child.once('message', (message: any) => message.error ? reject(new Error(message.error)) : resolve(message));
59
+ child.once('exit', (code, signal) => { if (code !== null && code !== 0 && signal !== 'SIGKILL') reject(new Error('synthetic crash worker exited early')); });
60
+ });
61
+ child.send({ mysql: h.mysql, approvalId: h.approvalId, jobId: h.job.job_id, requestId: h.job.request_id, stage, decisionId: h.decisionId });
62
+ const evidence = await checkpoint;
63
+ assert.equal(evidence.stage, stage); assert.notEqual(evidence.pid, process.pid);
64
+ assert.equal((await exited).signal, 'SIGKILL');
65
+ assert.equal((await h.ledger.get(h.approvalId))?.status, 'approved');
66
+ assert.equal((await h.ledger.getContinuation(h.approvalId))?.completed, false);
67
+ if (stage === 'after-queue') await h.store.updateJob(h.job.job_id, { status: 'done', result: { text: 'synthetic confirmed' }, metadata: {} });
68
+ const restarted = new MysqlStore(h.mysql, { get: async () => h.pool, close: async () => {} }); await restarted.init();
69
+ h.deps.stateStore = restarted;
70
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 1);
71
+ const recovered = await restarted.getJob(h.job.job_id);
72
+ assert.equal(recovered?.status, stage === 'after-decision' ? 'queued' : 'done');
73
+ assert.equal(recovered?.approval_continuation_keys?.[String(h.approvalId)], h.decisionId);
74
+ assert.equal(await reconcileApprovalContinuationsFor(h.deps), 0);
75
+ } finally { await h.close(); }
76
+ });
77
+
78
+ test('MySQL decision COMMIT acknowledgement lost retains decision and intent in the same transaction', { skip: !enabled }, async () => {
79
+ const h = await fixture();
80
+ try {
81
+ const faulty = new ApprovalLedger(() => ({ getConnection: async () => {
82
+ const connection = await h.pool.getConnection();
83
+ const commit = connection.commit.bind(connection);
84
+ connection.commit = async () => { connection.commit = commit; await commit(); throw new Error('synthetic decision COMMIT reply lost'); };
85
+ return connection;
86
+ } }));
87
+ await assert.rejects(() => faulty.decideWithContinuation(h.approvalId, 'approved', 'synthetic-operator', {
88
+ decision_id: h.decisionId, source: 'external', auth: 'fixture', mode: 'rerun' }), /COMMIT reply lost/);
89
+ assert.equal((await h.ledger.get(h.approvalId))?.status, 'approved');
90
+ assert.equal((await h.ledger.getContinuation(h.approvalId))?.decision_key, h.decisionId);
91
+ assert.equal(await h.decide(), 'same');
92
+ assert.equal((await continueApprovalDecisionFor(h.deps, h.approvalId)).rerun, true);
93
+ } finally { await h.close(); }
94
+ });
95
+
96
+ test('MySQL concurrent continuation and completed new run have one durable admission', { skip: !enabled }, async () => {
97
+ const h = await fixture();
98
+ try {
99
+ const decisions = await Promise.all(Array.from({ length: 8 }, () => h.decide()));
100
+ assert.equal(decisions.filter(item => item === 'decided').length, 1);
101
+ assert.equal(decisions.filter(item => item === 'same').length, 7);
102
+ const results = await Promise.all(Array.from({ length: 8 }, () => continueApprovalDecisionFor(h.deps, h.approvalId)));
103
+ assert.equal(results.filter(item => item.rerun).length, 1);
104
+ const intent = await h.ledger.getContinuation(h.approvalId);
105
+ assert.equal(intent?.completed, true);
106
+ await h.store.updateJob(h.job.job_id, { status: 'done', metadata: {}, approval_continuation_keys: {} });
107
+ assert.equal(await h.store.requeueApprovedJobOnce({ job_id: h.job.job_id, request_id: h.job.request_id,
108
+ approval_id: h.approvalId, decision_key: h.decisionId }), 'already_queued');
109
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
110
+ } finally { await h.close(); }
111
+ });
112
+
113
+ test('MySQL missing continuation table rolls back approval decision rather than orphaning it', { skip: !enabled }, async () => {
114
+ const h = await fixture();
115
+ try {
116
+ await h.pool.query('DROP TABLE bz_approval_continuations');
117
+ await assert.rejects(h.decide);
118
+ assert.equal((await h.ledger.get(h.approvalId))?.status, 'pending');
119
+ } finally { await h.close(); }
120
+ });
121
+
122
+ test('MySQL atomic admission rechecks approval consumed after the helper observation', { skip: !enabled }, async () => {
123
+ const h = await fixture();
124
+ try {
125
+ await h.decide();
126
+ const queue = h.store.requeueApprovedJobOnce.bind(h.store);
127
+ h.store.requeueApprovedJobOnce = async (input) => {
128
+ assert.equal(await h.ledger.use(h.approvalId), true);
129
+ return await queue(input);
130
+ };
131
+ const result = await continueApprovalDecisionFor(h.deps, h.approvalId);
132
+ assert.equal(result.rerun, false);
133
+ assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
134
+ assert.equal((await h.store.getJob(h.job.job_id))?.approval_continuation_keys, undefined);
135
+ assert.equal((await h.ledger.getContinuation(h.approvalId))?.completed, true);
136
+ assert.equal(h.kicks(), 0);
137
+ } finally { await h.close(); }
138
+ });
@@ -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
  }