agent-gear 2.10.0 → 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 (34) 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/dist/socketio-client.auth-gate.test.js +3 -3
  25. package/dist/socketio-client.auth-gate.test.js.map +1 -1
  26. package/package.json +1 -1
  27. package/src/cloud-host/supervisor.test.ts +58 -0
  28. package/src/cloud-host/supervisor.ts +20 -0
  29. package/src/github/commit-identity-manager.test.ts +272 -0
  30. package/src/github/commit-identity-manager.ts +284 -0
  31. package/src/github/commit-identity.test.ts +258 -0
  32. package/src/github/commit-identity.ts +284 -0
  33. package/src/socketio-client.auth-gate.test.ts +3 -3
  34. package/tests/socketio-client.test.ts +3 -2
@@ -0,0 +1,258 @@
1
+ import { describe, it, expect, vi, afterEach } from 'vitest';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { existsSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import {
8
+ CommitIdentity,
9
+ type GitRunResult,
10
+ type GitRunner,
11
+ } from './commit-identity.js';
12
+
13
+ const execFileAsync = promisify(execFile);
14
+ const TMP_BASE = '/tmp/opencode';
15
+
16
+ const HUMAN = {
17
+ name: 'Alice',
18
+ email: '1001+alice@users.noreply.github.com',
19
+ };
20
+
21
+ const CO_AUTHOR = {
22
+ name: 'Alice',
23
+ email: '1001+alice@users.noreply.github.com',
24
+ coAuthorName: 'zag-bot[bot]',
25
+ coAuthorEmail: '123456+zag-bot[bot]@users.noreply.github.com',
26
+ };
27
+
28
+ const CO_AUTHOR_TRAILER = 'Co-authored-by: zag-bot[bot] <123456+zag-bot[bot]@users.noreply.github.com>';
29
+
30
+ interface FakeGitState {
31
+ include: string[];
32
+ hooksPath: string | null;
33
+ }
34
+
35
+ /**
36
+ * 内存 git 配置假实现:按真实 `git config` 的参数形态维护 include.path(多值)与 core.hooksPath。
37
+ */
38
+ function fakeGit(initial: Partial<FakeGitState> = {}) {
39
+ const state: FakeGitState = {
40
+ include: [...(initial.include ?? [])],
41
+ hooksPath: initial.hooksPath ?? null,
42
+ };
43
+ const calls: string[][] = [];
44
+
45
+ const runGit = vi.fn(async (args: string[]): Promise<GitRunResult> => {
46
+ calls.push(args);
47
+
48
+ const indexOf = (flag: string): number => args.indexOf(flag);
49
+
50
+ if (indexOf('--get-all') >= 0 && args[indexOf('--get-all') + 1] === 'include.path') {
51
+ return state.include.length > 0
52
+ ? { code: 0, stdout: `${state.include.join('\n')}\n`, stderr: '' }
53
+ : { code: 1, stdout: '', stderr: '' };
54
+ }
55
+
56
+ if (indexOf('--get') >= 0 && args[indexOf('--get') + 1] === 'core.hooksPath') {
57
+ return state.hooksPath
58
+ ? { code: 0, stdout: `${state.hooksPath}\n`, stderr: '' }
59
+ : { code: 1, stdout: '', stderr: '' };
60
+ }
61
+
62
+ if (indexOf('--add') >= 0) {
63
+ const index = indexOf('--add');
64
+ expect(args[index + 1]).toBe('include.path');
65
+ state.include.push(args[index + 2]!);
66
+ return { code: 0, stdout: '', stderr: '' };
67
+ }
68
+
69
+ if (indexOf('--unset-all') >= 0) {
70
+ const index = indexOf('--unset-all');
71
+ const key = args[index + 1];
72
+ const pattern = args[args.length - 1]!;
73
+ if (key === 'include.path') {
74
+ state.include = state.include.filter((value) => value !== pattern);
75
+ }
76
+ return { code: 0, stdout: '', stderr: '' };
77
+ }
78
+
79
+ if (indexOf('--unset') >= 0) {
80
+ const key = args[indexOf('--unset') + 1];
81
+ if (key === 'core.hooksPath') {
82
+ if (state.hooksPath === null) return { code: 5, stdout: '', stderr: '' };
83
+ state.hooksPath = null;
84
+ }
85
+ return { code: 0, stdout: '', stderr: '' };
86
+ }
87
+
88
+ if (args[args.length - 2] === 'core.hooksPath') {
89
+ state.hooksPath = args[args.length - 1]!;
90
+ return { code: 0, stdout: '', stderr: '' };
91
+ }
92
+
93
+ return { code: 0, stdout: '', stderr: '' };
94
+ });
95
+
96
+ return { state, calls, runGit: runGit as unknown as GitRunner & typeof runGit, rawRun: runGit };
97
+ }
98
+
99
+ const dirs: string[] = [];
100
+
101
+ async function tempHome(): Promise<string> {
102
+ await mkdir(TMP_BASE, { recursive: true });
103
+ const dir = await mkdtemp(join(TMP_BASE, 'commit-identity-'));
104
+ dirs.push(dir);
105
+ return dir;
106
+ }
107
+
108
+ afterEach(async () => {
109
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
110
+ });
111
+
112
+ describe('CommitIdentity', () => {
113
+ it('T-CI1: apply writes the managed gitconfig (0600) and sets include.path exactly once', async () => {
114
+ const home = await tempHome();
115
+ const git = fakeGit();
116
+ const applier = new CommitIdentity({ home, runGit: git.runGit });
117
+
118
+ await applier.apply('human_only', HUMAN);
119
+
120
+ const configPath = join(home, '.zag', 'commit-identity.gitconfig');
121
+ const content = await readFile(configPath, 'utf8');
122
+ expect(content).toBe(`[user]\n\tname = ${HUMAN.name}\n\temail = ${HUMAN.email}\n`);
123
+ const mode = (await stat(configPath)).mode & 0o777;
124
+ expect(mode).toBe(0o600);
125
+ expect(git.state.include).toEqual([configPath]);
126
+
127
+ // 重复 apply 幂等:不追加第二个 include.path,文件内容不变
128
+ await applier.apply('human_only', HUMAN);
129
+ expect(git.state.include).toEqual([configPath]);
130
+ expect(git.calls.filter((args) => args.includes('--add'))).toHaveLength(1);
131
+ expect(await readFile(configPath, 'utf8')).toBe(content);
132
+ });
133
+
134
+ it('T-CI2: remove only touches values that exactly match the managed paths (zero residue)', async () => {
135
+ const home = await tempHome();
136
+ const userInclude = '/opt/user/gitconfig.inc';
137
+ const userHooks = '/opt/user/git-hooks';
138
+ const git = fakeGit({ include: [userInclude], hooksPath: userHooks });
139
+ const applier = new CommitIdentity({ home, runGit: git.runGit });
140
+ const configPath = join(home, '.zag', 'commit-identity.gitconfig');
141
+
142
+ await applier.apply('human_only', HUMAN);
143
+ expect(git.state.include).toEqual([userInclude, configPath]);
144
+
145
+ await applier.remove();
146
+
147
+ // 仅托管值被移除,用户既有值原样保留
148
+ expect(git.state.include).toEqual([userInclude]);
149
+ expect(git.state.hooksPath).toBe(userHooks);
150
+ expect(git.calls.some((args) => args.includes('--unset'))).toBe(false);
151
+
152
+ const unsetAll = git.calls.find((args) => args.includes('--unset-all'));
153
+ expect(unsetAll).toBeDefined();
154
+ expect(unsetAll).toContain('--fixed-value');
155
+ expect(unsetAll).toContain(configPath);
156
+
157
+ // 零残留:托管文件已删除
158
+ expect(existsSync(configPath)).toBe(false);
159
+ expect(existsSync(join(home, '.zag', 'git-hooks', 'prepare-commit-msg'))).toBe(false);
160
+
161
+ // 用户把 hooksPath 改走后,remove 不得改动(exact-match)
162
+ const second = fakeGit();
163
+ const secondApplier = new CommitIdentity({ home, runGit: second.runGit });
164
+ await secondApplier.apply('co_author', CO_AUTHOR);
165
+ second.state.hooksPath = '/opt/user/other-hooks';
166
+ await secondApplier.remove();
167
+ expect(second.state.hooksPath).toBe('/opt/user/other-hooks');
168
+ expect(second.calls.some((args) => args.includes('--unset'))).toBe(false);
169
+ });
170
+
171
+ it('T-CI3: co_author hook appends exactly one trailer (idempotent for repeat commits and --amend)', async () => {
172
+ const home = await tempHome();
173
+ const git = fakeGit();
174
+ const applier = new CommitIdentity({ home, runGit: git.runGit });
175
+ const hookPath = join(home, '.zag', 'git-hooks', 'prepare-commit-msg');
176
+
177
+ await applier.apply('co_author', CO_AUTHOR);
178
+
179
+ const hook = await readFile(hookPath, 'utf8');
180
+ expect(hook.startsWith('#!/bin/sh')).toBe(true);
181
+ expect(hook).toContain('# zag-managed');
182
+ expect(hook).toContain(`TRAILER='${CO_AUTHOR_TRAILER}'`);
183
+ expect((await stat(hookPath)).mode & 0o777).toBe(0o755);
184
+ expect(git.state.hooksPath).toBe(join(home, '.zag', 'git-hooks'));
185
+
186
+ const messageDir = join(home, 'messages');
187
+ await mkdir(messageDir, { recursive: true });
188
+ const messagePath = join(messageDir, 'COMMIT_EDITMSG');
189
+ await writeFile(messagePath, 'feat: first commit\n', 'utf8');
190
+
191
+ await execFileAsync('sh', [hookPath, messagePath]);
192
+ await execFileAsync('sh', [hookPath, messagePath]);
193
+
194
+ let message = await readFile(messagePath, 'utf8');
195
+ expect(message.split(CO_AUTHOR_TRAILER)).toHaveLength(2);
196
+
197
+ // --amend:消息里已有同一 trailer 时不得叠加(exact-trailer)
198
+ const amendPath = join(messageDir, 'AMEND_EDITMSG');
199
+ await writeFile(amendPath, `feat: amended\n\n${CO_AUTHOR_TRAILER}\n`, 'utf8');
200
+ await execFileAsync('sh', [hookPath, amendPath]);
201
+ message = await readFile(amendPath, 'utf8');
202
+ expect(message.split(CO_AUTHOR_TRAILER)).toHaveLength(2);
203
+ });
204
+
205
+ it('T-CI4: switching co_author → human_only removes the hook but keeps user identity; unset removes everything', async () => {
206
+ const home = await tempHome();
207
+ const git = fakeGit();
208
+ const applier = new CommitIdentity({ home, runGit: git.runGit });
209
+ const configPath = join(home, '.zag', 'commit-identity.gitconfig');
210
+ const hookPath = join(home, '.zag', 'git-hooks', 'prepare-commit-msg');
211
+
212
+ await applier.apply('co_author', CO_AUTHOR);
213
+ expect(existsSync(hookPath)).toBe(true);
214
+
215
+ await applier.apply('human_only', { name: 'Bob', email: 'bob@example.com' });
216
+ expect(existsSync(hookPath)).toBe(false);
217
+ expect(git.state.hooksPath).toBeNull();
218
+ expect(git.state.include).toEqual([configPath]);
219
+ expect(await readFile(configPath, 'utf8')).toContain('name = Bob');
220
+
221
+ await applier.apply('unset', { name: 'ignored', email: 'ignored@example.com' });
222
+ expect(git.state.include).toEqual([]);
223
+ expect(git.state.hooksPath).toBeNull();
224
+ expect(existsSync(configPath)).toBe(false);
225
+ expect(existsSync(hookPath)).toBe(false);
226
+ });
227
+
228
+ it('T-CI5: git spawn failures surface readable errors without leaking identity values', async () => {
229
+ const home = await tempHome();
230
+ const failing = new CommitIdentity({
231
+ home,
232
+ runGit: vi.fn(async (args: string[]): Promise<GitRunResult> => {
233
+ if (args.includes('--get-all')) return { code: 1, stdout: '', stderr: '' };
234
+ return { code: 1, stdout: '', stderr: 'fatal: could not lock config file' };
235
+ }) as unknown as GitRunner,
236
+ });
237
+
238
+ await expect(failing.apply('human_only', HUMAN)).rejects.toThrow(/git config.*失败/);
239
+ await expect(failing.apply('human_only', HUMAN)).rejects.toThrow(/could not lock config file/);
240
+
241
+ const crashing = new CommitIdentity({
242
+ home,
243
+ runGit: vi.fn(async () => {
244
+ throw new Error('spawn git ENOENT');
245
+ }) as unknown as GitRunner,
246
+ });
247
+ let message = '';
248
+ try {
249
+ await crashing.apply('human_only', { name: 'Secret Person', email: 'secret@example.com' });
250
+ } catch (error) {
251
+ message = (error as Error).message;
252
+ }
253
+ expect(message).toContain('git');
254
+ expect(message).toContain('ENOENT');
255
+ expect(message).not.toContain('secret@example.com');
256
+ expect(message).not.toContain('Secret Person');
257
+ });
258
+ });
@@ -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
+ }
@@ -75,11 +75,11 @@ function emitted(event: string) {
75
75
  }
76
76
 
77
77
  describe('CONTROLLER_VERSION', () => {
78
- it('register 上报版本取自 package.json(2.10.0,无第二处常量)', () => {
78
+ it('register 上报版本取自 package.json(无第二处常量)', () => {
79
79
  setup();
80
80
  fake.handlers.get('connect')?.();
81
- expect(PACKAGE_VERSION).toBe('2.10.0');
82
- expect(emitted('register')[0]).toMatchObject({ version: '2.10.0' });
81
+ expect(PACKAGE_VERSION).toMatch(/^\d+\.\d+\.\d+/);
82
+ expect(emitted('register')[0]).toMatchObject({ version: PACKAGE_VERSION });
83
83
  });
84
84
  });
85
85
 
@@ -1,4 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { version as PACKAGE_VERSION } from '../package.json';
2
3
 
3
4
  const { mockStart, mockStop, MockHeartbeat } = vi.hoisted(() => {
4
5
  const start = vi.fn();
@@ -229,7 +230,7 @@ describe('SocketIO Client', () => {
229
230
  expect(mockSocket.emit).toHaveBeenCalledWith('register', {
230
231
  key: 'zag_k_1_abc123',
231
232
  hostname: 'my-machine',
232
- version: '2.10.0',
233
+ version: PACKAGE_VERSION,
233
234
  resumeToken: undefined,
234
235
  homeDir: '/home/user',
235
236
  platform: 'linux',
@@ -247,7 +248,7 @@ describe('SocketIO Client', () => {
247
248
  expect(mockSocket.emit).toHaveBeenCalledWith('register', {
248
249
  key: 'zag_k_1_abc123',
249
250
  hostname: 'test-machine',
250
- version: '2.10.0',
251
+ version: PACKAGE_VERSION,
251
252
  resumeToken: undefined,
252
253
  homeDir: '/home/user',
253
254
  platform: 'linux',