agent-gear 2.13.0 → 2.14.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 (164) hide show
  1. package/AGENTS.md +14 -1
  2. package/dist/acp/bridge.d.ts +4 -0
  3. package/dist/acp/bridge.d.ts.map +1 -1
  4. package/dist/acp/bridge.js +72 -45
  5. package/dist/acp/bridge.js.map +1 -1
  6. package/dist/acp/bridge.test.js +40 -33
  7. package/dist/acp/bridge.test.js.map +1 -1
  8. package/dist/acp/process-registry.d.ts.map +1 -1
  9. package/dist/acp/process-registry.js +3 -1
  10. package/dist/acp/process-registry.js.map +1 -1
  11. package/dist/acp/process-registry.test.js +1 -0
  12. package/dist/acp/process-registry.test.js.map +1 -1
  13. package/dist/acp/spawner.d.ts +15 -0
  14. package/dist/acp/spawner.d.ts.map +1 -1
  15. package/dist/acp/spawner.js +51 -4
  16. package/dist/acp/spawner.js.map +1 -1
  17. package/dist/acp/sync-bridge.d.ts.map +1 -1
  18. package/dist/acp/sync-bridge.js +3 -1
  19. package/dist/acp/sync-bridge.js.map +1 -1
  20. package/dist/cloud-host/supervisor.d.ts +3 -1
  21. package/dist/cloud-host/supervisor.d.ts.map +1 -1
  22. package/dist/cloud-host/supervisor.js +18 -12
  23. package/dist/cloud-host/supervisor.js.map +1 -1
  24. package/dist/cloud-host/supervisor.test.js +19 -14
  25. package/dist/cloud-host/supervisor.test.js.map +1 -1
  26. package/dist/commands/harness.d.ts.map +1 -1
  27. package/dist/commands/harness.js +4 -2
  28. package/dist/commands/harness.js.map +1 -1
  29. package/dist/commands/mcp-proxy.d.ts +2 -1
  30. package/dist/commands/mcp-proxy.d.ts.map +1 -1
  31. package/dist/commands/mcp-proxy.js +26 -18
  32. package/dist/commands/mcp-proxy.js.map +1 -1
  33. package/dist/commands/mcp.js +1 -1
  34. package/dist/commands/mcp.js.map +1 -1
  35. package/dist/gateway.d.ts +3 -0
  36. package/dist/gateway.d.ts.map +1 -1
  37. package/dist/gateway.js +14 -8
  38. package/dist/gateway.js.map +1 -1
  39. package/dist/gateway.test.js +9 -4
  40. package/dist/gateway.test.js.map +1 -1
  41. package/dist/github/commit-identity-manager.d.ts +3 -1
  42. package/dist/github/commit-identity-manager.d.ts.map +1 -1
  43. package/dist/github/commit-identity-manager.js +13 -6
  44. package/dist/github/commit-identity-manager.js.map +1 -1
  45. package/dist/github/commit-identity-manager.test.js +26 -24
  46. package/dist/github/commit-identity-manager.test.js.map +1 -1
  47. package/dist/github/credential-manager.d.ts +3 -1
  48. package/dist/github/credential-manager.d.ts.map +1 -1
  49. package/dist/github/credential-manager.js +18 -10
  50. package/dist/github/credential-manager.js.map +1 -1
  51. package/dist/github/credential-manager.test.js +36 -33
  52. package/dist/github/credential-manager.test.js.map +1 -1
  53. package/dist/index.d.ts +1 -0
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +77 -70
  56. package/dist/index.js.map +1 -1
  57. package/dist/mcp/local-server.d.ts +3 -1
  58. package/dist/mcp/local-server.d.ts.map +1 -1
  59. package/dist/mcp/local-server.js +19 -9
  60. package/dist/mcp/local-server.js.map +1 -1
  61. package/dist/mcp/relay.d.ts +3 -1
  62. package/dist/mcp/relay.d.ts.map +1 -1
  63. package/dist/mcp/relay.js +20 -12
  64. package/dist/mcp/relay.js.map +1 -1
  65. package/dist/observability/http-context.d.ts +32 -0
  66. package/dist/observability/http-context.d.ts.map +1 -0
  67. package/dist/observability/http-context.js +97 -0
  68. package/dist/observability/http-context.js.map +1 -0
  69. package/dist/observability/log-context.d.ts +19 -0
  70. package/dist/observability/log-context.d.ts.map +1 -0
  71. package/dist/observability/log-context.js +21 -0
  72. package/dist/observability/log-context.js.map +1 -0
  73. package/dist/observability/logger.d.ts +31 -0
  74. package/dist/observability/logger.d.ts.map +1 -0
  75. package/dist/observability/logger.js +129 -0
  76. package/dist/observability/logger.js.map +1 -0
  77. package/dist/observability/no-console.test.d.ts +2 -0
  78. package/dist/observability/no-console.test.d.ts.map +1 -0
  79. package/dist/observability/no-console.test.js +78 -0
  80. package/dist/observability/no-console.test.js.map +1 -0
  81. package/dist/observability/register.d.ts +2 -0
  82. package/dist/observability/register.d.ts.map +1 -0
  83. package/dist/observability/register.js +29 -0
  84. package/dist/observability/register.js.map +1 -0
  85. package/dist/observability/telemetry.d.ts +12 -0
  86. package/dist/observability/telemetry.d.ts.map +1 -0
  87. package/dist/observability/telemetry.js +164 -0
  88. package/dist/observability/telemetry.js.map +1 -0
  89. package/dist/observability/testing.d.ts +24 -0
  90. package/dist/observability/testing.d.ts.map +1 -0
  91. package/dist/observability/testing.js +31 -0
  92. package/dist/observability/testing.js.map +1 -0
  93. package/dist/observability/trace.d.ts +42 -0
  94. package/dist/observability/trace.d.ts.map +1 -0
  95. package/dist/observability/trace.js +123 -0
  96. package/dist/observability/trace.js.map +1 -0
  97. package/dist/socketio-client.auth-gate.test.js +0 -3
  98. package/dist/socketio-client.auth-gate.test.js.map +1 -1
  99. package/dist/socketio-client.d.ts +3 -0
  100. package/dist/socketio-client.d.ts.map +1 -1
  101. package/dist/socketio-client.js +140 -69
  102. package/dist/socketio-client.js.map +1 -1
  103. package/dist/socketio-client.test.js +0 -6
  104. package/dist/socketio-client.test.js.map +1 -1
  105. package/dist/startup-span.d.ts +15 -0
  106. package/dist/startup-span.d.ts.map +1 -0
  107. package/dist/startup-span.js +21 -0
  108. package/dist/startup-span.js.map +1 -0
  109. package/dist/startup-span.test.d.ts +2 -0
  110. package/dist/startup-span.test.d.ts.map +1 -0
  111. package/dist/startup-span.test.js +71 -0
  112. package/dist/startup-span.test.js.map +1 -0
  113. package/dist/worktree-handler.d.ts +4 -1
  114. package/dist/worktree-handler.d.ts.map +1 -1
  115. package/dist/worktree-handler.js +10 -4
  116. package/dist/worktree-handler.js.map +1 -1
  117. package/dist/worktree-handler.test.js +6 -7
  118. package/dist/worktree-handler.test.js.map +1 -1
  119. package/package.json +8 -1
  120. package/src/acp/bridge.test.ts +63 -34
  121. package/src/acp/bridge.ts +95 -51
  122. package/src/acp/process-registry.test.ts +1 -0
  123. package/src/acp/process-registry.ts +4 -1
  124. package/src/acp/spawner.ts +68 -4
  125. package/src/acp/sync-bridge.ts +4 -1
  126. package/src/cloud-host/supervisor.test.ts +25 -14
  127. package/src/cloud-host/supervisor.ts +29 -14
  128. package/src/commands/harness.ts +4 -2
  129. package/src/commands/mcp-proxy.ts +41 -18
  130. package/src/commands/mcp.ts +1 -1
  131. package/src/gateway.test.ts +10 -5
  132. package/src/gateway.ts +15 -8
  133. package/src/github/commit-identity-manager.test.ts +30 -24
  134. package/src/github/commit-identity-manager.ts +19 -9
  135. package/src/github/credential-manager.test.ts +42 -33
  136. package/src/github/credential-manager.ts +28 -15
  137. package/src/index.ts +85 -74
  138. package/src/mcp/local-server.ts +31 -9
  139. package/src/mcp/relay.ts +32 -13
  140. package/src/observability/http-context.ts +122 -0
  141. package/src/observability/log-context.ts +39 -0
  142. package/src/observability/logger.ts +160 -0
  143. package/src/observability/no-console.test.ts +99 -0
  144. package/src/observability/register.ts +34 -0
  145. package/src/observability/telemetry.ts +180 -0
  146. package/src/observability/testing.ts +51 -0
  147. package/src/observability/trace.ts +163 -0
  148. package/src/socketio-client.auth-gate.test.ts +0 -3
  149. package/src/socketio-client.test.ts +0 -6
  150. package/src/socketio-client.ts +210 -69
  151. package/src/startup-span.test.ts +83 -0
  152. package/src/startup-span.ts +27 -0
  153. package/src/worktree-handler.test.ts +10 -7
  154. package/src/worktree-handler.ts +12 -8
  155. package/tests/acp-bridge.test.ts +11 -3
  156. package/tests/acp-spawner.test.ts +119 -14
  157. package/tests/acp-wire-elicitation.test.ts +0 -3
  158. package/tests/acp-wire-mcp.test.ts +9 -6
  159. package/tests/commands/harness.test.ts +6 -0
  160. package/tests/commands/mcp-proxy-dispatcher.test.ts +0 -2
  161. package/tests/commands/mcp-proxy.test.ts +43 -0
  162. package/tests/commands/mcp.test.ts +4 -0
  163. package/tests/socketio-client.test.ts +114 -36
  164. package/vitest.config.ts +3 -0
@@ -36,11 +36,13 @@ export function registerHarnessCommands(
36
36
  .action(async () => {
37
37
  try {
38
38
  const result = await (deps.prepare ?? prepareHarness)();
39
- console.log(formatPrepareSummary(result));
39
+ // 摘要为 CLI 结果输出(init 脚本/上游脚本按纯文本解析,R3),不走结构化日志。
40
+ console.log(formatPrepareSummary(result)); // no-console-allow: CLI 用户可见输出(结果摘要)
40
41
  } catch (error) {
41
42
  const secrets = collectSecretValues(process.env);
42
43
  const message = redactSecrets((error as Error).message, secrets);
43
- console.error(`harness prepare failed: ${message}`);
44
+ // 失败原因为 CLI 结果输出(给使用者的失败结果),不走结构化日志。
45
+ console.error(`harness prepare failed: ${message}`); // no-console-allow: CLI 用户可见输出(失败结果)
44
46
  // 非零退出:不直接 process.exit,便于测试断言 exitCode 与已刷新的日志。
45
47
  process.exitCode = 1;
46
48
  }
@@ -1,5 +1,6 @@
1
1
  import { spawn, ChildProcess } from 'child_process';
2
2
  import { io as ioClient, Socket } from 'socket.io-client';
3
+ import { logger as rootLogger, type ObservationLogger } from '../observability/logger.js';
3
4
 
4
5
  interface McpProxyOptions {
5
6
  server: string;
@@ -27,7 +28,8 @@ function isNotification(request: JsonRpcRequest): boolean {
27
28
  // Responses are matched to requests by id, so chunked responses (a single
28
29
  // 'data' event is NOT guaranteed to contain exactly one complete JSON
29
30
  // message) and concurrent in-flight requests are handled correctly.
30
- export function createStdioDispatcher(child: ChildProcess) {
31
+ export function createStdioDispatcher(child: ChildProcess, logger?: ObservationLogger) {
32
+ const log = logger ?? rootLogger.child({ component: 'mcp-proxy' });
31
33
  let buffer = '';
32
34
  const pending = new Map<unknown, { resolve: (value: unknown) => void; reject: (reason: Error) => void; timeout: NodeJS.Timeout; method: string }>();
33
35
 
@@ -42,17 +44,26 @@ export function createStdioDispatcher(child: ChildProcess) {
42
44
  try {
43
45
  msg = JSON.parse(line);
44
46
  } catch {
45
- console.error(`[MCP proxy] ignoring non-JSON line from child: ${line.slice(0, 200)}`);
47
+ log.error(
48
+ { event: 'non_json_line', preview: line.slice(0, 200) },
49
+ 'ignoring non-JSON line from child',
50
+ );
46
51
  continue;
47
52
  }
48
53
  const entry = pending.get(msg.id);
49
54
  if (!entry) {
50
- console.error(`[MCP proxy] ignoring response with unknown id: ${JSON.stringify(msg.id)}`);
55
+ log.error(
56
+ { event: 'unknown_response_id', id: typeof msg.id === 'string' || typeof msg.id === 'number' ? msg.id : undefined },
57
+ 'ignoring response with unknown id',
58
+ );
51
59
  continue;
52
60
  }
53
61
  clearTimeout(entry.timeout);
54
62
  pending.delete(msg.id);
55
- console.log(`[MCP proxy] response: method=${entry.method} id=${JSON.stringify(msg.id)}${msg.error ? ` error=${msg.error.message}` : ''}`);
63
+ log.debug(
64
+ { event: 'mcp_response', method: entry.method, id: msg.id, ...(msg.error ? { error: msg.error.message } : {}) },
65
+ 'mcp response',
66
+ );
56
67
  entry.resolve(msg);
57
68
  }
58
69
  });
@@ -66,7 +77,10 @@ export function createStdioDispatcher(child: ChildProcess) {
66
77
  };
67
78
 
68
79
  child.on('exit', (code) => {
69
- console.log(`[MCP proxy] MCP command exited with code ${code}, rejecting ${pending.size} pending request(s)`);
80
+ log.info(
81
+ { event: 'mcp_command_exited', exitCode: code, pendingCount: pending.size },
82
+ 'MCP command exited',
83
+ );
70
84
  rejectAll(new Error(`MCP command exited with code ${code}`));
71
85
  });
72
86
 
@@ -76,11 +90,11 @@ export function createStdioDispatcher(child: ChildProcess) {
76
90
  if (isNotification(request)) {
77
91
  // Fire-and-forget: deliver the notification (e.g. notifications/initialized
78
92
  // completes the MCP handshake) but do not wait for a response.
79
- console.log(`[MCP proxy] forwarding notification: method=${method}`);
93
+ log.debug({ event: 'forward_notification', method }, 'forwarding notification');
80
94
  child.stdin?.write(JSON.stringify(request) + '\n');
81
95
  return Promise.resolve(null);
82
96
  }
83
- console.log(`[MCP proxy] forwarding request: method=${method} id=${JSON.stringify(request.id)}`);
97
+ log.debug({ event: 'forward_request', method, id: request.id }, 'forwarding request');
84
98
  return new Promise((resolve, reject) => {
85
99
  const timeout = setTimeout(() => {
86
100
  pending.delete(request.id);
@@ -95,8 +109,9 @@ export function createStdioDispatcher(child: ChildProcess) {
95
109
 
96
110
  export async function startMcpRegistration(options: McpProxyOptions): Promise<void> {
97
111
  const { server, key, command } = options;
112
+ const log = rootLogger.child({ component: 'mcp-proxy' });
98
113
 
99
- console.log(`Registering MCP proxy with server ${server}...`);
114
+ console.log(`Registering MCP proxy with server ${server}...`); // no-console-allow: CLI 用户可见输出(进度)
100
115
 
101
116
  // 1. Register with server
102
117
  const response = await fetch(`${server}/api/mcp-proxy/register`, {
@@ -112,15 +127,15 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
112
127
 
113
128
  const result = await response.json() as any;
114
129
  if (!result.success) {
115
- console.error('Registration failed:', result.error);
130
+ console.error('Registration failed:', result.error); // no-console-allow: CLI 用户可见输出(失败结果)
116
131
  process.exit(1);
117
132
  }
118
133
 
119
- console.log(`Registered as proxy ${result.proxyId}, server ${result.serverId}`);
134
+ console.log(`Registered as proxy ${result.proxyId}, server ${result.serverId}`); // no-console-allow: CLI 用户可见输出(结果:代理标识)
120
135
 
121
136
  // 2. Spawn local command
122
137
  const [cmd, ...args] = command.split(' ');
123
- console.log(`Starting local MCP command: ${cmd} ${args.join(' ')}`);
138
+ console.log(`Starting local MCP command: ${cmd} ${args.join(' ')}`); // no-console-allow: CLI 用户可见输出(进度)
124
139
 
125
140
  const child = spawn(cmd, args, {
126
141
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -128,7 +143,7 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
128
143
  });
129
144
 
130
145
  child.on('error', (err) => {
131
- console.error('Failed to start MCP command:', err.message);
146
+ console.error('Failed to start MCP command:', err.message); // no-console-allow: CLI 用户可见输出(失败结果)
132
147
  });
133
148
 
134
149
  // 3. Establish WebSocket connection
@@ -138,26 +153,34 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
138
153
  });
139
154
 
140
155
  socket.on('connect', () => {
141
- console.log('WebSocket connected to proxy namespace');
156
+ console.log('WebSocket connected to proxy namespace'); // no-console-allow: CLI 用户可见输出(进度)
142
157
  socket.emit('proxy:register', { proxyId: result.proxyId, key });
143
158
  });
144
159
 
145
160
  socket.on('proxy:registered', (data: { proxyId: string; serverId: string }) => {
146
- console.log(`Registered with proxy namespace, serverId: ${data.serverId}`);
161
+ console.log(`Registered with proxy namespace, serverId: ${data.serverId}`); // no-console-allow: CLI 用户可见输出(结果)
147
162
  });
148
163
 
149
164
  socket.on('proxy:error', (data: { code: string; message: string }) => {
150
- console.error(`Proxy error: ${data.code} - ${data.message}`);
165
+ log.error({ event: 'proxy_error', code: data.code, serverMessage: data.message }, 'proxy error');
151
166
  });
152
167
 
153
168
  // 4. Bridge requests
154
- const dispatcher = createStdioDispatcher(child);
169
+ const dispatcher = createStdioDispatcher(child, log);
155
170
  socket.on('proxy:request', async (data: { requestId: string; request: JsonRpcRequest }) => {
156
171
  try {
157
172
  const response = await dispatcher.forward(data.request);
158
173
  socket.emit('proxy:response', { requestId: data.requestId, response });
159
174
  } catch (err: any) {
160
- console.error(`[MCP proxy] forward failed: method=${data.request?.method} id=${JSON.stringify(data.request?.id)} error=${err.message}`);
175
+ log.error(
176
+ {
177
+ event: 'forward_failed',
178
+ method: data.request?.method,
179
+ id: data.request?.id,
180
+ err: { message: err?.message ?? String(err) },
181
+ },
182
+ 'mcp forward failed',
183
+ );
161
184
  socket.emit('proxy:response', {
162
185
  requestId: data.requestId,
163
186
  response: {
@@ -178,7 +201,7 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
178
201
 
179
202
  // 6. Cleanup
180
203
  const shutdown = () => {
181
- console.log('Shutting down MCP proxy...');
204
+ console.log('Shutting down MCP proxy...'); // no-console-allow: CLI 用户可见输出(进度/生命周期)
182
205
  clearInterval(heartbeatInterval);
183
206
  socket.emit('proxy:unregister', { proxyId: result.proxyId });
184
207
  child.kill();
@@ -8,7 +8,7 @@ interface McpProxyOptions {
8
8
  export async function startMcpProxy(options: McpProxyOptions): Promise<void> {
9
9
  const { endpoint, token } = options;
10
10
 
11
- console.log(`Starting MCP proxy for endpoint: ${endpoint}`);
11
+ console.log(`Starting MCP proxy for endpoint: ${endpoint}`); // no-console-allow: CLI 用户可见输出(进度:代理端点)
12
12
 
13
13
  const rl = readline.createInterface({ input: process.stdin });
14
14
 
@@ -8,6 +8,7 @@ vi.mock('node:net', () => ({
8
8
 
9
9
  import net from 'node:net';
10
10
  import { GatewayManager } from './gateway.js';
11
+ import { createTestLogger, type TestLogger } from './observability/testing.js';
11
12
 
12
13
  function createMockLocalSocket() {
13
14
  const handlers = new Map<string, Function>();
@@ -39,10 +40,12 @@ function createMockServerSocket() {
39
40
 
40
41
  describe('GatewayManager', () => {
41
42
  let gatewayManager: GatewayManager;
43
+ let testLog: TestLogger;
42
44
 
43
45
  beforeEach(() => {
44
46
  vi.clearAllMocks();
45
- gatewayManager = new GatewayManager();
47
+ testLog = createTestLogger('gateway');
48
+ gatewayManager = new GatewayManager(testLog.logger);
46
49
  });
47
50
 
48
51
  describe('createTunnel', () => {
@@ -237,12 +240,14 @@ describe('GatewayManager', () => {
237
240
  });
238
241
 
239
242
  it('should log warning and ignore for unknown tunnelId', () => {
240
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
241
243
  gatewayManager.handleTunnelData('unknown-tunnel', 'data');
242
- expect(warnSpy).toHaveBeenCalledWith(
243
- expect.stringContaining('unknown tunnel'),
244
+ expect(testLog.records).toContainEqual(
245
+ expect.objectContaining({
246
+ level: 'warn',
247
+ msg: expect.stringContaining('unknown tunnel'),
248
+ tunnelId: 'unknown-tunnel',
249
+ }),
244
250
  );
245
- warnSpy.mockRestore();
246
251
  });
247
252
  });
248
253
 
package/src/gateway.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import net from 'node:net';
2
2
  import type { Socket } from 'socket.io-client';
3
+ import { logger as rootLogger, type ObservationLogger } from './observability/logger.js';
3
4
 
4
5
  interface Tunnel {
5
6
  id: string;
@@ -17,6 +18,11 @@ const HTTP_RESPONSE_COLLECT_MS = 100;
17
18
  export class GatewayManager {
18
19
  private tunnels: Map<string, Tunnel> = new Map();
19
20
  private reconnectTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
21
+ private log: ObservationLogger;
22
+
23
+ constructor(logger?: ObservationLogger) {
24
+ this.log = logger ?? rootLogger.child({ component: 'gateway' });
25
+ }
20
26
 
21
27
  async createTunnel(tunnelId: string, port: number, serverSocket: Socket): Promise<void> {
22
28
  this.tunnels.set(tunnelId, { id: tunnelId, port, localSocket: null, serverSocket, responseBuffer: [] });
@@ -32,7 +38,7 @@ export class GatewayManager {
32
38
 
33
39
  return new Promise<void>((resolve) => {
34
40
  const onError = (err: Error) => {
35
- console.error(`Gateway tunnel error: tunnelId=${tunnelId} error=${err.message}`);
41
+ this.log.error({ event: 'gateway_tunnel_error', tunnelId, err }, 'gateway tunnel error');
36
42
  localSocket.destroy();
37
43
  this.scheduleReconnect(tunnelId);
38
44
  resolve();
@@ -44,7 +50,7 @@ export class GatewayManager {
44
50
  localSocket.removeListener('error', onError);
45
51
 
46
52
  tunnel.localSocket = localSocket;
47
- console.log(`Gateway tunnel connected: tunnelId=${tunnelId} port=${tunnel.port}`);
53
+ this.log.info({ event: 'gateway_tunnel_connected', tunnelId, port: tunnel.port }, 'gateway tunnel connected');
48
54
 
49
55
  if (isInitial) {
50
56
  tunnel.serverSocket.emit('port-forward:created', { tunnelId, success: true });
@@ -64,13 +70,13 @@ export class GatewayManager {
64
70
  });
65
71
 
66
72
  localSocket.on('close', () => {
67
- console.log(`Gateway local socket closed: tunnelId=${tunnelId}`);
73
+ this.log.info({ event: 'gateway_local_socket_closed', tunnelId }, 'gateway local socket closed');
68
74
  tunnel.localSocket = null;
69
75
  this.scheduleReconnect(tunnelId);
70
76
  });
71
77
 
72
78
  localSocket.on('error', (err: Error) => {
73
- console.error(`Gateway local socket error: tunnelId=${tunnelId} error=${err.message}`);
79
+ this.log.error({ event: 'gateway_local_socket_error', tunnelId, err }, 'gateway local socket error');
74
80
  tunnel.serverSocket.emit('port-forward:error', { tunnelId, error: err.message });
75
81
  });
76
82
 
@@ -100,7 +106,8 @@ export class GatewayManager {
100
106
  private scheduleReconnect(tunnelId: string): void {
101
107
  if (!this.tunnels.has(tunnelId) || this.reconnectTimers.has(tunnelId)) return;
102
108
 
103
- console.log(`Gateway scheduling reconnection: tunnelId=${tunnelId}`);
109
+ // 3s 周期重连属轮询类高频事件 → debug(R6 日志量控制)
110
+ this.log.debug({ event: 'gateway_reconnect_scheduled', tunnelId }, 'gateway scheduling reconnection');
104
111
  const timer = setTimeout(() => {
105
112
  this.reconnectTimers.delete(tunnelId);
106
113
  this.connect(tunnelId, false);
@@ -112,7 +119,7 @@ export class GatewayManager {
112
119
  handleTunnelData(tunnelId: string, data: string): void {
113
120
  const tunnel = this.tunnels.get(tunnelId);
114
121
  if (!tunnel) {
115
- console.warn(`Gateway data for unknown tunnel: tunnelId=${tunnelId}`);
122
+ this.log.warn({ event: 'gateway_unknown_tunnel', tunnelId }, 'gateway data for unknown tunnel');
116
123
  return;
117
124
  }
118
125
 
@@ -156,7 +163,7 @@ export class GatewayManager {
156
163
  const tunnel = this.tunnels.get(tunnelId);
157
164
  if (!tunnel) return;
158
165
 
159
- console.log(`Gateway closing tunnel: tunnelId=${tunnelId}`);
166
+ this.log.info({ event: 'gateway_tunnel_close', tunnelId }, 'gateway closing tunnel');
160
167
 
161
168
  const timer = this.reconnectTimers.get(tunnelId);
162
169
  if (timer) {
@@ -173,7 +180,7 @@ export class GatewayManager {
173
180
  }
174
181
 
175
182
  closeAll(): void {
176
- console.log(`Gateway closing all tunnels: count=${this.tunnels.size}`);
183
+ this.log.info({ event: 'gateway_close_all', count: this.tunnels.size }, 'gateway closing all tunnels');
177
184
 
178
185
  for (const [tunnelId, tunnel] of [...this.tunnels]) {
179
186
  const timer = this.reconnectTimers.get(tunnelId);
@@ -6,6 +6,7 @@ import {
6
6
  type CommitIdentityApplier,
7
7
  type CommitIdentityRefreshResult,
8
8
  } from './commit-identity-manager.js';
9
+ import { createTestLogger, type TestLogger } from '../observability/testing.js';
9
10
 
10
11
  const HOST_KEY = 'zag_k_1_host_secret';
11
12
  const BASE_ENV: NodeJS.ProcessEnv = {
@@ -60,12 +61,12 @@ describe('CommitIdentityManager', () => {
60
61
  it('T-CIM1: first refresh posts with the host key and applies the returned identity', async () => {
61
62
  const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'co_author', ...CO_AUTHOR }));
62
63
  const applier = fakeApplier();
63
- const logs: string[] = [];
64
+ const testLog: TestLogger = createTestLogger();
64
65
  const manager = new CommitIdentityManager({
65
66
  env: BASE_ENV,
66
67
  fetch: fetchFn,
67
68
  applier,
68
- log: (message) => logs.push(message),
69
+ log: testLog.logger,
69
70
  });
70
71
 
71
72
  const result = await manager.refreshNow();
@@ -85,11 +86,12 @@ describe('CommitIdentityManager', () => {
85
86
  expect(init.signal).toBeInstanceOf(AbortSignal);
86
87
 
87
88
  // 日志不含身份值(邮箱 / 姓名)与 host key
88
- const output = logs.join('\n');
89
- expect(output).toContain('co_author');
90
- expect(output).not.toContain('Alice');
91
- expect(output).not.toContain('alice@users.noreply.github.com');
92
- expect(output).not.toContain(HOST_KEY);
89
+ expect(testLog.records).toContainEqual(
90
+ expect.objectContaining({ component: 'commit-identity', msg: '提交身份已更新', mode: 'co_author' }),
91
+ );
92
+ expect(JSON.stringify(testLog.records)).not.toContain('Alice');
93
+ expect(JSON.stringify(testLog.records)).not.toContain('alice@users.noreply.github.com');
94
+ expect(JSON.stringify(testLog.records)).not.toContain(HOST_KEY);
93
95
  });
94
96
 
95
97
  it('T-CIM2: mode=unset removes the managed configuration instead of applying it', async () => {
@@ -99,7 +101,7 @@ describe('CommitIdentityManager', () => {
99
101
  env: BASE_ENV,
100
102
  fetch: fetchFn,
101
103
  applier,
102
- log: () => {},
104
+ log: createTestLogger().logger,
103
105
  });
104
106
 
105
107
  const result = await manager.refreshNow();
@@ -117,7 +119,7 @@ describe('CommitIdentityManager', () => {
117
119
  env: BASE_ENV,
118
120
  fetch: fetchFn,
119
121
  applier,
120
- log: () => {},
122
+ log: createTestLogger().logger,
121
123
  setTimeout: scheduler.setTimeoutFn,
122
124
  });
123
125
 
@@ -144,7 +146,7 @@ describe('CommitIdentityManager', () => {
144
146
  env: BASE_ENV,
145
147
  fetch: fetchFn,
146
148
  applier,
147
- log: () => {},
149
+ log: createTestLogger().logger,
148
150
  sleep: async (ms) => {
149
151
  delays.push(ms);
150
152
  },
@@ -171,7 +173,7 @@ describe('CommitIdentityManager', () => {
171
173
  env: BASE_ENV,
172
174
  fetch: fetchFn,
173
175
  applier,
174
- log: () => {},
176
+ log: createTestLogger().logger,
175
177
  });
176
178
 
177
179
  const first = manager.refreshNow();
@@ -186,20 +188,24 @@ describe('CommitIdentityManager', () => {
186
188
 
187
189
  it('T-CIM6: missing env disables startup with a warn that only lists variable names', async () => {
188
190
  const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'unset' }));
189
- const logs: string[] = [];
191
+ const testLog: TestLogger = createTestLogger();
190
192
  const manager = new CommitIdentityManager({
191
193
  env: { ZAG_HOST_KEY: 'should-not-appear' },
192
194
  fetch: fetchFn,
193
- log: (message) => logs.push(message),
195
+ log: testLog.logger,
194
196
  });
195
197
 
196
198
  manager.start();
197
199
 
198
200
  expect(fetchFn).not.toHaveBeenCalled();
199
- const output = logs.join('\n');
200
- expect(output).toContain('ZAG_AGENT_API_ENDPOINT');
201
- expect(output).toContain('ZAG_CONTROLLER_ID');
202
- expect(output).not.toContain('should-not-appear');
201
+ expect(testLog.records).toContainEqual(
202
+ expect.objectContaining({
203
+ component: 'commit-identity',
204
+ msg: expect.stringContaining('disabled'),
205
+ missing: expect.arrayContaining(['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID']),
206
+ }),
207
+ );
208
+ expect(JSON.stringify(testLog.records)).not.toContain('should-not-appear');
203
209
  await expect(manager.refreshNow()).resolves.toEqual({ ok: false, error: 'disabled' });
204
210
  });
205
211
 
@@ -213,7 +219,7 @@ describe('CommitIdentityManager', () => {
213
219
  env: BASE_ENV,
214
220
  fetch: invalidJson,
215
221
  applier,
216
- log: () => {},
222
+ log: createTestLogger().logger,
217
223
  });
218
224
  const invalid = await manager.refreshNow();
219
225
  expect(invalid.ok).toBe(false);
@@ -224,7 +230,7 @@ describe('CommitIdentityManager', () => {
224
230
  env: BASE_ENV,
225
231
  fetch: invalidMode,
226
232
  applier,
227
- log: () => {},
233
+ log: createTestLogger().logger,
228
234
  });
229
235
  const modeResult = await modeManager.refreshNow();
230
236
  expect(modeResult.ok).toBe(false);
@@ -237,7 +243,7 @@ describe('CommitIdentityManager', () => {
237
243
  env: BASE_ENV,
238
244
  fetch: network,
239
245
  applier,
240
- log: () => {},
246
+ log: createTestLogger().logger,
241
247
  });
242
248
  const failed = await networkManager.refreshNow();
243
249
  expect(failed.ok).toBe(false);
@@ -249,7 +255,7 @@ describe('CommitIdentityManager', () => {
249
255
  });
250
256
 
251
257
  it('T-CIM8: logs and returned errors never contain the host key', async () => {
252
- const logs: string[] = [];
258
+ const testLog: TestLogger = createTestLogger();
253
259
  const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'co_author', ...CO_AUTHOR }));
254
260
  const applier = fakeApplier();
255
261
  applier.apply.mockImplementation(async () => {
@@ -259,14 +265,14 @@ describe('CommitIdentityManager', () => {
259
265
  env: BASE_ENV,
260
266
  fetch: fetchFn,
261
267
  applier,
262
- log: (message) => logs.push(message),
268
+ log: testLog.logger,
263
269
  });
264
270
 
265
271
  const result: CommitIdentityRefreshResult = await manager.refreshNow();
266
272
 
267
273
  expect(result.ok).toBe(false);
268
274
  expect(JSON.stringify(result)).not.toContain(HOST_KEY);
269
- expect(logs.join('\n')).not.toContain(HOST_KEY);
270
- expect(logs.join('\n')).not.toContain(CO_AUTHOR.coAuthorEmail);
275
+ expect(JSON.stringify(testLog.records)).not.toContain(HOST_KEY);
276
+ expect(JSON.stringify(testLog.records)).not.toContain(CO_AUTHOR.coAuthorEmail);
271
277
  });
272
278
  });
@@ -1,5 +1,7 @@
1
1
  import { CommitIdentity, type CommitIdentityMode } from './commit-identity.js';
2
2
  import { redactSecrets } from '../workload-executor.js';
3
+ import type { Logger as PinoLogger } from 'pino';
4
+ import { logger as rootLogger } from '../observability/logger.js';
3
5
 
4
6
  /** 提交身份同步间隔(50 分钟)。 */
5
7
  export const REFRESH_INTERVAL_MS = 50 * 60 * 1000;
@@ -29,7 +31,8 @@ export interface CommitIdentityManagerDeps {
29
31
  env?: NodeJS.ProcessEnv;
30
32
  fetch?: typeof fetch;
31
33
  applier?: CommitIdentityApplier;
32
- log?: (message: string) => void;
34
+ /** 注入 logger(测试用);缺省进程级单例,`component: 'commit-identity'`。 */
35
+ log?: PinoLogger;
33
36
  /** 定时器注入(测试用);缺省使用全局 `setTimeout`。 */
34
37
  setTimeout?: typeof setTimeout;
35
38
  /** 退避等待注入(测试用);缺省使用 `setTimeout`。 */
@@ -71,7 +74,7 @@ export class CommitIdentityManager {
71
74
  private readonly env: NodeJS.ProcessEnv;
72
75
  private readonly fetchFn: typeof fetch;
73
76
  private readonly applier: CommitIdentityApplier;
74
- private readonly log: (message: string) => void;
77
+ private readonly log: PinoLogger;
75
78
  private readonly setTimeoutFn: typeof setTimeout;
76
79
  private readonly sleepFn: (ms: number) => Promise<void>;
77
80
 
@@ -84,7 +87,8 @@ export class CommitIdentityManager {
84
87
  this.env = deps.env ?? process.env;
85
88
  this.fetchFn = deps.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
86
89
  this.applier = deps.applier ?? new CommitIdentity();
87
- this.log = deps.log ?? ((message: string) => console.log(message));
90
+ // component 固定绑定:无论注入哪路 logger,`[CommitIdentity]` 前缀语义由 component 字段承接
91
+ this.log = (deps.log ?? rootLogger).child({ component: 'commit-identity' });
88
92
  this.setTimeoutFn = deps.setTimeout ?? setTimeout;
89
93
  this.sleepFn =
90
94
  deps.sleep ??
@@ -106,7 +110,7 @@ export class CommitIdentityManager {
106
110
  this.stopped = false;
107
111
  const missing = this.missingEnv();
108
112
  if (missing.length > 0) {
109
- this.log(`[CommitIdentity] disabled: missing environment variable(s): ${missing.join(', ')}`);
113
+ this.log.warn({ event: 'disabled', missing }, 'commit identity manager disabled: missing environment variables');
110
114
  return;
111
115
  }
112
116
  this.started = true;
@@ -149,9 +153,15 @@ export class CommitIdentityManager {
149
153
  const result = await this.request(url, hostKey);
150
154
  if (result.kind === 'retryable' && attempt < BACKOFF_MS.length) {
151
155
  const delay = BACKOFF_MS[attempt]!;
152
- this.log(
153
- `[CommitIdentity] 提交身份下发未授权(HTTP ${result.status}),` +
154
- `${Math.round(delay / 60_000)} 分钟后重试(${attempt + 1}/${BACKOFF_MS.length})`,
156
+ this.log.warn(
157
+ {
158
+ event: 'unauthorized_retry',
159
+ status: result.status,
160
+ delayMs: delay,
161
+ attempt: attempt + 1,
162
+ maxAttempts: BACKOFF_MS.length,
163
+ },
164
+ '提交身份下发未授权,稍后重试',
155
165
  );
156
166
  await this.sleepFn(delay);
157
167
  continue;
@@ -223,7 +233,7 @@ export class CommitIdentityManager {
223
233
  } catch (error) {
224
234
  return { ok: false, error: this.applyError('移除', error, hostKey) };
225
235
  }
226
- this.log('[CommitIdentity] 托管配置已移除(mode=unset)');
236
+ this.log.info({ event: 'removed', mode: 'unset' }, '托管配置已移除');
227
237
  return { ok: true, mode: 'unset' };
228
238
  }
229
239
 
@@ -253,7 +263,7 @@ export class CommitIdentityManager {
253
263
  }
254
264
  }
255
265
 
256
- this.log(`[CommitIdentity] 提交身份已更新(mode=${mode})`);
266
+ this.log.info({ event: 'updated', mode }, '提交身份已更新');
257
267
  return { ok: true, mode: mode as CommitIdentityMode };
258
268
  }
259
269