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,357 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+
5
+ type IdentityState = 'verified' | 'unknown' | 'not_checked' | 'mismatch';
6
+ type CheckState = 'pass' | 'fail' | 'unknown' | 'not_checked';
7
+ type JsonObject = Record<string, unknown>;
8
+ type Check = { id: string; state: CheckState; reason: string; http_status?: number };
9
+ type Artifact = { version: string | null; commit: string | null; latest_migration: string | null; migration_count: number | null };
10
+
11
+ export interface DeploymentDoctorOptions {
12
+ root: string;
13
+ url?: string;
14
+ readiness?: boolean;
15
+ expectedVersion?: string;
16
+ expectedCommit?: string;
17
+ timeoutMs?: number;
18
+ }
19
+
20
+ export interface DeploymentDoctorReport {
21
+ schema: 'bailing.deployment-diagnostics.v1';
22
+ checked_at: string;
23
+ mode: 'deployment';
24
+ result: 'pass' | 'fail' | 'incomplete';
25
+ exit_code: 0 | 1 | 2;
26
+ target: { origin: string; base_path: 'root' | 'configured_not_printed' } | null;
27
+ source: Artifact & { state: IdentityState; commit_basis: 'git_head' | 'build_info' | 'unavailable'; worktree: 'clean' | 'dirty' | 'not_checked'; basis: 'local_metadata'; artifact_integrity: 'not_checked' };
28
+ runtime: Artifact & { state: IdentityState; paused: boolean | null; backend: 'mysql' | 'jsonl' | null; basis: 'reported_metadata'; artifact_integrity: 'not_checked' };
29
+ comparison: { state: IdentityState; expected_version: string | null; expected_commit: string | null; basis: 'local_source' | 'explicit_expectation'; version_matches: boolean | null; commit_matches: boolean | null };
30
+ configuration: { state: 'unknown'; reason: 'effective_configuration_not_read'; local_files: { config_json: string; dotenv: string }; credentials: 'not_checked' };
31
+ database: { state: 'not_checked'; reason: 'no_direct_database_connection' };
32
+ migrations: { identity: { state: 'not_checked'; reason: 'authenticated_migration_ledger_not_requested' }; readiness: { state: IdentityState; pending: number | null; reason: string } };
33
+ protected_endpoints: { state: 'not_checked'; reason: 'no_credentials_or_login'; paths: readonly ['/admin/api/version', '/admin/api/status'] };
34
+ upgrade: { state: 'not_checked'; reason: 'diagnostics_do_not_authorize_upgrade_or_rollback' };
35
+ checks: Check[];
36
+ scope: { methods: readonly ['GET']; paths: string[]; timeout_ms_per_request: number; max_response_bytes: number; redirects: 'rejected'; model_calls: false; mutations: false };
37
+ }
38
+
39
+ const MAX_BYTES = 64 * 1024;
40
+ const PUBLIC_PATHS = ['/health', '/version', '/health/ready'] as const;
41
+ const DEFAULT_TIMEOUT = 5000;
42
+ const EMPTY_ARTIFACT: Artifact = { version: null, commit: null, latest_migration: null, migration_count: null };
43
+
44
+ function object(value: unknown): JsonObject | null {
45
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : null;
46
+ }
47
+
48
+ function version(value: unknown): string | null {
49
+ return typeof value === 'string' && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value) && value.length <= 80 ? value : null;
50
+ }
51
+
52
+ function commit(value: unknown): string | null {
53
+ return typeof value === 'string' && /^[a-f0-9]{12,64}$/i.test(value) ? value.toLowerCase() : null;
54
+ }
55
+
56
+ function migration(value: unknown): string | null {
57
+ return typeof value === 'string' && /^\d{3}_[a-z0-9_]+\.sql$/.test(value) && value.length <= 160 ? value : null;
58
+ }
59
+
60
+ function count(value: unknown): number | null {
61
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
62
+ }
63
+
64
+ function readJson(file: string): JsonObject | null {
65
+ try {
66
+ const stat = statSync(file);
67
+ if (!stat.isFile() || stat.size > MAX_BYTES) return null;
68
+ return object(JSON.parse(readFileSync(file, 'utf8')));
69
+ } catch { return null; }
70
+ }
71
+
72
+ function presence(file: string): 'present' | 'absent' | 'unreadable' {
73
+ try { return statSync(file).isFile() ? 'present' : 'unreadable'; }
74
+ catch (error) { return object(error)?.code === 'ENOENT' ? 'absent' : 'unreadable'; }
75
+ }
76
+
77
+ function sourceIdentity(root: string): DeploymentDoctorReport['source'] {
78
+ const pkg = readJson(join(root, 'package.json'));
79
+ let gitCommit: string | null = null;
80
+ let worktree: DeploymentDoctorReport['source']['worktree'] = 'not_checked';
81
+ // These are the only subprocesses in deployment mode: Git reads checkout
82
+ // identity and dirtiness. No package scripts, config loader or DB drivers.
83
+ try {
84
+ statSync(join(root, '.git'));
85
+ const env = { ...process.env };
86
+ // Ambient Git overrides must not select a different repository or index.
87
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR']) delete env[key];
88
+ const gitOptions = {
89
+ cwd: root, env, encoding: 'utf8' as const, stdio: ['ignore', 'pipe', 'ignore'] as ['ignore', 'pipe', 'ignore'], timeout: 1000, maxBuffer: 1024 * 1024,
90
+ };
91
+ gitCommit = commit(execFileSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', 'rev-parse', '--verify', 'HEAD'], {
92
+ ...gitOptions, maxBuffer: 4096,
93
+ }).trim());
94
+ // Only emit clean/dirty, never filenames or contents. Disable fsmonitor
95
+ // hooks and optional index writes for the read-only command.
96
+ worktree = execFileSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', 'status', '--porcelain', '--untracked-files=normal', '--ignore-submodules=all'], gitOptions).trim() ? 'dirty' : 'clean';
97
+ } catch { /* Source archives may have only build-info.json. */ }
98
+ const buildCommit = commit(object(readJson(join(root, 'build-info.json'))?.build)?.commit);
99
+ let files: string[] | null = null;
100
+ try { files = readdirSync(join(root, 'sql')).filter((file) => migration(file) !== null).sort(); }
101
+ catch { /* Missing packaged SQL is unknown, not a database failure. */ }
102
+ return {
103
+ state: pkg?.name === 'bailinghub' && version(pkg.version) && (gitCommit ?? buildCommit) ? 'verified' : 'unknown',
104
+ version: pkg?.name === 'bailinghub' ? version(pkg.version) : null,
105
+ commit: gitCommit ?? buildCommit,
106
+ commit_basis: gitCommit ? 'git_head' : buildCommit ? 'build_info' : 'unavailable',
107
+ worktree, basis: 'local_metadata', artifact_integrity: 'not_checked',
108
+ latest_migration: files?.at(-1) ?? null,
109
+ migration_count: files?.length ?? null,
110
+ };
111
+ }
112
+
113
+ function targetUrl(input: string): URL | null {
114
+ try {
115
+ const url = new URL(input);
116
+ // Refuse credentials rather than silently converting an authenticated URL
117
+ // into a request. Never echo an input URL or an invalid argument.
118
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) return null;
119
+ if (!/^\/(?:[a-zA-Z0-9._~-]+\/)*[a-zA-Z0-9._~-]*$/.test(url.pathname)) return null;
120
+ if (url.pathname.split('/').some((part) => part === '.' || part === '..')) return null;
121
+ url.pathname = url.pathname.replace(/\/+$/, '');
122
+ return url;
123
+ } catch { return null; }
124
+ }
125
+
126
+ type Probe = { state: CheckState; reason: string; http_status?: number; body?: JsonObject };
127
+
128
+ async function probe(target: URL, path: typeof PUBLIC_PATHS[number], timeoutMs: number): Promise<Probe> {
129
+ if (!PUBLIC_PATHS.includes(path)) throw new Error('unsupported_diagnostic_path');
130
+ const url = new URL(target.href);
131
+ url.pathname = `${target.pathname.replace(/\/+$/, '')}${path}`;
132
+ const controller = new AbortController();
133
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
134
+ try {
135
+ const response = await fetch(url, {
136
+ method: 'GET', headers: { accept: 'application/json' }, credentials: 'omit',
137
+ redirect: 'manual', signal: controller.signal,
138
+ });
139
+ const http_status = response.status;
140
+ if (http_status >= 300 && http_status < 400) {
141
+ controller.abort();
142
+ return { state: 'fail', reason: 'redirect_rejected', http_status };
143
+ }
144
+ if (http_status === 401 || http_status === 403) {
145
+ controller.abort();
146
+ return { state: 'not_checked', reason: 'authentication_required', http_status };
147
+ }
148
+ if (http_status !== 200 && !(path === '/health/ready' && http_status === 503)) {
149
+ controller.abort();
150
+ return { state: 'fail', reason: 'unexpected_http_status', http_status };
151
+ }
152
+ const contentType = (response.headers.get('content-type') ?? '').split(';')[0]?.trim().toLowerCase();
153
+ if (contentType !== 'application/json' && !/^application\/[a-z0-9.-]+\+json$/.test(contentType ?? '')) {
154
+ controller.abort();
155
+ return { state: 'fail', reason: 'unexpected_content_type', http_status };
156
+ }
157
+ const length = response.headers.get('content-length');
158
+ if (length && /^\d+$/.test(length) && Number(length) > MAX_BYTES) {
159
+ controller.abort();
160
+ return { state: 'fail', reason: 'response_too_large', http_status };
161
+ }
162
+ const reader = response.body?.getReader();
163
+ const chunks: Uint8Array[] = [];
164
+ let bytes = 0;
165
+ if (reader) {
166
+ while (true) {
167
+ const next = await reader.read();
168
+ if (next.done) break;
169
+ bytes += next.value.byteLength;
170
+ if (bytes > MAX_BYTES) {
171
+ controller.abort();
172
+ return { state: 'fail', reason: 'response_too_large', http_status };
173
+ }
174
+ chunks.push(next.value);
175
+ }
176
+ }
177
+ let body: JsonObject | null;
178
+ try { body = object(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
179
+ catch { return { state: 'fail', reason: 'invalid_json', http_status }; }
180
+ if (!body) return { state: 'fail', reason: 'invalid_json_object', http_status };
181
+ return { state: 'pass', reason: 'response_received', http_status, body };
182
+ } catch {
183
+ return { state: 'fail', reason: controller.signal.aborted ? 'request_timeout' : 'unreachable' };
184
+ } finally { clearTimeout(timer); }
185
+ }
186
+
187
+ function identity(body: JsonObject | undefined): Artifact {
188
+ const app = object(body?.app);
189
+ const migrations = object(body?.migrations);
190
+ return {
191
+ version: app?.name === 'bailinghub' ? version(app.version) : null,
192
+ commit: commit(object(body?.build)?.commit),
193
+ latest_migration: migration(migrations?.latest),
194
+ migration_count: count(migrations?.total),
195
+ };
196
+ }
197
+
198
+ function sameCommit(a: string | null, b: string | null): boolean | null {
199
+ return a && b ? a.startsWith(b) || b.startsWith(a) : null;
200
+ }
201
+
202
+ function addProbe(checks: Check[], id: string, result: Probe): void {
203
+ checks.push({ id, state: result.state, reason: result.reason, ...(result.http_status ? { http_status: result.http_status } : {}) });
204
+ }
205
+
206
+ export async function runDeploymentDoctor(options: DeploymentDoctorOptions): Promise<DeploymentDoctorReport> {
207
+ const source = sourceIdentity(options.root);
208
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT;
209
+ const report: DeploymentDoctorReport = {
210
+ schema: 'bailing.deployment-diagnostics.v1', checked_at: new Date().toISOString(), mode: 'deployment',
211
+ result: 'incomplete', exit_code: 2, target: null, source,
212
+ runtime: { ...EMPTY_ARTIFACT, state: 'not_checked', paused: null, backend: null, basis: 'reported_metadata', artifact_integrity: 'not_checked' },
213
+ comparison: {
214
+ state: 'not_checked', expected_version: options.expectedVersion === undefined ? source.version : version(options.expectedVersion),
215
+ expected_commit: options.expectedCommit === undefined ? source.commit : commit(options.expectedCommit),
216
+ basis: options.expectedVersion || options.expectedCommit ? 'explicit_expectation' : 'local_source',
217
+ version_matches: null, commit_matches: null,
218
+ },
219
+ configuration: { state: 'unknown', reason: 'effective_configuration_not_read', local_files: {
220
+ config_json: presence(join(options.root, 'config.json')), dotenv: presence(join(options.root, '.env')),
221
+ }, credentials: 'not_checked' },
222
+ database: { state: 'not_checked', reason: 'no_direct_database_connection' },
223
+ migrations: { identity: { state: 'not_checked', reason: 'authenticated_migration_ledger_not_requested' },
224
+ readiness: { state: 'not_checked', pending: null, reason: 'readiness_not_requested' } },
225
+ protected_endpoints: { state: 'not_checked', reason: 'no_credentials_or_login', paths: ['/admin/api/version', '/admin/api/status'] },
226
+ upgrade: { state: 'not_checked', reason: 'diagnostics_do_not_authorize_upgrade_or_rollback' },
227
+ checks: [], scope: { methods: ['GET'], paths: [], timeout_ms_per_request: timeoutMs, max_response_bytes: MAX_BYTES,
228
+ redirects: 'rejected', model_calls: false, mutations: false },
229
+ };
230
+ report.checks.push({ id: 'source.package', state: source.version ? 'pass' : 'unknown', reason: source.version ? 'local_package_identity_read' : 'local_package_identity_unavailable' });
231
+ report.checks.push({ id: 'source.commit', state: source.commit ? 'pass' : 'unknown', reason: source.commit ? 'local_git_or_build_commit_read' : 'local_commit_unavailable' });
232
+ const target = options.url ? targetUrl(options.url) : null;
233
+ if (!options.url) report.checks.push({ id: 'target', state: 'not_checked', reason: 'explicit_url_required' });
234
+ else if (!target) report.checks.push({ id: 'target', state: 'fail', reason: 'invalid_or_credential_bearing_url' });
235
+ else if (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 30_000
236
+ || (options.expectedVersion !== undefined && !version(options.expectedVersion))
237
+ || (options.expectedCommit !== undefined && !commit(options.expectedCommit))) {
238
+ // Library callers receive the same redacted failure as the CLI. Never
239
+ // send a request using invalid options or echo an invalid expectation.
240
+ report.comparison.expected_version = version(report.comparison.expected_version);
241
+ report.comparison.expected_commit = commit(report.comparison.expected_commit);
242
+ report.checks.push({ id: 'options', state: 'fail', reason: 'invalid_diagnostic_options' });
243
+ } else {
244
+ report.target = { origin: target.origin, base_path: target.pathname === '/' ? 'root' : 'configured_not_printed' };
245
+ report.scope.paths = options.readiness ? [...PUBLIC_PATHS] : ['/health', '/version'];
246
+ const health = await probe(target, '/health', timeoutMs);
247
+ const runtimeVersion = await probe(target, '/version', timeoutMs);
248
+ addProbe(report.checks, 'http.health', health);
249
+ addProbe(report.checks, 'http.version', runtimeVersion);
250
+ if (health.body && health.body.status !== 'ok') report.checks.push({ id: 'runtime.health', state: 'fail', reason: 'health_status_not_ok' });
251
+ const observed = identity(runtimeVersion.body);
252
+ const healthIdentity = identity(health.body);
253
+ report.runtime = { ...observed, state: observed.version && observed.commit ? 'verified' : 'unknown',
254
+ paused: typeof health.body?.paused === 'boolean' ? health.body.paused : null,
255
+ backend: health.body?.backend === 'mysql' || health.body?.backend === 'jsonl' ? health.body.backend : null,
256
+ basis: 'reported_metadata', artifact_integrity: 'not_checked' };
257
+ if (!observed.version || !observed.commit) report.checks.push({ id: 'runtime.identity', state: 'unknown', reason: 'public_version_or_commit_unavailable' });
258
+ if ([health.body, runtimeVersion.body].some((body) => typeof object(body?.app)?.name === 'string' && object(body?.app)?.name !== 'bailinghub')) {
259
+ report.runtime.state = 'mismatch';
260
+ report.checks.push({ id: 'runtime.application', state: 'fail', reason: 'unexpected_application_identity' });
261
+ }
262
+ if (healthIdentity.version && observed.version && (healthIdentity.version !== observed.version || sameCommit(healthIdentity.commit, observed.commit) === false)) {
263
+ report.runtime.state = 'mismatch';
264
+ report.checks.push({ id: 'runtime.consistency', state: 'fail', reason: 'health_version_identity_mismatch' });
265
+ }
266
+ const comparison = report.comparison;
267
+ comparison.version_matches = comparison.expected_version && observed.version ? comparison.expected_version === observed.version : null;
268
+ comparison.commit_matches = sameCommit(comparison.expected_commit, observed.commit);
269
+ comparison.state = comparison.version_matches === false || comparison.commit_matches === false ? 'mismatch'
270
+ : comparison.version_matches === true && comparison.commit_matches === true ? 'verified' : 'unknown';
271
+ const dirtySource = source.worktree === 'dirty' && comparison.basis === 'local_source';
272
+ const unavailableWorktree = source.commit_basis === 'git_head' && source.worktree === 'not_checked' && comparison.basis === 'local_source';
273
+ if ((dirtySource || unavailableWorktree) && comparison.state === 'verified') comparison.state = 'unknown';
274
+ report.checks.push({ id: 'artifact.comparison', state: comparison.state === 'verified' ? 'pass' : comparison.state === 'mismatch' ? 'fail' : 'unknown',
275
+ reason: comparison.state === 'verified' ? 'reported_identity_matches_expectation' : comparison.state === 'mismatch' ? 'reported_identity_mismatch' : dirtySource ? 'local_worktree_modified' : unavailableWorktree ? 'local_worktree_unavailable' : 'version_or_commit_unavailable' });
276
+ const migrationMatches = source.latest_migration && observed.latest_migration ? source.latest_migration === observed.latest_migration : null;
277
+ report.checks.push({ id: 'artifact.migrations', state: comparison.basis === 'explicit_expectation' ? 'not_checked'
278
+ : migrationMatches === null || source.migration_count === null || observed.migration_count === null ? 'unknown'
279
+ : migrationMatches && source.migration_count === observed.migration_count ? 'pass' : 'fail',
280
+ reason: comparison.basis === 'explicit_expectation' ? 'different_source_comparison_not_requested' : migrationMatches === null || source.migration_count === null || observed.migration_count === null ? 'packaged_migration_list_unavailable' : 'packaged_migrations_compared_not_applied_ledger' });
281
+ if (options.readiness) {
282
+ const ready = await probe(target, '/health/ready', timeoutMs);
283
+ addProbe(report.checks, 'http.readiness', ready);
284
+ const checks = object(ready.body?.checks);
285
+ const migrations = object(checks?.migrations);
286
+ report.migrations.readiness.pending = count(migrations?.pending);
287
+ if (ready.body?.status === 'not_ready' || migrations?.status === 'pending' || migrations?.status === 'failed' || checks?.database === 'failed') {
288
+ report.migrations.readiness.state = 'mismatch';
289
+ report.migrations.readiness.reason = 'server_reports_not_ready';
290
+ report.checks.push({ id: 'runtime.readiness', state: 'fail', reason: 'server_reports_not_ready' });
291
+ } else if (ready.http_status === 200 && ready.body?.status === 'ready' && checks?.database === 'ok' && migrations?.status === 'ok' && migrations.pending === 0) {
292
+ report.migrations.readiness = { state: 'verified', pending: 0, reason: 'server_readiness_summary_only' };
293
+ report.checks.push({ id: 'runtime.readiness', state: 'pass', reason: 'server_readiness_summary_only' });
294
+ } else {
295
+ report.migrations.readiness.state = ready.state === 'not_checked' ? 'not_checked' : 'unknown';
296
+ report.migrations.readiness.reason = ready.state === 'not_checked' ? 'authentication_required' : 'database_or_migrations_not_verified';
297
+ report.checks.push({ id: 'runtime.readiness', state: report.migrations.readiness.state, reason: report.migrations.readiness.reason });
298
+ }
299
+ }
300
+ }
301
+ if (report.checks.some((check) => check.state === 'fail')) { report.result = 'fail'; report.exit_code = 1; }
302
+ else if (report.checks.some((check) => check.state === 'unknown' || (check.id.startsWith('http.') && check.state === 'not_checked')) || !report.target) { report.result = 'incomplete'; report.exit_code = 2; }
303
+ else { report.result = 'pass'; report.exit_code = 0; }
304
+ return report;
305
+ }
306
+
307
+ export const DEPLOYMENT_DOCTOR_USAGE = `BailingHub read-only deployment doctor
308
+ Usage: npm run doctor -- --deployment --url http://127.0.0.1:18900 --json
309
+ Options:
310
+ --url <http(s) URL> Explicit Core base URL, no credentials/query/fragment
311
+ --json Print one JSON report (use npm run --silent for clean stdout)
312
+ --expect-version <v> Expected package version; otherwise use local package.json
313
+ --expect-commit <SHA> Expected 12-64 hex commit; otherwise local Git/build info
314
+ --timeout-ms <100-30000> Per-request timeout, default 5000 ms, 64 KiB response cap
315
+ --readiness Also GET /health/ready (server reads its database/ledger)
316
+ --help Show this help
317
+ Exit: 0 selected checks pass; 1 observed failure/mismatch; 2 incomplete; 64 invalid arguments.
318
+ No login, model calls, direct DB connection, migration, update or rollback. Protected
319
+ endpoints and the applied migration identity remain not_checked, including on exit 0.
320
+ `;
321
+
322
+ export async function runDeploymentDoctorCli(args: string[], root: string): Promise<number> {
323
+ const options: DeploymentDoctorOptions = { root };
324
+ let json = false;
325
+ let invalid = false;
326
+ for (let i = 0; i < args.length; i++) {
327
+ const arg = args[i];
328
+ if (arg === '--deployment') continue;
329
+ if (arg === '--help') { console.log(DEPLOYMENT_DOCTOR_USAGE); return 0; }
330
+ if (arg === '--json') { json = true; continue; }
331
+ if (arg === '--readiness') { options.readiness = true; continue; }
332
+ const value = args[i + 1];
333
+ if (!value || value.startsWith('--')) { invalid = true; continue; }
334
+ if (arg === '--url') options.url = value;
335
+ else if (arg === '--expect-version') { options.expectedVersion = value; invalid ||= !version(value); }
336
+ else if (arg === '--expect-commit') { options.expectedCommit = value; invalid ||= !commit(value); }
337
+ else if (arg === '--timeout-ms') { options.timeoutMs = /^\d+$/.test(value) ? Number(value) : NaN; invalid ||= !Number.isInteger(options.timeoutMs) || options.timeoutMs < 100 || options.timeoutMs > 30_000; }
338
+ else invalid = true;
339
+ i++;
340
+ }
341
+ if (invalid) {
342
+ // No argv values, URLs, headers, exception messages or response bodies are
343
+ // ever included in the diagnostic error output.
344
+ const failure = { schema: 'bailing.deployment-diagnostics.v1', result: 'invalid_arguments', exit_code: 64, reason: 'invalid_or_unsupported_argument' };
345
+ if (json) console.log(JSON.stringify(failure));
346
+ else console.error('Invalid deployment doctor arguments. Use --deployment --help.');
347
+ return 64;
348
+ }
349
+ const report = await runDeploymentDoctor(options);
350
+ if (json) console.log(JSON.stringify(report, null, 2));
351
+ else {
352
+ console.log(`BailingHub deployment doctor: ${report.result}`);
353
+ for (const check of report.checks) console.log(`${check.state} ${check.id}: ${check.reason}`);
354
+ console.log('Applied migration identity and protected endpoints: not_checked. Use --json for scope and details.');
355
+ }
356
+ return report.exit_code;
357
+ }
package/scripts/doctor.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { runDeploymentDoctorCli } from './doctor-deployment';
5
+
6
+ if (process.argv.includes('--deployment')) {
7
+ process.exitCode = await runDeploymentDoctorCli(process.argv.slice(2), process.cwd());
8
+ } else {
4
9
 
5
10
  type Check = { name: string; run: () => void };
6
11
 
@@ -57,7 +62,8 @@ function checkRequiredFiles(): void {
57
62
  }
58
63
 
59
64
  function checkGitIgnore(): void {
60
- const ignored = command('git', ['check-ignore', 'config.json', '.env', '.oss-dist', 'web/console', 'data']).split('\n').filter(Boolean);
65
+ // Check the directory rule even before generated console assets exist.
66
+ const ignored = command('git', ['check-ignore', 'config.json', '.env', '.oss-dist/', 'web/console/', 'data/']).split('\n').filter(Boolean).map((file) => file.replace(/\/$/, ''));
61
67
  const expected = new Set(['config.json', '.env', '.oss-dist', 'web/console', 'data']);
62
68
  for (const file of expected) {
63
69
  if (!ignored.includes(file)) throw new Error(`${file} is not ignored`);
@@ -105,3 +111,4 @@ if (failures.length) {
105
111
  }
106
112
 
107
113
  console.log('Doctor passed. For runtime checks against a live hub, run BAILING_DOCTOR_SMOKE=1 npm run doctor.');
114
+ }
@@ -0,0 +1,185 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import test from 'node:test';
8
+
9
+ const INSTALLER = fileURLToPath(new URL('./install.sh', import.meta.url));
10
+ const source = readFileSync(INSTALLER, 'utf8');
11
+ const mainOffset = source.lastIndexOf('\nmain "$@"');
12
+ assert.ok(mainOffset > 0, 'installer entry point must be identifiable');
13
+ const functions = source.slice(0, mainOffset);
14
+ const SYNTHETIC_VALUE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345';
15
+
16
+ function hostCommand(name) {
17
+ const result = spawnSync('/bin/sh', ['-c', 'command -v "$1"', 'fixture-command', name], { encoding: 'utf8' });
18
+ if (result.status !== 0 || !result.stdout.trim()) throw new Error(`Test prerequisite missing: ${name}`);
19
+ return result.stdout.trim();
20
+ }
21
+
22
+ function executable(path, body) {
23
+ writeFileSync(path, `#!/bin/sh\n${body}\n`, { mode: 0o700 });
24
+ }
25
+
26
+ function fixture(t, opensslBody) {
27
+ const root = mkdtempSync(join(tmpdir(), 'bailing-install-secrets-'));
28
+ t.after(() => rmSync(root, { recursive: true, force: true }));
29
+ const bin = join(root, 'bin'), app = join(root, 'app');
30
+ mkdirSync(bin);
31
+ mkdirSync(join(app, 'scripts'), { recursive: true });
32
+ writeFileSync(join(app, 'package.json'), '{"name":"synthetic-install-fixture","version":"0.9.1"}\n');
33
+ writeFileSync(join(app, 'docker-compose.yml'), 'services: {}\n');
34
+ writeFileSync(join(app, 'docker-compose.images.yml'), 'services: {}\n');
35
+ for (const name of ['cat', 'sed', 'head', 'grep', 'cut', 'chmod', 'tr']) symlinkSync(hostCommand(name), join(bin, name));
36
+ // These legacy-fallback substitutes make the old timestamp path succeed.
37
+ // All outputs are public synthetic data; no host clock or credentials are read.
38
+ executable(join(bin, 'date'), "printf '%s\\n' 1791864000");
39
+ executable(join(bin, 'sha256sum'), `printf '%s -\\n' '${'0'.repeat(64)}'`);
40
+ executable(join(bin, 'awk'), 'read -r line\nprintf \'%s\\n\' "${line%% *}"');
41
+ executable(join(bin, 'uname'), "printf '%s\\n' x86_64");
42
+ for (const name of ['git', 'curl', 'tar']) executable(join(bin, name), 'exit 0');
43
+ executable(join(bin, 'docker'), 'printf \'%s\\n\' "$*" >> "$BAILING_TEST_DOCKER_CALLS"\nexit 0');
44
+ if (opensslBody !== undefined) executable(join(bin, 'openssl'), opensslBody);
45
+ const env = {
46
+ PATH: bin,
47
+ LC_ALL: 'C',
48
+ BAILING_INSTALL_DIR: app,
49
+ BAILING_INSTALL_MODE: 'image',
50
+ BAILING_INSTALL_SKIP_SMOKE: '1',
51
+ BAILING_SKIP_PORT_CHECK: '1',
52
+ BAILING_PUBLIC_HOST: '127.0.0.1',
53
+ BAILING_TEST_DOCKER_CALLS: join(root, 'docker-calls'),
54
+ BAILING_TEST_OPENSSL_CALLS: join(root, 'openssl-calls'),
55
+ BAILING_TEST_OPENSSL_COUNT: join(root, 'openssl-count'),
56
+ };
57
+ return { root, bin, app, env };
58
+ }
59
+
60
+ function runFunctions(f, commands = 'secret') {
61
+ return spawnSync('/bin/sh', ['-s'], { cwd: f.app, env: f.env, input: `${functions}\n${commands}\n`, encoding: 'utf8', timeout: 5000 });
62
+ }
63
+
64
+ function runInstaller(f) {
65
+ // Full entry point, but every external installation/network/container command
66
+ // is confined to a substitute. Any .env is a disposable synthetic fixture.
67
+ return spawnSync('/bin/sh', [INSTALLER], { cwd: f.app, env: f.env, encoding: 'utf8', timeout: 5000 });
68
+ }
69
+
70
+ function assertStopped(result) {
71
+ assert.equal(result.error === undefined, true, 'shell must finish without a harness error');
72
+ assert.notEqual(result.status, 0, 'unsafe credential generation must fail');
73
+ assert.equal(result.stdout.includes(SYNTHETIC_VALUE), false, 'generated output must not be disclosed on failure');
74
+ assert.equal(result.stderr.includes(SYNTHETIC_VALUE), false, 'random producer output must not enter error logs');
75
+ assert.equal(result.stderr.includes('producer-private-error'), false, 'raw producer stderr must not enter error logs');
76
+ assert.equal(result.stderr.includes('[bailinghub] ERROR:'), true, 'failure must have a stable installer error');
77
+ }
78
+
79
+ function assertNoInstallAfterFailure(f) {
80
+ assert.equal(existsSync(join(f.app, '.env')), false, 'failed generation must not create an environment file');
81
+ const calls = readFileSync(f.env.BAILING_TEST_DOCKER_CALLS, 'utf8').split('\n');
82
+ assert.equal(calls.some((line) => line.startsWith('compose ') && line.includes(' up ')), false, 'failed generation must not start containers');
83
+ }
84
+
85
+ const countingRandomSubstitute = `
86
+ [ "$#" -eq 3 ] && [ "$1" = rand ] && [ "$2" = -base64 ] && [ "$3" = 24 ] || exit 2
87
+ printf '%s\\n' "$*" >> "$BAILING_TEST_OPENSSL_CALLS"
88
+ n=0
89
+ if [ -f "$BAILING_TEST_OPENSSL_COUNT" ]; then read -r n < "$BAILING_TEST_OPENSSL_COUNT"; fi
90
+ n=$((n + 1))
91
+ printf '%s\\n' "$n" > "$BAILING_TEST_OPENSSL_COUNT"
92
+ printf '%032d\\n' "$n"
93
+ `;
94
+
95
+ test('installer retains POSIX sh syntax', () => {
96
+ const result = spawnSync('/bin/sh', ['-n', INSTALLER], { encoding: 'utf8' });
97
+ assert.equal(result.status, 0, 'installer must parse without Bash pipefail');
98
+ });
99
+
100
+ test('missing openssl fails without a predictable fallback', (t) => {
101
+ assertStopped(runFunctions(fixture(t)));
102
+ });
103
+
104
+ for (const [name, body] of [
105
+ ['producer failure even with plausible stdout', `printf '%s\\n' '${SYNTHETIC_VALUE}'\nprintf '%s\\n' producer-private-error >&2\nexit 1`],
106
+ ['producer failure without stdout', 'printf \'%s\\n\' producer-private-error >&2\nexit 1'],
107
+ ['empty successful output', 'exit 0'],
108
+ ['truncated successful output', `printf '%s\\n' '${'A'.repeat(31)}'`],
109
+ ['oversized successful output', `printf '%s\\n' '${'A'.repeat(33)}'`],
110
+ ['non-Base64 successful output', `printf '%s\\n' '${'A'.repeat(31)}!'`],
111
+ ['non-ASCII successful output', `printf '%s\\n' '${'A'.repeat(31)}é'`],
112
+ ['embedded newline in successful output', `printf '%s\\n%s\\n' '${'A'.repeat(16)}' '${'A'.repeat(16)}'`],
113
+ ]) {
114
+ test(`${name} stops credential generation`, (t) => {
115
+ assertStopped(runFunctions(fixture(t, body)));
116
+ });
117
+ }
118
+
119
+ test('valid output uses the 24-byte Base64 generator directly', (t) => {
120
+ const f = fixture(t, countingRandomSubstitute);
121
+ const result = runFunctions(f, 'value=$(secret)\nprintf \'%s\\n\' "$value"');
122
+ assert.equal(result.status, 0, 'valid random producer must succeed');
123
+ assert.equal(/^[A-Za-z0-9+/]{32}\n$/.test(result.stdout), true, 'encoding must retain 24 bytes without padding');
124
+ assert.equal(result.stderr, '');
125
+ assert.equal(readFileSync(f.env.BAILING_TEST_OPENSSL_CALLS, 'utf8'), 'rand -base64 24\n');
126
+ });
127
+
128
+ test('real openssl generates distinct 24-byte credentials without logging their values', (t) => {
129
+ const f = fixture(t);
130
+ symlinkSync(hostCommand('openssl'), join(f.bin, 'openssl'));
131
+ const result = runFunctions(f, 'i=0\nwhile [ "$i" -lt 6 ]; do value=$(secret); printf \'%s\\n\' "$value"; i=$((i + 1)); done');
132
+ assert.equal(result.status, 0, 'system secure random producer must succeed');
133
+ const values = result.stdout.trimEnd().split('\n');
134
+ assert.equal(values.length, 6);
135
+ assert.equal(values.every((value) => /^[A-Za-z0-9+/]{32}$/.test(value)), true);
136
+ assert.equal(new Set(values).size, 6, 'separate generated credentials must be distinct');
137
+ assert.equal(result.stderr, '');
138
+ });
139
+
140
+ test('full entry point stops before .env or startup when dependencies exist but openssl is missing', (t) => {
141
+ const f = fixture(t);
142
+ const result = runInstaller(f);
143
+ assertStopped(result);
144
+ assert.equal(result.stderr.includes('openssl'), true);
145
+ assertNoInstallAfterFailure(f);
146
+ });
147
+
148
+ test('full entry point stops on a producer error that a trailing pipeline could mask', (t) => {
149
+ const f = fixture(t, `printf '%s\\n' '${SYNTHETIC_VALUE}'\nprintf '%s\\n' producer-private-error >&2\nexit 1`);
150
+ assertStopped(runInstaller(f));
151
+ assertNoInstallAfterFailure(f);
152
+ });
153
+
154
+ test('failure after earlier credentials were generated still creates no partial .env or containers', (t) => {
155
+ const f = fixture(t, countingRandomSubstitute.replace('printf \'%032d\\n\' "$n"', '[ "$n" -ne 4 ] || exit 1\nprintf \'%032d\\n\' "$n"'));
156
+ assertStopped(runInstaller(f));
157
+ assert.equal(readFileSync(f.env.BAILING_TEST_OPENSSL_COUNT, 'utf8').trim(), '4');
158
+ assertNoInstallAfterFailure(f);
159
+ });
160
+
161
+ test('full entry point independently generates six synthetic credentials with private file permissions', (t) => {
162
+ const f = fixture(t, countingRandomSubstitute);
163
+ const result = runInstaller(f);
164
+ assert.equal(result.status, 0, 'safe generation and stubbed installation must succeed');
165
+ assert.equal(result.stderr, '');
166
+ const content = readFileSync(join(f.app, '.env'), 'utf8');
167
+ const keys = ['BAILING_TOKEN', 'BAILING_BOOTSTRAP_ADMIN_PASSWORD', 'BAILING_DEMO_MYSQL_ROOT_PASSWORD', 'BAILING_DEMO_MYSQL_PASSWORD', 'DEMO_TOOL_SECRET', 'DEMO_CLIENT_TOKEN'];
168
+ const values = keys.map((key) => content.split('\n').find((line) => line.startsWith(`${key}=`))?.slice(key.length + 1));
169
+ assert.equal(values.every((value) => typeof value === 'string' && /^[A-Za-z0-9+/]{32}$/.test(value)), true);
170
+ assert.equal(new Set(values).size, 6, 'independent credential slots must not share generated values');
171
+ assert.equal(readFileSync(f.env.BAILING_TEST_OPENSSL_CALLS, 'utf8').trimEnd().split('\n').length, 6);
172
+ assert.equal(statSync(join(f.app, '.env')).mode & 0o777, 0o600);
173
+ });
174
+
175
+ test('an existing environment is preserved byte-for-byte and does not need random regeneration', (t) => {
176
+ const f = fixture(t);
177
+ const envPath = join(f.app, '.env');
178
+ const original = 'BAILING_DEMO_ADMIN_PASSWORD=synthetic-existing-admin\nDEMO_CLIENT_TOKEN=synthetic-existing-client\nBAILING_TOKEN=synthetic-existing-root\nBAILINGHUB_IMAGE=synthetic/existing:0.9.1\n';
179
+ writeFileSync(envPath, original, { mode: 0o600 });
180
+ const result = runInstaller(f);
181
+ assert.equal(result.status, 0, 'existing installation must not generate replacement credentials');
182
+ assert.equal(result.stderr, '');
183
+ assert.equal(readFileSync(envPath, 'utf8') === original, true, 'existing environment must remain unchanged');
184
+ assert.equal(existsSync(f.env.BAILING_TEST_OPENSSL_CALLS), false);
185
+ });
@@ -33,11 +33,15 @@ as_root() {
33
33
  }
34
34
 
35
35
  secret() {
36
- if have openssl; then
37
- openssl rand -base64 24 | tr -d '\n'
38
- else
39
- date +%s | sha256sum | awk '{print $1}'
40
- fi
36
+ have openssl || die "生成安装凭据需要 openssl 安全随机源,请先安装 openssl 后重试。"
37
+ # Keep the producer's exit status: a POSIX pipeline can hide openssl failure.
38
+ SECRET_VALUE="$(openssl rand -base64 24 2>/dev/null)" || die "安全随机凭据生成失败,安装已停止。"
39
+ # 24 random bytes encode to exactly 32 unpadded Base64 characters.
40
+ case "$SECRET_VALUE" in
41
+ ''|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/]*) die "安全随机凭据格式异常,安装已停止。" ;;
42
+ esac
43
+ [ "${#SECRET_VALUE}" -eq 32 ] || die "安全随机凭据长度异常,安装已停止。"
44
+ printf '%s\n' "$SECRET_VALUE"
41
45
  }
42
46
 
43
47
  install_packages() {
@@ -275,7 +279,7 @@ write_env() {
275
279
  TOOL_SECRET="${DEMO_TOOL_SECRET:-$(secret)}"
276
280
  CLIENT_TOKEN="${DEMO_CLIENT_TOKEN:-$(secret)}"
277
281
  IMAGE_TAG="${BAILING_IMAGE_TAG:-$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$APP_DIR/package.json" | head -1)}"
278
- [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.9.1"
282
+ [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.9.2"
279
283
  IMAGE_REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_IMAGE_REGISTRY}"
280
284
  IMAGE_NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_IMAGE_NAMESPACE}"
281
285
  cat > "$ENV_FILE" <<EOF
@@ -9,7 +9,7 @@ REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_REGISTRY}"
9
9
  NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_NAMESPACE}"
10
10
  PACKAGE_VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)"
11
11
  TAG="${BAILING_IMAGE_TAG:-$PACKAGE_VERSION}"
12
- [ -n "$TAG" ] || TAG="0.9.1"
12
+ [ -n "$TAG" ] || TAG="0.9.2"
13
13
  NODE_IMAGE="${BAILING_NODE_IMAGE:-node:22-bookworm-slim}"
14
14
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
15
15
  PUSH="${BAILING_PUSH_IMAGES:-0}"
@@ -41,6 +41,10 @@ const requiredRepoFiles = [
41
41
  'docs/RELEASE_NOTES_v0.8.0.md',
42
42
  'docs/RELEASE_NOTES_v0.9.0.md',
43
43
  'docs/RELEASE_NOTES_v0.9.1.md',
44
+ 'docs/RELEASE_NOTES_v0.9.2.md',
45
+ 'docs/RELEASE_NOTES_v0.9.2.en.md',
46
+ 'docs/UPGRADE_v0.9.2.md',
47
+ 'docs/UPGRADE_v0.9.2.en.md',
44
48
  'docs/RELEASE_NOTES_v0.6.1.md',
45
49
  'docs/RELEASE_NOTES_v0.6.0.md',
46
50
  'docs/CHANGELOG.md',
@@ -133,6 +133,10 @@ const requiredFiles = [
133
133
  'docs/RELEASE_NOTES_v0.8.0.md',
134
134
  'docs/RELEASE_NOTES_v0.9.0.md',
135
135
  'docs/RELEASE_NOTES_v0.9.1.md',
136
+ 'docs/RELEASE_NOTES_v0.9.2.md',
137
+ 'docs/RELEASE_NOTES_v0.9.2.en.md',
138
+ 'docs/UPGRADE_v0.9.2.md',
139
+ 'docs/UPGRADE_v0.9.2.en.md',
136
140
  'docs/RELEASE_NOTES_v0.6.1.md',
137
141
  'docs/RELEASE_NOTES_v0.6.0.md',
138
142
  'docs/CHANGELOG.md',
@@ -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);