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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailinghub",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Open-source ACC runtime and agent control plane for existing business systems.",
@@ -55,6 +55,7 @@
55
55
  "executor": "tsx src/executor.ts",
56
56
  "executor:watch": "tsx watch src/executor.ts",
57
57
  "typecheck": "tsc --noEmit",
58
+ "installer:secrets:test": "node --test scripts/install-secrets.test.mjs",
58
59
  "test": "node --import tsx --test \"src/**/*.test.ts\"",
59
60
  "db:init": "tsx scripts/init-db.ts",
60
61
  "demo:seed": "tsx scripts/seed-demo.ts",
@@ -90,7 +91,7 @@
90
91
  "release:consistency:test": "node --test scripts/check-release-consistency.test.mjs",
91
92
  "release:audit": "npm run release:consistency && npm run release:consistency:test && npm run images:policy:test && npm run public-content:denylist:test && npm run security:scan && npm run oss:guard && node scripts/release-audit.mjs && npm run package:artifact:check",
92
93
  "github:verify": "node scripts/verify-github-repo.mjs",
93
- "release:check": "npm run notices:check && npm run assets:check && npm run audit:deps && npm run client-api:contract && npm run client-api:ecosystem:clone && npm run typecheck && npm test && npm run widget:renderer:test && npm run web-admin:check && npm run docs:check && npm run examples:check && npm run sdk:test && npm run sdk:test7 && npm run sdk:test-node && npm run sdk:test-python && npm run sdk:test-runtime && npm run sdk:test-p1 && npm run release:audit && npm run oss:verify && npm run github:verify",
94
+ "release:check": "npm run notices:check && npm run assets:check && npm run audit:deps && npm run client-api:contract && npm run client-api:ecosystem:clone && npm run typecheck && npm run installer:secrets:test && npm run doctor:deployment:typecheck && npm run doctor:deployment:test && npm test && npm run widget:renderer:test && npm run web-admin:check && npm run docs:check && npm run examples:check && npm run sdk:test && npm run sdk:test7 && npm run sdk:test-node && npm run sdk:test-python && npm run sdk:test-runtime && npm run sdk:test-p1 && npm run release:audit && npm run oss:verify && npm run github:verify",
94
95
  "images:build": "sh scripts/publish-images.sh",
95
96
  "images:publish": "BAILING_PUSH_IMAGES=1 sh scripts/publish-images.sh",
96
97
  "images:publish-mysql": "BAILING_PUSH_IMAGES=1 sh scripts/publish-mysql-image.sh",
@@ -105,7 +106,10 @@
105
106
  "sdk:test-p1": "node scripts/sdk-p1-check.mjs",
106
107
  "sdk:pack": "COPYFILE_DISABLE=1 tar --no-xattrs -czf web/connect/bailing-connect-php.tgz -s '|^php|bailing-connect-php|' -C sdk php",
107
108
  "sdk:pack7": "COPYFILE_DISABLE=1 tar --no-xattrs -czf web/connect/bailing-connect-php7.tgz -s '|^php7|bailing-connect-php7|' -C sdk php7",
108
- "audit:deps:test": "node --test scripts/dependency-audit.test.mjs"
109
+ "audit:deps:test": "node --test scripts/dependency-audit.test.mjs",
110
+ "doctor:deployment:test": "node --import tsx --test scripts/doctor-deployment.test.ts",
111
+ "doctor:deployment:typecheck": "tsc --noEmit --strict --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --lib ES2022 --types node scripts/doctor.ts scripts/doctor-deployment.ts scripts/doctor-deployment.test.ts",
112
+ "test:model-process-recovery": "node --import tsx --test src/app/kernel-model-process-crash.mysql.test.ts"
109
113
  },
110
114
  "dependencies": {
111
115
  "mammoth": "^1.12.0",
@@ -107,6 +107,8 @@ const englishCompanions = {
107
107
  'docs/RELEASE_NOTES_v0.9.0.md': 'docs/RELEASE_NOTES_v0.9.0.en.md',
108
108
  'docs/UPGRADE_v0.9.0.md': 'docs/UPGRADE_v0.9.0.en.md',
109
109
  'docs/RELEASE_NOTES_v0.9.1.md': 'docs/RELEASE_NOTES_v0.9.1.en.md',
110
+ 'docs/RELEASE_NOTES_v0.9.2.md': 'docs/RELEASE_NOTES_v0.9.2.en.md',
111
+ 'docs/UPGRADE_v0.9.2.md': 'docs/UPGRADE_v0.9.2.en.md',
110
112
  'docs/UPGRADE_v0.9.1.md': 'docs/UPGRADE_v0.9.1.en.md',
111
113
  'docs/MODEL_BILLING.md': 'docs/MODEL_BILLING.en.md',
112
114
  'docs/PERIOD_ALLOWANCE_UPGRADE.md': 'docs/PERIOD_ALLOWANCE_UPGRADE.en.md',
@@ -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
  MYSQL_TAG="${BAILING_MYSQL_IMAGE_TAG:-8.4}"
14
14
  MYSQL_IMAGE="${BAILING_MYSQL_IMAGE:-$REGISTRY/$NAMESPACE/bailing-mysql:$MYSQL_TAG}"
15
15
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
@@ -38,8 +38,8 @@ function updateJson(root, relativePath, update) {
38
38
  test('current release surface is internally consistent', () => {
39
39
  const result = checkReleaseConsistency({ root: repoRoot });
40
40
  assert.deepEqual(result.findings, []);
41
- assert.equal(result.version, '0.9.1');
42
- assert.equal(result.stableVersion, '0.9.1');
41
+ assert.equal(result.version, '0.9.2');
42
+ assert.equal(result.stableVersion, '0.9.2');
43
43
  assert.equal(result.publishTag, 'latest');
44
44
  });
45
45
 
@@ -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
+ });