@teamclaws/teamclaw 2026.4.4 → 2026.5.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.
@@ -0,0 +1,254 @@
1
+ import type { GithubAuthManager } from "../controller/github-auth.js";
2
+
3
+ /**
4
+ * Minimal GitHub REST client for TeamAuto: ETag-conditional GETs, light
5
+ * pagination, and the write endpoints we need. All requests ride the stored
6
+ * device-flow token via the auth manager (transparent refresh).
7
+ */
8
+
9
+ const API = "https://api.github.com";
10
+ const VERSION = "2026-03-10";
11
+ const USER_AGENT = "teamclaw-teamauto";
12
+
13
+ export class GithubClientError extends Error {
14
+ readonly status: number;
15
+ constructor(message: string, status: number) {
16
+ super(message);
17
+ this.name = "GithubClientError";
18
+ this.status = status;
19
+ }
20
+ }
21
+
22
+ export type EtagCache = Record<string, string>;
23
+
24
+ export type SweepableIssue = {
25
+ number: number;
26
+ title: string;
27
+ body: string;
28
+ state: "open" | "closed";
29
+ assignees: string[];
30
+ labels: string[];
31
+ updatedAt: string;
32
+ user: string;
33
+ htmlUrl: string;
34
+ };
35
+
36
+ export type SweepablePull = {
37
+ number: number;
38
+ title: string;
39
+ body: string;
40
+ state: "open" | "closed";
41
+ draft: boolean;
42
+ updated_at: string;
43
+ user: string;
44
+ head: string;
45
+ htmlUrl: string;
46
+ };
47
+
48
+ export type GithubRepoInfo = {
49
+ fullName: string;
50
+ defaultBranch: string;
51
+ cloneUrl: string;
52
+ permissions: { push: boolean; pull: boolean };
53
+ };
54
+
55
+ export function createGithubClient(auth: GithubAuthManager) {
56
+ async function request(
57
+ method: string,
58
+ urlPath: string,
59
+ options: { body?: unknown; etagKey?: string; etags?: EtagCache } = {},
60
+ ): Promise<{ status: number; data: unknown; notModified: boolean }> {
61
+ const headers: Record<string, string> = {
62
+ ...(await auth.getAuthHeaders()),
63
+ "User-Agent": USER_AGENT,
64
+ "X-GitHub-Api-Version": VERSION,
65
+ };
66
+ if (options.body !== undefined) {
67
+ headers["Content-Type"] = "application/json";
68
+ }
69
+ const etagKey = options.etagKey ? `${method} ${urlPath}` : undefined;
70
+ if (etagKey && options.etags?.[etagKey]) {
71
+ headers["If-None-Match"] = options.etags[etagKey];
72
+ }
73
+ const response = await fetch(`${API}${urlPath}`, {
74
+ method,
75
+ headers,
76
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
77
+ signal: AbortSignal.timeout(20_000),
78
+ });
79
+ if (etagKey) {
80
+ const etag = response.headers.get("etag");
81
+ if (etag && options.etags) {
82
+ options.etags[etagKey] = etag;
83
+ }
84
+ }
85
+ if (response.status === 304) {
86
+ return { status: 304, data: null, notModified: true };
87
+ }
88
+ const text = await response.text();
89
+ let data: unknown = null;
90
+ if (text) {
91
+ try {
92
+ data = JSON.parse(text);
93
+ } catch {
94
+ data = { raw: text.slice(0, 500) };
95
+ }
96
+ }
97
+ if (!response.ok) {
98
+ const message = (data as { message?: string } | null)?.message ?? `HTTP ${response.status}`;
99
+ throw new GithubClientError(message, response.status);
100
+ }
101
+ return { status: response.status, data, notModified: false };
102
+ }
103
+
104
+ async function getJson<T>(urlPath: string, etags?: EtagCache): Promise<T | null> {
105
+ const { data, notModified } = await request("GET", urlPath, { etagKey: etags ? urlPath : undefined, etags });
106
+ return notModified ? null : data as T;
107
+ }
108
+
109
+ return {
110
+ request,
111
+
112
+ async getRepoInfo(owner: string, repo: string): Promise<GithubRepoInfo> {
113
+ const data = await getJson<Record<string, unknown>>(`/repos/${owner}/${repo}`);
114
+ if (!data) {
115
+ throw new GithubClientError("unexpected 304 without etag", 500);
116
+ }
117
+ const perms = (data.permissions ?? {}) as Record<string, boolean>;
118
+ return {
119
+ fullName: String(data.full_name ?? `${owner}/${repo}`),
120
+ defaultBranch: String(data.default_branch ?? "main"),
121
+ cloneUrl: String(data.clone_url ?? `https://github.com/${owner}/${repo}.git`),
122
+ permissions: { push: Boolean(perms.push), pull: Boolean(perms.pull ?? true) },
123
+ };
124
+ },
125
+
126
+ /** Issues updated since the cursor; pass 0 for a first (bounded) backfill. */
127
+ async listIssues(owner: string, repo: string, sinceMs: number, etags?: EtagCache): Promise<SweepableIssue[]> {
128
+ const since = sinceMs > 0 ? new Date(sinceMs).toISOString() : new Date(Date.now() - 7 * 24 * 3600_000).toISOString();
129
+ const data = await getJson<unknown[]>(
130
+ `/repos/${owner}/${repo}/issues?state=open&sort=updated&direction=desc&per_page=50&since=${encodeURIComponent(since)}`,
131
+ etags,
132
+ );
133
+ if (!data) {
134
+ return [];
135
+ }
136
+ return data
137
+ .filter((raw) => {
138
+ const item = raw as Record<string, unknown>;
139
+ // The issues API also returns PRs; drop them (pull_request field).
140
+ return !item.pull_request;
141
+ })
142
+ .map((raw) => {
143
+ const item = raw as Record<string, unknown>;
144
+ return {
145
+ number: Number(item.number ?? 0),
146
+ title: String(item.title ?? ""),
147
+ body: String(item.body ?? ""),
148
+ state: item.state === "closed" ? "closed" : "open",
149
+ assignees: Array.isArray(item.assignees) ? item.assignees.map((a) => String((a as { login?: string }).login ?? "")) : [],
150
+ labels: Array.isArray(item.labels) ? item.labels.map((l) => String((l as { name?: string }).name ?? "")) : [],
151
+ updatedAt: String(item.updated_at ?? ""),
152
+ user: String((item.user as { login?: string } | undefined)?.login ?? ""),
153
+ htmlUrl: String(item.html_url ?? ""),
154
+ } satisfies SweepableIssue;
155
+ });
156
+ },
157
+
158
+ async listPulls(owner: string, repo: string, etags?: EtagCache): Promise<SweepablePull[]> {
159
+ const data = await getJson<unknown[]>(
160
+ `/repos/${owner}/${repo}/pulls?state=open&sort=updated&direction=desc&per_page=30`,
161
+ etags,
162
+ );
163
+ if (!data) {
164
+ return [];
165
+ }
166
+ return data.map((raw) => {
167
+ const item = raw as Record<string, unknown>;
168
+ return {
169
+ number: Number(item.number ?? 0),
170
+ title: String(item.title ?? ""),
171
+ body: String(item.body ?? ""),
172
+ state: item.state === "closed" ? "closed" : "open",
173
+ draft: Boolean(item.draft),
174
+ updated_at: String(item.updated_at ?? ""),
175
+ user: String((item.user as { login?: string } | undefined)?.login ?? ""),
176
+ head: String((item.head as { ref?: string } | undefined)?.ref ?? ""),
177
+ htmlUrl: String(item.html_url ?? ""),
178
+ } satisfies SweepablePull;
179
+ });
180
+ },
181
+
182
+ async listCommits(owner: string, repo: string, sinceSha: string): Promise<{ sha: string; message: string }[]> {
183
+ const suffix = sinceSha ? `?sha=${encodeURIComponent(sinceSha)}` : "?per_page=20";
184
+ void suffix;
185
+ // Compare-style walk is heavy; use the commits feed and filter client-side.
186
+ const data = await getJson<unknown[]>(`/repos/${owner}/${repo}/commits?per_page=30`);
187
+ if (!data) {
188
+ return [];
189
+ }
190
+ const commits = data.map((raw) => {
191
+ const item = raw as Record<string, unknown>;
192
+ return {
193
+ sha: String(item.sha ?? ""),
194
+ message: String((item.commit as { message?: string } | undefined)?.message ?? "").split("\n")[0],
195
+ };
196
+ });
197
+ if (!sinceSha) {
198
+ return commits.slice(0, 10);
199
+ }
200
+ const index = commits.findIndex((c) => c.sha.startsWith(sinceSha.slice(0, 10)));
201
+ return index === -1 ? commits.slice(0, 5) : commits.slice(0, index);
202
+ },
203
+
204
+ // ---- write side (require Contents/Issues/PR write on the App) ----
205
+
206
+ async postIssueComment(owner: string, repo: string, issueNumber: number, body: string): Promise<number> {
207
+ const { data } = await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body: { body } });
208
+ return Number((data as { id?: number }).id ?? 0);
209
+ },
210
+
211
+ async postPullReviewComment(owner: string, repo: string, pullNumber: number, body: string): Promise<void> {
212
+ await request("POST", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews`, { body: { event: "COMMENT", body } });
213
+ },
214
+
215
+ async createIssue(owner: string, repo: string, title: string, body: string, labels?: string[]): Promise<number> {
216
+ const { data } = await request("POST", `/repos/${owner}/${repo}/issues`, {
217
+ body: { title, body, ...(labels?.length ? { labels } : {}) },
218
+ });
219
+ return Number((data as { number?: number }).number ?? 0);
220
+ },
221
+
222
+ async assignIssue(owner: string, repo: string, issueNumber: number, assignee: string): Promise<void> {
223
+ await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees: [assignee] } });
224
+ },
225
+
226
+ /** Open a PR from a task worktree branch (collaboration contract delivery). */
227
+ async createPullRequest(owner: string, repo: string, head: string, base: string, title: string, body: string): Promise<{ number: number; url: string }> {
228
+ const { data } = await request("POST", `/repos/${owner}/${repo}/pulls`, {
229
+ body: { title, head, base, body },
230
+ });
231
+ const item = data as { number?: number; html_url?: string };
232
+ return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };
233
+ },
234
+
235
+ /** Repos the logged-in user can select in the TeamAuto bind picker. */
236
+ async listUserRepos(): Promise<{ id: string; fullName: string; private: boolean; pushedAt: string | null }[]> {
237
+ const data = await getJson<unknown[]>("/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&per_page=100");
238
+ if (!data) {
239
+ return [];
240
+ }
241
+ return data.map((raw) => {
242
+ const item = raw as Record<string, unknown>;
243
+ return {
244
+ id: String(item.full_name ?? ""),
245
+ fullName: String(item.full_name ?? ""),
246
+ private: Boolean(item.private),
247
+ pushedAt: typeof item.pushed_at === "string" ? item.pushed_at : null,
248
+ };
249
+ }).filter((r) => r.id);
250
+ },
251
+ };
252
+ }
253
+
254
+ export type TeamAutoGithubClient = ReturnType<typeof createGithubClient>;
@@ -0,0 +1,103 @@
1
+ import type { TeamAutoRepo, TeamAutoRepoNorms } from "./store.js";
2
+ import type { TeamAutoGithubClient } from "./github-client.js";
3
+ import type { TeamAutoRepoSync } from "./repo-sync.js";
4
+
5
+ /**
6
+ * Norms learning: absorb the target repo's collaboration conventions
7
+ * (CONTRIBUTING, issue/PR templates, commit style) so every TeamClaw worker
8
+ * prompt for that repo carries them - "转手目标仓库里面的协作规范".
9
+ */
10
+
11
+ const CONVENTIONAL_RE = /^(\w+)(\([^)]+\))?!?:\s.+/;
12
+
13
+ function detectCommitStyle(messages: string[]): string {
14
+ if (!messages.length) {
15
+ return "unspecified - keep subject lines short and descriptive";
16
+ }
17
+ const matches = messages.filter((m) => CONVENTIONAL_RE.test(m)).length;
18
+ if (matches >= messages.length * 0.6) {
19
+ return "conventional commits (type(scope)!: subject)";
20
+ }
21
+ const chinese = messages.filter((m) => /[\u4e00-\u9fff]/.test(m)).length;
22
+ if (chinese >= messages.length * 0.6) {
23
+ return "plain subject lines, Chinese";
24
+ }
25
+ return "plain subject lines, English";
26
+ }
27
+
28
+ export async function learnNorms(
29
+ repo: TeamAutoRepo,
30
+ client: TeamAutoGithubClient,
31
+ sync: TeamAutoRepoSync,
32
+ cloneUrl: string,
33
+ defaultBranch: string,
34
+ ): Promise<TeamAutoRepoNorms> {
35
+ let dir: string | null = null;
36
+ try {
37
+ dir = await sync.ensureCloned(repo.id, cloneUrl, defaultBranch);
38
+ } catch {
39
+ dir = null;
40
+ }
41
+
42
+ const [owner, name] = repo.id.split("/");
43
+ const fetchRemote = async (apiPath: string): Promise<string | null> => {
44
+ try {
45
+ const { data } = await client.request("GET", apiPath);
46
+ const record = data as { content?: string; encoding?: string };
47
+ if (typeof record.content === "string" && record.encoding === "base64") {
48
+ return Buffer.from(record.content, "base64").toString("utf8");
49
+ }
50
+ } catch {
51
+ // absent file is fine
52
+ }
53
+ return null;
54
+ };
55
+
56
+ const contributing =
57
+ (await fetchRemote(`/repos/${owner}/${name}/contents/CONTRIBUTING.md`)) ??
58
+ (dir ? await sync.readFileIfPresent(dir, "CONTRIBUTING.md") : null);
59
+ const issueTemplate =
60
+ (await fetchRemote(`/repos/${owner}/${name}/contents/.github/ISSUE_TEMPLATE.md`)) ??
61
+ (dir ? await sync.readFileIfPresent(dir, ".github/ISSUE_TEMPLATE.md") : null);
62
+ const prTemplate =
63
+ (await fetchRemote(`/repos/${owner}/${name}/contents/.github/PULL_REQUEST_TEMPLATE.md`)) ??
64
+ (dir ? await sync.readFileIfPresent(dir, ".github/PULL_REQUEST_TEMPLATE.md") : null);
65
+
66
+ let commitStyle = "unspecified";
67
+ if (dir) {
68
+ try {
69
+ commitStyle = detectCommitStyle(await sync.recentCommitMessages(dir, 100));
70
+ } catch {
71
+ commitStyle = "unspecified";
72
+ }
73
+ }
74
+
75
+ return {
76
+ commitStyle,
77
+ issueTemplate: issueTemplate?.slice(0, 2000) ?? null,
78
+ prTemplate: prTemplate?.slice(0, 2000) ?? null,
79
+ contributing: contributing?.slice(0, 4000) ?? null,
80
+ learnedAt: Date.now(),
81
+ };
82
+ }
83
+
84
+ /** Render the learned norms into a compact prompt block for workers. */
85
+ export function renderNormsBlock(norms: TeamAutoRepoNorms | null, repoId: string): string {
86
+ if (!norms) {
87
+ return `Target repo: ${repoId}\nCollaboration norms: not learned yet - follow common sense and read existing issues/PRs for style.\n`;
88
+ }
89
+ const lines = [
90
+ `Target repo: ${repoId}`,
91
+ `Commit style: ${norms.commitStyle}`,
92
+ ];
93
+ if (norms.contributing) {
94
+ lines.push(`CONTRIBUTING.md excerpt:\n${norms.contributing.slice(0, 1500)}`);
95
+ }
96
+ if (norms.issueTemplate) {
97
+ lines.push(`Issue template excerpt:\n${norms.issueTemplate.slice(0, 800)}`);
98
+ }
99
+ if (norms.prTemplate) {
100
+ lines.push(`PR template excerpt:\n${norms.prTemplate.slice(0, 800)}`);
101
+ }
102
+ return lines.join("\n") + "\n";
103
+ }
@@ -0,0 +1,218 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ import type { GithubAuthManager } from "../controller/github-auth.js";
7
+ import { repoSlugToDirName, resolveTeamAutoPaths } from "./store.js";
8
+
9
+ const exec = promisify(execFile);
10
+
11
+ export const TEAMCLAW_BRANCH_PREFIX = "teamclaw/";
12
+
13
+ /** TaskInfo.projectDir slug for a bound repo (relative to the projects dir). */
14
+ export function teamAutoProjectDir(repoId: string): string {
15
+ return `teamauto/${repoSlugToDirName(repoId)}`;
16
+ }
17
+
18
+ /**
19
+ * Git operations for TeamAuto. Authentication uses the device-flow token
20
+ * inline in the remote URL (x-access-token basic auth) - proven to survive
21
+ * GitHub's smart-HTTP redirects where extraheader injection does not. The
22
+ * token never touches disk: remotes are rewritten per invocation and the
23
+ * on-disk remote stays a clean https URL.
24
+ */
25
+
26
+ function gitEnv(): Record<string, string> {
27
+ return {
28
+ ...process.env,
29
+ GIT_TERMINAL_PROMPT: "0",
30
+ GIT_ASKPASS: "/bin/true",
31
+ GIT_CONFIG_NOSYSTEM: "1",
32
+ };
33
+ }
34
+
35
+ async function run(args: string[], cwd?: string): Promise<string> {
36
+ const { stdout } = await exec("git", args, {
37
+ cwd,
38
+ env: gitEnv(),
39
+ maxBuffer: 16 * 1024 * 1024,
40
+ timeout: 120_000,
41
+ });
42
+ return stdout;
43
+ }
44
+
45
+ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: string) => void }) {
46
+ async function tokenizedUrl(cloneUrl: string): Promise<string> {
47
+ const token = await auth.getAccessToken();
48
+ const clean = cloneUrl.replace(/^https:\/\//, "").replace(/\.git$/, "");
49
+ return `https://x-access-token:${token}@${clean}.git`;
50
+ }
51
+
52
+ async function repoDir(repoId: string): Promise<string> {
53
+ const { reposRoot, legacyReposRoot } = resolveTeamAutoPaths();
54
+ await fs.mkdir(reposRoot, { recursive: true });
55
+ const dir = path.join(reposRoot, repoSlugToDirName(repoId));
56
+ const legacy = path.join(legacyReposRoot, repoSlugToDirName(repoId));
57
+ // One-time migration: move pre-workspace clones into the projects tree.
58
+ try {
59
+ await fs.stat(path.join(legacy, ".git"));
60
+ try {
61
+ await fs.stat(path.join(dir, ".git"));
62
+ } catch {
63
+ await fs.mkdir(path.dirname(dir), { recursive: true });
64
+ try {
65
+ await fs.rename(legacy, dir);
66
+ } catch {
67
+ // Cross-device (EXDEV): copy then remove the original.
68
+ await fs.cp(legacy, dir, { recursive: true });
69
+ await fs.rm(legacy, { recursive: true, force: true });
70
+ }
71
+ }
72
+ } catch {
73
+ // No legacy clone - normal path.
74
+ }
75
+ return dir;
76
+ }
77
+
78
+ /** Clone if absent, otherwise fetch + reset to the default branch tip. */
79
+ async function ensureCloned(repoId: string, cloneUrl: string, defaultBranch: string): Promise<string> {
80
+ const dir = await repoDir(repoId);
81
+ const gitDir = path.join(dir, ".git");
82
+ let exists = false;
83
+ try {
84
+ const stat = await fs.stat(gitDir);
85
+ exists = stat.isDirectory() || stat.isFile();
86
+ } catch {
87
+ exists = false;
88
+ }
89
+ if (!exists) {
90
+ const authed = await tokenizedUrl(cloneUrl);
91
+ await run(["clone", "--filter=blob:none", "--no-checkout", authed, dir]);
92
+ await run(["checkout", defaultBranch], dir);
93
+ } else {
94
+ const authed = await tokenizedUrl(cloneUrl);
95
+ // Fetch via a one-shot URL override; the stored remote stays clean.
96
+ await run(["fetch", authed, defaultBranch], dir);
97
+ await run(["reset", "--hard", `FETCH_HEAD`], dir);
98
+ }
99
+ return dir;
100
+ }
101
+
102
+ async function currentSha(dir: string): Promise<string> {
103
+ return (await run(["rev-parse", "HEAD"], dir)).trim();
104
+ }
105
+
106
+ async function recentCommitMessages(dir: string, count: number): Promise<string[]> {
107
+ const out = await run(["log", `--format=%s`, `-n`, String(count)], dir);
108
+ return out.split("\n").filter(Boolean);
109
+ }
110
+
111
+ async function readFileIfPresent(dir: string, relPath: string): Promise<string | null> {
112
+ try {
113
+ return await fs.readFile(path.join(dir, relPath), "utf8");
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ /** Safety-checked worktree path for repo files (blocks traversal). */
120
+ function safeRepoPath(dir: string, relPath: string): string | null {
121
+ const target = path.resolve(dir, relPath);
122
+ if (!target.startsWith(path.resolve(dir) + path.sep)) {
123
+ return null;
124
+ }
125
+ return target;
126
+ }
127
+
128
+ async function createWorkBranch(dir: string, name: string): Promise<void> {
129
+ await run(["checkout", "-B", name], dir);
130
+ }
131
+
132
+ async function commitAll(dir: string, message: string, authorName: string, authorEmail: string): Promise<boolean> {
133
+ const status = await run(["status", "--porcelain"], dir);
134
+ if (!status.trim()) {
135
+ return false;
136
+ }
137
+ await run(["add", "-A"], dir);
138
+ await run(["-c", `user.name=${authorName}`, "-c", `user.email=${authorEmail}`, "commit", "-m", message], dir);
139
+ return true;
140
+ }
141
+
142
+ async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string): Promise<void> {
143
+ const authed = await tokenizedUrl(cloneUrl);
144
+ try {
145
+ await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
146
+ } catch (err) {
147
+ logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${err instanceof Error ? err.message : String(err)}`);
148
+ throw err;
149
+ }
150
+ }
151
+
152
+ /** Deterministic worktree dir (relative name) for a TeamAuto write task. */
153
+ function taskWorktreeDirName(repoId: string, taskId: string): string {
154
+ return `${teamAutoProjectDir(repoId)}__task-${taskId.replace(/[^\w-]/g, "")}`;
155
+ }
156
+
157
+ function taskBranchName(taskId: string): string {
158
+ return `teamclaw/task-${taskId.replace(/[^\w-]/g, "")}`;
159
+ }
160
+
161
+ /**
162
+ * Collaboration contract: write tasks execute in a dedicated git worktree
163
+ * branched from HEAD. Reuses an existing worktree (resume-safe) so the
164
+ * checkpoint/retry path lands in the same tree.
165
+ */
166
+ async function ensureTaskWorktree(repoId: string, taskId: string): Promise<string> {
167
+ const base = await repoDir(repoId);
168
+ const wtName = taskWorktreeDirName(repoId, taskId);
169
+ // wtName carries the teamauto/ level for the REL path; the physical dir is
170
+ // a SIBLING of the base checkout (path.join would nest teamauto/ twice).
171
+ const wtPath = path.join(path.dirname(base), path.basename(wtName));
172
+ if (await fs.access(path.join(wtPath, ".git")).then(() => true, () => false)) {
173
+ return wtPath; // resume case
174
+ }
175
+ await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
176
+ logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
177
+ return wtPath;
178
+ }
179
+
180
+ /** Remove a task worktree and its local branch (terminal cleanup). */
181
+ async function removeTaskWorktree(repoId: string, taskId: string): Promise<void> {
182
+ const base = await repoDir(repoId);
183
+ const wtName = taskWorktreeDirName(repoId, taskId);
184
+ const wtPath = path.join(path.dirname(base), path.basename(wtName));
185
+ try {
186
+ if (await fs.access(wtPath).then(() => true, () => false)) {
187
+ await run(["worktree", "remove", "--force", wtPath], base);
188
+ }
189
+ await run(["branch", "-D", taskBranchName(taskId)], base).catch(() => undefined);
190
+ } catch (err) {
191
+ logger.warn(`TeamAuto: worktree cleanup failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);
192
+ }
193
+ }
194
+
195
+ function taskWorktreeRelDir(repoId: string, taskId: string): string {
196
+ return taskWorktreeDirName(repoId, taskId);
197
+ }
198
+
199
+ /** True when HEAD has commits beyond the base branch (worktree delivery). */
200
+ async function branchHasCommits(dir: string, baseBranch: string): Promise<boolean> {
201
+ try {
202
+ const out = await run(["rev-list", "--count", "HEAD", "--not", baseBranch], dir);
203
+ return Number(out.trim()) > 0;
204
+ } catch {
205
+ // Base branch name unknown/unfetched - fall back to diff against first parent chain
206
+ try {
207
+ const root = await run(["rev-list", "--max-parents=0", "HEAD"], dir);
208
+ return root.trim().length > 0;
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+ }
214
+
215
+ return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
216
+ }
217
+
218
+ export type TeamAutoRepoSync = ReturnType<typeof createRepoSync>;