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
@@ -94,7 +94,7 @@
94
94
  "node_modules/mammoth|dependencies|argparse|~1.0.3"
95
95
  ],
96
96
  "reviewedUsageFiles": {
97
- "src/adapters/llm/file.ts": "0c101ab6d18ac544285e3f0c9efdf0584d8833327625ff88a42fc51af9097f7a"
97
+ "src/adapters/llm/file.ts": "7e793f4d4a36402cf7b4ca295483ab7327ca29fb045c91c2ef35c3c4f9187d84"
98
98
  }
99
99
  },
100
100
  "web-admin": {
@@ -0,0 +1,4 @@
1
+ -- Supports the bounded owner-local keyset scan of already saved usage evidence.
2
+ -- No original result, request ID, price snapshot or monetary ledger is rewritten.
3
+ ALTER TABLE bz_usage_billing_requests
4
+ ADD KEY idx_usage_reconciliation_scan (billing_state, updated_at, id);
@@ -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';
@@ -0,0 +1,10 @@
1
+ -- Keep native channels separate from executor notification targets. Legacy rows
2
+ -- stay unclassified until their original job can be checked by Core.
3
+ ALTER TABLE `bz_delivery_dlq`
4
+ ADD COLUMN `delivery_kind` VARCHAR(24) DEFAULT NULL,
5
+ ADD COLUMN `notification_job_id` VARCHAR(191) DEFAULT NULL,
6
+ ADD COLUMN `executor_replay_key` VARCHAR(191) DEFAULT NULL;
7
+
8
+ ALTER TABLE `bz_jobs`
9
+ ADD COLUMN `delivery_replay_keys` JSON DEFAULT NULL
10
+ COMMENT 'Core-owned notification DLQ queue markers, never business metadata';
package/sql/README.en.md CHANGED
@@ -62,3 +62,9 @@ For incompatible changes, use a transition window and document the upgrade path.
62
62
  ## Naming
63
63
 
64
64
  Use `NNN_short_description.sql` with three-digit increasing numbers. Gaps are allowed. New files should use the current maximum number plus one.
65
+
66
+ ## Core 0.9.3: migration 067 for notification DLQ replay
67
+
68
+ `067_delivery_dlq_replay.sql` adds DLQ `delivery_kind`, `notification_job_id`, `executor_replay_key` and Job `delivery_replay_keys` for original notification binding and separate admission markers. Legacy rows remain without bulk-guessing kinds. Replay verifies the original notification child rather than rerunning its business parent.
69
+
70
+ Explicitly apply 067 before all new Core MySQL DLQ reads/writes, including native-channel record/get, and match state/config adapters. Startup does not migrate. Rollback retains queues, markers and history. Older artifact schema manifests do not automatically accept 067; verify in an isolated copy without clearing markers to replay or deleting migration rows to bypass checks. See the [0.9.3 upgrade guide](../docs/UPGRADE_v0.9.3.en.md).
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 引入,只给已有归档增加
@@ -71,3 +80,9 @@ Host 需把官方 SQL 一起打包,并通过现有迁移入口显式执行;
71
80
  ## 命名
72
81
 
73
82
  `NNN_简短描述.sql`,三位编号递增。编号只用于排序,**允许缺号**;新文件取当前最大编号 +1 即可。
83
+
84
+ ## Core 0.9.3:067 通知死信重投
85
+
86
+ `067_delivery_dlq_replay.sql` 增加 DLQ 的 `delivery_kind`、`notification_job_id`、`executor_replay_key` 及 Job 的 `delivery_replay_keys`,保存原通知绑定和独立入队标记。旧行保留,不批量猜测类型;重投时核对原通知子任务,不能重跑业务父任务。
87
+
88
+ 启动新 Core 的全部 MySQL DLQ 读写前显式应用 067,包含原生渠道 record/get,并配套 state/config 仓储。运行时不自动迁移。回退保留队列、标记和账本;旧制品 schema manifest 不保证接受 067,须在隔离副本核验,不能删标记重投或删迁移记录绕过检查。见[0.9.3 升级指南](../docs/UPGRADE_v0.9.3.md)。
@@ -79,3 +79,62 @@ test('buildFileContext: PDF 文本型文档可本地抽取并审计 parser/pages
79
79
  assert.equal(audits[0]?.detail['parser'], 'pdf');
80
80
  assert.equal(audits[0]?.detail['pages'], 1);
81
81
  });
82
+
83
+ test('buildFileContext: 超限声明不读取正文,不运行解析器', async () => {
84
+ let pulls = 0;
85
+ let cancels = 0;
86
+ const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
87
+ const got = await withMockFetch(() => new Response(new ReadableStream<Uint8Array>({
88
+ pull(controller) { pulls++; controller.enqueue(new Uint8Array(1024)); },
89
+ cancel() { cancels++; },
90
+ }, { highWaterMark: 0 }), { headers: { 'content-type': 'text/plain', 'content-length': '1025' } }),
91
+ () => buildFileContext({ files: [{ url: 'https://synthetic.invalid/a.txt' }],
92
+ config: { mode: 'extract', max_bytes: 1024 }, audit: (event, detail) => audits.push({ event, detail }) }));
93
+ assert.match(got, /文件过大/);
94
+ assert.equal(pulls, 0);
95
+ assert.equal(cancels, 1);
96
+ assert.equal(audits[0]!.detail.ok, false);
97
+ assert.equal(audits[0]!.detail.parser, undefined);
98
+ assert.equal(audits[0]!.detail.bytes, undefined, 'declared length is not consumed bytes');
99
+ });
100
+
101
+ test('buildFileContext: 无长度/低报长度均流式停止,半截文件不注入', async () => {
102
+ for (const declared of [false, true]) {
103
+ let pulls = 0;
104
+ let cancels = 0;
105
+ const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
106
+ const got = await withMockFetch(() => new Response(new ReadableStream<Uint8Array>({
107
+ pull(controller) { pulls++; controller.enqueue(new Uint8Array(pulls === 1 ? 1024 : 1).fill(65)); },
108
+ cancel() { cancels++; },
109
+ }, { highWaterMark: 0 }), { headers: { 'content-type': 'text/plain', ...(declared ? { 'content-length': '1' } : {}) } }),
110
+ () => buildFileContext({ files: [{ url: 'https://synthetic.invalid/a.txt' }],
111
+ config: { mode: 'extract', max_bytes: 1024 }, audit: (event, detail) => audits.push({ event, detail }) }));
112
+ assert.match(got, /文件过大/);
113
+ assert.equal(got.includes('AAAA'), false);
114
+ assert.equal(pulls, 2);
115
+ assert.equal(cancels, 1);
116
+ assert.equal(audits[0]!.detail.ok, false);
117
+ assert.equal(audits[0]!.detail.parser, undefined);
118
+ assert.equal(audits[0]!.detail.bytes, 1025);
119
+ }
120
+ });
121
+
122
+ test('buildFileContext: 恰好达到预算的文件仍正常抽取', async () => {
123
+ const got = await withMockFetch(() => new Response('a'.repeat(1024)),
124
+ () => buildFileContext({ files: [{ url: 'https://synthetic.invalid/a.txt' }], config: { mode: 'extract', max_bytes: 1024 } }));
125
+ assert.equal(got.includes('a'.repeat(1024)), true);
126
+ assert.equal(got.includes('文件过大'), false);
127
+ });
128
+
129
+ test('buildFileContext: HTTP 错误取消正文而不读取', async () => {
130
+ let cancels = 0;
131
+ let pulls = 0;
132
+ const got = await withMockFetch(() => new Response(new ReadableStream<Uint8Array>({
133
+ pull(controller) { pulls++; controller.enqueue(new Uint8Array(1024)); },
134
+ cancel() { cancels++; return new Promise<void>(() => undefined); },
135
+ }, { highWaterMark: 0 }), { status: 500 }),
136
+ () => buildFileContext({ files: [{ url: 'https://synthetic.invalid/a.txt' }], config: { mode: 'extract' } }));
137
+ assert.match(got, /文件下载失败(HTTP 500)/);
138
+ assert.equal(cancels, 1);
139
+ assert.equal(pulls, 0);
140
+ });
@@ -1,5 +1,6 @@
1
1
  import type { FileRef } from '../../core/platform/content';
2
2
  import type { ResolvedCredential } from './perception';
3
+ import { cancelResponseBody, readResponseBody, ResponseBodyLimitError } from '../../core/platform/http-body';
3
4
 
4
5
  export interface FileConfig {
5
6
  /** 文件处理凭证名;留空复用 brain 凭证 */
@@ -153,10 +154,12 @@ async function fetchFile(file: FileRef, index: number, maxBytes: number): Promis
153
154
  const name = fileName(file, index);
154
155
  try {
155
156
  const resp = await fetch(file.url, { signal: AbortSignal.timeout(FILE_TIMEOUT_MS) });
156
- if (!resp.ok) return { ok: false, name, text: `文件下载失败(HTTP ${resp.status}):${file.url}` };
157
+ if (!resp.ok) {
158
+ cancelResponseBody(resp);
159
+ return { ok: false, name, text: `文件下载失败(HTTP ${resp.status}):${file.url}` };
160
+ }
157
161
  const mime = String(resp.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase();
158
- const ab = await resp.arrayBuffer();
159
- if (ab.byteLength > maxBytes) return { ok: false, name, mime, bytes: ab.byteLength, text: `文件过大(${ab.byteLength} bytes > ${maxBytes} bytes),未读取内容:${file.url}` };
162
+ const ab = await readResponseBody(resp, maxBytes);
160
163
  const extracted = await extractFileText(file, mime, ab);
161
164
  return {
162
165
  ok: extracted.ok,
@@ -168,6 +171,10 @@ async function fetchFile(file: FileRef, index: number, maxBytes: number): Promis
168
171
  text: extracted.text,
169
172
  };
170
173
  } catch (e) {
174
+ if (e instanceof ResponseBodyLimitError) {
175
+ return { ok: false, name, ...(e.source === 'stream' ? { bytes: e.observedBytes } : {}),
176
+ text: `文件过大(超过 ${maxBytes} bytes 上限),已停止下载:${file.url}` };
177
+ }
171
178
  const isTimeout = (e as Error)?.name === 'TimeoutError';
172
179
  return { ok: false, name, text: isTimeout ? `文件下载超时(${FILE_TIMEOUT_MS}ms):${file.url}` : `文件读取失败:${String(e).slice(0, 200)}` };
173
180
  }
@@ -215,7 +222,7 @@ export async function buildFileContext(opts: {
215
222
  : FILE_MODE_DEFAULT;
216
223
  if (!opts.files.length || mode === 'off' || mode === 'inline') return '';
217
224
 
218
- const maxBytes = Math.max(1024, Math.min(Number(cfg.max_bytes ?? FILE_MAX_BYTES_DEFAULT) || FILE_MAX_BYTES_DEFAULT, 100 * 1024 * 1024));
225
+ const maxBytes = Math.floor(Math.max(1024, Math.min(Number(cfg.max_bytes ?? FILE_MAX_BYTES_DEFAULT) || FILE_MAX_BYTES_DEFAULT, 100 * 1024 * 1024)));
219
226
  const maxChars = Math.max(1000, Math.min(Number(cfg.max_chars ?? FILE_MAX_CHARS_DEFAULT) || FILE_MAX_CHARS_DEFAULT, 200000));
220
227
  const lines: string[] = [];
221
228
  const perFileChars = Math.max(1000, Math.floor(maxChars / Math.max(1, opts.files.length)));
@@ -616,7 +616,9 @@ test('Agent direct: transport uncertainty and lost client receipts resume the or
616
616
  attempts++;
617
617
  if (failure === 'fetch_rejected') throw new TypeError('synthetic transport failure');
618
618
  if (failure === 'client_receipt_lost') return new Response('{"ok":true}', { status: 200 });
619
- return { status: 200, text: async () => { throw new TypeError('synthetic response body loss'); } } as unknown as Response;
619
+ return new Response(new ReadableStream({
620
+ start(controller) { controller.error(new TypeError('synthetic response body loss')); },
621
+ }), { status: 200 });
620
622
  });
621
623
  const fx = fixture('https://business.invalid');
622
624
  if (kind === 'idempotent_write') {
@@ -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
+ });