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
@@ -0,0 +1,83 @@
1
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
2
+ import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace';
3
+ import { ExportResultCode, type ExportResult } from '@opentelemetry/core';
4
+ import { shutdownTelemetry, startTelemetry } from './observability/telemetry.js';
5
+ import { startupLinks, withStartupSpan } from './startup-span.js';
6
+
7
+ /**
8
+ * 本地 RecordingExporter(T-OBS18):自维护数组留存导出快照。
9
+ * 不用 InMemorySpanExporter——其 `shutdown()` 会清空缓冲,shutdown 后读不到。
10
+ */
11
+ function createRecordingExporter(): { exporter: SpanExporter; spans: ReadableSpan[] } {
12
+ const spans: ReadableSpan[] = [];
13
+ return {
14
+ spans,
15
+ exporter: {
16
+ export(batch: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {
17
+ spans.push(...batch);
18
+ resultCallback({ code: ExportResultCode.SUCCESS });
19
+ },
20
+ async shutdown(): Promise<void> {},
21
+ async forceFlush(): Promise<void> {},
22
+ },
23
+ };
24
+ }
25
+
26
+ const INIT_TRACEPARENT = '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01';
27
+
28
+ describe('startup span links (T-OBS18)', () => {
29
+ it('ZAG_INIT_TRACEPARENT 合法值产生 link;缺失/非法不产生 links', () => {
30
+ expect(startupLinks({ ZAG_INIT_TRACEPARENT: INIT_TRACEPARENT })).toEqual([
31
+ {
32
+ context: {
33
+ traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
34
+ spanId: '00f067aa0ba902b7',
35
+ traceFlags: 1,
36
+ isRemote: true,
37
+ },
38
+ },
39
+ ]);
40
+ expect(startupLinks({})).toEqual([]);
41
+ expect(startupLinks({ ZAG_INIT_TRACEPARENT: 'not-a-traceparent' })).toEqual([]);
42
+ expect(startupLinks({ ZAG_INIT_TRACEPARENT: '00-zeros-zeros-01' })).toEqual([]);
43
+ });
44
+
45
+ describe('withStartupSpan + RecordingExporter', () => {
46
+ const recording = createRecordingExporter();
47
+
48
+ beforeAll(() => {
49
+ process.env.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://127.0.0.1:4318';
50
+ delete process.env.OTEL_SDK_DISABLED;
51
+ startTelemetry({ traceExporter: recording.exporter });
52
+ });
53
+
54
+ afterAll(async () => {
55
+ await shutdownTelemetry();
56
+ delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
57
+ });
58
+
59
+ it('ZAG_INIT_TRACEPARENT 存在时 startup span 的 links[0].context.traceId 与注入值一致;缺失时无 links', async () => {
60
+ // case A:注入 ZAG_INIT_TRACEPARENT
61
+ process.env.ZAG_INIT_TRACEPARENT = INIT_TRACEPARENT;
62
+ await withStartupSpan({ 'agent.mode': 'test' }, () => undefined);
63
+
64
+ // case B:未注入
65
+ delete process.env.ZAG_INIT_TRACEPARENT;
66
+ await withStartupSpan({ 'agent.mode': 'test' }, () => undefined);
67
+
68
+ // BatchSpanProcessor 在 shutdown 时冲刷 → RecordingExporter 自维护数组内可读
69
+ await shutdownTelemetry();
70
+
71
+ const startups = recording.spans.filter((s) => s.name === 'startup');
72
+ expect(startups).toHaveLength(2);
73
+
74
+ // T-OBS18:links[0].context.traceId 等于注入值的 trace-id(link 而非 parent)
75
+ expect(startups[0].links).toHaveLength(1);
76
+ expect(startups[0].links[0].context.traceId).toBe('4bf92f3577b34da6a3ce929d0e0e4736');
77
+ expect(startups[0].links[0].context.spanId).toBe('00f067aa0ba902b7');
78
+
79
+ // 未注入:无 links(不注入无效上下文)
80
+ expect(startups[1].links).toHaveLength(0);
81
+ });
82
+ });
83
+ });
@@ -0,0 +1,27 @@
1
+ import type { Attributes, Link } from '@opentelemetry/api';
2
+ import { parseTraceparent, withSpan } from './observability/trace.js';
3
+
4
+ /**
5
+ * `startup` span 与 `ZAG_INIT_TRACEPARENT` link(T-OBS18)。
6
+ *
7
+ * cloud-controller 创建云电脑 Job 时把 `container.start` span 的 traceparent 注入
8
+ * `ZAG_INIT_TRACEPARENT`;agent-gear 启动时以 **link**(不是 parent)关联创建链路。
9
+ * 未注入 / 非法值 → 无 links(不注入无效上下文)。
10
+ */
11
+ export function startupLinks(env: NodeJS.ProcessEnv = process.env): Link[] {
12
+ const spanContext = parseTraceparent(env.ZAG_INIT_TRACEPARENT);
13
+ return spanContext ? [{ context: spanContext }] : [];
14
+ }
15
+
16
+ /**
17
+ * 创建 `startup` span 并在其上下文中执行 `fn`。
18
+ * `ZAG_INIT_TRACEPARENT` 存在且合法时 `links[0].context.traceId` 等于注入值的 trace-id。
19
+ */
20
+ export function withStartupSpan<T>(
21
+ attrs: Attributes,
22
+ fn: () => T | Promise<T>,
23
+ env: NodeJS.ProcessEnv = process.env,
24
+ ): T | Promise<T> {
25
+ const links = startupLinks(env);
26
+ return withSpan('startup', attrs, fn, links.length > 0 ? { links } : undefined);
27
+ }
@@ -15,6 +15,7 @@ vi.mock('fs', () => ({
15
15
  import { exec } from 'child_process';
16
16
  import { writeFileSync } from 'fs';
17
17
  import { WorktreeHandler, renderCoAuthorHook } from './worktree-handler.js';
18
+ import { createTestLogger, type TestLogger } from './observability/testing.js';
18
19
 
19
20
  type ExecCallback = (err: Error | null, stdout: string, stderr: string) => void;
20
21
 
@@ -60,10 +61,12 @@ function mockExecRecorder(commands: string[], shouldFail?: (command: string) =>
60
61
 
61
62
  describe('WorktreeHandler', () => {
62
63
  let handler: WorktreeHandler;
64
+ let testLog: TestLogger;
63
65
 
64
66
  beforeEach(() => {
65
67
  vi.clearAllMocks();
66
- handler = new WorktreeHandler();
68
+ testLog = createTestLogger('worktree-handler');
69
+ handler = new WorktreeHandler(testLog.logger);
67
70
  });
68
71
 
69
72
  describe('add', () => {
@@ -254,7 +257,6 @@ describe('WorktreeHandler', () => {
254
257
  vi.mocked(writeFileSync).mockImplementationOnce(() => {
255
258
  throw new Error('EACCES');
256
259
  });
257
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
258
260
 
259
261
  const result = await handler.add('/repo', '/wt', 'feat/branch', {
260
262
  name: 'Deliay',
@@ -264,15 +266,15 @@ describe('WorktreeHandler', () => {
264
266
  });
265
267
 
266
268
  expect(result.success).toBe(true);
267
- expect(warnSpy).toHaveBeenCalled();
269
+ expect(testLog.records).toContainEqual(
270
+ expect.objectContaining({ level: 'warn', msg: '写入 worktree 共同作者 hook 失败(忽略)' }),
271
+ );
268
272
  expect(commands.some((command) => command.includes('zag.coAuthor'))).toBe(false);
269
- warnSpy.mockRestore();
270
273
  });
271
274
 
272
275
  it('T-WTC4: 单条身份命令失败只告警,不阻断 worktree 创建结果', async () => {
273
276
  const commands: string[] = [];
274
277
  mockExecRecorder(commands, (command) => command.includes('user.name'));
275
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
276
278
 
277
279
  const result = await handler.add('/repo', '/wt', 'feat/branch', {
278
280
  name: 'Deliay',
@@ -283,8 +285,9 @@ describe('WorktreeHandler', () => {
283
285
  expect(result.worktreePath).toBe('/wt');
284
286
  expect(commands).toHaveLength(4);
285
287
  expect(commands[3]).toContain('user.email');
286
- expect(warnSpy).toHaveBeenCalled();
287
- warnSpy.mockRestore();
288
+ expect(testLog.records).toContainEqual(
289
+ expect.objectContaining({ level: 'warn', msg: '写入 worktree 提交人配置失败(忽略)' }),
290
+ );
288
291
  });
289
292
  });
290
293
 
@@ -2,6 +2,7 @@ import { exec, type ExecException } from 'child_process';
2
2
  import { chmodSync, mkdirSync, rmSync, existsSync, writeFileSync } from 'fs';
3
3
  import { homedir } from 'os';
4
4
  import { dirname, join, resolve } from 'path';
5
+ import { logger as rootLogger, type ObservationLogger } from './observability/logger.js';
5
6
 
6
7
  function expandTilde(p: string): string {
7
8
  return p.startsWith('~/') ? join(homedir(), p.slice(2)) : p;
@@ -128,6 +129,12 @@ export interface GitCommitResult {
128
129
  }
129
130
 
130
131
  export class WorktreeHandler {
132
+ private log: ObservationLogger;
133
+
134
+ constructor(logger?: ObservationLogger) {
135
+ this.log = logger ?? rootLogger.child({ component: 'worktree-handler' });
136
+ }
137
+
131
138
  async add(
132
139
  repoPath: string,
133
140
  worktreePath: string,
@@ -164,7 +171,7 @@ export class WorktreeHandler {
164
171
  * - `extensions.worktreeConfig true` 落在共享配置(幂等,重复 set 同值无副作用);
165
172
  * - `--worktree user.name/user.email` 落在 `.git/worktrees/<name>/config.worktree`;
166
173
  * - name/email 为**用户可控值**,一律经 `shellQuote` 转义后拼接;
167
- * - 单条失败仅 `console.warn`,不阻断 worktree 创建(身份缺失可接受)。
174
+ * - 单条失败仅 `this.log.warn`,不阻断 worktree 创建(身份缺失可接受)。
168
175
  */
169
176
  private async applyWorktreeCommitter(worktreePath: string, committer: WorktreeCommitter): Promise<void> {
170
177
  const pathArg = shellQuote(worktreePath);
@@ -178,7 +185,7 @@ export class WorktreeHandler {
178
185
  await execAsync(command);
179
186
  } catch (err) {
180
187
  // 不输出 name/email 值(用户数据),仅记录失败步骤与原因
181
- console.warn(`[WorktreeHandler] 写入 worktree 提交人配置失败(忽略):${(err as Error).message}`);
188
+ this.log.warn({ err }, '写入 worktree 提交人配置失败(忽略)');
182
189
  }
183
190
  }
184
191
 
@@ -219,9 +226,8 @@ export class WorktreeHandler {
219
226
  writeFileSync(hookPath, renderCoAuthorHook(), { mode: 0o755 });
220
227
  chmodSync(hookPath, 0o755);
221
228
  } catch (err) {
222
- console.warn(
223
- `[WorktreeHandler] 写入 worktree 共同作者 hook 失败(忽略):${(err as Error).message}`,
224
- );
229
+ // 不输出路径/用户数据,仅记录失败原因
230
+ this.log.warn({ err }, '写入 worktree 共同作者 hook 失败(忽略)');
225
231
  return;
226
232
  }
227
233
 
@@ -235,9 +241,7 @@ export class WorktreeHandler {
235
241
  await execAsync(command);
236
242
  } catch (err) {
237
243
  // 不输出共同作者值(服务端数据),仅记录失败步骤与原因
238
- console.warn(
239
- `[WorktreeHandler] 写入 worktree 共同作者配置失败(忽略):${(err as Error).message}`,
240
- );
244
+ this.log.warn({ err }, '写入 worktree 共同作者配置失败(忽略)');
241
245
  }
242
246
  }
243
247
  }
@@ -27,6 +27,7 @@ vi.mock('@agentclientprotocol/sdk', () => ({
27
27
  }));
28
28
 
29
29
  import { AcpSessionBridge, extractConfigOptions } from '../../src/acp/bridge.js';
30
+ import { createTestLogger, type TestLogger } from '../../src/observability/testing.js';
30
31
 
31
32
  class MockAcpSpawner {
32
33
  start = vi.fn();
@@ -48,11 +49,12 @@ function mc() { return mockConnInstance; }
48
49
  describe('AcpSessionBridge', () => {
49
50
  let mockSocket: ReturnType<typeof createMockSocket>;
50
51
  let mockSpawner: MockAcpSpawner;
52
+ let testLog: TestLogger;
51
53
 
52
54
  function createBridge() {
53
55
  return new AcpSessionBridge(
54
56
  mockSocket as never,
55
- { sessionId: 'sess-1', cwd: '/home/user' },
57
+ { sessionId: 'sess-1', cwd: '/home/user', logger: testLog.logger },
56
58
  mockSpawner as never,
57
59
  );
58
60
  }
@@ -64,6 +66,7 @@ describe('AcpSessionBridge', () => {
64
66
 
65
67
  mockSocket = createMockSocket();
66
68
  mockSpawner = new MockAcpSpawner();
69
+ testLog = createTestLogger('acp-bridge');
67
70
  });
68
71
 
69
72
  afterEach(() => {
@@ -624,10 +627,15 @@ describe('AcpSessionBridge', () => {
624
627
 
625
628
  it('handleElicitationResponse 未知 requestId 打 warn 不抛错', () => {
626
629
  const bridge = createBridge();
627
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
628
630
 
629
631
  expect(() => bridge.handleElicitationResponse('elic_unknown', 'cancel')).not.toThrow();
630
- expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('elic_unknown'));
632
+ expect(testLog.records).toContainEqual(
633
+ expect.objectContaining({
634
+ level: 'warn',
635
+ msg: 'elicitation request not found',
636
+ elicitationId: 'elic_unknown',
637
+ }),
638
+ );
631
639
  });
632
640
  });
633
641
 
@@ -6,6 +6,7 @@ import * as os from 'os';
6
6
 
7
7
  vi.mock('os', () => ({
8
8
  platform: vi.fn(() => 'linux'),
9
+ hostname: vi.fn(() => 'test-host'),
9
10
  }));
10
11
 
11
12
  vi.mock('child_process', () => ({
@@ -19,9 +20,10 @@ vi.mock('fs', async (importOriginal) => {
19
20
  return { ...actual, existsSync: vi.fn(() => false), mkdirSync: vi.fn() };
20
21
  });
21
22
 
22
- import { AcpSpawner } from '../../src/acp/spawner.js';
23
+ import { AcpSpawner, redactStderrText, STDERR_LOG_MAX_CHARS } from '../../src/acp/spawner.js';
23
24
  import { spawn, execFileSync, execFile } from 'child_process';
24
25
  import { existsSync } from 'fs';
26
+ import { createTestLogger, type TestLogger } from '../../src/observability/testing.js';
25
27
 
26
28
  function createMockChildProcess(): ChildProcess & EventEmitter {
27
29
  const proc = new EventEmitter() as ChildProcess & EventEmitter;
@@ -39,7 +41,7 @@ function createMockChildProcess(): ChildProcess & EventEmitter {
39
41
  describe('AcpSpawner', () => {
40
42
  let spawner: AcpSpawner;
41
43
  let mockProcess: ChildProcess & EventEmitter;
42
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
44
+ let testLog: TestLogger;
43
45
 
44
46
  beforeEach(() => {
45
47
  vi.clearAllMocks();
@@ -47,9 +49,9 @@ describe('AcpSpawner', () => {
47
49
  mockProcess = createMockChildProcess();
48
50
  vi.mocked(spawn).mockReturnValue(mockProcess as never);
49
51
 
50
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
52
+ testLog = createTestLogger('acp-spawner');
51
53
 
52
- spawner = new AcpSpawner({ sessionId: 'sess-1', cwd: '/tmp/project' });
54
+ spawner = new AcpSpawner({ sessionId: 'sess-1', cwd: '/tmp/project', logger: testLog.logger });
53
55
  });
54
56
 
55
57
  afterEach(() => {
@@ -71,23 +73,41 @@ describe('AcpSpawner', () => {
71
73
  spawner.start();
72
74
  const stderr = mockProcess.stderr as Readable;
73
75
  stderr.emit('data', Buffer.from('some warning\n'));
74
- expect(consoleErrorSpy).toHaveBeenCalledWith('ACP stderr (session=sess-1): some warning\n');
76
+ expect(testLog.records).toContainEqual(
77
+ expect.objectContaining({
78
+ component: 'acp-spawner',
79
+ level: 'error',
80
+ msg: 'acp server stderr',
81
+ stderr: 'some warning\n',
82
+ }),
83
+ );
75
84
  });
76
85
 
77
86
  it('should log resolved command, args and cwd on start', () => {
78
- const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
79
87
  spawner.start();
80
- expect(consoleLogSpy).toHaveBeenCalledWith(
81
- 'Starting ACP server: session=sess-1 cmd=/usr/bin/opencode args=["acp"] cwd=/tmp/project',
88
+ expect(testLog.records).toContainEqual(
89
+ expect.objectContaining({
90
+ component: 'acp-spawner',
91
+ msg: 'starting ACP server',
92
+ command: '/usr/bin/opencode',
93
+ args: ['acp'],
94
+ cwd: '/tmp/project',
95
+ }),
82
96
  );
83
97
  });
84
98
 
85
99
  it('should log exit code, signal and spawn params on process exit', () => {
86
- const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
87
100
  spawner.start();
88
101
  mockProcess.emit('exit', 1, null);
89
- expect(consoleLogSpy).toHaveBeenCalledWith(
90
- 'ACP process exited: session=sess-1 code=1 signal=null cmd=/usr/bin/opencode args=["acp"]',
102
+ expect(testLog.records).toContainEqual(
103
+ expect.objectContaining({
104
+ component: 'acp-spawner',
105
+ msg: 'acp process exited',
106
+ exitCode: 1,
107
+ signal: null,
108
+ command: '/usr/bin/opencode',
109
+ args: ['acp'],
110
+ }),
91
111
  );
92
112
  });
93
113
 
@@ -95,9 +115,14 @@ describe('AcpSpawner', () => {
95
115
  spawner.start();
96
116
  const error = new Error('spawn opencode ENOENT');
97
117
  mockProcess.emit('error', error);
98
- expect(consoleErrorSpy).toHaveBeenCalledWith(
99
- 'ACP process error (session=sess-1, cmd=/usr/bin/opencode):',
100
- error,
118
+ expect(testLog.records).toContainEqual(
119
+ expect.objectContaining({
120
+ component: 'acp-spawner',
121
+ level: 'error',
122
+ msg: 'acp process error',
123
+ command: '/usr/bin/opencode',
124
+ err: expect.objectContaining({ message: 'spawn opencode ENOENT' }),
125
+ }),
101
126
  );
102
127
  });
103
128
 
@@ -108,6 +133,86 @@ describe('AcpSpawner', () => {
108
133
  });
109
134
  });
110
135
 
136
+ describe('acp stderr 脱敏(B4)', () => {
137
+ it('B4: 已知 secret 值(process.env)不入日志', () => {
138
+ process.env.ZAG_HOST_KEY = 'opaque-host-key-value-42';
139
+ try {
140
+ spawner.start();
141
+ const stderr = mockProcess.stderr as Readable;
142
+ stderr.emit('data', Buffer.from('auth failed: opaque-host-key-value-42\n'));
143
+ expect(testLog.records).toContainEqual(
144
+ expect.objectContaining({
145
+ event: 'acp_stderr',
146
+ level: 'error',
147
+ stderr: 'auth failed: ***\n',
148
+ }),
149
+ );
150
+ } finally {
151
+ delete process.env.ZAG_HOST_KEY;
152
+ }
153
+ });
154
+
155
+ it('B4: token/key/password/secret 等键值对只留键名与占位符', () => {
156
+ const raw = 'password: hunter2 token=abc123 apiKey="sk-x" secret: s3cr3t authorization: Bearer abcdef0123456789 key=mapkey\n';
157
+ spawner.start();
158
+ (mockProcess.stderr as Readable).emit('data', Buffer.from(raw));
159
+ const record = testLog.records.find((r) => r.event === 'acp_stderr');
160
+ expect(record?.stderr).toBe('password: *** token=*** apiKey=*** secret: *** authorization: *** key=***\n');
161
+ });
162
+
163
+ it('B4: 形似凭据的串被替换(ghp_/github_pat_/sk-/JWT/Bearer/zag key)', () => {
164
+ const parts = [
165
+ `ghp_${'a'.repeat(20)}`,
166
+ `github_pat_${'b'.repeat(20)}`,
167
+ `sk-${'c'.repeat(20)}`,
168
+ `eyJhbGciOiJIUzI1NiJ9.${'d'.repeat(12)}.${'e'.repeat(12)}`,
169
+ `Bearer ${'f'.repeat(20)}`,
170
+ `zag_k_1_${'0'.repeat(48)}`,
171
+ ];
172
+ spawner.start();
173
+ (mockProcess.stderr as Readable).emit('data', Buffer.from(parts.join(' ')));
174
+ const record = testLog.records.find((r) => r.event === 'acp_stderr');
175
+ expect(record?.stderr).not.toContain('ghp_');
176
+ expect(record?.stderr).not.toContain('github_pat_');
177
+ expect(record?.stderr).not.toContain('sk-');
178
+ expect(record?.stderr).not.toContain('eyJ');
179
+ expect(record?.stderr).not.toContain('f'.repeat(20));
180
+ expect(record?.stderr).not.toContain('zag_k_');
181
+ expect(record?.stderr).toContain('***');
182
+ });
183
+
184
+ it('B4: 超长 stderr 截断到上限并标记 stderrTruncated', () => {
185
+ spawner.start();
186
+ (mockProcess.stderr as Readable).emit('data', Buffer.from('x'.repeat(STDERR_LOG_MAX_CHARS + 100)));
187
+ const record = testLog.records.find((r) => r.event === 'acp_stderr');
188
+ expect(record?.stderr).toHaveLength(STDERR_LOG_MAX_CHARS);
189
+ expect(record?.stderrTruncated).toBe(true);
190
+ });
191
+
192
+ it('B4: 短 stderr 不截断、不带截断标记', () => {
193
+ spawner.start();
194
+ (mockProcess.stderr as Readable).emit('data', Buffer.from('some warning\n'));
195
+ const record = testLog.records.find((r) => r.event === 'acp_stderr');
196
+ expect(record?.stderr).toBe('some warning\n');
197
+ expect(record?.stderrTruncated).toBeUndefined();
198
+ });
199
+ });
200
+
201
+ describe('redactStderrText', () => {
202
+ it('B4: 无敏感内容原样返回', () => {
203
+ expect(redactStderrText('some warning\n', {})).toBe('some warning\n');
204
+ });
205
+
206
+ it('B4: 键值对脱敏不误伤相邻普通文本', () => {
207
+ expect(redactStderrText('retrying in 5s, token expired', {})).toBe('retrying in 5s, token expired');
208
+ });
209
+
210
+ it('B4: 命令行 flag 形态(--token <值>)同样脱敏', () => {
211
+ expect(redactStderrText('run with --token abcdef123 --api-key=xyz987 done', {}))
212
+ .toBe('run with --token *** --api-key=*** done');
213
+ });
214
+ });
215
+
111
216
  describe('stdin', () => {
112
217
  it('should return a WritableStream when process is running', () => {
113
218
  spawner.start();
@@ -71,7 +71,6 @@ describe('AcpSessionBridge - Elicitation wire format (ACP spec)', () => {
71
71
  }
72
72
 
73
73
  it('should advertise elicitation capabilities in initialize on the wire', async () => {
74
- vi.spyOn(console, 'log').mockImplementation(() => {});
75
74
  setup('form');
76
75
 
77
76
  await bridge!.start();
@@ -83,7 +82,6 @@ describe('AcpSessionBridge - Elicitation wire format (ACP spec)', () => {
83
82
  }, 15000);
84
83
 
85
84
  it('should forward form elicitation and respond with spec-compliant payload', async () => {
86
- vi.spyOn(console, 'log').mockImplementation(() => {});
87
85
  const socket = setup('form');
88
86
 
89
87
  await bridge!.start();
@@ -120,7 +118,6 @@ describe('AcpSessionBridge - Elicitation wire format (ACP spec)', () => {
120
118
  }, 20000);
121
119
 
122
120
  it('should forward url elicitation and relay the completion notification', async () => {
123
- vi.spyOn(console, 'log').mockImplementation(() => {});
124
121
  const socket = setup('url');
125
122
 
126
123
  await bridge!.start();
@@ -13,6 +13,7 @@ vi.mock('@agentclientprotocol/sdk', async (importOriginal) => {
13
13
 
14
14
  import { AcpSessionBridge } from '../../src/acp/bridge.js';
15
15
  import { AcpSpawner } from '../../src/acp/spawner.js';
16
+ import { createTestLogger, type TestLogger } from '../../src/observability/testing.js';
16
17
 
17
18
  const FAKE_AGENT = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'fake-acp-agent.mjs');
18
19
 
@@ -23,6 +24,7 @@ describe('AcpSessionBridge - MCP wire format (ACP spec)', () => {
23
24
  let workdir: string;
24
25
  let captureFile: string;
25
26
  let bridge: AcpSessionBridge | null = null;
27
+ let testLog: TestLogger;
26
28
 
27
29
  afterEach(async () => {
28
30
  delete process.env.CAPTURE_FILE;
@@ -38,11 +40,13 @@ describe('AcpSessionBridge - MCP wire format (ACP spec)', () => {
38
40
  workdir = mkdtempSync(join(tmpdir(), 'acp-wire-'));
39
41
  captureFile = join(workdir, 'capture.jsonl');
40
42
  process.env.CAPTURE_FILE = captureFile;
43
+ testLog = createTestLogger('acp-bridge');
41
44
  const spawner = new AcpSpawner({
42
45
  sessionId: 'sess-wire',
43
46
  cwd: workdir,
44
47
  command: process.execPath,
45
48
  args: [FAKE_AGENT],
49
+ logger: createTestLogger('acp-spawner').logger,
46
50
  });
47
51
  const socket = { emit: vi.fn(), on: vi.fn(), off: vi.fn() };
48
52
  bridge = new AcpSessionBridge(socket as never, {
@@ -53,6 +57,7 @@ describe('AcpSessionBridge - MCP wire format (ACP spec)', () => {
53
57
  serverNames: ['fluentui-mcp', 'fs-mcp'],
54
58
  },
55
59
  mcpPort: 41234,
60
+ logger: testLog.logger,
56
61
  }, spawner);
57
62
  return socket;
58
63
  }
@@ -62,7 +67,6 @@ describe('AcpSessionBridge - MCP wire format (ACP spec)', () => {
62
67
  }
63
68
 
64
69
  it('should send session/new with spec-compliant mcpServers on the wire', async () => {
65
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
66
70
  setup();
67
71
 
68
72
  await bridge!.start();
@@ -89,15 +93,14 @@ describe('AcpSessionBridge - MCP wire format (ACP spec)', () => {
89
93
  expect(captured[0].params.cwd).toBe(workdir);
90
94
 
91
95
  // The MCP handoff must be visible in logs, without leaking the token
92
- const logLines = logSpy.mock.calls.map((c) => String(c[0]));
93
- const mcpLog = logLines.find((l) => l.includes('passing MCP servers via session/new'));
96
+ const mcpLog = testLog.records.find((r) => r.event === 'mcp_servers_passed');
94
97
  expect(mcpLog).toBeDefined();
95
- expect(mcpLog).toContain('fluentui-mcp(type=http, url=http://127.0.0.1:41234/mcp/sess-wire/fluentui-mcp, headers=Authorization)');
96
- expect(mcpLog).not.toContain('wire-token');
98
+ expect(mcpLog).toEqual(expect.objectContaining({ component: 'acp-bridge', method: 'session/new' }));
99
+ expect(String(mcpLog?.servers)).toContain('fluentui-mcp(type=http, url=http://127.0.0.1:41234/mcp/sess-wire/fluentui-mcp, headers=Authorization)');
100
+ expect(JSON.stringify(mcpLog)).not.toContain('wire-token');
97
101
  }, 15000);
98
102
 
99
103
  it('should send session/resume with spec-compliant mcpServers on the wire', async () => {
100
- vi.spyOn(console, 'log').mockImplementation(() => {});
101
104
  setup();
102
105
 
103
106
  await bridge!.resume('ext-session-1');
@@ -77,9 +77,13 @@ describe('agent-gear harness command (T-AG15)', () => {
77
77
  expect(prepare).toHaveBeenCalledTimes(1);
78
78
  expect(process.exitCode).toBeUndefined();
79
79
  const output = vi.mocked(console.log).mock.calls.flat().join(' ');
80
+ // R3:摘要为用户可见纯文本 stdout(被 init/上游脚本按行解析,非 JSON)
80
81
  expect(output).toContain('Harness prepared: types=opencode');
81
82
  expect(output).toContain('version=1.2.3');
82
83
  expect(output).not.toContain('zag_sk_');
84
+ for (const call of vi.mocked(console.log).mock.calls) {
85
+ expect(String(call[0])).not.toMatch(/^\s*\{/);
86
+ }
83
87
  });
84
88
 
85
89
  it('exits non-zero and redacts secrets when prepare fails', async () => {
@@ -93,8 +97,10 @@ describe('agent-gear harness command (T-AG15)', () => {
93
97
 
94
98
  expect(process.exitCode).toBe(1);
95
99
  const errors = vi.mocked(console.error).mock.calls.flat().join(' ');
100
+ // R3:失败原因同样为用户可见纯文本(保留原文可读,仅脱敏)
96
101
  expect(errors).toContain('harness prepare failed');
97
102
  expect(errors).not.toContain('zag_sk_super_secret');
98
103
  expect(errors).toContain('***');
104
+ expect(String(vi.mocked(console.error).mock.calls[0][0])).not.toMatch(/^\s*\{/);
99
105
  });
100
106
  });
@@ -23,8 +23,6 @@ describe('createStdioDispatcher', () => {
23
23
 
24
24
  beforeEach(() => {
25
25
  child = createFakeChild();
26
- vi.spyOn(console, 'log').mockImplementation(() => {});
27
- vi.spyOn(console, 'error').mockImplementation(() => {});
28
26
  });
29
27
 
30
28
  afterEach(() => {
@@ -42,6 +42,9 @@ beforeEach(() => {
42
42
  describe('mcp-proxy command', () => {
43
43
  it('should register with server and spawn child process', async () => {
44
44
  const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
45
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
46
+ const { io } = await import('socket.io-client');
47
+ const childProcess = await import('child_process');
45
48
 
46
49
  await startMcpRegistration({
47
50
  server: 'http://localhost:4001',
@@ -60,7 +63,44 @@ describe('mcp-proxy command', () => {
60
63
  }),
61
64
  });
62
65
 
66
+ // R3:用户可见进度/结果保持纯文本 stdout(保留输出逐条人工确认,见计划 §4.7)
67
+ const lines = consoleSpy.mock.calls.map((c) => String(c[0]));
68
+ expect(lines).toContain('Registering MCP proxy with server http://localhost:4001...');
69
+ expect(lines).toContain('Registered as proxy proxy_1, server server_1');
70
+ expect(lines).toContain('Starting local MCP command: npx @modelcontextprotocol/server-github');
71
+
72
+ // socket / 子进程 / 退出路径的用户可见输出同样保持纯文本
73
+ const socketMock = vi.mocked(io).mock.results[0]?.value as { on: ReturnType<typeof vi.fn> };
74
+ const socketHandlers = (event: string) =>
75
+ socketMock.on.mock.calls.filter((c) => c[0] === event).map((c) => c[1] as () => void);
76
+ socketHandlers('connect').forEach((h) => h());
77
+ socketHandlers('proxy:registered').forEach((h) => (h as (d: object) => void)({ proxyId: 'proxy_1', serverId: 'server_1' }));
78
+
79
+ const childOn = vi.mocked(childProcess.spawn).mock.results[0]?.value.on as ReturnType<typeof vi.fn>;
80
+ childOn.mock.calls
81
+ .filter((c) => c[0] === 'error')
82
+ .forEach((c) => (c[1] as (e: Error) => void)(new Error('ENOENT')));
83
+
84
+ const processOn = (globalThis.process as unknown as { on: ReturnType<typeof vi.fn> }).on;
85
+ const shutdown = processOn.mock.calls.find((c) => c[0] === 'SIGINT')![1] as () => void;
86
+ shutdown();
87
+
88
+ const allLines = consoleSpy.mock.calls.map((c) => String(c[0]));
89
+ expect(allLines).toContain('WebSocket connected to proxy namespace');
90
+ expect(allLines).toContain('Registered with proxy namespace, serverId: server_1');
91
+ expect(allLines).toContain('Shutting down MCP proxy...');
92
+ expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to start MCP command:', 'ENOENT');
93
+
94
+ // 纯文本(非 JSON):每个用户可见输出逐行断言
95
+ for (const line of allLines) {
96
+ expect(line).not.toMatch(/^\s*\{/);
97
+ }
98
+ for (const call of consoleErrorSpy.mock.calls) {
99
+ expect(String(call[0])).not.toMatch(/^\s*\{/);
100
+ }
101
+
63
102
  consoleSpy.mockRestore();
103
+ consoleErrorSpy.mockRestore();
64
104
  });
65
105
 
66
106
  it('should exit if registration fails', async () => {
@@ -77,6 +117,9 @@ describe('mcp-proxy command', () => {
77
117
  });
78
118
 
79
119
  expect(processExitSpy).toHaveBeenCalledWith(1);
120
+ // R3:失败结果为用户可见输出(保持纯文本与原文文案)
121
+ expect(consoleErrorSpy).toHaveBeenCalledWith('Registration failed:', 'Invalid key');
122
+ expect(String(consoleErrorSpy.mock.calls[0][0])).not.toMatch(/^\s*\{/);
80
123
 
81
124
  consoleErrorSpy.mockRestore();
82
125
  processExitSpy.mockRestore();