@teamclaws/teamclaw 2026.7.1 → 2026.8.1
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/README.md +8 -0
- package/dist/api.js +1 -0
- package/dist/index.js +325 -0
- package/dist/src/config.js +381 -0
- package/dist/src/controller/controller-capacity.js +14 -0
- package/dist/src/controller/controller-service.js +393 -0
- package/dist/src/controller/controller-tools.js +582 -0
- package/dist/src/controller/delivery-report.js +458 -0
- package/dist/src/controller/github-auth.js +564 -0
- package/dist/src/controller/http-server.js +6032 -0
- package/dist/src/controller/kickoff-orchestrator.js +220 -0
- package/dist/src/controller/managed-gateway-process.js +286 -0
- package/dist/src/controller/message-router.js +38 -0
- package/dist/src/controller/orchestration-manifest.js +173 -0
- package/dist/src/controller/preview-manager.js +586 -0
- package/dist/src/controller/prompt-injector.js +187 -0
- package/dist/src/controller/role-inference.js +35 -0
- package/dist/src/controller/task-router.js +67 -0
- package/dist/src/controller/tunnel-manager.js +548 -0
- package/dist/src/controller/websocket.js +42 -0
- package/dist/src/controller/worker-provisioning.js +1648 -0
- package/dist/src/discovery.js +86 -0
- package/dist/src/git-collaboration.js +694 -0
- package/dist/src/identity.js +131 -0
- package/dist/src/install-defaults.js +1 -0
- package/dist/src/interaction-contracts.js +531 -0
- package/dist/src/networking.js +91 -0
- package/dist/src/openclaw-workspace.js +903 -0
- package/dist/src/prompt-policy.js +373 -0
- package/dist/src/protocol.js +58 -0
- package/dist/src/roles.js +349 -0
- package/dist/src/state.js +183 -0
- package/dist/src/task-executor.js +1033 -0
- package/dist/src/teamauto/github-client.js +192 -0
- package/dist/src/teamauto/norms.js +85 -0
- package/dist/src/teamauto/repo-sync.js +201 -0
- package/dist/src/teamauto/scanner.js +179 -0
- package/dist/src/teamauto/schedule.js +123 -0
- package/dist/src/teamauto/scheduler.js +688 -0
- package/dist/src/teamauto/store.js +133 -0
- package/dist/src/types.js +243 -0
- package/dist/src/ui/app.js +4292 -0
- package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
- package/dist/src/ui/github-login.html +296 -0
- package/dist/src/ui/index.html +414 -0
- package/dist/src/ui/style.css +2611 -0
- package/dist/src/worker/http-handler.js +146 -0
- package/dist/src/worker/message-queue.js +24 -0
- package/dist/src/worker/prompt-injector.js +42 -0
- package/dist/src/worker/skill-installer.js +253 -0
- package/dist/src/worker/tools.js +541 -0
- package/dist/src/worker/worker-service.js +234 -0
- package/dist/src/workspace-browser.js +269 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +9 -7
- package/src/controller/http-server.ts +26 -1
- package/src/controller/tunnel-manager.ts +139 -15
- package/src/ui/app.js +97 -20
- package/src/ui/index.html +16 -4
- package/src/ui/style.css +49 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal GitHub REST client for TeamAuto: ETag-conditional GETs, light
|
|
3
|
+
* pagination, and the write endpoints we need. All requests ride the stored
|
|
4
|
+
* device-flow token via the auth manager (transparent refresh).
|
|
5
|
+
*/
|
|
6
|
+
const API = "https://api.github.com";
|
|
7
|
+
const VERSION = "2026-03-10";
|
|
8
|
+
const USER_AGENT = "teamclaw-teamauto";
|
|
9
|
+
export class GithubClientError extends Error {
|
|
10
|
+
status;
|
|
11
|
+
constructor(message, status) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "GithubClientError";
|
|
14
|
+
this.status = status;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function createGithubClient(auth) {
|
|
18
|
+
async function request(method, urlPath, options = {}) {
|
|
19
|
+
const headers = {
|
|
20
|
+
...(await auth.getAuthHeaders()),
|
|
21
|
+
"User-Agent": USER_AGENT,
|
|
22
|
+
"X-GitHub-Api-Version": VERSION,
|
|
23
|
+
};
|
|
24
|
+
if (options.body !== undefined) {
|
|
25
|
+
headers["Content-Type"] = "application/json";
|
|
26
|
+
}
|
|
27
|
+
const etagKey = options.etagKey ? `${method} ${urlPath}` : undefined;
|
|
28
|
+
if (etagKey && options.etags?.[etagKey]) {
|
|
29
|
+
headers["If-None-Match"] = options.etags[etagKey];
|
|
30
|
+
}
|
|
31
|
+
const response = await fetch(`${API}${urlPath}`, {
|
|
32
|
+
method,
|
|
33
|
+
headers,
|
|
34
|
+
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
35
|
+
signal: AbortSignal.timeout(20_000),
|
|
36
|
+
});
|
|
37
|
+
if (etagKey) {
|
|
38
|
+
const etag = response.headers.get("etag");
|
|
39
|
+
if (etag && options.etags) {
|
|
40
|
+
options.etags[etagKey] = etag;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (response.status === 304) {
|
|
44
|
+
return { status: 304, data: null, notModified: true };
|
|
45
|
+
}
|
|
46
|
+
const text = await response.text();
|
|
47
|
+
let data = null;
|
|
48
|
+
if (text) {
|
|
49
|
+
try {
|
|
50
|
+
data = JSON.parse(text);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
data = { raw: text.slice(0, 500) };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
const message = data?.message ?? `HTTP ${response.status}`;
|
|
58
|
+
throw new GithubClientError(message, response.status);
|
|
59
|
+
}
|
|
60
|
+
return { status: response.status, data, notModified: false };
|
|
61
|
+
}
|
|
62
|
+
async function getJson(urlPath, etags) {
|
|
63
|
+
const { data, notModified } = await request("GET", urlPath, { etagKey: etags ? urlPath : undefined, etags });
|
|
64
|
+
return notModified ? null : data;
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
request,
|
|
68
|
+
async getRepoInfo(owner, repo) {
|
|
69
|
+
const data = await getJson(`/repos/${owner}/${repo}`);
|
|
70
|
+
if (!data) {
|
|
71
|
+
throw new GithubClientError("unexpected 304 without etag", 500);
|
|
72
|
+
}
|
|
73
|
+
const perms = (data.permissions ?? {});
|
|
74
|
+
return {
|
|
75
|
+
fullName: String(data.full_name ?? `${owner}/${repo}`),
|
|
76
|
+
defaultBranch: String(data.default_branch ?? "main"),
|
|
77
|
+
cloneUrl: String(data.clone_url ?? `https://github.com/${owner}/${repo}.git`),
|
|
78
|
+
permissions: { push: Boolean(perms.push), pull: Boolean(perms.pull ?? true) },
|
|
79
|
+
};
|
|
80
|
+
},
|
|
81
|
+
/** Issues updated since the cursor; pass 0 for a first (bounded) backfill. */
|
|
82
|
+
async listIssues(owner, repo, sinceMs, etags) {
|
|
83
|
+
const since = sinceMs > 0 ? new Date(sinceMs).toISOString() : new Date(Date.now() - 7 * 24 * 3600_000).toISOString();
|
|
84
|
+
const data = await getJson(`/repos/${owner}/${repo}/issues?state=open&sort=updated&direction=desc&per_page=50&since=${encodeURIComponent(since)}`, etags);
|
|
85
|
+
if (!data) {
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
return data
|
|
89
|
+
.filter((raw) => {
|
|
90
|
+
const item = raw;
|
|
91
|
+
// The issues API also returns PRs; drop them (pull_request field).
|
|
92
|
+
return !item.pull_request;
|
|
93
|
+
})
|
|
94
|
+
.map((raw) => {
|
|
95
|
+
const item = raw;
|
|
96
|
+
return {
|
|
97
|
+
number: Number(item.number ?? 0),
|
|
98
|
+
title: String(item.title ?? ""),
|
|
99
|
+
body: String(item.body ?? ""),
|
|
100
|
+
state: item.state === "closed" ? "closed" : "open",
|
|
101
|
+
assignees: Array.isArray(item.assignees) ? item.assignees.map((a) => String(a.login ?? "")) : [],
|
|
102
|
+
labels: Array.isArray(item.labels) ? item.labels.map((l) => String(l.name ?? "")) : [],
|
|
103
|
+
updatedAt: String(item.updated_at ?? ""),
|
|
104
|
+
user: String(item.user?.login ?? ""),
|
|
105
|
+
htmlUrl: String(item.html_url ?? ""),
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
async listPulls(owner, repo, etags) {
|
|
110
|
+
const data = await getJson(`/repos/${owner}/${repo}/pulls?state=open&sort=updated&direction=desc&per_page=30`, etags);
|
|
111
|
+
if (!data) {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
return data.map((raw) => {
|
|
115
|
+
const item = raw;
|
|
116
|
+
return {
|
|
117
|
+
number: Number(item.number ?? 0),
|
|
118
|
+
title: String(item.title ?? ""),
|
|
119
|
+
body: String(item.body ?? ""),
|
|
120
|
+
state: item.state === "closed" ? "closed" : "open",
|
|
121
|
+
draft: Boolean(item.draft),
|
|
122
|
+
updated_at: String(item.updated_at ?? ""),
|
|
123
|
+
user: String(item.user?.login ?? ""),
|
|
124
|
+
head: String(item.head?.ref ?? ""),
|
|
125
|
+
htmlUrl: String(item.html_url ?? ""),
|
|
126
|
+
};
|
|
127
|
+
});
|
|
128
|
+
},
|
|
129
|
+
async listCommits(owner, repo, sinceSha) {
|
|
130
|
+
const suffix = sinceSha ? `?sha=${encodeURIComponent(sinceSha)}` : "?per_page=20";
|
|
131
|
+
void suffix;
|
|
132
|
+
// Compare-style walk is heavy; use the commits feed and filter client-side.
|
|
133
|
+
const data = await getJson(`/repos/${owner}/${repo}/commits?per_page=30`);
|
|
134
|
+
if (!data) {
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
const commits = data.map((raw) => {
|
|
138
|
+
const item = raw;
|
|
139
|
+
return {
|
|
140
|
+
sha: String(item.sha ?? ""),
|
|
141
|
+
message: String(item.commit?.message ?? "").split("\n")[0],
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
if (!sinceSha) {
|
|
145
|
+
return commits.slice(0, 10);
|
|
146
|
+
}
|
|
147
|
+
const index = commits.findIndex((c) => c.sha.startsWith(sinceSha.slice(0, 10)));
|
|
148
|
+
return index === -1 ? commits.slice(0, 5) : commits.slice(0, index);
|
|
149
|
+
},
|
|
150
|
+
// ---- write side (require Contents/Issues/PR write on the App) ----
|
|
151
|
+
async postIssueComment(owner, repo, issueNumber, body) {
|
|
152
|
+
const { data } = await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body: { body } });
|
|
153
|
+
return Number(data.id ?? 0);
|
|
154
|
+
},
|
|
155
|
+
async postPullReviewComment(owner, repo, pullNumber, body) {
|
|
156
|
+
await request("POST", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews`, { body: { event: "COMMENT", body } });
|
|
157
|
+
},
|
|
158
|
+
async createIssue(owner, repo, title, body, labels) {
|
|
159
|
+
const { data } = await request("POST", `/repos/${owner}/${repo}/issues`, {
|
|
160
|
+
body: { title, body, ...(labels?.length ? { labels } : {}) },
|
|
161
|
+
});
|
|
162
|
+
return Number(data.number ?? 0);
|
|
163
|
+
},
|
|
164
|
+
async assignIssue(owner, repo, issueNumber, assignee) {
|
|
165
|
+
await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees: [assignee] } });
|
|
166
|
+
},
|
|
167
|
+
/** Open a PR from a task worktree branch (collaboration contract delivery). */
|
|
168
|
+
async createPullRequest(owner, repo, head, base, title, body) {
|
|
169
|
+
const { data } = await request("POST", `/repos/${owner}/${repo}/pulls`, {
|
|
170
|
+
body: { title, head, base, body },
|
|
171
|
+
});
|
|
172
|
+
const item = data;
|
|
173
|
+
return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };
|
|
174
|
+
},
|
|
175
|
+
/** Repos the logged-in user can select in the TeamAuto bind picker. */
|
|
176
|
+
async listUserRepos() {
|
|
177
|
+
const data = await getJson("/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&per_page=100");
|
|
178
|
+
if (!data) {
|
|
179
|
+
return [];
|
|
180
|
+
}
|
|
181
|
+
return data.map((raw) => {
|
|
182
|
+
const item = raw;
|
|
183
|
+
return {
|
|
184
|
+
id: String(item.full_name ?? ""),
|
|
185
|
+
fullName: String(item.full_name ?? ""),
|
|
186
|
+
private: Boolean(item.private),
|
|
187
|
+
pushedAt: typeof item.pushed_at === "string" ? item.pushed_at : null,
|
|
188
|
+
};
|
|
189
|
+
}).filter((r) => r.id);
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Norms learning: absorb the target repo's collaboration conventions
|
|
3
|
+
* (CONTRIBUTING, issue/PR templates, commit style) so every TeamClaw worker
|
|
4
|
+
* prompt for that repo carries them - "转手目标仓库里面的协作规范".
|
|
5
|
+
*/
|
|
6
|
+
const CONVENTIONAL_RE = /^(\w+)(\([^)]+\))?!?:\s.+/;
|
|
7
|
+
function detectCommitStyle(messages) {
|
|
8
|
+
if (!messages.length) {
|
|
9
|
+
return "unspecified - keep subject lines short and descriptive";
|
|
10
|
+
}
|
|
11
|
+
const matches = messages.filter((m) => CONVENTIONAL_RE.test(m)).length;
|
|
12
|
+
if (matches >= messages.length * 0.6) {
|
|
13
|
+
return "conventional commits (type(scope)!: subject)";
|
|
14
|
+
}
|
|
15
|
+
const chinese = messages.filter((m) => /[\u4e00-\u9fff]/.test(m)).length;
|
|
16
|
+
if (chinese >= messages.length * 0.6) {
|
|
17
|
+
return "plain subject lines, Chinese";
|
|
18
|
+
}
|
|
19
|
+
return "plain subject lines, English";
|
|
20
|
+
}
|
|
21
|
+
export async function learnNorms(repo, client, sync, cloneUrl, defaultBranch) {
|
|
22
|
+
let dir = null;
|
|
23
|
+
try {
|
|
24
|
+
dir = await sync.ensureCloned(repo.id, cloneUrl, defaultBranch);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
dir = null;
|
|
28
|
+
}
|
|
29
|
+
const [owner, name] = repo.id.split("/");
|
|
30
|
+
const fetchRemote = async (apiPath) => {
|
|
31
|
+
try {
|
|
32
|
+
const { data } = await client.request("GET", apiPath);
|
|
33
|
+
const record = data;
|
|
34
|
+
if (typeof record.content === "string" && record.encoding === "base64") {
|
|
35
|
+
return Buffer.from(record.content, "base64").toString("utf8");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// absent file is fine
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
};
|
|
43
|
+
const contributing = (await fetchRemote(`/repos/${owner}/${name}/contents/CONTRIBUTING.md`)) ??
|
|
44
|
+
(dir ? await sync.readFileIfPresent(dir, "CONTRIBUTING.md") : null);
|
|
45
|
+
const issueTemplate = (await fetchRemote(`/repos/${owner}/${name}/contents/.github/ISSUE_TEMPLATE.md`)) ??
|
|
46
|
+
(dir ? await sync.readFileIfPresent(dir, ".github/ISSUE_TEMPLATE.md") : null);
|
|
47
|
+
const prTemplate = (await fetchRemote(`/repos/${owner}/${name}/contents/.github/PULL_REQUEST_TEMPLATE.md`)) ??
|
|
48
|
+
(dir ? await sync.readFileIfPresent(dir, ".github/PULL_REQUEST_TEMPLATE.md") : null);
|
|
49
|
+
let commitStyle = "unspecified";
|
|
50
|
+
if (dir) {
|
|
51
|
+
try {
|
|
52
|
+
commitStyle = detectCommitStyle(await sync.recentCommitMessages(dir, 100));
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
commitStyle = "unspecified";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
commitStyle,
|
|
60
|
+
issueTemplate: issueTemplate?.slice(0, 2000) ?? null,
|
|
61
|
+
prTemplate: prTemplate?.slice(0, 2000) ?? null,
|
|
62
|
+
contributing: contributing?.slice(0, 4000) ?? null,
|
|
63
|
+
learnedAt: Date.now(),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** Render the learned norms into a compact prompt block for workers. */
|
|
67
|
+
export function renderNormsBlock(norms, repoId) {
|
|
68
|
+
if (!norms) {
|
|
69
|
+
return `Target repo: ${repoId}\nCollaboration norms: not learned yet - follow common sense and read existing issues/PRs for style.\n`;
|
|
70
|
+
}
|
|
71
|
+
const lines = [
|
|
72
|
+
`Target repo: ${repoId}`,
|
|
73
|
+
`Commit style: ${norms.commitStyle}`,
|
|
74
|
+
];
|
|
75
|
+
if (norms.contributing) {
|
|
76
|
+
lines.push(`CONTRIBUTING.md excerpt:\n${norms.contributing.slice(0, 1500)}`);
|
|
77
|
+
}
|
|
78
|
+
if (norms.issueTemplate) {
|
|
79
|
+
lines.push(`Issue template excerpt:\n${norms.issueTemplate.slice(0, 800)}`);
|
|
80
|
+
}
|
|
81
|
+
if (norms.prTemplate) {
|
|
82
|
+
lines.push(`PR template excerpt:\n${norms.prTemplate.slice(0, 800)}`);
|
|
83
|
+
}
|
|
84
|
+
return lines.join("\n") + "\n";
|
|
85
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
import { repoSlugToDirName, resolveTeamAutoPaths } from "./store.js";
|
|
6
|
+
const exec = promisify(execFile);
|
|
7
|
+
export const TEAMCLAW_BRANCH_PREFIX = "teamclaw/";
|
|
8
|
+
/** TaskInfo.projectDir slug for a bound repo (relative to the projects dir). */
|
|
9
|
+
export function teamAutoProjectDir(repoId) {
|
|
10
|
+
return `teamauto/${repoSlugToDirName(repoId)}`;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Git operations for TeamAuto. Authentication uses the device-flow token
|
|
14
|
+
* inline in the remote URL (x-access-token basic auth) - proven to survive
|
|
15
|
+
* GitHub's smart-HTTP redirects where extraheader injection does not. The
|
|
16
|
+
* token never touches disk: remotes are rewritten per invocation and the
|
|
17
|
+
* on-disk remote stays a clean https URL.
|
|
18
|
+
*/
|
|
19
|
+
function gitEnv() {
|
|
20
|
+
return {
|
|
21
|
+
...process.env,
|
|
22
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
23
|
+
GIT_ASKPASS: "/bin/true",
|
|
24
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
async function run(args, cwd) {
|
|
28
|
+
const { stdout } = await exec("git", args, {
|
|
29
|
+
cwd,
|
|
30
|
+
env: gitEnv(),
|
|
31
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
32
|
+
timeout: 120_000,
|
|
33
|
+
});
|
|
34
|
+
return stdout;
|
|
35
|
+
}
|
|
36
|
+
export function createRepoSync(auth, logger) {
|
|
37
|
+
async function tokenizedUrl(cloneUrl) {
|
|
38
|
+
const token = await auth.getAccessToken();
|
|
39
|
+
const clean = cloneUrl.replace(/^https:\/\//, "").replace(/\.git$/, "");
|
|
40
|
+
return `https://x-access-token:${token}@${clean}.git`;
|
|
41
|
+
}
|
|
42
|
+
async function repoDir(repoId) {
|
|
43
|
+
const { reposRoot, legacyReposRoot } = resolveTeamAutoPaths();
|
|
44
|
+
await fs.mkdir(reposRoot, { recursive: true });
|
|
45
|
+
const dir = path.join(reposRoot, repoSlugToDirName(repoId));
|
|
46
|
+
const legacy = path.join(legacyReposRoot, repoSlugToDirName(repoId));
|
|
47
|
+
// One-time migration: move pre-workspace clones into the projects tree.
|
|
48
|
+
try {
|
|
49
|
+
await fs.stat(path.join(legacy, ".git"));
|
|
50
|
+
try {
|
|
51
|
+
await fs.stat(path.join(dir, ".git"));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
await fs.mkdir(path.dirname(dir), { recursive: true });
|
|
55
|
+
try {
|
|
56
|
+
await fs.rename(legacy, dir);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// Cross-device (EXDEV): copy then remove the original.
|
|
60
|
+
await fs.cp(legacy, dir, { recursive: true });
|
|
61
|
+
await fs.rm(legacy, { recursive: true, force: true });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// No legacy clone - normal path.
|
|
67
|
+
}
|
|
68
|
+
return dir;
|
|
69
|
+
}
|
|
70
|
+
/** Clone if absent, otherwise fetch + reset to the default branch tip. */
|
|
71
|
+
async function ensureCloned(repoId, cloneUrl, defaultBranch) {
|
|
72
|
+
const dir = await repoDir(repoId);
|
|
73
|
+
const gitDir = path.join(dir, ".git");
|
|
74
|
+
let exists = false;
|
|
75
|
+
try {
|
|
76
|
+
const stat = await fs.stat(gitDir);
|
|
77
|
+
exists = stat.isDirectory() || stat.isFile();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
exists = false;
|
|
81
|
+
}
|
|
82
|
+
if (!exists) {
|
|
83
|
+
const authed = await tokenizedUrl(cloneUrl);
|
|
84
|
+
await run(["clone", "--filter=blob:none", "--no-checkout", authed, dir]);
|
|
85
|
+
await run(["checkout", defaultBranch], dir);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
const authed = await tokenizedUrl(cloneUrl);
|
|
89
|
+
// Fetch via a one-shot URL override; the stored remote stays clean.
|
|
90
|
+
await run(["fetch", authed, defaultBranch], dir);
|
|
91
|
+
await run(["reset", "--hard", `FETCH_HEAD`], dir);
|
|
92
|
+
}
|
|
93
|
+
return dir;
|
|
94
|
+
}
|
|
95
|
+
async function currentSha(dir) {
|
|
96
|
+
return (await run(["rev-parse", "HEAD"], dir)).trim();
|
|
97
|
+
}
|
|
98
|
+
async function recentCommitMessages(dir, count) {
|
|
99
|
+
const out = await run(["log", `--format=%s`, `-n`, String(count)], dir);
|
|
100
|
+
return out.split("\n").filter(Boolean);
|
|
101
|
+
}
|
|
102
|
+
async function readFileIfPresent(dir, relPath) {
|
|
103
|
+
try {
|
|
104
|
+
return await fs.readFile(path.join(dir, relPath), "utf8");
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Safety-checked worktree path for repo files (blocks traversal). */
|
|
111
|
+
function safeRepoPath(dir, relPath) {
|
|
112
|
+
const target = path.resolve(dir, relPath);
|
|
113
|
+
if (!target.startsWith(path.resolve(dir) + path.sep)) {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
return target;
|
|
117
|
+
}
|
|
118
|
+
async function createWorkBranch(dir, name) {
|
|
119
|
+
await run(["checkout", "-B", name], dir);
|
|
120
|
+
}
|
|
121
|
+
async function commitAll(dir, message, authorName, authorEmail) {
|
|
122
|
+
const status = await run(["status", "--porcelain"], dir);
|
|
123
|
+
if (!status.trim()) {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
await run(["add", "-A"], dir);
|
|
127
|
+
await run(["-c", `user.name=${authorName}`, "-c", `user.email=${authorEmail}`, "commit", "-m", message], dir);
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
async function pushBranch(repoId, dir, cloneUrl, branch) {
|
|
131
|
+
const authed = await tokenizedUrl(cloneUrl);
|
|
132
|
+
try {
|
|
133
|
+
await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${err instanceof Error ? err.message : String(err)}`);
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** Deterministic worktree dir (relative name) for a TeamAuto write task. */
|
|
141
|
+
function taskWorktreeDirName(repoId, taskId) {
|
|
142
|
+
return `${teamAutoProjectDir(repoId)}__task-${taskId.replace(/[^\w-]/g, "")}`;
|
|
143
|
+
}
|
|
144
|
+
function taskBranchName(taskId) {
|
|
145
|
+
return `teamclaw/task-${taskId.replace(/[^\w-]/g, "")}`;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Collaboration contract: write tasks execute in a dedicated git worktree
|
|
149
|
+
* branched from HEAD. Reuses an existing worktree (resume-safe) so the
|
|
150
|
+
* checkpoint/retry path lands in the same tree.
|
|
151
|
+
*/
|
|
152
|
+
async function ensureTaskWorktree(repoId, taskId) {
|
|
153
|
+
const base = await repoDir(repoId);
|
|
154
|
+
const wtName = taskWorktreeDirName(repoId, taskId);
|
|
155
|
+
// wtName carries the teamauto/ level for the REL path; the physical dir is
|
|
156
|
+
// a SIBLING of the base checkout (path.join would nest teamauto/ twice).
|
|
157
|
+
const wtPath = path.join(path.dirname(base), path.basename(wtName));
|
|
158
|
+
if (await fs.access(path.join(wtPath, ".git")).then(() => true, () => false)) {
|
|
159
|
+
return wtPath; // resume case
|
|
160
|
+
}
|
|
161
|
+
await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
|
|
162
|
+
logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
|
|
163
|
+
return wtPath;
|
|
164
|
+
}
|
|
165
|
+
/** Remove a task worktree and its local branch (terminal cleanup). */
|
|
166
|
+
async function removeTaskWorktree(repoId, taskId) {
|
|
167
|
+
const base = await repoDir(repoId);
|
|
168
|
+
const wtName = taskWorktreeDirName(repoId, taskId);
|
|
169
|
+
const wtPath = path.join(path.dirname(base), path.basename(wtName));
|
|
170
|
+
try {
|
|
171
|
+
if (await fs.access(wtPath).then(() => true, () => false)) {
|
|
172
|
+
await run(["worktree", "remove", "--force", wtPath], base);
|
|
173
|
+
}
|
|
174
|
+
await run(["branch", "-D", taskBranchName(taskId)], base).catch(() => undefined);
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
logger.warn(`TeamAuto: worktree cleanup failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function taskWorktreeRelDir(repoId, taskId) {
|
|
181
|
+
return taskWorktreeDirName(repoId, taskId);
|
|
182
|
+
}
|
|
183
|
+
/** True when HEAD has commits beyond the base branch (worktree delivery). */
|
|
184
|
+
async function branchHasCommits(dir, baseBranch) {
|
|
185
|
+
try {
|
|
186
|
+
const out = await run(["rev-list", "--count", "HEAD", "--not", baseBranch], dir);
|
|
187
|
+
return Number(out.trim()) > 0;
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
// Base branch name unknown/unfetched - fall back to diff against first parent chain
|
|
191
|
+
try {
|
|
192
|
+
const root = await run(["rev-list", "--max-parents=0", "HEAD"], dir);
|
|
193
|
+
return root.trim().length > 0;
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
|
|
201
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/** Roles that jointly author a scheduled full review (one section each). */
|
|
2
|
+
export const JOINT_REVIEW_ROLES = ["architect", "qa", "security-engineer"];
|
|
3
|
+
const JOINT_REVIEW_FOCUS = {
|
|
4
|
+
architect: "architecture and structure: module boundaries, layering, README/docs accuracy, maintainability hotspots, dead or duplicated code paths",
|
|
5
|
+
qa: "quality and tests: test coverage gaps, flaky-test hotspots, error-handling weaknesses, missing failure-path tests, CI blind spots",
|
|
6
|
+
"security-engineer": "security surface: dependency risks, secret handling, injection/validation gaps, auth-sensitive paths, unsafe defaults",
|
|
7
|
+
};
|
|
8
|
+
function matchesAny(text, keywords) {
|
|
9
|
+
const lower = text.toLowerCase();
|
|
10
|
+
return keywords.some((k) => k.trim() && lower.includes(k.trim().toLowerCase()));
|
|
11
|
+
}
|
|
12
|
+
function labelAllowed(issue, repo) {
|
|
13
|
+
const { include, exclude } = repo.policy.labelFilter;
|
|
14
|
+
if (exclude.some((l) => issue.labels.includes(l))) {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
if (include.length && !include.some((l) => issue.labels.includes(l))) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
function keywordAllowed(title, repo) {
|
|
23
|
+
const { include, exclude } = repo.policy.keywordFilter;
|
|
24
|
+
if (exclude.length && matchesAny(title, exclude)) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
if (include.length && !matchesAny(title, include)) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
const TEAMCLAW_MARKER_RE = /\[teamclaw(?::\w+)?\]/i;
|
|
33
|
+
function truncate(text, max) {
|
|
34
|
+
return text.length > max ? text.slice(0, max) + "..." : text;
|
|
35
|
+
}
|
|
36
|
+
export async function sweepRepo(repo, client, now = Date.now()) {
|
|
37
|
+
const [owner, name] = repo.id.split("/");
|
|
38
|
+
const issues = await client.listIssues(owner, name, repo.cursors.lastIssueSince, repo.cursors.etags);
|
|
39
|
+
const pulls = repo.policy.actions.prReview
|
|
40
|
+
? await client.listPulls(owner, name, repo.cursors.etags)
|
|
41
|
+
: [];
|
|
42
|
+
const candidates = [];
|
|
43
|
+
for (const issue of issues) {
|
|
44
|
+
// Dedup: seen map survives sweeps; a closed-then-reopened issue updates.
|
|
45
|
+
const key = `${repo.id}#issue-${issue.number}`;
|
|
46
|
+
const updatedAtMs = Date.parse(issue.updatedAt) || 0;
|
|
47
|
+
if ((repo.cursors.seen[key] ?? 0) >= updatedAtMs) {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
// NOTE: no first-sweep gate here. Gating candidates on "first sweep"
|
|
51
|
+
// combined with the dry-run not advancing cursors deadlocked repos in
|
|
52
|
+
// observe-only mode forever (zero candidates -> dryRunDone never set).
|
|
53
|
+
// Backlog protection comes from the per-sweep cap + one dry-run pass.
|
|
54
|
+
if (!labelAllowed(issue, repo) || !keywordAllowed(issue.title, repo)) {
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (repo.policy.skipAssignedToHumans && issue.assignees.length > 0) {
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
// Never self-assign or review our own threads.
|
|
61
|
+
if (TEAMCLAW_MARKER_RE.test(issue.title) || TEAMCLAW_MARKER_RE.test(issue.body)) {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const base = {
|
|
65
|
+
repoId: repo.id,
|
|
66
|
+
key,
|
|
67
|
+
number: issue.number,
|
|
68
|
+
role: "qa",
|
|
69
|
+
writeMode: "read-only",
|
|
70
|
+
};
|
|
71
|
+
if (repo.policy.actions.issueReview) {
|
|
72
|
+
candidates.push({
|
|
73
|
+
...base,
|
|
74
|
+
kind: "issueReview",
|
|
75
|
+
title: truncate(`Review issue #${issue.number}: ${issue.title}`, 120),
|
|
76
|
+
reason: "new/updated issue needs triage",
|
|
77
|
+
context: `Issue #${issue.number} by @${issue.user}\nTitle: ${issue.title}\nLabels: ${issue.labels.join(", ") || "none"}\nLink: ${issue.htmlUrl}\n\nBody:\n${truncate(issue.body, 4000)}`,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (repo.policy.actions.takeOwnership && issue.state === "open") {
|
|
81
|
+
candidates.push({
|
|
82
|
+
...base,
|
|
83
|
+
kind: "takeOwnership",
|
|
84
|
+
role: "developer",
|
|
85
|
+
writeMode: "write",
|
|
86
|
+
title: truncate(`Take ownership of issue #${issue.number}: ${issue.title}`, 120),
|
|
87
|
+
reason: "unassigned issue eligible for autonomous ownership",
|
|
88
|
+
context: `Own and implement issue #${issue.number}: ${issue.title}\nLink: ${issue.htmlUrl}\n\nBody:\n${truncate(issue.body, 6000)}`,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const pull of pulls) {
|
|
93
|
+
const key = `${repo.id}#pr-${pull.number}`;
|
|
94
|
+
const updatedAtMs = Date.parse(pull.updated_at) || 0;
|
|
95
|
+
if ((repo.cursors.seen[key] ?? 0) >= updatedAtMs) {
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
// See the issue-loop note: no first-sweep gate (deadlock source).
|
|
99
|
+
// Skip our own PRs and drafts.
|
|
100
|
+
if (pull.head.startsWith("teamclaw/") || pull.draft || TEAMCLAW_MARKER_RE.test(pull.title)) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (repo.policy.actions.prReview) {
|
|
104
|
+
candidates.push({
|
|
105
|
+
repoId: repo.id,
|
|
106
|
+
key,
|
|
107
|
+
kind: "prReview",
|
|
108
|
+
number: pull.number,
|
|
109
|
+
role: "qa",
|
|
110
|
+
writeMode: "read-only",
|
|
111
|
+
title: truncate(`Review PR #${pull.number}: ${pull.title}`, 120),
|
|
112
|
+
reason: "new/updated pull request needs review",
|
|
113
|
+
context: `PR #${pull.number} by @${pull.user} (head: ${pull.head})\nLink: ${pull.htmlUrl}\n\nDescription:\n${truncate(pull.body, 4000)}`,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// Periodic full review (weekly/daily), independent of per-object cursors.
|
|
118
|
+
if (repo.policy.actions.fullReview !== "off") {
|
|
119
|
+
const intervalMs = repo.policy.actions.fullReview === "daily" ? 24 * 3600_000 : 7 * 24 * 3600_000;
|
|
120
|
+
// Interval-gated only (the old !firstSweep gate could never open for a
|
|
121
|
+
// repo whose first sweep observed nothing - see the deadlock note above).
|
|
122
|
+
if (now - repo.cursors.lastFullReviewAt >= intervalMs) {
|
|
123
|
+
const cycle = Math.floor(now / intervalMs);
|
|
124
|
+
// Joint review: one candidate per role, one shared cycle. Each role's
|
|
125
|
+
// reply becomes a labeled section of a single umbrella review issue
|
|
126
|
+
// (the write-back reconciler groups by the cycle key).
|
|
127
|
+
for (const role of JOINT_REVIEW_ROLES) {
|
|
128
|
+
candidates.push({
|
|
129
|
+
repoId: repo.id,
|
|
130
|
+
key: `${repo.id}#fullreview-${cycle}-${role}`,
|
|
131
|
+
kind: "fullReview",
|
|
132
|
+
number: 0,
|
|
133
|
+
role,
|
|
134
|
+
writeMode: "read-only",
|
|
135
|
+
cycle,
|
|
136
|
+
title: `Full repository review (${role}): ${repo.id}`,
|
|
137
|
+
reason: `scheduled ${repo.policy.actions.fullReview} full review (joint, ${role} section)`,
|
|
138
|
+
context: [
|
|
139
|
+
`Perform the ${role} section of a joint full-repository review of ${repo.id}.`,
|
|
140
|
+
`Your focus: ${JOINT_REVIEW_FOCUS[role]}.`,
|
|
141
|
+
"Other roles cover complementary areas in parallel - do NOT duplicate their scope; go deep on yours.",
|
|
142
|
+
"Your reply becomes the " + role + " section of the joint review issue on GitHub. Do not change code.",
|
|
143
|
+
].join("\n"),
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls };
|
|
149
|
+
}
|
|
150
|
+
/** Advance cursors after tasks were enqueued (or observed on first sweep). */
|
|
151
|
+
export function advanceCursors(repo, issues, pulls, now = Date.now()) {
|
|
152
|
+
for (const issue of issues) {
|
|
153
|
+
repo.cursors.seen[`${repo.id}#issue-${issue.number}`] = Date.parse(issue.updatedAt) || now;
|
|
154
|
+
}
|
|
155
|
+
for (const pull of pulls) {
|
|
156
|
+
repo.cursors.seen[`${repo.id}#pr-${pull.number}`] = Date.parse(pull.updated_at) || now;
|
|
157
|
+
}
|
|
158
|
+
// Cap the seen map so it cannot grow unbounded.
|
|
159
|
+
const entries = Object.entries(repo.cursors.seen);
|
|
160
|
+
if (entries.length > 2000) {
|
|
161
|
+
entries.sort((a, b) => a[1] - b[1]);
|
|
162
|
+
for (const [key] of entries.slice(0, entries.length - 2000)) {
|
|
163
|
+
delete repo.cursors.seen[key];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// `since` cursors track the newest observed object time, never the sweep's
|
|
167
|
+
// wall clock - objects updated between fetch and save must not fall behind
|
|
168
|
+
// the cursor forever.
|
|
169
|
+
let maxIssueUpdated = 0;
|
|
170
|
+
let maxPullUpdated = 0;
|
|
171
|
+
for (const issue of issues) {
|
|
172
|
+
maxIssueUpdated = Math.max(maxIssueUpdated, Date.parse(issue.updatedAt) || now);
|
|
173
|
+
}
|
|
174
|
+
for (const pull of pulls) {
|
|
175
|
+
maxPullUpdated = Math.max(maxPullUpdated, Date.parse(pull.updated_at) || now);
|
|
176
|
+
}
|
|
177
|
+
repo.cursors.lastIssueSince = Math.max(repo.cursors.lastIssueSince, maxIssueUpdated);
|
|
178
|
+
repo.cursors.lastPrSince = Math.max(repo.cursors.lastPrSince, maxPullUpdated);
|
|
179
|
+
}
|