bailinghub 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/CHANGELOG.en.md +23 -1
  5. package/docs/CHANGELOG.md +23 -1
  6. package/docs/CORE_RELIABILITY.en.md +79 -0
  7. package/docs/CORE_RELIABILITY.md +79 -0
  8. package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
  9. package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
  10. package/docs/IMPLEMENTATION_STATUS.en.md +27 -15
  11. package/docs/IMPLEMENTATION_STATUS.md +27 -15
  12. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  13. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  14. package/docs/KERNEL_HOST_API.en.md +2 -0
  15. package/docs/KERNEL_HOST_API.md +2 -0
  16. package/docs/MODEL_BILLING.en.md +4 -0
  17. package/docs/MODEL_BILLING.md +4 -0
  18. package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
  19. package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
  20. package/docs/OPERATIONS.en.md +13 -0
  21. package/docs/OPERATIONS.md +12 -0
  22. package/docs/README.en.md +7 -0
  23. package/docs/README.md +7 -0
  24. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  25. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  26. package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
  27. package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
  28. package/docs/TOOLS_DESIGN.md +1 -0
  29. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  30. package/docs/UPGRADE_v0.9.2.md +62 -0
  31. package/docs/UPGRADE_v0.9.3.en.md +63 -0
  32. package/docs/UPGRADE_v0.9.3.md +63 -0
  33. package/package.json +7 -3
  34. package/scripts/check-doc-links.mjs +4 -0
  35. package/scripts/check-image-tags.sh +1 -1
  36. package/scripts/check-release-consistency.test.mjs +2 -2
  37. package/scripts/doctor-deployment.test.ts +419 -0
  38. package/scripts/doctor-deployment.ts +357 -0
  39. package/scripts/doctor.ts +8 -1
  40. package/scripts/install-secrets.test.mjs +185 -0
  41. package/scripts/install.sh +10 -6
  42. package/scripts/publish-images.sh +1 -1
  43. package/scripts/release-audit.mjs +8 -0
  44. package/scripts/verify-github-repo.mjs +8 -0
  45. package/security/dependency-audit-exceptions.json +1 -1
  46. package/sql/065_usage_reconciliation_scan.sql +4 -0
  47. package/sql/066_approval_continuations.sql +15 -0
  48. package/sql/067_delivery_dlq_replay.sql +10 -0
  49. package/sql/README.en.md +6 -0
  50. package/sql/README.md +15 -0
  51. package/src/adapters/llm/file.test.ts +59 -0
  52. package/src/adapters/llm/file.ts +11 -4
  53. package/src/app/agent-tool-invocations.test.ts +3 -1
  54. package/src/app/approval-continuations.mysql.test.ts +138 -0
  55. package/src/app/approval-continuations.test.ts +351 -0
  56. package/src/app/approval-continuations.ts +148 -0
  57. package/src/app/channels-attachments.test.ts +63 -0
  58. package/src/app/channels.ts +7 -4
  59. package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
  60. package/src/app/delivery-dlq-replay.test.ts +75 -0
  61. package/src/app/delivery-dlq-replay.ts +41 -0
  62. package/src/app/delivery.ts +3 -2
  63. package/src/app/http-server.ts +3 -0
  64. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  65. package/src/app/kernel-notification-lifecycle.test.ts +49 -0
  66. package/src/app/kernel.ts +22 -0
  67. package/src/app/notification-outbound.test.ts +53 -0
  68. package/src/app/operational-metrics.test.ts +37 -1
  69. package/src/app/operational-metrics.ts +25 -2
  70. package/src/app/outbound.ts +13 -2
  71. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  72. package/src/app/runtime-lifecycle-default.ts +7 -0
  73. package/src/app/runtime-lifecycle.test.ts +89 -0
  74. package/src/app/runtime-lifecycle.ts +52 -11
  75. package/src/app/tool-approvals.ts +2 -1
  76. package/src/core/contracts/approval-continuation.ts +43 -0
  77. package/src/core/contracts/delivery-replay.ts +41 -0
  78. package/src/core/contracts/tools-idempotency.test.ts +121 -5
  79. package/src/core/contracts/tools.ts +21 -11
  80. package/src/core/contracts/types.ts +4 -0
  81. package/src/core/observability/openmetrics.test.ts +28 -0
  82. package/src/core/observability/openmetrics.ts +91 -0
  83. package/src/core/platform/http-body.test.ts +185 -0
  84. package/src/core/platform/http-body.ts +58 -0
  85. package/src/core/runtime/finish-runtime.test.ts +2 -0
  86. package/src/core/runtime/finish-runtime.ts +10 -7
  87. package/src/core/runtime/notification-background-work.test.ts +50 -0
  88. package/src/core/runtime/notification-background-work.ts +101 -0
  89. package/src/core/state/approval-continuation.ts +22 -0
  90. package/src/core/state/delivery-replay.ts +19 -0
  91. package/src/core/state/state-codec.ts +2 -0
  92. package/src/core/state/state-contracts.ts +6 -0
  93. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  94. package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
  95. package/src/infrastructure/config/configstore.ts +4 -3
  96. package/src/infrastructure/state/state-jsonl.ts +56 -11
  97. package/src/infrastructure/state/state-mysql.ts +54 -0
  98. package/src/modules/usage/background-work.test.ts +28 -0
  99. package/src/modules/usage/background-work.ts +43 -7
  100. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  101. package/src/modules/usage/billing-reconciliation.test.ts +85 -0
  102. package/src/modules/usage/billing-repository.ts +63 -11
  103. package/src/modules/usage/maintenance.test.ts +78 -0
  104. package/src/modules/usage/maintenance.ts +39 -0
  105. package/src/modules/usage/model-gateway.ts +2 -1
  106. package/src/routes/admin-default.ts +2 -2
  107. package/src/routes/admin-runtime-default.ts +2 -2
  108. package/src/routes/admin-runtime.test.ts +1 -1
  109. package/src/routes/admin-runtime.ts +39 -18
  110. package/src/routes/admin.ts +1 -1
  111. package/src/routes/approvals-default.ts +2 -2
  112. package/src/routes/approvals.ts +30 -33
  113. package/src/routes/critical-routes.test.ts +16 -3
  114. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  115. package/src/test-support/model-process-crash-child.ts +78 -0
@@ -0,0 +1,419 @@
1
+ import test, { type TestContext } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
4
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { execFileSync, spawnSync } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { runDeploymentDoctor, type DeploymentDoctorReport } from './doctor-deployment';
10
+ import { handlePublicHttpFor, type PublicHttpDeps } from '../src/routes/public';
11
+ import type { AppConfig } from '../src/core/config/config';
12
+ import { buildMeta } from '../src/core/platform/version';
13
+ import { LocalInstanceBrandingProvider } from '../src/infrastructure/config/local-instance-branding-provider';
14
+
15
+ const SHA = 'abcdef0123456789abcdef0123456789abcdef0123';
16
+ const OTHER_SHA = '0123456789abcdef0123456789abcdef0123456789';
17
+ const VERSION = '0.9.1';
18
+ const SECRET = 'test-credential-that-must-stay-private';
19
+ const CLI = fileURLToPath(new URL('./doctor.ts', import.meta.url));
20
+ const TSX = fileURLToPath(new URL('../node_modules/tsx/dist/loader.mjs', import.meta.url));
21
+
22
+ function fixture(t: TestContext, overrides: { build?: unknown; pkg?: unknown; withConfig?: boolean } = {}): string {
23
+ const root = mkdtempSync(join(tmpdir(), 'bailing-deployment-doctor-'));
24
+ t.after(() => rmSync(root, { recursive: true, force: true }));
25
+ mkdirSync(join(root, 'sql'));
26
+ writeFileSync(join(root, 'package.json'), JSON.stringify(overrides.pkg ?? {
27
+ name: 'bailinghub', version: VERSION,
28
+ scripts: { smoke: 'touch unsafe-model-call', typecheck: 'touch unsafe-typecheck' },
29
+ }));
30
+ writeFileSync(join(root, 'sql', '001_initial.sql'), '-- packaged migration, never run\n');
31
+ writeFileSync(join(root, 'sql', '064_period_plan_allowance.sql'), '-- packaged migration, never run\n');
32
+ writeFileSync(join(root, 'build-info.json'), JSON.stringify(overrides.build ?? { build: { commit: SHA } }));
33
+ if (overrides.withConfig) {
34
+ writeFileSync(join(root, '.env'), `BAILING_TOKEN=${SECRET}\nBAILING_MYSQL_PASSWORD=${SECRET}\n`);
35
+ writeFileSync(join(root, 'config.json'), `{invalid-json-and-private-value:${SECRET}}`);
36
+ }
37
+ return root;
38
+ }
39
+
40
+ function payloads(): Record<string, unknown> {
41
+ return {
42
+ '/health': { status: 'ok', app: { name: 'bailinghub', version: VERSION }, build: { commit: SHA.slice(0, 12) }, paused: false, backend: 'mysql' },
43
+ '/version': { app: { name: 'bailinghub', version: VERSION }, build: { commit: SHA.slice(0, 12) }, migrations: { latest: '064_period_plan_allowance.sql', total: 2 } },
44
+ '/health/ready': { status: 'ready', checks: { database: 'ok', migrations: { status: 'ok', pending: 0 } } },
45
+ };
46
+ }
47
+
48
+ type Seen = { method: string | undefined; path: string | undefined; authorization: string | undefined; cookie: string | undefined };
49
+
50
+ async function httpFixture(t: TestContext, handler?: (req: IncomingMessage, res: ServerResponse) => void): Promise<{ url: string; seen: Seen[] }> {
51
+ const seen: Seen[] = [];
52
+ const bodies = payloads();
53
+ const server = createServer((req, res) => {
54
+ seen.push({ method: req.method, path: req.url, authorization: req.headers.authorization, cookie: req.headers.cookie });
55
+ if (handler) handler(req, res);
56
+ else { res.writeHead(bodies[req.url ?? ''] ? 200 : 404, { 'content-type': 'application/json' }); res.end(JSON.stringify(bodies[req.url ?? ''] ?? { error: SECRET })); }
57
+ });
58
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
59
+ t.after(async () => {
60
+ server.closeAllConnections();
61
+ await new Promise<void>((resolve) => server.close(() => resolve()));
62
+ });
63
+ const address = server.address();
64
+ assert.ok(address && typeof address !== 'string');
65
+ return { url: `http://127.0.0.1:${address.port}`, seen };
66
+ }
67
+
68
+ function check(report: DeploymentDoctorReport, id: string) {
69
+ const entry = report.checks.find((item) => item.id === id);
70
+ assert.ok(entry, `missing ${id}`);
71
+ return entry;
72
+ }
73
+
74
+ test('without an explicit target, report incomplete and do not discover URLs or load config', async (t) => {
75
+ const root = fixture(t, { withConfig: true });
76
+ const report = await runDeploymentDoctor({ root });
77
+ assert.equal(report.exit_code, 2);
78
+ assert.equal(report.runtime.state, 'not_checked');
79
+ assert.equal(report.configuration.local_files.config_json, 'present');
80
+ assert.equal(report.configuration.local_files.dotenv, 'present');
81
+ assert.equal(report.configuration.state, 'unknown');
82
+ assert.equal(report.configuration.credentials, 'not_checked');
83
+ assert.deepEqual(report.scope.paths, []);
84
+ assert.ok(!JSON.stringify(report).includes(SECRET));
85
+ });
86
+
87
+ test('default checks only GET health/version, verify reported identities, and keep DB/schema protected checks separate', async (t) => {
88
+ const root = fixture(t, { withConfig: true });
89
+ const server = await httpFixture(t);
90
+ const report = await runDeploymentDoctor({ root, url: server.url });
91
+ assert.equal(report.result, 'pass');
92
+ assert.equal(report.exit_code, 0);
93
+ assert.equal(report.source.commit_basis, 'build_info');
94
+ assert.equal(report.comparison.commit_matches, true);
95
+ assert.equal(report.comparison.state, 'verified');
96
+ assert.equal(report.runtime.state, 'verified');
97
+ assert.equal(report.runtime.basis, 'reported_metadata');
98
+ assert.equal(report.runtime.artifact_integrity, 'not_checked');
99
+ assert.equal(report.source.artifact_integrity, 'not_checked');
100
+ assert.equal(report.database.state, 'not_checked');
101
+ assert.equal(report.migrations.identity.state, 'not_checked');
102
+ assert.equal(report.migrations.readiness.state, 'not_checked');
103
+ assert.equal(report.protected_endpoints.state, 'not_checked');
104
+ assert.equal(report.upgrade.state, 'not_checked');
105
+ assert.equal(check(report, 'artifact.migrations').state, 'pass');
106
+ assert.deepEqual(server.seen.map(({ method, path }) => ({ method, path })), [
107
+ { method: 'GET', path: '/health' }, { method: 'GET', path: '/version' },
108
+ ]);
109
+ assert.ok(server.seen.every((req) => !req.authorization && !req.cookie));
110
+ assert.ok(!JSON.stringify(report).includes(SECRET));
111
+ });
112
+
113
+ test('explicit readiness checks only its public summary, not an applied migration identity', async (t) => {
114
+ const root = fixture(t);
115
+ const server = await httpFixture(t);
116
+ const report = await runDeploymentDoctor({ root, url: server.url, readiness: true });
117
+ assert.equal(report.exit_code, 0);
118
+ assert.equal(report.migrations.readiness.state, 'verified');
119
+ assert.equal(report.migrations.readiness.pending, 0);
120
+ assert.equal(report.migrations.identity.state, 'not_checked');
121
+ assert.equal(report.database.state, 'not_checked');
122
+ assert.deepEqual(server.seen.map((req) => req.path), ['/health', '/version', '/health/ready']);
123
+ });
124
+
125
+ test('the existing public HTTP implementation works with this doctor; default mode never invokes its readiness callback', async (t) => {
126
+ const root = fixture(t);
127
+ let readinessCalls = 0;
128
+ const unexpected = () => { throw new Error('unexpected non-diagnostic route'); };
129
+ const deps: PublicHttpDeps = {
130
+ cfg: { root, state: { backend: 'mysql' } } as unknown as AppConfig,
131
+ configStore: null, brandingProvider: new LocalInstanceBrandingProvider(null),
132
+ queue: { stats: () => ({ running: 0, waiting: 0 }) }, isPaused: () => false,
133
+ readiness: async () => { readinessCalls++; return { ready: true, checks: { database: 'ok', migrations: { status: 'ok', pending: 0 } } }; },
134
+ serveConsole: unexpected, serveChatDemo: unexpected,
135
+ handleChat: async () => unexpected(), handleChatConfig: async () => unexpected(),
136
+ handleChatEvents: async () => unexpected(), handleChatThread: async () => unexpected(),
137
+ handleChatUpload: async () => unexpected(), handleChatRate: async () => unexpected(),
138
+ };
139
+ const server = await httpFixture(t, (req, res) => {
140
+ void handlePublicHttpFor(deps, req, res, new URL(req.url ?? '/', 'http://127.0.0.1')).then((handled) => {
141
+ if (!handled) { res.writeHead(404); res.end(); }
142
+ }).catch(() => { res.writeHead(500); res.end(); });
143
+ });
144
+ // CI may supply GITHUB_SHA; use the existing build function's same stated
145
+ // commit without changing or trusting a process environment credential.
146
+ const expectedCommit = String(buildMeta(root).commit);
147
+ const report = await runDeploymentDoctor({ root, url: server.url, expectedCommit });
148
+ assert.equal(report.exit_code, 0);
149
+ assert.equal(readinessCalls, 0);
150
+ const ready = await runDeploymentDoctor({ root, url: server.url, expectedCommit, readiness: true });
151
+ assert.equal(ready.exit_code, 0);
152
+ assert.equal(readinessCalls, 1);
153
+ assert.deepEqual(server.seen.map((req) => req.path), ['/health', '/version', '/health', '/version', '/health/ready']);
154
+ });
155
+
156
+ test('readiness failure, skipped database, and required authentication remain distinguishable', async (t) => {
157
+ const root = fixture(t);
158
+ const bodies = payloads();
159
+ let mode = 'failed';
160
+ const server = await httpFixture(t, (req, res) => {
161
+ if (req.url === '/health/ready') {
162
+ if (mode === 'auth') { res.writeHead(401); res.end(SECRET); }
163
+ else {
164
+ res.writeHead(mode === 'failed' ? 503 : 200, { 'content-type': 'application/json' });
165
+ res.end(JSON.stringify(mode === 'failed'
166
+ ? { status: 'not_ready', checks: { database: 'failed', migrations: { status: 'failed', pending: 0 } }, error: SECRET }
167
+ : { status: 'ready', checks: { database: 'skipped', migrations: { status: 'skipped', pending: 0 } } }));
168
+ }
169
+ } else { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(bodies[req.url ?? ''])); }
170
+ });
171
+ const failed = await runDeploymentDoctor({ root, url: server.url, readiness: true });
172
+ assert.equal(failed.exit_code, 1);
173
+ assert.equal(failed.migrations.readiness.reason, 'server_reports_not_ready');
174
+ mode = 'skipped';
175
+ const skipped = await runDeploymentDoctor({ root, url: server.url, readiness: true });
176
+ assert.equal(skipped.exit_code, 2);
177
+ assert.equal(skipped.migrations.readiness.state, 'unknown');
178
+ mode = 'auth';
179
+ const auth = await runDeploymentDoctor({ root, url: server.url, readiness: true });
180
+ assert.equal(auth.exit_code, 2);
181
+ assert.equal(auth.migrations.readiness.state, 'not_checked');
182
+ assert.equal(check(auth, 'http.readiness').reason, 'authentication_required');
183
+ for (const report of [failed, skipped, auth]) assert.ok(!JSON.stringify(report).includes(SECRET));
184
+ });
185
+
186
+ test('a version or commit mismatch fails; absence of a commit never becomes verified', async (t) => {
187
+ const root = fixture(t);
188
+ const bodies = payloads();
189
+ let body: unknown = { app: { name: 'bailinghub', version: VERSION }, build: { commit: OTHER_SHA }, migrations: { latest: '064_period_plan_allowance.sql', total: 2 } };
190
+ const server = await httpFixture(t, (req, res) => {
191
+ res.writeHead(200, { 'content-type': 'application/json' });
192
+ res.end(JSON.stringify(req.url === '/version' ? body : bodies[req.url ?? '']));
193
+ });
194
+ const mismatch = await runDeploymentDoctor({ root, url: server.url });
195
+ assert.equal(mismatch.exit_code, 1);
196
+ assert.equal(mismatch.comparison.state, 'mismatch');
197
+ assert.equal(check(mismatch, 'runtime.consistency').state, 'fail');
198
+ body = { app: { name: 'bailinghub', version: VERSION }, migrations: { latest: '064_period_plan_allowance.sql', total: 2 } };
199
+ const noCommit = await runDeploymentDoctor({ root, url: server.url });
200
+ assert.equal(noCommit.exit_code, 2);
201
+ assert.equal(noCommit.comparison.state, 'unknown');
202
+ assert.equal(noCommit.runtime.state, 'unknown');
203
+ body = { app: { name: 'bailinghub', version: '0.9.0' }, build: { commit: SHA }, migrations: { latest: '064_period_plan_allowance.sql', total: 2 } };
204
+ const oldVersion = await runDeploymentDoctor({ root, url: server.url });
205
+ assert.equal(oldVersion.exit_code, 1);
206
+ assert.equal(oldVersion.comparison.version_matches, false);
207
+ });
208
+
209
+ test('a source without a commit stays incomplete even with a matching explicit runtime expectation', async (t) => {
210
+ const root = fixture(t, { build: {} });
211
+ const server = await httpFixture(t);
212
+ const report = await runDeploymentDoctor({ root, url: server.url, expectedVersion: VERSION, expectedCommit: SHA });
213
+ assert.equal(report.exit_code, 2);
214
+ assert.equal(report.source.state, 'unknown');
215
+ assert.equal(check(report, 'source.commit').reason, 'local_commit_unavailable');
216
+ assert.equal(report.comparison.state, 'verified');
217
+ });
218
+
219
+ test('wrong application and secret-shaped fields are not printed or accepted as identity', async (t) => {
220
+ const root = fixture(t);
221
+ const server = await httpFixture(t, (_req, res) => {
222
+ res.writeHead(200, { 'content-type': 'application/json' });
223
+ res.end(JSON.stringify({ status: 'ok', app: { name: SECRET, version: SECRET }, build: { commit: SECRET }, migrations: { latest: SECRET, total: SECRET }, config: { password: SECRET }, error: SECRET }));
224
+ });
225
+ const report = await runDeploymentDoctor({ root, url: server.url });
226
+ assert.equal(report.exit_code, 1);
227
+ assert.equal(report.runtime.state, 'mismatch');
228
+ assert.ok(!JSON.stringify(report).includes(SECRET));
229
+ });
230
+
231
+ test('explicit expected identity can compare a different artifact without claiming local migration alignment', async (t) => {
232
+ const root = fixture(t, { pkg: { name: 'bailinghub', version: '0.9.0' }, build: { build: { commit: OTHER_SHA } } });
233
+ const server = await httpFixture(t);
234
+ const report = await runDeploymentDoctor({ root, url: server.url, expectedVersion: VERSION, expectedCommit: SHA });
235
+ assert.equal(report.exit_code, 0);
236
+ assert.equal(report.source.version, '0.9.0');
237
+ assert.equal(report.comparison.basis, 'explicit_expectation');
238
+ assert.equal(check(report, 'artifact.migrations').state, 'not_checked');
239
+ });
240
+
241
+ test('local Git dirtiness prevents an artifact identity claim; fsmonitor hooks do not run', async (t) => {
242
+ const root = fixture(t);
243
+ execFileSync('git', ['init', '--quiet'], { cwd: root });
244
+ execFileSync('git', ['add', 'package.json', 'build-info.json', 'sql'], { cwd: root });
245
+ execFileSync('git', ['-c', 'user.name=Deployment Doctor Test', '-c', 'user.email=doctor@example.invalid', 'commit', '--quiet', '-m', 'local fixture'], { cwd: root });
246
+ const sha = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();
247
+ const marker = join(root, '.git', 'unexpected-fsmonitor-hook');
248
+ const hook = join(root, '.git', 'fsmonitor.sh');
249
+ writeFileSync(hook, `#!/bin/sh\ntouch '${marker}'\n`, { mode: 0o755 });
250
+ execFileSync('git', ['config', 'core.fsmonitor', hook], { cwd: root });
251
+ const bodies = payloads();
252
+ for (const path of ['/health', '/version']) (bodies[path] as { build: { commit: string } }).build.commit = sha;
253
+ const server = await httpFixture(t, (req, res) => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(bodies[req.url ?? ''])); });
254
+ const clean = await runDeploymentDoctor({ root, url: server.url });
255
+ assert.equal(clean.source.worktree, 'clean');
256
+ assert.equal(clean.exit_code, 0);
257
+ assert.equal(existsSync(marker), false);
258
+ writeFileSync(join(root, 'sql', '001_initial.sql'), '-- uncommitted source changes\n');
259
+ const dirty = await runDeploymentDoctor({ root, url: server.url });
260
+ assert.equal(dirty.source.worktree, 'dirty');
261
+ assert.equal(dirty.exit_code, 2);
262
+ assert.equal(dirty.comparison.state, 'unknown');
263
+ assert.equal(check(dirty, 'artifact.comparison').reason, 'local_worktree_modified');
264
+ assert.equal(existsSync(marker), false);
265
+ const explicit = await runDeploymentDoctor({ root, url: server.url, expectedCommit: sha, expectedVersion: VERSION });
266
+ assert.equal(explicit.exit_code, 0);
267
+ assert.equal(explicit.source.worktree, 'dirty');
268
+ assert.equal(explicit.runtime.artifact_integrity, 'not_checked');
269
+ });
270
+
271
+ test('authentication required for a selected public check reports incomplete without trying protected APIs', async (t) => {
272
+ const root = fixture(t);
273
+ const bodies = payloads();
274
+ const server = await httpFixture(t, (req, res) => {
275
+ if (req.url === '/health') { res.writeHead(403); res.end(SECRET); }
276
+ else { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(bodies[req.url ?? ''])); }
277
+ });
278
+ const report = await runDeploymentDoctor({ root, url: server.url });
279
+ assert.equal(report.exit_code, 2);
280
+ assert.equal(check(report, 'http.health').state, 'not_checked');
281
+ assert.equal(check(report, 'http.health').reason, 'authentication_required');
282
+ assert.equal(server.seen.length, 2);
283
+ assert.ok(!JSON.stringify(report).includes(SECRET));
284
+ });
285
+
286
+ test('userinfo, query, fragment, invalid protocols and malformed URLs produce no request or credential output', async (t) => {
287
+ const root = fixture(t);
288
+ const server = await httpFixture(t);
289
+ for (const url of [
290
+ server.url.replace('http://', `http://user:${SECRET}@`), `${server.url}/?token=${SECRET}`,
291
+ `${server.url}/#${SECRET}`, `file:///${SECRET}`, SECRET,
292
+ ]) {
293
+ const report = await runDeploymentDoctor({ root, url });
294
+ assert.equal(report.exit_code, 1);
295
+ assert.equal(report.target, null);
296
+ assert.equal(check(report, 'target').reason, 'invalid_or_credential_bearing_url');
297
+ assert.ok(!JSON.stringify(report).includes(SECRET));
298
+ }
299
+ assert.deepEqual(server.seen, []);
300
+ });
301
+
302
+ test('both same-origin and cross-origin redirects are rejected without following their location', async (t) => {
303
+ const root = fixture(t);
304
+ const destination = await httpFixture(t);
305
+ let location = `${destination.url}/?token=${SECRET}`;
306
+ const server = await httpFixture(t, (_req, res) => { res.writeHead(302, { location }); res.end(SECRET); });
307
+ const cross = await runDeploymentDoctor({ root, url: server.url });
308
+ assert.equal(cross.exit_code, 1);
309
+ assert.equal(check(cross, 'http.health').reason, 'redirect_rejected');
310
+ assert.deepEqual(destination.seen, []);
311
+ location = `${server.url}/redirected?token=${SECRET}`;
312
+ const same = await runDeploymentDoctor({ root, url: server.url });
313
+ assert.equal(same.exit_code, 1);
314
+ assert.deepEqual(server.seen.map((req) => req.path), ['/health', '/version', '/health', '/version']);
315
+ for (const report of [cross, same]) assert.ok(!JSON.stringify(report).includes(SECRET));
316
+ });
317
+
318
+ test('response cap rejects both declared and streamed oversize JSON', async (t) => {
319
+ const root = fixture(t);
320
+ let declared = true;
321
+ const server = await httpFixture(t, (_req, res) => {
322
+ res.writeHead(200, { 'content-type': 'application/json', ...(declared ? { 'content-length': '100000' } : {}) });
323
+ res.end(`{"error":"${SECRET}${'x'.repeat(70000)}"}`);
324
+ });
325
+ const length = await runDeploymentDoctor({ root, url: server.url });
326
+ assert.equal(length.exit_code, 1);
327
+ assert.equal(check(length, 'http.health').reason, 'response_too_large');
328
+ declared = false;
329
+ const streamed = await runDeploymentDoctor({ root, url: server.url });
330
+ assert.equal(streamed.exit_code, 1);
331
+ assert.equal(check(streamed, 'http.health').reason, 'response_too_large');
332
+ for (const report of [length, streamed]) assert.ok(!JSON.stringify(report).includes(SECRET));
333
+ });
334
+
335
+ test('timeout covers both response headers and streaming bodies without printing network errors', async (t) => {
336
+ const root = fixture(t);
337
+ let headers = false;
338
+ const server = await httpFixture(t, (_req, res) => {
339
+ if (headers) { res.writeHead(200, { 'content-type': 'application/json' }); res.write(`{"error":"${SECRET}`); }
340
+ });
341
+ for (const bodyTimeout of [false, true]) {
342
+ headers = bodyTimeout;
343
+ const start = performance.now();
344
+ const report = await runDeploymentDoctor({ root, url: server.url, timeoutMs: 100 });
345
+ assert.equal(report.exit_code, 1);
346
+ assert.equal(check(report, 'http.health').reason, 'request_timeout');
347
+ assert.ok(performance.now() - start < 2000);
348
+ assert.ok(!JSON.stringify(report).includes(SECRET));
349
+ }
350
+ });
351
+
352
+ test('content type, invalid JSON and non-object JSON have stable redacted errors', async (t) => {
353
+ const root = fixture(t);
354
+ let mode = 'html';
355
+ const server = await httpFixture(t, (_req, res) => {
356
+ res.writeHead(200, { 'content-type': mode === 'html' ? 'text/html' : 'application/json' });
357
+ res.end(mode === 'array' ? JSON.stringify([SECRET]) : SECRET);
358
+ });
359
+ for (const [nextMode, expected] of [['html', 'unexpected_content_type'], ['json', 'invalid_json'], ['array', 'invalid_json_object']]) {
360
+ mode = nextMode!;
361
+ const report = await runDeploymentDoctor({ root, url: server.url });
362
+ assert.equal(report.exit_code, 1);
363
+ assert.equal(check(report, 'http.health').reason, expected);
364
+ assert.ok(!JSON.stringify(report).includes(SECRET));
365
+ }
366
+ });
367
+
368
+ test('unreachable target gets a stable reason without host error details', async (t) => {
369
+ const root = fixture(t);
370
+ const report = await runDeploymentDoctor({ root, url: 'http://127.0.0.1:0', timeoutMs: 100 });
371
+ assert.equal(report.exit_code, 1);
372
+ assert.equal(check(report, 'http.health').reason, 'unreachable');
373
+ });
374
+
375
+ test('mounted base paths append only the allowlisted suffix and are not echoed', async (t) => {
376
+ const root = fixture(t);
377
+ const bodies = payloads();
378
+ const prefix = '/configured-prefix';
379
+ const server = await httpFixture(t, (req, res) => {
380
+ res.writeHead(200, { 'content-type': 'application/json' });
381
+ res.end(JSON.stringify(bodies[req.url?.slice(prefix.length) ?? '']));
382
+ });
383
+ const report = await runDeploymentDoctor({ root, url: `${server.url}${prefix}/` });
384
+ assert.equal(report.exit_code, 0);
385
+ assert.equal(report.target?.base_path, 'configured_not_printed');
386
+ assert.deepEqual(server.seen.map((req) => req.path), [`${prefix}/health`, `${prefix}/version`]);
387
+ assert.ok(!JSON.stringify(report).includes(prefix));
388
+ });
389
+
390
+ test('invalid library expectations stay redacted, including when URL is missing', async (t) => {
391
+ const root = fixture(t);
392
+ const server = await httpFixture(t);
393
+ for (const url of [undefined, server.url]) {
394
+ const report = await runDeploymentDoctor({ root, url, expectedVersion: SECRET, expectedCommit: SECRET });
395
+ assert.ok(!JSON.stringify(report).includes(SECRET));
396
+ }
397
+ assert.deepEqual(server.seen, []);
398
+ });
399
+
400
+ test('CLI deployment mode is JSON-only, ignores legacy FULL/SMOKE and credential environment, and has machine exit codes', (t) => {
401
+ const root = fixture(t, { withConfig: true });
402
+ const child = spawnSync(process.execPath, ['--import', TSX, CLI, '--deployment', '--json'], {
403
+ cwd: root, encoding: 'utf8', env: { ...process.env, BAILING_DOCTOR_FULL: '1', BAILING_DOCTOR_SMOKE: '1', BAILING_SMOKE_TOKEN: SECRET, BAILING_SMOKE_URL: `http://user:${SECRET}@127.0.0.1:9` }, timeout: 10_000,
404
+ });
405
+ assert.equal(child.status, 2, child.stderr);
406
+ assert.equal(child.stderr, '');
407
+ const report = JSON.parse(child.stdout);
408
+ assert.equal(report.mode, 'deployment');
409
+ assert.equal(report.exit_code, child.status);
410
+ assert.ok(!child.stdout.includes(SECRET));
411
+ assert.equal(existsSync(join(root, 'unsafe-model-call')), false);
412
+ assert.equal(existsSync(join(root, 'unsafe-typecheck')), false);
413
+ for (const args of [['--token', SECRET], ['--timeout-ms', '99'], ['--expect-commit', SECRET]]) {
414
+ const invalid = spawnSync(process.execPath, ['--import', TSX, CLI, '--deployment', ...args, '--json'], { cwd: root, encoding: 'utf8', timeout: 10_000 });
415
+ assert.equal(invalid.status, 64, invalid.stderr);
416
+ assert.equal(JSON.parse(invalid.stdout).reason, 'invalid_or_unsupported_argument');
417
+ assert.ok(!invalid.stdout.includes(SECRET));
418
+ }
419
+ });