bailinghub 0.6.1 → 0.7.0

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 (145) hide show
  1. package/README.en.md +9 -5
  2. package/README.md +8 -5
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.md +4 -1
  9. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  10. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  11. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  12. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  13. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  14. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  15. package/docs/CHANGELOG.en.md +14 -1
  16. package/docs/CHANGELOG.md +14 -1
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  20. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  21. package/docs/README.en.md +6 -0
  22. package/docs/README.md +6 -0
  23. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  24. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  25. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  26. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  27. package/docs/SDK.en.md +31 -0
  28. package/docs/user-guide/conversations.en.md +4 -2
  29. package/docs/user-guide/conversations.md +4 -2
  30. package/package.json +1 -1
  31. package/schemas/config/route.schema.json +15 -2
  32. package/scripts/check-doc-links.mjs +1 -0
  33. package/scripts/check-image-tags.sh +1 -1
  34. package/scripts/check-release-consistency.test.mjs +2 -2
  35. package/scripts/install.sh +1 -1
  36. package/scripts/publish-images.sh +1 -1
  37. package/scripts/release-audit.mjs +1 -0
  38. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  39. package/scripts/sdk-runtime-test.mjs +5 -2
  40. package/scripts/verify-github-repo.mjs +1 -0
  41. package/sdk/php/README.md +29 -0
  42. package/sdk/php/src/AgentAuth.php +100 -4
  43. package/sdk/php/src/HubClient.php +2 -1
  44. package/sdk/php7/README.md +31 -0
  45. package/sdk/php7/src/AgentAuth.php +99 -4
  46. package/sdk/php7/src/HubClient.php +2 -1
  47. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  48. package/sql/059_agent_subject_display.sql +5 -0
  49. package/sql/README.en.md +15 -0
  50. package/sql/README.md +25 -0
  51. package/src/app/agent-conversation-audit.ts +20 -0
  52. package/src/app/agent-system-info.ts +41 -0
  53. package/src/app/agent-tool-invocations.ts +16 -4
  54. package/src/core/config/agent-setup.ts +37 -0
  55. package/src/core/config/client-agent-setup.ts +25 -0
  56. package/src/core/config/config-schema.test.ts +11 -0
  57. package/src/core/config/route-config.test.ts +28 -0
  58. package/src/core/config/route-config.ts +43 -4
  59. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  60. package/src/core/contracts/agent-subject-display.ts +36 -0
  61. package/src/core/contracts/types.ts +15 -0
  62. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  63. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  64. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  65. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  66. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  67. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  68. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  69. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  70. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  71. package/src/infrastructure/config/config-client-repository.ts +21 -0
  72. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  73. package/src/infrastructure/config/config-route-repository.ts +24 -0
  74. package/src/infrastructure/config/configstore.ts +7 -3
  75. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  76. package/src/routes/admin-access.ts +37 -0
  77. package/src/routes/admin-agent-clients.ts +11 -0
  78. package/src/routes/admin-agent-setup.test.ts +130 -0
  79. package/src/routes/admin-agent-setup.ts +68 -0
  80. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  81. package/src/routes/admin-dispatch-config.ts +2 -0
  82. package/src/routes/agent-api.ts +7 -0
  83. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  84. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  85. package/src/routes/agent-auth.test.ts +1 -1
  86. package/src/routes/agent-auth.ts +206 -16
  87. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  88. package/src/routes/agent-conversation-audit.ts +8 -2
  89. package/src/routes/agent-subject-display-http.test.ts +145 -0
  90. package/src/routes/agent-system-info.test.ts +132 -0
  91. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  92. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  93. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  94. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  95. package/web/connect/bailing-connect-php.tgz +0 -0
  96. package/web/connect/bailing-connect-php7.tgz +0 -0
  97. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
  98. package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
  99. package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
  100. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
  101. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
  102. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
  103. package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
  104. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
  105. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  106. package/web/console/assets/Clients-DGkkSXyA.js +3 -0
  107. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
  108. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
  109. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
  110. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
  111. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
  112. package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
  113. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
  114. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  115. package/web/console/assets/Routes-DubfjlBD.js +124 -0
  116. package/web/console/assets/Runs-1hxgkuR4.js +3 -0
  117. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  118. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
  119. package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
  120. package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
  121. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
  122. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
  123. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
  124. package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
  125. package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
  126. package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
  127. package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
  128. package/web/console/index.html +1 -1
  129. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  130. package/web-admin/src/components/AgentSetupPanel.vue +262 -0
  131. package/web-admin/src/components/ClientConversations.vue +21 -4
  132. package/web-admin/src/components/conversation-audit.ts +20 -0
  133. package/web-admin/src/pages/AgentClients.vue +97 -23
  134. package/web-admin/src/pages/Clients.vue +4 -1
  135. package/web-admin/src/pages/Routes.vue +10 -1
  136. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  137. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  138. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  139. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  140. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  141. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  142. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  143. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  144. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  145. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
@@ -0,0 +1,132 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { Readable } from 'node:stream';
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { AgentSession, Client, Route } from '../core/contracts/types';
6
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
8
+ import type { ToolProxyDeps } from '../app/tool-proxy';
9
+ import { AgentToolApiError, listAgentToolsFor } from '../app/agent-tool-invocations';
10
+ import { handleAgentApiHttpFor } from './agent-api';
11
+
12
+ class Response {
13
+ statusCode = 0;
14
+ headers: Record<string, unknown> = {};
15
+ body = '';
16
+ setHeader(name: string, value: unknown) { this.headers[name] = value; }
17
+ writeHead(code: number, headers: Record<string, unknown> = {}) { this.statusCode = code; Object.assign(this.headers, headers); }
18
+ end(value = '') { this.body = String(value); }
19
+ json() { return JSON.parse(this.body); }
20
+ }
21
+
22
+ function fixture() {
23
+ const token = `bha_${'s'.repeat(43)}`;
24
+ const client: Client = {
25
+ app_id: 'helpdesk-client', name: 'Helpdesk Client', token: 'not-returned', enabled: true,
26
+ agent_authorize_url: 'https://helpdesk.example.com/authorize', allowed_routes: ['helpdesk'], allowed_channels: [], rate_limit_per_min: 0,
27
+ };
28
+ const session: AgentSession = {
29
+ session_id: '123e4567-e89b-42d3-a456-426614174000', client_app_id: client.app_id, device_label: 'Untrusted account label',
30
+ principal: { id: 'operator-1', tenant: 'tenant-a', roles: ['staff'] }, on_behalf_of: 'tenant-a:operator-1', allowed_routes: ['helpdesk'],
31
+ created_at: '2026-01-01T00:00:00.000Z', access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-01-30T00:00:00.000Z',
32
+ };
33
+ const route: Route = {
34
+ route_key: 'helpdesk', name: 'Internal routing label', enabled: true, target: 'llm', target_config: { system_prompt: 'hidden rules', credential: 'hidden-credential' },
35
+ profile: 'general', session_policy: 'new', audience: { enabled: true, roles: ['staff'], clients: ['helpdesk-client'] },
36
+ agent_client: { enabled: true, instructions: 'hidden local rules', system_info: {
37
+ name: 'Helpdesk', summary: 'Manages customer support tickets.', domains: ['Ticket triage'], boundaries: ['Inventory changes belong to another system.'],
38
+ } },
39
+ tools: { sources: [{ provider: 'helpdesk-tools', allow: ['*'] }], agent_direct: { enabled: true } },
40
+ memory: { recent_messages: 12 }, knowledge: { kb_id: 'hidden-knowledge' },
41
+ };
42
+ let active = true;
43
+ const reads: string[] = [];
44
+ const unexpected = new Proxy({}, { get: (_object, property) => { throw new Error(`Unexpected service access: ${String(property)}`); } });
45
+ const configStore = {
46
+ agentAuth: { getSessionByAccessHash: async () => active ? session : null },
47
+ clients: { get: async () => client },
48
+ routes: { get: async (key: string) => { reads.push(key); return key === route.route_key ? route : null; }, list: () => { throw new Error('Must not enumerate routes'); } },
49
+ toolProviders: unexpected, conversations: unexpected, agentClientRuntime: unexpected,
50
+ } as unknown as ConfigStoreContract;
51
+ async function get(workspace = 'helpdesk', bearer = token) {
52
+ let bodyReads = 0;
53
+ const req = new Readable({ read() { bodyReads++; this.push(null); } }) as IncomingMessage;
54
+ req.method = 'GET'; req.headers = { authorization: `Bearer ${bearer}` };
55
+ const res = new Response();
56
+ await handleAgentApiHttpFor({
57
+ configStore, stateStore: unexpected as RuntimeStateStore, isPaused: () => false,
58
+ handleRun: async () => { throw new Error('Must not start run'); },
59
+ // Deliberately no toolProxyDeps: product descriptions do not load a tool runtime.
60
+ }, req, res as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/workspaces/${workspace}/system-info`));
61
+ assert.equal(bodyReads, 0);
62
+ return res;
63
+ }
64
+ return { route, client, session, configStore, reads, get, revoke: () => { active = false; } };
65
+ }
66
+
67
+ test('system-info reads only the selected binding before tools, body or business runs', async () => {
68
+ const f = fixture();
69
+ const res = await f.get();
70
+ assert.equal(res.statusCode, 200);
71
+ assert.equal(res.headers['cache-control'], 'no-store');
72
+ assert.deepEqual(res.json(), {
73
+ schema_version: 'bailing.agent-system-info.v1',
74
+ binding: { client_app_id: f.client.app_id, session_id: f.session.session_id, workspace: 'helpdesk' },
75
+ metadata_status: 'configured', revision: res.json().revision, system: f.route.agent_client!.system_info,
76
+ tool_status: 'not_loaded', availability: 'unknown',
77
+ });
78
+ assert.match(res.json().revision, /^[a-f0-9]{64}$/);
79
+ assert.deepEqual(f.reads, ['helpdesk']);
80
+ assert.doesNotMatch(res.body, /not-returned|hidden|Untrusted account label|Internal routing label/);
81
+ const same = await f.get();
82
+ assert.equal(same.json().revision, res.json().revision);
83
+ f.route.agent_client!.system_info!.summary = 'Supports ticket review and response drafts.';
84
+ assert.notEqual((await f.get()).json().revision, res.json().revision);
85
+ });
86
+
87
+ test('system-info remains readable with runtime/direct switches off, without enabling tools', async () => {
88
+ const f = fixture();
89
+ f.route.agent_client!.enabled = false;
90
+ let response = await f.get();
91
+ assert.equal(response.statusCode, 200);
92
+ assert.equal(response.json().metadata_status, 'configured');
93
+ assert.equal(response.json().unavailable_reason, 'agent_client_disabled');
94
+ f.route.agent_client!.enabled = true;
95
+ f.route.tools!.agent_direct = { enabled: false };
96
+ response = await f.get();
97
+ assert.equal(response.json().availability, 'unavailable');
98
+ assert.equal(response.json().unavailable_reason, 'agent_direct_disabled');
99
+ await assert.rejects(listAgentToolsFor({ configStore: f.configStore } as ToolProxyDeps, f, 'helpdesk'),
100
+ (error) => error instanceof AgentToolApiError && error.code === 'agent_direct_disabled');
101
+ });
102
+
103
+ test('system-info missing or malformed metadata stays unknown rather than inventing identity', async () => {
104
+ const f = fixture();
105
+ delete f.route.agent_client!.system_info;
106
+ const res = await f.get();
107
+ assert.equal(res.statusCode, 200);
108
+ assert.equal(res.json().metadata_status, 'missing');
109
+ assert.equal(res.json().system, null);
110
+ assert.equal(res.json().revision, null);
111
+ f.route.agent_client!.system_info = { name: 'Helpdesk', summary: '', domains: [], boundaries: [] };
112
+ assert.equal((await f.get()).json().metadata_status, 'missing');
113
+ });
114
+
115
+ test('system-info rejects unselected routes and wrong Client/Session/audience without metadata', async () => {
116
+ for (const mutation of ['client-route', 'session-route', 'client-binding', 'audience', 'revoked', 'disabled-route'] as const) {
117
+ const f = fixture();
118
+ if (mutation === 'client-route') f.client.allowed_routes = [];
119
+ if (mutation === 'session-route') f.session.allowed_routes = [];
120
+ if (mutation === 'client-binding') f.client.app_id = 'another-client';
121
+ if (mutation === 'audience') f.session.principal.roles = [];
122
+ if (mutation === 'revoked') f.revoke();
123
+ if (mutation === 'disabled-route') f.route.enabled = false;
124
+ const res = await f.get();
125
+ assert.equal(res.statusCode, mutation === 'revoked' ? 401 : mutation === 'disabled-route' ? 404 : 403, mutation);
126
+ assert.doesNotMatch(res.body, /Manages customer|Ticket triage/);
127
+ }
128
+ const f = fixture();
129
+ const res = await f.get('inventory');
130
+ assert.equal(res.statusCode, 403);
131
+ assert.deepEqual(f.reads, []);
132
+ });
@@ -0,0 +1,43 @@
1
+ import assert from 'node:assert/strict';
2
+
3
+ type Row = Record<string, any>;
4
+
5
+ /** Narrow in-memory SELECT evaluator shared by repository and loopback HTTP tests. */
6
+ export function evaluateBusinessSessionQuery(sessions: Row[], authorizations: Row[], sql: string, params: unknown[]): any[] {
7
+ assert.match(sql, /FROM bz_agent_sessions s WHERE s\.client_app_id=\?/);
8
+ assert.doesNotMatch(sql, /SELECT s\.\*|access_token_hash|refresh_token/);
9
+ let index = 0;
10
+ let found: Row[] = sessions.map((row): Row => ({ ...row, principal_json: typeof row.principal_json === 'string' ? JSON.parse(row.principal_json) : row.principal_json })).filter((row) => row.client_app_id === params[index]);
11
+ index++;
12
+ if (sql.includes('AND s.session_id=?')) { const id = params[index++]; found = found.filter((row) => row.session_id === id); }
13
+ if (sql.includes('matched.authorization_id=?')) {
14
+ const id = params[index++];
15
+ found = found.filter((row) => authorizations.some((item) => item.authorization_id === id && item.session_id === row.session_id && item.client_app_id === row.client_app_id && item.status === 'consumed'));
16
+ }
17
+ if (sql.includes('BINARY s.on_behalf_of=BINARY ?')) { const subject = params[index++]; found = found.filter((row) => row.on_behalf_of === subject); }
18
+ if (sql.includes("BINARY JSON_UNQUOTE(JSON_EXTRACT(s.principal_json,'$.id'))=BINARY ?")) {
19
+ const id = params[index++]; found = found.filter((row) => row.principal_json.id === id);
20
+ }
21
+ if (sql.includes("JSON_EXTRACT(s.principal_json,'$.tenant')")) {
22
+ const tenant = params[index++]; found = found.filter((row) => (row.principal_json.tenant ?? '') === tenant);
23
+ }
24
+ if (sql.includes('s.revoked_at IS NULL AND s.refresh_expires_at>?')) {
25
+ const now = String(params[index++]); found = found.filter((row) => !row.revoked_at && row.refresh_expires_at > now);
26
+ } else if (sql.includes('s.revoked_at IS NULL AND s.refresh_expires_at<=?')) {
27
+ const now = String(params[index++]); found = found.filter((row) => !row.revoked_at && row.refresh_expires_at <= now);
28
+ } else if (sql.includes('s.revoked_at IS NOT NULL')) found = found.filter((row) => row.revoked_at);
29
+ if (sql.includes('(s.created_at<? OR (s.created_at=? AND s.session_id<?))')) {
30
+ const created = params[index++]; assert.equal(params[index++], created); const id = params[index++];
31
+ found = found.filter((row) => row.created_at < String(created) || (row.created_at === created && row.session_id < String(id)));
32
+ }
33
+ if (sql.includes('ORDER BY')) {
34
+ assert.match(sql, /ORDER BY s\.created_at DESC,s\.session_id DESC LIMIT \?$/);
35
+ found.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.session_id.localeCompare(a.session_id));
36
+ found = found.slice(0, Number(params[index++]));
37
+ } else found = found.slice(0, 1);
38
+ assert.equal(index, params.length, 'every SQL placeholder has an explicitly consumed value');
39
+ return [found.map((row) => {
40
+ const links = authorizations.filter((item) => item.client_app_id === row.client_app_id && item.session_id === row.session_id && item.status === 'consumed');
41
+ return { ...structuredClone(row), cursor_created_at: `${row.created_at.replace(' ', 'T')}.000Z`, authorization_id: links.length === 1 ? links[0]!.authorization_id : null };
42
+ }), []];
43
+ }
@@ -0,0 +1,288 @@
1
+ import assert from 'node:assert/strict';
2
+ import type { Pool } from 'mysql2/promise';
3
+ import { AgentAuthRepository } from '../infrastructure/config/config-agent-auth-repository';
4
+
5
+ type Row = Record<string, any>;
6
+ type Table = 'authorization' | 'session' | 'token';
7
+ type Transaction = { id: number; writes: Map<string, Row>; locks: Set<string> };
8
+
9
+ function deferred() {
10
+ let resolve!: () => void;
11
+ const promise = new Promise<void>((done) => { resolve = done; });
12
+ return { promise, resolve };
13
+ }
14
+
15
+ export const AUTH = '11111111-1111-4111-8111-111111111111';
16
+ export const SESSION = '22222222-2222-4222-8222-222222222222';
17
+ export const OTHER_SESSION = '33333333-3333-4333-8333-333333333333';
18
+ export const APP = 'synthetic-shop';
19
+ export const FUTURE = '2099-01-01T00:00:00.000Z';
20
+ export const REDIRECT = 'http://127.0.0.1:43111/callback';
21
+
22
+ /**
23
+ * Executes the real repository SQL against a narrow transactional test double.
24
+ * Writes are private until commit; row locks persist through commit/rollback.
25
+ * Locking reads re-read committed rows after waiting. Unknown SQL fails closed.
26
+ * This validates repository scheduling and rollback, not MySQL/InnoDB semantics.
27
+ */
28
+ export class LedgerFixture {
29
+ readonly rows: Record<Table, Map<string, Row>> = {
30
+ authorization: new Map(), session: new Map(), token: new Map(),
31
+ };
32
+ private sequence = 0;
33
+ private owners = new Map<string, number>();
34
+ private changed = new Map<string, ReturnType<typeof deferred>[]>();
35
+ private blocked = new Map<string, ReturnType<typeof deferred>>();
36
+ private pauseLocks = new Map<string, { arrived: ReturnType<typeof deferred>; resume: ReturnType<typeof deferred> }>();
37
+ private failure?: { fragment: string; error: Error };
38
+ private failCommit = false;
39
+ readonly pool: Pool;
40
+ readonly repository: AgentAuthRepository;
41
+
42
+ constructor() {
43
+ this.rows.authorization.set(AUTH, {
44
+ authorization_id: AUTH, client_app_id: APP, redirect_uri: REDIRECT,
45
+ state_value: 'synthetic-state', requested_routes: '["shop"]', device_label: 'Synthetic device',
46
+ code_challenge: 'synthetic-challenge', status: 'pending', created_at: '2026-01-01 00:00:00',
47
+ expires_at: FUTURE, principal_json: null, allowed_routes: null, on_behalf_of: null,
48
+ code_hash: null, code_expires_at: null, session_id: null,
49
+ });
50
+ this.pool = {
51
+ getConnection: async () => {
52
+ const tx: Transaction = { id: ++this.sequence, writes: new Map(), locks: new Set() };
53
+ return {
54
+ beginTransaction: async () => {},
55
+ query: async (sql: string, params: unknown[] = []) => this.query(tx, sql, params),
56
+ commit: async () => {
57
+ if (this.failCommit) { this.failCommit = false; throw new Error('synthetic commit unavailable'); }
58
+ for (const [key, row] of tx.writes) {
59
+ const colon = key.indexOf(':');
60
+ this.rows[key.slice(0, colon) as Table].set(key.slice(colon + 1), structuredClone(row));
61
+ }
62
+ tx.writes.clear();
63
+ this.unlock(tx);
64
+ },
65
+ rollback: async () => { tx.writes.clear(); this.unlock(tx); },
66
+ release: () => { assert.equal(tx.locks.size, 0, 'connection must not release uncommitted locks'); },
67
+ };
68
+ },
69
+ query: async (sql: string, params: unknown[] = []) => this.query(null, sql, params),
70
+ } as unknown as Pool;
71
+ this.repository = new AgentAuthRepository(() => this.pool);
72
+ }
73
+
74
+ private all(table: Table, tx: Transaction | null): Row[] {
75
+ const rows = new Map(this.rows[table]);
76
+ for (const [key, row] of tx?.writes ?? []) if (key.startsWith(`${table}:`)) rows.set(key.slice(table.length + 1), row);
77
+ return [...rows.values()].map((row) => structuredClone(row));
78
+ }
79
+
80
+ private row(table: Table, id: string, tx: Transaction | null): Row | undefined {
81
+ const value = tx?.writes.get(`${table}:${id}`) ?? this.rows[table].get(id);
82
+ return value ? structuredClone(value) : undefined;
83
+ }
84
+
85
+ private async lock(tx: Transaction | null, key: string) {
86
+ assert.ok(tx, 'mutations/locking reads require a transaction');
87
+ while (this.owners.has(key) && this.owners.get(key) !== tx.id) {
88
+ this.blocked.get(key)?.resolve();
89
+ const wake = deferred();
90
+ const waiters = this.changed.get(key) ?? [];
91
+ waiters.push(wake);
92
+ this.changed.set(key, waiters);
93
+ let timer: ReturnType<typeof setTimeout> | undefined;
94
+ try {
95
+ await Promise.race([wake.promise, new Promise<never>((_, reject) => {
96
+ timer = setTimeout(() => reject(new Error(`synthetic row-lock timeout: ${key}`)), 2000);
97
+ })]);
98
+ } finally { clearTimeout(timer); this.changed.set(key, (this.changed.get(key) ?? []).filter((item) => item !== wake)); }
99
+ }
100
+ this.owners.set(key, tx.id);
101
+ tx.locks.add(key);
102
+ const pause = this.pauseLocks.get(key);
103
+ if (pause) {
104
+ this.pauseLocks.delete(key);
105
+ pause.arrived.resolve();
106
+ await pause.resume.promise;
107
+ }
108
+ }
109
+
110
+ private unlock(tx: Transaction) {
111
+ for (const key of tx.locks) {
112
+ this.owners.delete(key);
113
+ for (const waiter of this.changed.get(key) ?? []) waiter.resolve();
114
+ }
115
+ tx.locks.clear();
116
+ }
117
+
118
+ holdNextLock(table: Table, id: string) {
119
+ const pause = { arrived: deferred(), resume: deferred() };
120
+ this.pauseLocks.set(`${table}:${id}`, pause);
121
+ return { arrived: pause.arrived.promise, release: () => pause.resume.resolve() };
122
+ }
123
+
124
+ waitForBlocked(table: Table, id: string) {
125
+ const blocked = deferred();
126
+ this.blocked.set(`${table}:${id}`, blocked);
127
+ return blocked.promise;
128
+ }
129
+
130
+ failNext(fragment: string) { this.failure = { fragment, error: new Error('synthetic storage unavailable') }; }
131
+ failNextCommit() { this.failCommit = true; }
132
+
133
+ private async save(tx: Transaction | null, table: Table, id: string, row: Row) {
134
+ await this.lock(tx, `${table}:${id}`);
135
+ tx!.writes.set(`${table}:${id}`, structuredClone(row));
136
+ }
137
+
138
+ private async query(tx: Transaction | null, originalSql: string, params: unknown[]): Promise<any[]> {
139
+ const sql = originalSql.replace(/\s+/g, ' ').trim();
140
+ const p = params as any[];
141
+ if (this.failure && sql.includes(this.failure.fragment)) {
142
+ const error = this.failure.error; this.failure = undefined; throw error;
143
+ }
144
+ if (sql.startsWith('INSERT INTO bz_agent_authorizations ')) {
145
+ assert.equal(tx, null, 'authorization creation uses an autocommit insert');
146
+ assert.equal(this.rows.authorization.has(p[0]), false, 'duplicate authorization');
147
+ const names = ['authorization_id', 'client_app_id', 'redirect_uri', 'state_value', 'requested_routes', 'device_label', 'code_challenge', 'created_at', 'expires_at'];
148
+ this.rows.authorization.set(p[0], { ...Object.fromEntries(names.map((name, i) => [name, p[i]])), status: 'pending',
149
+ principal_json: null, allowed_routes: null, on_behalf_of: null, code_hash: null, code_expires_at: null, session_id: null });
150
+ return [{ affectedRows: 1 }];
151
+ }
152
+ if (sql.startsWith('SELECT * FROM bz_agent_authorizations WHERE')) {
153
+ const byCode = sql.includes('WHERE code_hash=?');
154
+ const locate = () => byCode ? this.all('authorization', tx).find((row) => row.code_hash === p[0]) : this.row('authorization', p[0], tx);
155
+ const initial = locate();
156
+ if (sql.endsWith('FOR UPDATE') && initial) await this.lock(tx, `authorization:${initial.authorization_id}`);
157
+ const row = locate();
158
+ return [row ? [row] : []];
159
+ }
160
+ if (sql.startsWith('SELECT ') && sql.includes('FROM bz_agent_sessions WHERE session_id=?')) {
161
+ if (sql.endsWith('FOR UPDATE')) await this.lock(tx, `session:${p[0]}`);
162
+ const row = this.row('session', p[0], tx);
163
+ return [row && (!sql.includes('AND client_app_id=?') || row.client_app_id === p[1]) ? [row] : []];
164
+ }
165
+ if (sql.startsWith('SELECT ') && sql.includes('FROM bz_agent_sessions s WHERE s.client_app_id=? AND s.session_id=? LIMIT 1')) {
166
+ const row = this.row('session', p[1], tx);
167
+ if (!row || row.client_app_id !== p[0]) return [[]];
168
+ const linked = this.all('authorization', tx).filter((a) => a.session_id === row.session_id && a.client_app_id === row.client_app_id && a.status === 'consumed');
169
+ return [[{ ...row, authorization_id: linked.length === 1 ? linked[0]!.authorization_id : null }]];
170
+ }
171
+ if (sql.startsWith('SELECT ') && sql.includes('FROM bz_agent_refresh_tokens WHERE token_hash=?')) {
172
+ if (sql.endsWith('FOR UPDATE')) await this.lock(tx, `token:${p[0]}`);
173
+ const row = this.row('token', p[0], tx);
174
+ return [row ? [row] : []];
175
+ }
176
+ if (sql.startsWith('SELECT * FROM bz_agent_sessions WHERE access_token_hash=?')) {
177
+ return [this.all('session', tx).filter((row) => row.access_token_hash === p[0] && !row.revoked_at &&
178
+ String(row.access_expires_at) >= p[1] && String(row.refresh_expires_at) >= p[2])];
179
+ }
180
+ if (sql.startsWith('UPDATE bz_agent_sessions SET last_seen_at=')) return [{ affectedRows: 1 }];
181
+ if (sql.startsWith("UPDATE bz_agent_authorizations SET status='approved'")) {
182
+ assert.equal(p.length, 8);
183
+ const row = this.row('authorization', p[7], tx);
184
+ if (!row || row.status !== 'pending') return [{ affectedRows: 0 }];
185
+ Object.assign(row, { status: 'approved', principal_json: p[0], on_behalf_of: p[1], allowed_routes: p[2], code_hash: p[3], code_expires_at: p[4], approved_at: p[5], subject_display: p[6] });
186
+ await this.save(tx, 'authorization', p[7], row);
187
+ return [{ affectedRows: 1 }];
188
+ }
189
+ if (sql.startsWith("UPDATE bz_agent_authorizations SET status='revoked'")) {
190
+ const row = this.row('authorization', p[0], tx)!;
191
+ Object.assign(row, { status: 'revoked', code_hash: null, code_expires_at: null });
192
+ await this.save(tx, 'authorization', p[0], row);
193
+ return [{ affectedRows: 1 }];
194
+ }
195
+ if (sql.startsWith("UPDATE bz_agent_authorizations SET status='consumed'")) {
196
+ const row = this.row('authorization', p[2], tx);
197
+ if (!row || row.status !== 'approved') return [{ affectedRows: 0 }];
198
+ Object.assign(row, { status: 'consumed', session_id: p[0], consumed_at: p[1] });
199
+ await this.save(tx, 'authorization', p[2], row);
200
+ return [{ affectedRows: 1 }];
201
+ }
202
+ if (sql.startsWith('INSERT INTO bz_agent_sessions ')) {
203
+ assert.equal(this.row('session', p[0], tx), undefined, 'duplicate session');
204
+ const names = ['session_id', 'client_app_id', 'device_label', 'principal_json', 'on_behalf_of', 'allowed_routes', 'access_token_hash', 'access_expires_at', 'refresh_expires_at', 'created_at', 'updated_at', 'subject_display'];
205
+ await this.save(tx, 'session', p[0], { ...Object.fromEntries(names.map((name, i) => [name, p[i]])), revoked_at: null });
206
+ return [{ affectedRows: 1 }];
207
+ }
208
+ if (sql.startsWith('INSERT INTO bz_agent_refresh_tokens ')) {
209
+ assert.equal(this.row('token', p[0], tx), undefined, 'duplicate refresh token');
210
+ await this.save(tx, 'token', p[0], { token_hash: p[0], session_id: p[1], status: 'active', created_at: p[2], expires_at: p[3], used_at: null });
211
+ return [{ affectedRows: 1 }];
212
+ }
213
+ if (sql.startsWith('UPDATE bz_agent_sessions SET revoked_at=')) {
214
+ const row = this.row('session', p[2], tx)!;
215
+ Object.assign(row, { revoked_at: row.revoked_at ?? p[0], updated_at: p[1] });
216
+ await this.save(tx, 'session', p[2], row);
217
+ return [{ affectedRows: 1 }];
218
+ }
219
+ if (sql.startsWith('UPDATE bz_agent_sessions SET access_token_hash=')) {
220
+ const row = this.row('session', p[3], tx);
221
+ if (!row || row.revoked_at) return [{ affectedRows: 0 }];
222
+ Object.assign(row, { access_token_hash: p[0], access_expires_at: p[1], updated_at: p[2] });
223
+ await this.save(tx, 'session', p[3], row);
224
+ return [{ affectedRows: 1 }];
225
+ }
226
+ if (sql === 'UPDATE bz_agent_sessions SET subject_display=?,updated_at=? WHERE session_id=? AND client_app_id=?') {
227
+ const row = this.row('session', p[2], tx);
228
+ if (!row || row.client_app_id !== p[3]) return [{ affectedRows: 0 }];
229
+ Object.assign(row, { subject_display: p[0], updated_at: p[1] });
230
+ await this.save(tx, 'session', p[2], row);
231
+ return [{ affectedRows: 1 }];
232
+ }
233
+ if (sql.startsWith("UPDATE bz_agent_refresh_tokens SET status='used'")) {
234
+ const row = this.row('token', p[1], tx);
235
+ if (!row || row.status !== 'active') return [{ affectedRows: 0 }];
236
+ Object.assign(row, { status: 'used', used_at: p[0] });
237
+ await this.save(tx, 'token', p[1], row);
238
+ return [{ affectedRows: 1 }];
239
+ }
240
+ if (sql.startsWith("UPDATE bz_agent_refresh_tokens SET status='revoked'") || sql.startsWith('UPDATE bz_agent_refresh_tokens SET status=CASE')) {
241
+ const replay = sql.includes('status=CASE');
242
+ const sessionId = p[replay ? 2 : 1];
243
+ let affectedRows = 0;
244
+ for (const row of this.all('token', tx)) {
245
+ if (row.session_id !== sessionId || !(replay ? ['active', 'used'] : ['active']).includes(row.status)) continue;
246
+ await this.lock(tx, `token:${row.token_hash}`);
247
+ const current = this.row('token', row.token_hash, tx)!;
248
+ current.status = replay && row.token_hash === p[0] ? 'replayed' : 'revoked';
249
+ current.used_at ??= p[replay ? 1 : 0];
250
+ await this.save(tx, 'token', row.token_hash, current);
251
+ affectedRows++;
252
+ }
253
+ return [{ affectedRows }];
254
+ }
255
+ throw new Error(`Unsupported lifecycle fixture SQL: ${sql}`);
256
+ }
257
+
258
+ async approve() {
259
+ const result = await this.repository.approveAuthorization({ authorizationId: AUTH, clientAppId: APP,
260
+ principal: { id: 'synthetic-owner', tenant: 'store-a', roles: ['manager'] }, onBehalfOf: 'store-a',
261
+ allowedRoutes: ['shop'], codeHash: 'synthetic-code-hash', codeExpiresAt: FUTURE });
262
+ assert.equal(result.ok, true);
263
+ }
264
+
265
+ exchange() {
266
+ return this.repository.exchangeAuthorizationCode({ codeHash: 'synthetic-code-hash', clientAppId: APP,
267
+ redirectUri: REDIRECT, codeChallenge: 'synthetic-challenge', sessionId: SESSION,
268
+ accessTokenHash: 'access-original', refreshTokenHash: 'refresh-original', accessExpiresAt: FUTURE, refreshExpiresAt: FUTURE });
269
+ }
270
+
271
+ rotate() {
272
+ return this.repository.rotateRefreshToken({ refreshTokenHash: 'refresh-original', clientAppId: APP,
273
+ accessTokenHash: 'access-next', nextRefreshTokenHash: 'refresh-next', accessExpiresAt: FUTURE });
274
+ }
275
+
276
+ revoke() { return this.repository.revokeAuthorization({ authorizationId: AUTH, clientAppId: APP }); }
277
+
278
+ async assertNoCredentialsWork() {
279
+ assert.equal(await this.repository.getSessionByAccessHash('access-original'), null);
280
+ assert.equal(await this.repository.getSessionByAccessHash('access-next'), null);
281
+ for (const hash of ['refresh-original', 'refresh-next']) {
282
+ const result = await this.repository.rotateRefreshToken({ refreshTokenHash: hash, clientAppId: APP,
283
+ accessTokenHash: 'must-not-exist', nextRefreshTokenHash: `must-not-exist-${hash}`, accessExpiresAt: FUTURE });
284
+ assert.equal(result.ok, false, `${hash} cannot issue a new credential`);
285
+ }
286
+ assert.equal([...this.rows.token.values()].some((row) => row.status === 'active'), false);
287
+ }
288
+ }
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
2
2
  import type { AgentSession, Client } from '../core/contracts/types';
3
3
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
4
4
  import { AgentConversationAuditRepository } from '../infrastructure/config/config-agent-conversation-audit-repository';
5
- import { parseCreateConversationAudit } from '../core/runtime/agent-conversation-audit';
5
+ import { parseCreateConversationAudit, parseCreateCrossBindingConversationAudit } from '../core/runtime/agent-conversation-audit';
6
6
 
7
7
  type Row = Record<string, any>;
8
8
  export const AUDIT_SESSION_A = '123e4567-e89b-42d3-a456-426614174001';
@@ -15,13 +15,19 @@ export const AUDIT_ARCHIVE = '323e4567-e89b-42d3-a456-426614174001';
15
15
  function duplicate(): never { throw Object.assign(new Error('duplicate fixture key'), { code: 'ER_DUP_ENTRY' }); }
16
16
 
17
17
  /** Synthetic SQL model for transactional repository tests; no socket, user DB or credentials. */
18
- export function conversationAuditFixture() {
18
+ export function conversationAuditFixture(options: { crossBinding?: boolean; schemaReady?: boolean } = {}) {
19
19
  const client: Client = {
20
20
  app_id: 'example-business', name: 'Example', token: '', agent_authorize_url: 'https://business.example.com/authorize',
21
21
  allowed_routes: ['orders'], allowed_channels: [], rate_limit_per_min: 0, enabled: true,
22
22
  };
23
23
  const route: Row = { route_key: 'orders', name: 'Orders', enabled: true, profile: 'general',
24
24
  agent_client: { enabled: true }, tools: { agent_direct: { enabled: true } } };
25
+ const clients = new Map<string, Client>([[client.app_id, client]]);
26
+ const routes = new Map<string, Row>([[route.route_key, route]]);
27
+ const migrationColumns = new Set(options.schemaReady === false ? [] : [
28
+ 'bz_agent_conversation_audits.membership_version', 'bz_agent_conversation_members.client_app_id',
29
+ 'bz_agent_conversation_members.route_key', 'bz_agent_conversation_members.client_name',
30
+ ]);
25
31
  const sessions = new Map<string, Row>();
26
32
  for (const [id, tenant] of [[AUDIT_SESSION_A, 'store-a'], [AUDIT_SESSION_B, 'store-b'], [AUDIT_SESSION_C, 'store-c']]) {
27
33
  sessions.set(id!, {
@@ -37,6 +43,12 @@ export function conversationAuditFixture() {
37
43
  [AUDIT_RUN_A, { run_id: AUDIT_RUN_A, session_id: AUDIT_SESSION_A, client_app_id: client.app_id, route_key: 'orders', thread_id: 101, client_conversation_id: 'client-conversation', client_turn_id: 'turn-1' }],
38
44
  [AUDIT_RUN_B, { run_id: AUDIT_RUN_B, session_id: AUDIT_SESSION_B, client_app_id: client.app_id, route_key: 'orders', thread_id: 102, client_conversation_id: 'client-conversation', client_turn_id: 'turn-1' }],
39
45
  ]);
46
+ if (options.crossBinding) {
47
+ clients.set('example-erp', { ...structuredClone(client), app_id: 'example-erp', name: 'Example ERP', allowed_routes: ['inventory'] });
48
+ routes.set('inventory', { ...structuredClone(route), route_key: 'inventory', name: 'Inventory' });
49
+ Object.assign(sessions.get(AUDIT_SESSION_B)!, { client_app_id: 'example-erp', allowed_routes: ['inventory'] });
50
+ Object.assign(runs.get(AUDIT_RUN_B)!, { client_app_id: 'example-erp', route_key: 'inventory' });
51
+ }
40
52
  const queries: Array<{ sql: string; params: any[]; transactional: boolean }> = [];
41
53
  let transaction = false;
42
54
  let snapshot: { archives: Map<string, Row>; members: Map<string, Row>; events: Map<string, Row> };
@@ -44,8 +56,11 @@ export function conversationAuditFixture() {
44
56
  queries.push({ sql, params: structuredClone(params), transactional: transaction });
45
57
  if (sql.includes('FOR UPDATE')) assert.equal(transaction, true, 'locking reads must be inside the mutation transaction');
46
58
  let result: any;
47
- if (sql.startsWith('SELECT') && sql.includes('FROM bz_clients')) result = params[0] === client.app_id ? [client] : [];
48
- else if (sql.startsWith('SELECT') && sql.includes('FROM bz_routes')) result = params[0] === route.route_key ? [route] : [];
59
+ if (sql.startsWith('SELECT') && sql.includes('FROM information_schema.COLUMNS')) result = [...migrationColumns].map((column) => {
60
+ const [table_name, column_name] = column.split('.'); return { table_name, column_name };
61
+ });
62
+ else if (sql.startsWith('SELECT') && sql.includes('FROM bz_clients')) result = clients.has(params[0]) ? [clients.get(params[0])] : [];
63
+ else if (sql.startsWith('SELECT') && sql.includes('FROM bz_routes')) result = routes.has(params[0]) ? [routes.get(params[0])] : [];
49
64
  else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_sessions')) result = sessions.has(params[0]) ? [sessions.get(params[0])] : [];
50
65
  else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_client_runs')) result = runs.has(params[0]) ? [runs.get(params[0])] : [];
51
66
  else if (sql.startsWith('INSERT INTO bz_agent_conversation_audits')) {
@@ -105,7 +120,7 @@ export function conversationAuditFixture() {
105
120
  const repo = new AgentConversationAuditRepository(() => ({ query, getConnection: async () => connection }));
106
121
  const auth = (id = AUDIT_SESSION_A) => {
107
122
  const row = sessions.get(id)!;
108
- return { client: structuredClone(client), session: {
123
+ return { client: structuredClone(clients.get(row.client_app_id)!), session: {
109
124
  ...structuredClone(row), principal: structuredClone(row.principal_json),
110
125
  } as AgentSession };
111
126
  };
@@ -115,9 +130,18 @@ export function conversationAuditFixture() {
115
130
  member_labels: { [AUDIT_SESSION_A]: 'Store A', [AUDIT_SESSION_B]: 'Store B' }, ...overrides,
116
131
  });
117
132
  const store = { agentConversationAudit: repo } as unknown as ConfigStoreContract;
133
+ const crossInput = (overrides: Row = {}) => parseCreateCrossBindingConversationAudit({
134
+ schema: 'bailing.agent-conversation-audit-create.v2', client_archive_id: AUDIT_ARCHIVE,
135
+ client_conversation_id: 'client-conversation', members: [
136
+ { session_id: AUDIT_SESSION_A, client_app_id: client.app_id, route: 'orders', label: 'CRM account' },
137
+ { session_id: AUDIT_SESSION_B, client_app_id: options.crossBinding ? 'example-erp' : client.app_id,
138
+ route: options.crossBinding ? 'inventory' : 'orders', label: 'ERP account' },
139
+ ], ...overrides,
140
+ });
118
141
  return {
119
- repo, store, auth, input, client, route, sessions, runs, queries,
142
+ repo, store, auth, input, crossInput, client, route, clients, routes, migrationColumns, sessions, runs, queries,
120
143
  get archives() { return archives; }, get members() { return members; }, get events() { return events; },
121
144
  async ready() { const result = await repo.create(auth(), input()); return repo.confirm(auth(AUDIT_SESSION_B), String(result.conversation_id)); },
145
+ async readyCross() { const result = await repo.createCrossBinding(auth(), crossInput()); return repo.confirm(auth(AUDIT_SESSION_B), String(result.conversation_id)); },
122
146
  };
123
147
  }
@@ -0,0 +1,84 @@
1
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
2
+ import type { AddressInfo } from 'node:net';
3
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
4
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
5
+ import type { Principal } from '../app/auth';
6
+ import { send } from '../app/http';
7
+ import { handleAgentApiHttpFor, type AgentApiHttpDeps } from '../routes/agent-api';
8
+ import { tokenHash } from '../routes/agent-auth';
9
+ import { handleAdminConversationAuditFor } from '../routes/admin-conversation-audit';
10
+ import { conversationAuditFixture, AUDIT_SESSION_A, AUDIT_SESSION_B, AUDIT_SESSION_C } from './agent-conversation-audit-fixture';
11
+
12
+ /**
13
+ * Real loopback HTTP + production Agent authentication/routes/repository, with a
14
+ * transactional in-memory SQL model. All credentials/data are synthetic. The
15
+ * admin bootstrap below supplies test principals; it does not replace or claim
16
+ * coverage of production admin login. No business executor is installed.
17
+ */
18
+ export async function conversationAuditHttpFixture(options: {
19
+ crossBinding?: boolean; schemaReady?: boolean; legacyHost?: boolean;
20
+ } = {}) {
21
+ const fx = conversationAuditFixture(options);
22
+ const tokens = new Map([AUDIT_SESSION_A, AUDIT_SESSION_B, AUDIT_SESSION_C]
23
+ .map((id, index) => [id, `bha_${String(index).repeat(43)}`]));
24
+ const adminToken = 'synthetic-audit-viewer';
25
+ const deniedAdminToken = 'synthetic-admin-without-runs-read';
26
+ // An old private Host implements only the original contract. New capability
27
+ // methods must remain optional, and absence must not enable cross binding.
28
+ const repository: NonNullable<ConfigStoreContract['agentConversationAudit']> = options.legacyHost ? {
29
+ create: fx.repo.create.bind(fx.repo), confirm: fx.repo.confirm.bind(fx.repo), append: fx.repo.append.bind(fx.repo),
30
+ listForAdmin: fx.repo.listForAdmin.bind(fx.repo), detailForAdmin: fx.repo.detailForAdmin.bind(fx.repo),
31
+ findRunLinkForAdmin: fx.repo.findRunLinkForAdmin.bind(fx.repo),
32
+ } : fx.repo;
33
+ const store = {
34
+ ...fx.store, agentConversationAudit: repository,
35
+ clients: { get: async (id: string) => fx.clients.get(id) ?? null },
36
+ agentAuth: { getSessionByAccessHash: async (hash: string) => {
37
+ const pair = [...tokens].find(([, token]) => tokenHash(token) === hash);
38
+ if (!pair) return null;
39
+ const session = fx.auth(pair[0]).session;
40
+ return session.revoked_at ? null : session;
41
+ } },
42
+ } as unknown as ConfigStoreContract;
43
+ const deps: AgentApiHttpDeps = {
44
+ configStore: store, stateStore: {} as RuntimeStateStore, isPaused: () => false,
45
+ handleRun: async () => { throw new Error('No business dispatch is installed in the archive fixture'); },
46
+ };
47
+ const requests: Array<{ method: string; path: string; sessionId: string | null }> = [];
48
+ const handler = async (req: IncomingMessage, res: ServerResponse) => {
49
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
50
+ const token = String(req.headers.authorization ?? '').replace(/^Bearer /, '');
51
+ const sessionId = [...tokens].find(([, value]) => value === token)?.[0] ?? null;
52
+ requests.push({ method: req.method ?? 'GET', path: url.pathname, sessionId });
53
+ if (await handleAgentApiHttpFor(deps, req, res, url)) return;
54
+ let principal: Principal | null = null;
55
+ if (token === adminToken) principal = { kind: 'admin', via: 'session', role: 'viewer' };
56
+ if (token === deniedAdminToken) principal = { kind: 'admin', via: 'session', role: 'admin', permissions: [] };
57
+ if (sessionId) principal = { kind: 'agent', ...fx.auth(sessionId) };
58
+ if (!principal) { send(res, 401, { error: 'unauthorized' }); return; }
59
+ if (await handleAdminConversationAuditFor(store, req.method ?? 'GET', url.pathname, req, res, principal)) return;
60
+ send(res, 404, { error: 'not_found' });
61
+ };
62
+ const server = createServer((req, res) => {
63
+ void handler(req, res).catch(() => send(res, 500, { error: 'fixture_failure' }));
64
+ });
65
+ await new Promise<void>((resolve, reject) => {
66
+ server.once('error', reject);
67
+ server.listen(0, '127.0.0.1', () => { server.off('error', reject); resolve(); });
68
+ });
69
+ const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
70
+ return Object.assign(fx, {
71
+ store, deps, origin, tokens, adminToken, deniedAdminToken, requests,
72
+ async api(method: string, path: string, body?: unknown, token: string | null = tokens.get(AUDIT_SESSION_A)!) {
73
+ const response = await fetch(`${origin}${path}`, {
74
+ method, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
75
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
76
+ });
77
+ const text = await response.text();
78
+ return { status: response.status, headers: response.headers, body: JSON.parse(text), text };
79
+ },
80
+ async close() {
81
+ await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
82
+ },
83
+ });
84
+ }
Binary file