agent-gear 2.21.0 → 2.23.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 (71) hide show
  1. package/AGENTS.md +30 -2
  2. package/dist/cloud-host/supervisor.d.ts.map +1 -1
  3. package/dist/cloud-host/supervisor.js +6 -1
  4. package/dist/cloud-host/supervisor.js.map +1 -1
  5. package/dist/cloud-host/supervisor.test.js +35 -0
  6. package/dist/cloud-host/supervisor.test.js.map +1 -1
  7. package/dist/commands/github.d.ts +17 -0
  8. package/dist/commands/github.d.ts.map +1 -0
  9. package/dist/commands/github.js +24 -0
  10. package/dist/commands/github.js.map +1 -0
  11. package/dist/commands/github.test.d.ts +2 -0
  12. package/dist/commands/github.test.d.ts.map +1 -0
  13. package/dist/commands/github.test.js +31 -0
  14. package/dist/commands/github.test.js.map +1 -0
  15. package/dist/github/credential-manager.d.ts +11 -3
  16. package/dist/github/credential-manager.d.ts.map +1 -1
  17. package/dist/github/credential-manager.js +65 -19
  18. package/dist/github/credential-manager.js.map +1 -1
  19. package/dist/github/credential-manager.test.js +89 -0
  20. package/dist/github/credential-manager.test.js.map +1 -1
  21. package/dist/github/gh-config.d.ts +6 -0
  22. package/dist/github/gh-config.d.ts.map +1 -1
  23. package/dist/github/gh-config.js +16 -4
  24. package/dist/github/gh-config.js.map +1 -1
  25. package/dist/github/gh-config.test.js +25 -0
  26. package/dist/github/gh-config.test.js.map +1 -1
  27. package/dist/github/project-token.d.ts +81 -0
  28. package/dist/github/project-token.d.ts.map +1 -0
  29. package/dist/github/project-token.js +232 -0
  30. package/dist/github/project-token.js.map +1 -0
  31. package/dist/github/project-token.test.d.ts +2 -0
  32. package/dist/github/project-token.test.d.ts.map +1 -0
  33. package/dist/github/project-token.test.js +256 -0
  34. package/dist/github/project-token.test.js.map +1 -0
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +3 -0
  37. package/dist/index.js.map +1 -1
  38. package/dist/knowledge-bases.d.ts +7 -2
  39. package/dist/knowledge-bases.d.ts.map +1 -1
  40. package/dist/knowledge-bases.js +10 -4
  41. package/dist/knowledge-bases.js.map +1 -1
  42. package/dist/knowledge-bases.test.js +87 -2
  43. package/dist/knowledge-bases.test.js.map +1 -1
  44. package/dist/socketio-client.d.ts.map +1 -1
  45. package/dist/socketio-client.js +2 -1
  46. package/dist/socketio-client.js.map +1 -1
  47. package/dist/socketio-client.test.js +1 -0
  48. package/dist/socketio-client.test.js.map +1 -1
  49. package/dist/workload-executor.d.ts +5 -0
  50. package/dist/workload-executor.d.ts.map +1 -1
  51. package/dist/workload-executor.js.map +1 -1
  52. package/dist/workload-executor.test.js +34 -0
  53. package/dist/workload-executor.test.js.map +1 -1
  54. package/package.json +1 -1
  55. package/src/cloud-host/supervisor.test.ts +43 -0
  56. package/src/cloud-host/supervisor.ts +5 -1
  57. package/src/commands/github.test.ts +38 -0
  58. package/src/commands/github.ts +36 -0
  59. package/src/github/credential-manager.test.ts +113 -0
  60. package/src/github/credential-manager.ts +68 -17
  61. package/src/github/gh-config.test.ts +25 -0
  62. package/src/github/gh-config.ts +17 -4
  63. package/src/github/project-token.test.ts +314 -0
  64. package/src/github/project-token.ts +292 -0
  65. package/src/index.ts +4 -0
  66. package/src/knowledge-bases.test.ts +104 -2
  67. package/src/knowledge-bases.ts +14 -3
  68. package/src/socketio-client.test.ts +1 -0
  69. package/src/socketio-client.ts +2 -1
  70. package/src/workload-executor.test.ts +48 -0
  71. package/src/workload-executor.ts +5 -0
@@ -0,0 +1,292 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ /** 成功:已向 stdout 输出单行 token。 */
4
+ export const EXIT_OK = 0;
5
+ /** 当前目录不是 Github 项目(wrapper 需静默降级)。 */
6
+ export const EXIT_NOT_PROJECT = 3;
7
+ /** 项目未在平台初始化 / 云主机无绑定。 */
8
+ export const EXIT_NOT_BOUND = 4;
9
+ /** 当前账号无该项目权限。 */
10
+ export const EXIT_UNAUTHORIZED = 5;
11
+ /** 其它失败(env 缺失、平台不可达、超时、回显不匹配、非法响应)。 */
12
+ export const EXIT_FAILED = 6;
13
+
14
+ /** 申请接口超时(10 秒)。 */
15
+ export const REQUEST_TIMEOUT_MS = 10_000;
16
+
17
+ /** token 长度硬上限(防御异常响应污染 wrapper 的 env)。 */
18
+ export const MAX_TOKEN_LENGTH = 4096;
19
+
20
+ const GITHUB_HOST = 'github.com';
21
+ const REPO_SEGMENT = /^[\w.-]+$/;
22
+
23
+ /**
24
+ * 把 `git remote get-url origin` 的输出归一为 `owner/repo`(保留原大小写)。
25
+ *
26
+ * 支持 `https://`、`http://`、`ssh://`、`git://`、`git@github.com:owner/repo.git`、
27
+ * 带 userinfo 的 URL、尾部 `/` 与 `.git`;host 大小写不敏感。非 Github / 段数不为 2 /
28
+ * 含非法字符时返回 `null`。
29
+ */
30
+ export function normalizeGitHubRemote(remote: string): string | null {
31
+ if (typeof remote !== 'string') return null;
32
+ let value = remote.trim();
33
+ if (!value) return null;
34
+
35
+ for (const prefix of ['https://', 'http://', 'ssh://', 'git://']) {
36
+ if (value.toLowerCase().startsWith(prefix)) {
37
+ value = value.slice(prefix.length);
38
+ break;
39
+ }
40
+ }
41
+ // 剥 userinfo(`user:pass@host/...` 与 `git@host:...`)
42
+ const at = value.indexOf('@');
43
+ if (at >= 0) value = value.slice(at + 1);
44
+
45
+ // scp-like 形态 `github.com:owner/repo` → `github.com/owner/repo`
46
+ const colon = value.indexOf(':');
47
+ if (colon >= 0 && !value.slice(0, colon).includes('/')) {
48
+ value = `${value.slice(0, colon)}/${value.slice(colon + 1)}`;
49
+ }
50
+
51
+ value = value.replace(/\/+$/, '');
52
+ if (value.toLowerCase().endsWith('.git')) value = value.slice(0, -4);
53
+ value = value.replace(/\/+$/, '');
54
+ if (!value) return null;
55
+
56
+ const segments = value.split('/');
57
+ if (segments.length !== 3) return null;
58
+ const [host, owner, repo] = segments as [string, string, string];
59
+ if (host.toLowerCase() !== GITHUB_HOST) return null;
60
+ if (!REPO_SEGMENT.test(owner) || !REPO_SEGMENT.test(repo)) return null;
61
+ return `${owner}/${repo}`;
62
+ }
63
+
64
+ export interface GitCommandResult {
65
+ code: number;
66
+ stdout: string;
67
+ }
68
+
69
+ /** git 子命令执行器(测试注入;生产使用 `node:child_process.spawn`)。 */
70
+ export type GitRunner = (args: string[], cwd: string) => Promise<GitCommandResult | null>;
71
+
72
+ const defaultGitRunner: GitRunner = (args, cwd) =>
73
+ new Promise((resolve) => {
74
+ let settled = false;
75
+ const finish = (value: GitCommandResult | null): void => {
76
+ if (settled) return;
77
+ settled = true;
78
+ clearTimeout(timer);
79
+ resolve(value);
80
+ };
81
+ const child = spawn('git', ['-C', cwd, ...args], { stdio: ['ignore', 'pipe', 'ignore'] });
82
+ let stdout = '';
83
+ const timer = setTimeout(() => {
84
+ child.kill('SIGKILL');
85
+ finish(null);
86
+ }, REQUEST_TIMEOUT_MS);
87
+ timer.unref?.();
88
+ child.stdout?.on('data', (chunk: Buffer | string) => {
89
+ stdout += chunk.toString();
90
+ });
91
+ child.on('error', () => finish(null));
92
+ child.on('close', (code: number | null) => finish({ code: code ?? -1, stdout }));
93
+ });
94
+
95
+ export type GitProjectResolution =
96
+ | { kind: 'project'; repoFullName: string }
97
+ | { kind: 'not-project' };
98
+
99
+ export interface ResolveGitProjectDeps {
100
+ runGit?: GitRunner;
101
+ }
102
+
103
+ /**
104
+ * 解析 `cwd` 所属 Git 项目的 Github 仓库(`owner/repo`)。
105
+ * 不是 Git 仓库 / 无 origin / origin 非 Github 形态一律 `not-project`。
106
+ */
107
+ export async function resolveGitProject(
108
+ cwd: string,
109
+ deps: ResolveGitProjectDeps = {},
110
+ ): Promise<GitProjectResolution> {
111
+ const runGit = deps.runGit ?? defaultGitRunner;
112
+ try {
113
+ const topLevel = await runGit(['rev-parse', '--show-toplevel'], cwd);
114
+ if (!topLevel || topLevel.code !== 0) return { kind: 'not-project' };
115
+ const root = topLevel.stdout.trim();
116
+ if (!root) return { kind: 'not-project' };
117
+
118
+ const origin = await runGit(['remote', 'get-url', 'origin'], root);
119
+ if (!origin || origin.code !== 0) return { kind: 'not-project' };
120
+
121
+ const repoFullName = normalizeGitHubRemote(origin.stdout);
122
+ if (!repoFullName) return { kind: 'not-project' };
123
+ return { kind: 'project', repoFullName };
124
+ } catch {
125
+ return { kind: 'not-project' };
126
+ }
127
+ }
128
+
129
+ export type ProjectTokenResult =
130
+ | { kind: 'token'; token: string }
131
+ | { kind: 'error'; code: 4 | 5 | 6; message: string };
132
+
133
+ export interface RequestProjectTokenInput {
134
+ repoFullName: string;
135
+ env: NodeJS.ProcessEnv;
136
+ /** 注入 fetch(测试用);生产使用全局 fetch。 */
137
+ fetch?: typeof fetch;
138
+ /** 注入超时(测试或用例需要时)。 */
139
+ timeoutMs?: number;
140
+ }
141
+
142
+ const MISSING_ENV_KEYS = ['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID', 'ZAG_HOST_KEY'] as const;
143
+
144
+ function missingEnvKeys(env: NodeJS.ProcessEnv): string[] {
145
+ return MISSING_ENV_KEYS.filter((key) => {
146
+ const value = env[key];
147
+ return typeof value !== 'string' || value.trim().length === 0;
148
+ });
149
+ }
150
+
151
+ function isValidToken(token: unknown): token is string {
152
+ return (
153
+ typeof token === 'string' &&
154
+ token.length > 0 &&
155
+ token.length <= MAX_TOKEN_LENGTH &&
156
+ !/\s/.test(token)
157
+ );
158
+ }
159
+
160
+ function sameRepo(a: string, b: string): boolean {
161
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
162
+ }
163
+
164
+ function parseJson(text: string): Record<string, unknown> | null {
165
+ try {
166
+ const value = JSON.parse(text) as unknown;
167
+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : null;
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ /**
174
+ * 向 agent-api 申请项目级 Github token。
175
+ *
176
+ * 错误信息只含可读文案,不含 token / 响应体原文;退出码语义见 D6。
177
+ */
178
+ export async function requestProjectToken(
179
+ input: RequestProjectTokenInput,
180
+ ): Promise<ProjectTokenResult> {
181
+ const missing = missingEnvKeys(input.env);
182
+ if (missing.length > 0) {
183
+ return { kind: 'error', code: 6, message: `缺少环境变量:${missing.join('、')}` };
184
+ }
185
+
186
+ const endpoint = input.env.ZAG_AGENT_API_ENDPOINT!.trim().replace(/\/+$/, '');
187
+ const controllerId = input.env.ZAG_CONTROLLER_ID!.trim();
188
+ const hostKey = input.env.ZAG_HOST_KEY!.trim();
189
+ const url = `${endpoint}/internal/cloud-hosts/${encodeURIComponent(controllerId)}/github-credential`;
190
+ const fetchFn = input.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
191
+
192
+ const controller = new AbortController();
193
+ const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? REQUEST_TIMEOUT_MS);
194
+ timer.unref?.();
195
+
196
+ let status: number;
197
+ let text: string;
198
+ try {
199
+ const response = await fetchFn(url, {
200
+ method: 'POST',
201
+ headers: {
202
+ Authorization: `Bearer ${hostKey}`,
203
+ 'Content-Type': 'application/json',
204
+ },
205
+ body: JSON.stringify({ repoFullName: input.repoFullName }),
206
+ signal: controller.signal,
207
+ });
208
+ status = response.status;
209
+ text = await response.text();
210
+ } catch (error) {
211
+ const reason = error instanceof Error ? error.message : String(error);
212
+ const message = /abort/i.test(reason)
213
+ ? 'Github 凭据申请超时'
214
+ : 'Github 凭据申请失败(平台不可达)';
215
+ return { kind: 'error', code: 6, message };
216
+ } finally {
217
+ clearTimeout(timer);
218
+ }
219
+
220
+ const payload = text ? parseJson(text) : null;
221
+ const errorCode = typeof payload?.error === 'string' ? payload.error : '';
222
+
223
+ if (status === 200) {
224
+ const token = payload?.token;
225
+ const echoed = payload?.repoFullName;
226
+ if (typeof echoed !== 'string' || !sameRepo(echoed, input.repoFullName)) {
227
+ return { kind: 'error', code: 6, message: 'Github 凭据响应与请求项目不一致' };
228
+ }
229
+ if (!isValidToken(token)) {
230
+ return { kind: 'error', code: 6, message: 'Github 凭据响应缺少合法 token' };
231
+ }
232
+ return { kind: 'token', token };
233
+ }
234
+
235
+ if (status === 404) {
236
+ return {
237
+ kind: 'error',
238
+ code: 4,
239
+ message:
240
+ errorCode === 'PROJECT_NOT_BOUND'
241
+ ? '该项目尚未在平台初始化'
242
+ : '云主机未绑定 Github 项目',
243
+ };
244
+ }
245
+ if (status === 403) {
246
+ return {
247
+ kind: 'error',
248
+ code: 5,
249
+ message:
250
+ errorCode === 'REPO_NOT_AUTHORIZED' ? '当前账号无该项目权限' : 'Github 凭据申请被拒绝',
251
+ };
252
+ }
253
+ return { kind: 'error', code: 6, message: `Github 凭据申请失败(HTTP ${status})` };
254
+ }
255
+
256
+ export interface RunGithubTokenCommandOptions {
257
+ cwd?: string;
258
+ env?: NodeJS.ProcessEnv;
259
+ resolveGitProject?: typeof resolveGitProject;
260
+ requestProjectToken?: typeof requestProjectToken;
261
+ /** 输出通道(测试注入);生产为 `process.stdout.write`。 */
262
+ stdout?: (text: string) => void;
263
+ stderr?: (text: string) => void;
264
+ }
265
+
266
+ /**
267
+ * `agent-gear github-token` 的完整编排。
268
+ *
269
+ * 纪律(D5):**零 logger**;成功时 stdout 只有一行 token,失败时 stdout 为空、stderr 一行。
270
+ * 返回退出码(不调用 `process.exit`,便于测试)。
271
+ */
272
+ export async function runGithubTokenCommand(
273
+ options: RunGithubTokenCommandOptions = {},
274
+ ): Promise<number> {
275
+ const cwd = options.cwd ?? process.cwd();
276
+ const env = options.env ?? process.env;
277
+ const writeStdout = options.stdout ?? ((text: string) => void process.stdout.write(text));
278
+ const writeStderr = options.stderr ?? ((text: string) => void process.stderr.write(text));
279
+ const resolve = options.resolveGitProject ?? resolveGitProject;
280
+ const request = options.requestProjectToken ?? requestProjectToken;
281
+
282
+ const project = await resolve(cwd);
283
+ if (project.kind !== 'project') return EXIT_NOT_PROJECT;
284
+
285
+ const result = await request({ repoFullName: project.repoFullName, env });
286
+ if (result.kind === 'token') {
287
+ writeStdout(`${result.token}\n`);
288
+ return EXIT_OK;
289
+ }
290
+ writeStderr(`${result.message}\n`);
291
+ return result.code;
292
+ }
package/src/index.ts CHANGED
@@ -9,6 +9,7 @@ import { writePid, removePid, isRunning } from './daemon.js';
9
9
  import { startMcpRegistration } from './commands/mcp-proxy.js';
10
10
  import { startMcpProxy } from './commands/mcp.js';
11
11
  import { registerHarnessCommands } from './commands/harness.js';
12
+ import { registerGithubCommands } from './commands/github.js';
12
13
  import { isCloudHostMode, startCloudHostSupervisor } from './cloud-host/supervisor.js';
13
14
  import { processRegistry, isProcessAlive } from './acp/process-registry.js';
14
15
  import { logger as rootLogger } from './observability/logger.js';
@@ -155,4 +156,7 @@ program
155
156
  // 云电脑 harness 初始化子命令:`agent-gear harness prepare`(init 脚本调用)。
156
157
  registerHarnessCommands(program);
157
158
 
159
+ // 云电脑 Github 项目级凭据:`agent-gear github-token`(gh wrapper 调用)。
160
+ registerGithubCommands(program);
161
+
158
162
  program.parse();
@@ -12,6 +12,7 @@ import {
12
12
  let root: string;
13
13
  let zagDir: string;
14
14
  let docsDir: string;
15
+ let docsRoot: string;
15
16
 
16
17
  async function makeKb(sourceDir: string, folder: string, schema = '{"name":"kb"}') {
17
18
  const dir = join(sourceDir, folder);
@@ -24,6 +25,7 @@ beforeEach(async () => {
24
25
  root = await mkdtemp(join(tmpdir(), 'rkb-scan-'));
25
26
  zagDir = join(root, '.zag', 'knowledges');
26
27
  docsDir = join(root, 'docs', 'knowledges');
28
+ docsRoot = join(root, 'docs');
27
29
  await mkdir(zagDir, { recursive: true });
28
30
  await mkdir(docsDir, { recursive: true });
29
31
  });
@@ -43,7 +45,7 @@ describe('scanKnowledgeBases', () => {
43
45
  const result = await scanKnowledgeBases(root);
44
46
 
45
47
  expect(result.success).toBe(true);
46
- expect(result.sources.map((item) => item.source)).toEqual(['zag', 'docs']);
48
+ expect(result.sources.map((item) => item.source)).toEqual(['zag', 'docs', 'docs-root']);
47
49
  expect(result.sources[0].knowledgeBases.map((item) => item.folder)).toEqual(['a']);
48
50
  expect(result.sources[1].knowledgeBases.map((item) => item.folder)).toEqual(['b']);
49
51
  expect(result.sources[0].knowledgeBases[0].schema).toBe('{"name":"A"}');
@@ -100,6 +102,7 @@ describe('scanKnowledgeBases', () => {
100
102
  sources: [
101
103
  { source: 'zag', knowledgeBases: [], truncated: false },
102
104
  { source: 'docs', knowledgeBases: [], truncated: false },
105
+ { source: 'docs-root', knowledgeBases: [], truncated: false },
103
106
  ],
104
107
  truncated: false,
105
108
  });
@@ -234,6 +237,104 @@ describe('scanKnowledgeBases', () => {
234
237
  expect(result.truncated).toBe(true);
235
238
  });
236
239
 
240
+ it('T-RKB3-SCAN1 docs 一层文件夹含 knowledge-base.json → 第三来源识别,文档路径正确', async () => {
241
+ const kb = await makeKb(docsRoot, 'guides', '{"name":"指南"}');
242
+ await writeFile(join(kb, 'intro.md'), '# 简介');
243
+ await mkdir(join(kb, 'api'), { recursive: true });
244
+ await writeFile(join(kb, 'api', 'rest.md'), '# REST');
245
+
246
+ const result = await scanKnowledgeBases(root);
247
+ const source = result.sources.find((item) => item.source === 'docs-root');
248
+
249
+ expect(source?.knowledgeBases.map((item) => item.folder)).toEqual(['guides']);
250
+ expect(source?.knowledgeBases[0].schema).toBe('{"name":"指南"}');
251
+ expect(source?.knowledgeBases[0].documents?.map((doc) => doc.path)).toEqual([
252
+ 'api/rest.md',
253
+ 'intro.md',
254
+ ]);
255
+ });
256
+
257
+ it('T-RKB3-SCAN2 三来源同名文件夹互不覆盖,来源顺序固定', async () => {
258
+ await makeKb(zagDir, 'same', '{"name":"ZAG 库"}');
259
+ await makeKb(docsDir, 'same', '{"name":"DOCS 库"}');
260
+ await makeKb(docsRoot, 'same', '{"name":"DOCS_ROOT 库"}');
261
+
262
+ const result = await scanKnowledgeBases(root);
263
+
264
+ expect(result.sources.map((item) => item.source)).toEqual(['zag', 'docs', 'docs-root']);
265
+ expect(result.sources.map((item) => item.knowledgeBases[0]?.schema)).toEqual([
266
+ '{"name":"ZAG 库"}',
267
+ '{"name":"DOCS 库"}',
268
+ '{"name":"DOCS_ROOT 库"}',
269
+ ]);
270
+ });
271
+
272
+ it('T-RKB3-SCAN3 docs/knowledges 容器本身不被识别;其子文件夹仍属 docs 来源', async () => {
273
+ // 容器目录直接含 knowledge-base.json:docs-root 必须跳过
274
+ await writeFile(join(docsRoot, 'knowledges', 'knowledge-base.json'), '{"name":"容器"}', 'utf8');
275
+ await makeKb(docsDir, 'child', '{"name":"子库"}');
276
+ await makeKb(docsRoot, 'guides', '{"name":"指南"}');
277
+
278
+ const result = await scanKnowledgeBases(root);
279
+ const docsSource = result.sources.find((item) => item.source === 'docs');
280
+ const docsRootSource = result.sources.find((item) => item.source === 'docs-root');
281
+
282
+ expect(docsSource?.knowledgeBases.map((item) => item.folder)).toEqual(['child']);
283
+ expect(docsRootSource?.knowledgeBases.map((item) => item.folder)).toEqual(['guides']);
284
+ });
285
+
286
+ it('T-RKB3-SCAN4 docs 深层嵌套 knowledge-base.json 不识别(发现不递归)', async () => {
287
+ const nested = join(docsRoot, 'outer', 'inner');
288
+ await mkdir(nested, { recursive: true });
289
+ await writeFile(join(nested, 'knowledge-base.json'), '{"name":"inner"}', 'utf8');
290
+
291
+ const result = await scanKnowledgeBases(root);
292
+ const source = result.sources.find((item) => item.source === 'docs-root');
293
+
294
+ expect(source?.knowledgeBases).toEqual([]);
295
+ });
296
+
297
+ it('T-RKB3-SCAN5 docs 目录不存在 → 第三来源空列表;子项 >1000 → 来源截断', async () => {
298
+ const emptyRoot = await mkdtemp(join(tmpdir(), 'rkb-docs-root-empty-'));
299
+ const empty = await scanKnowledgeBases(emptyRoot);
300
+ expect(empty.sources.find((item) => item.source === 'docs-root')).toEqual({
301
+ source: 'docs-root',
302
+ knowledgeBases: [],
303
+ truncated: false,
304
+ });
305
+ await rm(emptyRoot, { recursive: true, force: true });
306
+
307
+ for (let i = 0; i <= MAX_ENTRIES_PER_FOLDER; i += 1) {
308
+ await makeKb(docsRoot, `kb${String(i).padStart(4, '0')}`);
309
+ }
310
+ const result = await scanKnowledgeBases(root);
311
+ const source = result.sources.find((item) => item.source === 'docs-root');
312
+ expect(source?.knowledgeBases).toHaveLength(MAX_ENTRIES_PER_FOLDER);
313
+ expect(source?.truncated).toBe(true);
314
+ expect(result.truncated).toBe(true);
315
+ });
316
+
317
+ it('T-RKB3-SCAN6 docs-root 单文件上限:schema 超限整库 error、单文档超限逐条 error', async () => {
318
+ const badSchema = join(docsRoot, 'bad-schema');
319
+ await mkdir(badSchema, { recursive: true });
320
+ await writeFile(join(badSchema, 'knowledge-base.json'), 'x'.repeat(MAX_FILE_BYTES + 1));
321
+ const mixed = await makeKb(docsRoot, 'mixed', '{"name":"混合"}');
322
+ await writeFile(join(mixed, 'big.md'), 'x'.repeat(MAX_FILE_BYTES + 1));
323
+ await writeFile(join(mixed, 'ok.md'), '# ok');
324
+
325
+ const result = await scanKnowledgeBases(root);
326
+ const source = result.sources.find((item) => item.source === 'docs-root');
327
+ const bad = source?.knowledgeBases.find((item) => item.folder === 'bad-schema');
328
+ const entry = source?.knowledgeBases.find((item) => item.folder === 'mixed');
329
+
330
+ expect(bad).toEqual({ folder: 'bad-schema', error: 'file too large' });
331
+ expect(entry?.documents?.find((doc) => doc.path === 'big.md')).toEqual({
332
+ path: 'big.md',
333
+ error: 'file too large',
334
+ });
335
+ expect(entry?.documents?.find((doc) => doc.path === 'ok.md')?.content).toBe('# ok');
336
+ });
337
+
237
338
  it('T-RKB-SCAN8 符号链接:指向常规 .md 文件读取;指向目录/悬空跳过', async () => {
238
339
  const kb = await makeKb(zagDir, 'kb');
239
340
  await writeFile(join(kb, 'real.md'), '# real');
@@ -254,10 +355,11 @@ describe('scanKnowledgeBases', () => {
254
355
  });
255
356
 
256
357
  describe('REPO_KNOWLEDGE_BASE_SOURCES', () => {
257
- it('两个固定约定目录', () => {
358
+ it('三个来源(zag / docs / docs-root,docs-root 跳过 knowledges 容器)', () => {
258
359
  expect(REPO_KNOWLEDGE_BASE_SOURCES).toEqual([
259
360
  { source: 'zag', subdir: '.zag/knowledges' },
260
361
  { source: 'docs', subdir: 'docs/knowledges' },
362
+ { source: 'docs-root', subdir: 'docs', excludeFolders: ['knowledges'] },
261
363
  ]);
262
364
  });
263
365
  });
@@ -4,8 +4,9 @@ import { join, resolve, sep } from 'node:path';
4
4
  /**
5
5
  * 项目仓库内建知识库扫描(契约 agent-session-websocket.md §3.29/§3.30)。
6
6
  *
7
- * 仓库为知识库唯一事实源:仅直读 `<workspacePath>/.zag/knowledges/` 与
8
- * `<workspacePath>/docs/knowledges/` 两个固定子目录。知识库发现不递归(仅直接子文件夹,
7
+ * 仓库为知识库唯一事实源:仅直读 `<workspacePath>/.zag/knowledges/`、
8
+ * `<workspacePath>/docs/knowledges/` 与 `<workspacePath>/docs/` 的一层文件夹(来源 `docs-root`,
9
+ * 跳过 `docs/knowledges` 容器)。知识库发现不递归(仅直接子文件夹,
9
10
  * 含常规文件 `knowledge-base.json` 即识别),库内文档递归收集 `.md` 常规文件并读取内容。
10
11
  * 仅读不写、不执行;不使用会话路径白名单。
11
12
  *
@@ -17,6 +18,8 @@ import { join, resolve, sep } from 'node:path';
17
18
  export const REPO_KNOWLEDGE_BASE_SOURCES = [
18
19
  { source: 'zag', subdir: '.zag/knowledges' },
19
20
  { source: 'docs', subdir: 'docs/knowledges' },
21
+ // 仓库 docs/ 的一层文件夹(跳过既有 docs/knowledges 容器目录)
22
+ { source: 'docs-root', subdir: 'docs', excludeFolders: ['knowledges'] },
20
23
  ] as const;
21
24
 
22
25
  export type RepoKnowledgeBaseSource = (typeof REPO_KNOWLEDGE_BASE_SOURCES)[number]['source'];
@@ -195,6 +198,7 @@ async function scanSource(
195
198
  workspacePath: string,
196
199
  source: RepoKnowledgeBaseSource,
197
200
  subdir: string,
201
+ excludeFolders: readonly string[] = [],
198
202
  ): Promise<KnowledgeBaseSourceResult | null> {
199
203
  const sourceDir = resolve(workspacePath, subdir);
200
204
 
@@ -221,6 +225,8 @@ async function scanSource(
221
225
 
222
226
  const folders: string[] = [];
223
227
  for (const entry of ordered) {
228
+ // 已知容器目录(docs-root 的 docs/knowledges):不参与知识库发现
229
+ if (excludeFolders.includes(entry.name)) continue;
224
230
  if (entry.isDirectory()) {
225
231
  folders.push(entry.name);
226
232
  continue;
@@ -258,7 +264,12 @@ export async function scanKnowledgeBases(
258
264
  ): Promise<KnowledgeBaseScanResult> {
259
265
  const sources: KnowledgeBaseSourceResult[] = [];
260
266
  for (const item of REPO_KNOWLEDGE_BASE_SOURCES) {
261
- const result = await scanSource(workspacePath, item.source, item.subdir);
267
+ const result = await scanSource(
268
+ workspacePath,
269
+ item.source,
270
+ item.subdir,
271
+ 'excludeFolders' in item ? item.excludeFolders : [],
272
+ );
262
273
  if (!result) {
263
274
  return { success: false, sources: [], truncated: false, error: 'permission denied' };
264
275
  }
@@ -683,6 +683,7 @@ describe('knowledge-bases:scan 事件注册(契约 §3.29/§3.30)', () => {
683
683
  truncated: false,
684
684
  },
685
685
  { source: 'docs', knowledgeBases: [], truncated: false },
686
+ { source: 'docs-root', knowledgeBases: [], truncated: false },
686
687
  ],
687
688
  truncated: false,
688
689
  });
@@ -31,6 +31,7 @@ import { logger as rootLogger, type ObservationLogger } from './observability/lo
31
31
  import { injectTraceparent, withSpan } from './observability/trace.js';
32
32
 
33
33
  // 版本号唯一事实源为 package.json(register 上报的完整版本;服务端按 MIN_WORKER_VERSION=2.2.0 门禁)。
34
+ // 2.23.0 起仓库知识库扫描新增第三来源 `docs-root`(docs 一层文件夹,跳过 knowledges 容器);
34
35
  // 2.8.0 起 `kimi_code` 使用前登录闸门(`kimi login` stdio 判定 + `harness:login:*` 事件族);
35
36
  // 2.6.0 起支持 `workload:run.githubAuth` 与云电脑 Github 凭据管理器(该能力自 2.10.0 起,当前 harness 基线 MIN_HARNESS_WORKER_VERSION=2.12.0);
36
37
  // 2.5.0 起支持云电脑双连接(`/worker` + controller-api)与 `harness prepare`。
@@ -1621,7 +1622,7 @@ export function connectToServer(
1621
1622
  socket.emit('workflow-templates:scan:result', { requestId: data.requestId, ...result });
1622
1623
  });
1623
1624
 
1624
- // 仓库内建知识库扫描(契约 §3.29/§3.30:两个约定子目录 + knowledge-base.json + 分级上限)
1625
+ // 仓库内建知识库扫描(契约 §3.29/§3.30:三个来源 + knowledge-base.json + 分级上限)
1625
1626
  socket.on('knowledge-bases:scan', async (data: { requestId: string; path: string }) => {
1626
1627
  log.info(
1627
1628
  { event: 'knowledge_bases_scan', requestId: data.requestId, path: data.path },
@@ -818,3 +818,51 @@ describe('WorkloadExecutor githubAuth prefetch (T-WE-G)', () => {
818
818
  expect(results[0].log).not.toContain(secret);
819
819
  });
820
820
  });
821
+
822
+ describe('WorkloadExecutor githubRepoFullName passthrough (T-WE-G5)', () => {
823
+ it('T-WE-G5: passes githubRepoFullName to the hook payload', async () => {
824
+ const executor = new WorkloadExecutor();
825
+ const { results, sink } = collect();
826
+ const seen: Array<string | undefined> = [];
827
+
828
+ await executor.runBatch(
829
+ {
830
+ phase: 'init',
831
+ githubAuth: true,
832
+ githubRepoFullName: 'owner/repo',
833
+ items: [{ logId: 'g1', workloadName: 'One', script: 'echo ok', timeoutMs: 5000 }],
834
+ },
835
+ sink,
836
+ {
837
+ beforeGithubAuth: async (payload) => {
838
+ seen.push(payload.githubRepoFullName);
839
+ },
840
+ },
841
+ );
842
+
843
+ expect(seen).toEqual(['owner/repo']);
844
+ expect(results.map((result) => result.status)).toEqual(['success']);
845
+ });
846
+
847
+ it('T-WE-G6: absent githubRepoFullName keeps the legacy payload', async () => {
848
+ const executor = new WorkloadExecutor();
849
+ const { sink } = collect();
850
+ const seen: Array<string | undefined> = [];
851
+
852
+ await executor.runBatch(
853
+ {
854
+ phase: 'init',
855
+ githubAuth: true,
856
+ items: [{ logId: 'g1', workloadName: 'One', script: 'echo ok', timeoutMs: 5000 }],
857
+ },
858
+ sink,
859
+ {
860
+ beforeGithubAuth: async (payload) => {
861
+ seen.push(payload.githubRepoFullName);
862
+ },
863
+ },
864
+ );
865
+
866
+ expect(seen).toEqual([undefined]);
867
+ });
868
+ });
@@ -49,6 +49,11 @@ export interface WorkloadRunPayload {
49
49
  * 缺省/false 行为与旧版完全一致。
50
50
  */
51
51
  githubAuth?: boolean;
52
+ /**
53
+ * 本批针对的仓库 `owner/repo`(仅 `githubAuth === true` 时有意义)。
54
+ * 提供时客户端按该项目预取凭据;缺省保持主项目语义。
55
+ */
56
+ githubRepoFullName?: string;
52
57
  }
53
58
 
54
59
  /** `runBatch` 的可选行为注入(默认空实现,保证旧调用方零变化)。 */