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.
- package/AGENTS.md +22 -1
- package/dist/cloud-host/supervisor.d.ts +9 -0
- package/dist/cloud-host/supervisor.d.ts.map +1 -1
- package/dist/cloud-host/supervisor.js +6 -0
- package/dist/cloud-host/supervisor.js.map +1 -1
- package/dist/cloud-host/supervisor.test.js +42 -0
- package/dist/cloud-host/supervisor.test.js.map +1 -1
- package/dist/github/commit-identity-manager.d.ts +75 -0
- package/dist/github/commit-identity-manager.d.ts.map +1 -0
- package/dist/github/commit-identity-manager.js +223 -0
- package/dist/github/commit-identity-manager.js.map +1 -0
- package/dist/github/commit-identity-manager.test.d.ts +2 -0
- package/dist/github/commit-identity-manager.test.d.ts.map +1 -0
- package/dist/github/commit-identity-manager.test.js +224 -0
- package/dist/github/commit-identity-manager.test.js.map +1 -0
- package/dist/github/commit-identity.d.ts +68 -0
- package/dist/github/commit-identity.d.ts.map +1 -0
- package/dist/github/commit-identity.js +242 -0
- package/dist/github/commit-identity.js.map +1 -0
- package/dist/github/commit-identity.test.d.ts +2 -0
- package/dist/github/commit-identity.test.d.ts.map +1 -0
- package/dist/github/commit-identity.test.js +210 -0
- package/dist/github/commit-identity.test.js.map +1 -0
- package/package.json +1 -1
- package/src/cloud-host/supervisor.test.ts +58 -0
- package/src/cloud-host/supervisor.ts +20 -0
- package/src/github/commit-identity-manager.test.ts +272 -0
- package/src/github/commit-identity-manager.ts +284 -0
- package/src/github/commit-identity.test.ts +258 -0
- package/src/github/commit-identity.ts +284 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { CommitIdentity, type CommitIdentityMode } from './commit-identity.js';
|
|
2
|
+
import { redactSecrets } from '../workload-executor.js';
|
|
3
|
+
|
|
4
|
+
/** 提交身份同步间隔(50 分钟)。 */
|
|
5
|
+
export const REFRESH_INTERVAL_MS = 50 * 60 * 1000;
|
|
6
|
+
|
|
7
|
+
/** 下发接口超时(10 秒)。 */
|
|
8
|
+
export const REQUEST_TIMEOUT_MS = 10_000;
|
|
9
|
+
|
|
10
|
+
/** 401/403 退避序列(1/2/4 分钟,最多 3 次重试)。 */
|
|
11
|
+
export const BACKOFF_MS = [60_000, 120_000, 240_000] as const;
|
|
12
|
+
|
|
13
|
+
/** 托管配置应用器(测试注入;生产为 `CommitIdentity`)。 */
|
|
14
|
+
export interface CommitIdentityApplier {
|
|
15
|
+
apply(
|
|
16
|
+
mode: Exclude<CommitIdentityMode, 'unset'>,
|
|
17
|
+
identity: {
|
|
18
|
+
name: string;
|
|
19
|
+
email: string;
|
|
20
|
+
coAuthorName?: string;
|
|
21
|
+
coAuthorEmail?: string;
|
|
22
|
+
},
|
|
23
|
+
): Promise<void>;
|
|
24
|
+
remove(): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 提交身份管理器依赖注入(测试锚定网络 / 时钟 / 副作用;生产使用缺省实现)。 */
|
|
28
|
+
export interface CommitIdentityManagerDeps {
|
|
29
|
+
env?: NodeJS.ProcessEnv;
|
|
30
|
+
fetch?: typeof fetch;
|
|
31
|
+
applier?: CommitIdentityApplier;
|
|
32
|
+
log?: (message: string) => void;
|
|
33
|
+
/** 定时器注入(测试用);缺省使用全局 `setTimeout`。 */
|
|
34
|
+
setTimeout?: typeof setTimeout;
|
|
35
|
+
/** 退避等待注入(测试用);缺省使用 `setTimeout`。 */
|
|
36
|
+
sleep?: (ms: number) => Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `refreshNow()` 的统一返回(不含任何身份值)。 */
|
|
40
|
+
export interface CommitIdentityRefreshResult {
|
|
41
|
+
ok: boolean;
|
|
42
|
+
/** 成功应用 / 移除的模式;失败或缺省时不返回。 */
|
|
43
|
+
mode?: CommitIdentityMode;
|
|
44
|
+
/** 可读错误文案;`disabled` 表示 env 缺失。 */
|
|
45
|
+
error?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const VALID_MODES: readonly CommitIdentityMode[] = [
|
|
49
|
+
'agent_only',
|
|
50
|
+
'co_author',
|
|
51
|
+
'human_only',
|
|
52
|
+
'unset',
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
type Timer = ReturnType<typeof setTimeout>;
|
|
56
|
+
|
|
57
|
+
function nonEmptyString(value: unknown): string | null {
|
|
58
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 容器内提交身份同步管理器(实现点 3,与 `GithubCredentialManager` 同构)。
|
|
63
|
+
*
|
|
64
|
+
* - `start()`:校验 env 后立即拉取一次,之后每 50 分钟拉取;定时器 `unref()`;
|
|
65
|
+
* - `refreshNow()`:POST 内部端点,并发调用合并为一次请求;401/403 按 1/2/4 分钟退避(≤3 次);
|
|
66
|
+
* - 成功响应按字段存在性消费:`mode=unset` → `remove()`,其余 → `apply()`;
|
|
67
|
+
* - 网络 / 解析 / 应用失败保留现状,返回可读错误,不崩溃、不回滚已应用配置;
|
|
68
|
+
* - 与凭据管理器相互独立(不依赖 gh 凭据 / Git 项目绑定);日志不含 host key 与身份值。
|
|
69
|
+
*/
|
|
70
|
+
export class CommitIdentityManager {
|
|
71
|
+
private readonly env: NodeJS.ProcessEnv;
|
|
72
|
+
private readonly fetchFn: typeof fetch;
|
|
73
|
+
private readonly applier: CommitIdentityApplier;
|
|
74
|
+
private readonly log: (message: string) => void;
|
|
75
|
+
private readonly setTimeoutFn: typeof setTimeout;
|
|
76
|
+
private readonly sleepFn: (ms: number) => Promise<void>;
|
|
77
|
+
|
|
78
|
+
private timer: Timer | null = null;
|
|
79
|
+
private started = false;
|
|
80
|
+
private stopped = false;
|
|
81
|
+
private activeRefresh: Promise<CommitIdentityRefreshResult> | null = null;
|
|
82
|
+
|
|
83
|
+
constructor(deps: CommitIdentityManagerDeps = {}) {
|
|
84
|
+
this.env = deps.env ?? process.env;
|
|
85
|
+
this.fetchFn = deps.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
|
|
86
|
+
this.applier = deps.applier ?? new CommitIdentity();
|
|
87
|
+
this.log = deps.log ?? ((message: string) => console.log(message));
|
|
88
|
+
this.setTimeoutFn = deps.setTimeout ?? setTimeout;
|
|
89
|
+
this.sleepFn =
|
|
90
|
+
deps.sleep ??
|
|
91
|
+
((ms: number) =>
|
|
92
|
+
new Promise<void>((resolve) => {
|
|
93
|
+
const timer = setTimeout(resolve, ms);
|
|
94
|
+
timer.unref?.();
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 当前是否具备拉取条件(三个 env 均非空)。 */
|
|
99
|
+
isEnabled(): boolean {
|
|
100
|
+
return this.missingEnv().length === 0;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 启动:立即拉取一次并安排下一次同步(env 缺失时只 warn,不抛错)。 */
|
|
104
|
+
start(): void {
|
|
105
|
+
if (this.started) return;
|
|
106
|
+
this.stopped = false;
|
|
107
|
+
const missing = this.missingEnv();
|
|
108
|
+
if (missing.length > 0) {
|
|
109
|
+
this.log(`[CommitIdentity] disabled: missing environment variable(s): ${missing.join(', ')}`);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
this.started = true;
|
|
113
|
+
void this.refreshNow()
|
|
114
|
+
.catch(() => undefined)
|
|
115
|
+
.finally(() => this.scheduleNext());
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 停止周期同步(进程退出 / 云主机 shutdown)。 */
|
|
119
|
+
stop(): void {
|
|
120
|
+
this.stopped = true;
|
|
121
|
+
this.started = false;
|
|
122
|
+
if (this.timer) {
|
|
123
|
+
clearTimeout(this.timer);
|
|
124
|
+
this.timer = null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 立即拉取并应用 / 移除托管配置;并发调用共享同一个 in-flight Promise。 */
|
|
129
|
+
refreshNow(): Promise<CommitIdentityRefreshResult> {
|
|
130
|
+
if (this.activeRefresh) return this.activeRefresh;
|
|
131
|
+
const refresh = this.doRefresh().finally(() => {
|
|
132
|
+
if (this.activeRefresh === refresh) this.activeRefresh = null;
|
|
133
|
+
});
|
|
134
|
+
this.activeRefresh = refresh;
|
|
135
|
+
return refresh;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private async doRefresh(): Promise<CommitIdentityRefreshResult> {
|
|
139
|
+
if (!this.isEnabled()) {
|
|
140
|
+
return { ok: false, error: 'disabled' };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const endpoint = this.env.ZAG_AGENT_API_ENDPOINT!.trim().replace(/\/+$/, '');
|
|
144
|
+
const controllerId = this.env.ZAG_CONTROLLER_ID!.trim();
|
|
145
|
+
const hostKey = this.env.ZAG_HOST_KEY!.trim();
|
|
146
|
+
const url = `${endpoint}/internal/cloud-hosts/${encodeURIComponent(controllerId)}/commit-identity`;
|
|
147
|
+
|
|
148
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
149
|
+
const result = await this.request(url, hostKey);
|
|
150
|
+
if (result.kind === 'retryable' && attempt < BACKOFF_MS.length) {
|
|
151
|
+
const delay = BACKOFF_MS[attempt]!;
|
|
152
|
+
this.log(
|
|
153
|
+
`[CommitIdentity] 提交身份下发未授权(HTTP ${result.status}),` +
|
|
154
|
+
`${Math.round(delay / 60_000)} 分钟后重试(${attempt + 1}/${BACKOFF_MS.length})`,
|
|
155
|
+
);
|
|
156
|
+
await this.sleepFn(delay);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (result.kind === 'retryable') {
|
|
160
|
+
return { ok: false, error: `提交身份下发未授权(HTTP ${result.status})` };
|
|
161
|
+
}
|
|
162
|
+
return result.value;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private async request(
|
|
167
|
+
url: string,
|
|
168
|
+
hostKey: string,
|
|
169
|
+
): Promise<
|
|
170
|
+
| { kind: 'retryable'; status: number }
|
|
171
|
+
| { kind: 'result'; value: CommitIdentityRefreshResult }
|
|
172
|
+
> {
|
|
173
|
+
const controller = new AbortController();
|
|
174
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
175
|
+
timer.unref?.();
|
|
176
|
+
try {
|
|
177
|
+
const response = await this.fetchFn(url, {
|
|
178
|
+
method: 'POST',
|
|
179
|
+
headers: { Authorization: `Bearer ${hostKey}` },
|
|
180
|
+
signal: controller.signal,
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
if (response.status === 401 || response.status === 403) {
|
|
184
|
+
return { kind: 'retryable', status: response.status };
|
|
185
|
+
}
|
|
186
|
+
if (!response.ok) {
|
|
187
|
+
return {
|
|
188
|
+
kind: 'result',
|
|
189
|
+
value: { ok: false, error: `提交身份下发失败(HTTP ${response.status})` },
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
let payload: unknown;
|
|
194
|
+
try {
|
|
195
|
+
payload = await response.json();
|
|
196
|
+
} catch {
|
|
197
|
+
return { kind: 'result', value: { ok: false, error: '提交身份响应不是合法 JSON' } };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return { kind: 'result', value: await this.consume(payload, hostKey) };
|
|
201
|
+
} catch (error) {
|
|
202
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
203
|
+
const message = /abort/i.test(reason)
|
|
204
|
+
? '提交身份下发超时(10s)'
|
|
205
|
+
: `提交身份下发失败:${redactSecrets(reason, [hostKey])}`;
|
|
206
|
+
return { kind: 'result', value: { ok: false, error: message } };
|
|
207
|
+
} finally {
|
|
208
|
+
clearTimeout(timer);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** 按字段存在性消费响应:unset → remove;其余 → apply。 */
|
|
213
|
+
private async consume(payload: unknown, hostKey: string): Promise<CommitIdentityRefreshResult> {
|
|
214
|
+
const body = (payload ?? {}) as Record<string, unknown>;
|
|
215
|
+
const mode = body.mode;
|
|
216
|
+
if (typeof mode !== 'string' || !VALID_MODES.includes(mode as CommitIdentityMode)) {
|
|
217
|
+
return { ok: false, error: `提交身份响应 mode 非法:${String(mode)}` };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (mode === 'unset') {
|
|
221
|
+
try {
|
|
222
|
+
await this.applier.remove();
|
|
223
|
+
} catch (error) {
|
|
224
|
+
return { ok: false, error: this.applyError('移除', error, hostKey) };
|
|
225
|
+
}
|
|
226
|
+
this.log('[CommitIdentity] 托管配置已移除(mode=unset)');
|
|
227
|
+
return { ok: true, mode: 'unset' };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const name = nonEmptyString(body.name);
|
|
231
|
+
const email = nonEmptyString(body.email);
|
|
232
|
+
if (!name || !email) {
|
|
233
|
+
return { ok: false, error: '提交身份响应缺少 name/email' };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (mode === 'co_author') {
|
|
237
|
+
const coAuthorName = nonEmptyString(body.coAuthorName);
|
|
238
|
+
const coAuthorEmail = nonEmptyString(body.coAuthorEmail);
|
|
239
|
+
if (!coAuthorName || !coAuthorEmail) {
|
|
240
|
+
return { ok: false, error: '提交身份响应缺少 coAuthorName/coAuthorEmail' };
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
await this.applier.apply(mode, { name, email, coAuthorName, coAuthorEmail });
|
|
244
|
+
} catch (error) {
|
|
245
|
+
return { ok: false, error: this.applyError('应用', error, hostKey) };
|
|
246
|
+
}
|
|
247
|
+
} else {
|
|
248
|
+
const narrowed = mode as 'agent_only' | 'human_only';
|
|
249
|
+
try {
|
|
250
|
+
await this.applier.apply(narrowed, { name, email });
|
|
251
|
+
} catch (error) {
|
|
252
|
+
return { ok: false, error: this.applyError('应用', error, hostKey) };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
this.log(`[CommitIdentity] 提交身份已更新(mode=${mode})`);
|
|
257
|
+
return { ok: true, mode: mode as CommitIdentityMode };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
private applyError(action: string, error: unknown, hostKey: string): string {
|
|
261
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
262
|
+
return `提交身份${action}失败:${redactSecrets(reason, [hostKey])}`;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** 下一次同步:固定 50 分钟;定时器 unref,不阻止进程退出。 */
|
|
266
|
+
private scheduleNext(): void {
|
|
267
|
+
if (this.stopped || !this.started || !this.isEnabled()) return;
|
|
268
|
+
this.timer = this.setTimeoutFn(() => {
|
|
269
|
+
this.timer = null;
|
|
270
|
+
void this.refreshNow()
|
|
271
|
+
.catch(() => undefined)
|
|
272
|
+
.finally(() => this.scheduleNext());
|
|
273
|
+
}, REFRESH_INTERVAL_MS);
|
|
274
|
+
this.timer.unref?.();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
private missingEnv(): string[] {
|
|
278
|
+
const keys = ['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID', 'ZAG_HOST_KEY'] as const;
|
|
279
|
+
return keys.filter((key) => {
|
|
280
|
+
const value = this.env[key];
|
|
281
|
+
return typeof value !== 'string' || value.trim().length === 0;
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
@@ -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
|
+
});
|