agent-gear 2.10.1 → 2.11.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 (30) hide show
  1. package/AGENTS.md +22 -1
  2. package/dist/cloud-host/supervisor.d.ts +9 -0
  3. package/dist/cloud-host/supervisor.d.ts.map +1 -1
  4. package/dist/cloud-host/supervisor.js +6 -0
  5. package/dist/cloud-host/supervisor.js.map +1 -1
  6. package/dist/cloud-host/supervisor.test.js +42 -0
  7. package/dist/cloud-host/supervisor.test.js.map +1 -1
  8. package/dist/github/commit-identity-manager.d.ts +75 -0
  9. package/dist/github/commit-identity-manager.d.ts.map +1 -0
  10. package/dist/github/commit-identity-manager.js +223 -0
  11. package/dist/github/commit-identity-manager.js.map +1 -0
  12. package/dist/github/commit-identity-manager.test.d.ts +2 -0
  13. package/dist/github/commit-identity-manager.test.d.ts.map +1 -0
  14. package/dist/github/commit-identity-manager.test.js +224 -0
  15. package/dist/github/commit-identity-manager.test.js.map +1 -0
  16. package/dist/github/commit-identity.d.ts +68 -0
  17. package/dist/github/commit-identity.d.ts.map +1 -0
  18. package/dist/github/commit-identity.js +242 -0
  19. package/dist/github/commit-identity.js.map +1 -0
  20. package/dist/github/commit-identity.test.d.ts +2 -0
  21. package/dist/github/commit-identity.test.d.ts.map +1 -0
  22. package/dist/github/commit-identity.test.js +210 -0
  23. package/dist/github/commit-identity.test.js.map +1 -0
  24. package/package.json +1 -1
  25. package/src/cloud-host/supervisor.test.ts +58 -0
  26. package/src/cloud-host/supervisor.ts +20 -0
  27. package/src/github/commit-identity-manager.test.ts +272 -0
  28. package/src/github/commit-identity-manager.ts +284 -0
  29. package/src/github/commit-identity.test.ts +258 -0
  30. package/src/github/commit-identity.ts +284 -0
@@ -0,0 +1,284 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { chmod, mkdir, readFile, rmdir, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ /** 提交身份模式(与 agent-api 内部端点响应一致)。 */
7
+ export type CommitIdentityMode = 'agent_only' | 'co_author' | 'human_only' | 'unset';
8
+
9
+ /** 托管提交身份(`co_author` 模式额外携带 bot 署名)。 */
10
+ export interface CommitIdentityInfo {
11
+ name: string;
12
+ email: string;
13
+ coAuthorName?: string;
14
+ coAuthorEmail?: string;
15
+ }
16
+
17
+ /** 单次 `git` 子进程执行结果(非零退出码不抛错,由调用方判断)。 */
18
+ export interface GitRunResult {
19
+ code: number;
20
+ stdout: string;
21
+ stderr: string;
22
+ }
23
+
24
+ /** `git` 命令执行器(测试注入;生产使用 `node:child_process.spawn`)。 */
25
+ export type GitRunner = (args: string[]) => Promise<GitRunResult>;
26
+
27
+ export interface CommitIdentityOptions {
28
+ /** 容器主目录(测试注入临时目录);缺省 `os.homedir()`。 */
29
+ home?: string;
30
+ /** 注入 git 执行器(测试用);缺省真实 spawn `git`。 */
31
+ runGit?: GitRunner;
32
+ }
33
+
34
+ /** 托管文件相对 `~/.zag` 的路径约定(唯一事实源)。 */
35
+ export const MANAGED_ZAG_DIR = '.zag';
36
+ export const MANAGED_GITCONFIG_NAME = 'commit-identity.gitconfig';
37
+ export const MANAGED_HOOKS_DIR_NAME = 'git-hooks';
38
+ export const MANAGED_HOOK_NAME = 'prepare-commit-msg';
39
+ /** 托管 hook 标记:仅带此标记的文件才会被移除(用户文件零触碰)。 */
40
+ export const MANAGED_HOOK_MARKER = '# zag-managed';
41
+
42
+ /** 缺省 git 执行器:`HOME` 指向注入的主目录,保证 `--global` 落点一致。 */
43
+ function createGitRunner(home: string): GitRunner {
44
+ return (args) =>
45
+ new Promise<GitRunResult>((resolve, reject) => {
46
+ const child = spawn('git', args, {
47
+ stdio: ['ignore', 'pipe', 'pipe'],
48
+ env: { ...process.env, HOME: home },
49
+ });
50
+ let stdout = '';
51
+ let stderr = '';
52
+ let settled = false;
53
+
54
+ const finish = (result: GitRunResult): void => {
55
+ if (settled) return;
56
+ settled = true;
57
+ resolve(result);
58
+ };
59
+
60
+ child.stdout?.on('data', (chunk: Buffer | string) => {
61
+ stdout += chunk.toString();
62
+ });
63
+ child.stderr?.on('data', (chunk: Buffer | string) => {
64
+ stderr += chunk.toString();
65
+ });
66
+ child.on('error', (error: Error) => {
67
+ if (settled) return;
68
+ settled = true;
69
+ reject(error);
70
+ });
71
+ child.on('close', (code: number | null) => {
72
+ finish({ code: code ?? -1, stdout, stderr });
73
+ });
74
+ });
75
+ }
76
+
77
+ function isControlFree(value: string): boolean {
78
+ return !/[\r\n\0]/.test(value);
79
+ }
80
+
81
+ function requireText(value: string | undefined, label: string): string {
82
+ if (typeof value !== 'string') throw new Error(`提交身份缺少 ${label}`);
83
+ const trimmed = value.trim();
84
+ if (trimmed.length === 0) throw new Error(`提交身份 ${label} 为空`);
85
+ if (!isControlFree(trimmed)) throw new Error(`提交身份 ${label} 含非法控制字符`);
86
+ return trimmed;
87
+ }
88
+
89
+ function normalizeIdentity(mode: CommitIdentityMode, identity: CommitIdentityInfo): CommitIdentityInfo {
90
+ const name = requireText(identity?.name, 'name');
91
+ const email = requireText(identity?.email, 'email');
92
+ if (mode !== 'co_author') return { name, email };
93
+ return {
94
+ name,
95
+ email,
96
+ coAuthorName: requireText(identity?.coAuthorName, 'coAuthorName'),
97
+ coAuthorEmail: requireText(identity?.coAuthorEmail, 'coAuthorEmail'),
98
+ };
99
+ }
100
+
101
+ /** git config 值转义:仅在含引号 / 反斜杠 / 行首注释符时使用双引号包裹。 */
102
+ function formatConfigValue(value: string): string {
103
+ if (/["\\\t]/.test(value) || /^[#;]/.test(value)) {
104
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\t/g, '\\t')}"`;
105
+ }
106
+ return value;
107
+ }
108
+
109
+ /** shell 单引号转义(hook 中的 trailer 字面量)。 */
110
+ function shellSingleQuote(value: string): string {
111
+ return `'${value.replace(/'/g, `'\\''`)}'`;
112
+ }
113
+
114
+ /**
115
+ * 容器内托管提交身份(实现点 1/2)。
116
+ *
117
+ * - `apply()`:写 `~/.zag/commit-identity.gitconfig`(0600,`[user] name/email`)并幂等保证
118
+ * `include.path` 只设置一次;`co_author` 额外写 `~/.zag/git-hooks/prepare-commit-msg`(0755,
119
+ * `# zag-managed` 标记,trailer 固化为字面量)并设置 `core.hooksPath`;其他模式移除托管 hook。
120
+ * - `remove()`:仅当全局配置值**恰为**托管路径时才 `--unset`(include.path 支持多值,逐值 exact-match),
121
+ * 再删除托管文件;用户其他 git 配置零触碰。
122
+ * - 所有错误可读;错误信息不包含身份值以外的任何配置内容(本模块无 secret)。
123
+ */
124
+ export class CommitIdentity {
125
+ readonly home: string;
126
+ readonly zagDir: string;
127
+ readonly gitConfigPath: string;
128
+ readonly hooksDir: string;
129
+ readonly hookPath: string;
130
+
131
+ private readonly runGit: GitRunner;
132
+
133
+ constructor(options: CommitIdentityOptions = {}) {
134
+ this.home = options.home ?? homedir();
135
+ this.zagDir = join(this.home, MANAGED_ZAG_DIR);
136
+ this.gitConfigPath = join(this.zagDir, MANAGED_GITCONFIG_NAME);
137
+ this.hooksDir = join(this.zagDir, MANAGED_HOOKS_DIR_NAME);
138
+ this.hookPath = join(this.hooksDir, MANAGED_HOOK_NAME);
139
+ this.runGit = options.runGit ?? createGitRunner(this.home);
140
+ }
141
+
142
+ /** 应用(或按 `unset` 移除)托管提交身份;重复调用幂等。 */
143
+ async apply(mode: CommitIdentityMode, identity: CommitIdentityInfo): Promise<void> {
144
+ if (mode === 'unset') {
145
+ await this.remove();
146
+ return;
147
+ }
148
+ if (mode !== 'agent_only' && mode !== 'co_author' && mode !== 'human_only') {
149
+ throw new Error(`未知的提交身份模式:${String(mode)}`);
150
+ }
151
+
152
+ const normalized = normalizeIdentity(mode, identity);
153
+ await mkdir(this.zagDir, { recursive: true, mode: 0o700 });
154
+ await writeFile(this.gitConfigPath, this.renderGitConfig(normalized), { mode: 0o600 });
155
+ await chmod(this.gitConfigPath, 0o600);
156
+ await this.ensureIncludePath();
157
+
158
+ if (mode === 'co_author') {
159
+ await this.writeHook(normalized);
160
+ await this.ensureHooksPath();
161
+ } else {
162
+ await this.removeManagedHook();
163
+ await this.removeHooksPath();
164
+ }
165
+ }
166
+
167
+ /** 移除全部托管配置 / 文件(「未设置 = 上线前行为」)。 */
168
+ async remove(): Promise<void> {
169
+ await this.removeIncludePath();
170
+ await this.removeHooksPath();
171
+ await rm(this.gitConfigPath, { force: true });
172
+ await this.removeManagedHook();
173
+ }
174
+
175
+ private renderGitConfig(identity: CommitIdentityInfo): string {
176
+ return `[user]\n\tname = ${formatConfigValue(identity.name)}\n\temail = ${formatConfigValue(identity.email)}\n`;
177
+ }
178
+
179
+ private async gitConfig(args: string[], tolerateCodes: number[] = []): Promise<GitRunResult> {
180
+ let result: GitRunResult;
181
+ try {
182
+ result = await this.runGit(['config', '--global', ...args]);
183
+ } catch (error) {
184
+ const reason = error instanceof Error ? error.message : String(error);
185
+ throw new Error(`执行 git config ${args.join(' ')} 失败:${reason}`);
186
+ }
187
+ if (result.code !== 0 && !tolerateCodes.includes(result.code)) {
188
+ const detail = result.stderr.trim();
189
+ throw new Error(
190
+ `git config ${args.join(' ')} 失败(退出码 ${result.code})${detail ? `:${detail}` : ''}`,
191
+ );
192
+ }
193
+ return result;
194
+ }
195
+
196
+ /** 全局 include.path 多值读取(key 不存在时 git 退出码为 1)。 */
197
+ private async getIncludePaths(): Promise<string[]> {
198
+ const result = await this.gitConfig(['--get-all', 'include.path'], [1]);
199
+ if (result.code !== 0) return [];
200
+ return result.stdout
201
+ .split('\n')
202
+ .map((value) => value.trim())
203
+ .filter((value) => value.length > 0);
204
+ }
205
+
206
+ /** 全局 core.hooksPath 读取(key 不存在时 git 退出码为 1)。 */
207
+ private async getHooksPath(): Promise<string | null> {
208
+ const result = await this.gitConfig(['--get', 'core.hooksPath'], [1]);
209
+ if (result.code !== 0) return null;
210
+ const value = result.stdout.trim();
211
+ return value.length > 0 ? value : null;
212
+ }
213
+
214
+ private async ensureIncludePath(): Promise<void> {
215
+ const values = await this.getIncludePaths();
216
+ // 已存在(含多值中的任意一项)即视为已设置:重复 apply 不追加。
217
+ if (values.includes(this.gitConfigPath)) return;
218
+ await this.gitConfig(['--add', 'include.path', this.gitConfigPath]);
219
+ }
220
+
221
+ private async removeIncludePath(): Promise<void> {
222
+ const values = await this.getIncludePaths();
223
+ // exact-match:仅当存在与托管路径完全相等的值时移除该项(其余值原样保留)。
224
+ if (!values.includes(this.gitConfigPath)) return;
225
+ // `--fixed-value` 保证路径按字面量匹配(避免 `.` 等被当作正则);退出码 5 = 并发下已无匹配。
226
+ await this.gitConfig(
227
+ ['--fixed-value', '--unset-all', 'include.path', this.gitConfigPath],
228
+ [5],
229
+ );
230
+ }
231
+
232
+ private async ensureHooksPath(): Promise<void> {
233
+ const current = await this.getHooksPath();
234
+ if (current === this.hooksDir) return;
235
+ await this.gitConfig(['core.hooksPath', this.hooksDir]);
236
+ }
237
+
238
+ private async removeHooksPath(): Promise<void> {
239
+ const current = await this.getHooksPath();
240
+ // exact-match:用户已把 core.hooksPath 改走时零触碰。
241
+ if (current !== this.hooksDir) return;
242
+ await this.gitConfig(['--unset', 'core.hooksPath'], [5]);
243
+ }
244
+
245
+ private renderHook(identity: CommitIdentityInfo): string {
246
+ const trailer = `Co-authored-by: ${identity.coAuthorName} <${identity.coAuthorEmail}>`;
247
+ return [
248
+ '#!/bin/sh',
249
+ `${MANAGED_HOOK_MARKER}: append Co-authored-by trailer (idempotent)`,
250
+ 'MSG="$1"',
251
+ '[ -n "$MSG" ] || exit 0',
252
+ `TRAILER=${shellSingleQuote(trailer)}`,
253
+ 'grep -qF "$TRAILER" "$MSG" 2>/dev/null && exit 0',
254
+ 'git interpret-trailers --in-place --trailer "$TRAILER" "$MSG" 2>/dev/null \\',
255
+ " || printf '\\n%s\\n' \"$TRAILER\" >> \"$MSG\"",
256
+ 'exit 0',
257
+ '',
258
+ ].join('\n');
259
+ }
260
+
261
+ private async writeHook(identity: CommitIdentityInfo): Promise<void> {
262
+ await mkdir(this.hooksDir, { recursive: true, mode: 0o700 });
263
+ await writeFile(this.hookPath, this.renderHook(identity), { mode: 0o755 });
264
+ await chmod(this.hookPath, 0o755);
265
+ }
266
+
267
+ /** 仅删除带 `# zag-managed` 标记的 hook 文件;空目录一并清理(非空则保留)。 */
268
+ private async removeManagedHook(): Promise<void> {
269
+ let content: string;
270
+ try {
271
+ content = await readFile(this.hookPath, 'utf8');
272
+ } catch (error) {
273
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
274
+ throw error;
275
+ }
276
+ if (!content.includes(MANAGED_HOOK_MARKER)) return;
277
+ await rm(this.hookPath, { force: true });
278
+ try {
279
+ await rmdir(this.hooksDir);
280
+ } catch {
281
+ // 目录不存在或非空(用户文件):保留。
282
+ }
283
+ }
284
+ }