@teamclaws/teamclaw 2026.8.0 → 2026.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/cli.mjs +46 -15
- package/dist/api.js +1 -0
- package/dist/index.js +325 -0
- package/dist/src/config.js +412 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-capacity.js +14 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +813 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +624 -0
- package/dist/src/controller/controller-tools.js +587 -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 +284 -0
- package/dist/src/controller/kickoff-orchestrator.js +246 -0
- package/dist/src/controller/managed-gateway-process.js +286 -0
- package/dist/src/controller/message-delivery.js +28 -0
- package/dist/src/controller/message-router.js +38 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +151 -0
- package/dist/src/controller/preview-manager.js +586 -0
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +289 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +197 -0
- package/dist/src/controller/repo-routes.js +63 -0
- package/dist/src/controller/role-inference.js +246 -0
- package/dist/src/controller/route-table.js +1353 -0
- package/dist/src/controller/task-assignment.js +508 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +240 -0
- package/dist/src/controller/task-results.js +461 -0
- package/dist/src/controller/task-router.js +137 -0
- package/dist/src/controller/task-routes.js +703 -0
- package/dist/src/controller/teamauto-routes.js +124 -0
- package/dist/src/controller/tunnel-manager.js +548 -0
- package/dist/src/controller/ui-assets.js +68 -0
- package/dist/src/controller/websocket.js +42 -0
- package/dist/src/controller/worker-provisioning.js +1674 -0
- package/dist/src/controller/worker-routes.js +188 -0
- package/dist/src/discovery.js +86 -0
- package/dist/src/git-collaboration.js +694 -0
- package/dist/src/identity.js +132 -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 +925 -0
- package/dist/src/profile-loader.js +486 -0
- package/dist/src/profiles/banking.json +178 -0
- package/dist/src/profiles/crossborder-ecom.json +253 -0
- package/dist/src/profiles/insurance.json +157 -0
- package/dist/src/profiles/knowledge/hs-structure.md +97 -0
- package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/dist/src/profiles/knowledge/vat-principles.md +85 -0
- package/dist/src/profiles/schema.json +201 -0
- package/dist/src/profiles/securities.json +137 -0
- package/dist/src/profiles/software-rd.json +264 -0
- package/dist/src/profiles/trading-co.json +200 -0
- package/dist/src/prompt-policy.js +386 -0
- package/dist/src/protocol.js +58 -0
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +390 -0
- package/dist/src/session-roles.js +14 -0
- package/dist/src/state.js +361 -0
- package/dist/src/task-executor.js +1023 -0
- package/dist/src/teamauto/github-client.js +210 -0
- package/dist/src/teamauto/norms.js +85 -0
- package/dist/src/teamauto/repo-sync.js +423 -0
- package/dist/src/teamauto/scanner.js +207 -0
- package/dist/src/teamauto/schedule.js +123 -0
- package/dist/src/teamauto/scheduler.js +907 -0
- package/dist/src/teamauto/store.js +133 -0
- package/dist/src/types.js +290 -0
- package/dist/src/ui/app.js +4860 -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 +447 -0
- package/dist/src/ui/style.css +2805 -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 +78 -0
- package/dist/src/worker/skill-installer.js +255 -0
- package/dist/src/worker/tools.js +541 -0
- package/dist/src/worker/worker-service.js +307 -0
- package/dist/src/workspace-browser.js +269 -0
- package/openclaw.plugin.json +28 -1
- package/package.json +3 -2
- package/src/config.ts +33 -2
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1029 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +295 -41
- package/src/controller/controller-tools.ts +11 -7
- package/src/controller/http-server.ts +294 -6971
- package/src/controller/kickoff-orchestrator.ts +70 -7
- package/src/controller/message-delivery.ts +49 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +6 -29
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +366 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- package/src/controller/repo-routes.ts +91 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +1616 -0
- package/src/controller/task-assignment.ts +618 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +356 -0
- package/src/controller/task-results.ts +544 -0
- package/src/controller/task-router.ts +98 -6
- package/src/controller/task-routes.ts +812 -0
- package/src/controller/teamauto-routes.ts +121 -0
- package/src/controller/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +13 -1
- package/src/controller/worker-provisioning.ts +32 -4
- package/src/controller/worker-routes.ts +241 -0
- package/src/identity.ts +3 -2
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +650 -0
- package/src/profiles/banking.json +178 -0
- package/src/profiles/crossborder-ecom.json +253 -0
- package/src/profiles/insurance.json +157 -0
- package/src/profiles/knowledge/hs-structure.md +97 -0
- package/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/src/profiles/knowledge/vat-principles.md +85 -0
- package/src/profiles/schema.json +201 -0
- package/src/profiles/securities.json +137 -0
- package/src/profiles/software-rd.json +264 -0
- package/src/profiles/trading-co.json +200 -0
- package/src/prompt-policy.ts +27 -13
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- package/src/state.ts +236 -9
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +21 -0
- package/src/teamauto/repo-sync.ts +246 -6
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +259 -16
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +133 -16
- package/src/ui/app.js +592 -24
- package/src/ui/index.html +44 -11
- package/src/ui/style.css +194 -0
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +3 -1
- package/src/worker/worker-service.ts +83 -3
|
@@ -0,0 +1,423 @@
|
|
|
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
|
+
// ---------- in-use sentinel (#173 follow-up 2) ----------
|
|
148
|
+
// The lock lives in the per-worktree git ADMIN dir, never inside the worktree
|
|
149
|
+
// tree: a file in the tree would dirty `git status --porcelain` and wedge the
|
|
150
|
+
// GC dirty guard. The admin dir is removed together with the worktree.
|
|
151
|
+
const TASK_LOCK_NAME = "teamclaw-task-lock.json";
|
|
152
|
+
async function taskLockPath(wtPath) {
|
|
153
|
+
try {
|
|
154
|
+
const out = (await run(["rev-parse", "--git-dir"], wtPath)).trim();
|
|
155
|
+
return path.join(path.resolve(wtPath, out), TASK_LOCK_NAME);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function processAlive(pid) {
|
|
162
|
+
try {
|
|
163
|
+
process.kill(pid, 0);
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
catch (err) {
|
|
167
|
+
// EPERM: alive but owned by another user - treat as in use.
|
|
168
|
+
return err.code === "EPERM";
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
async function writeTaskLock(wtPath) {
|
|
172
|
+
const lockPath = await taskLockPath(wtPath);
|
|
173
|
+
if (!lockPath) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
await fs.writeFile(lockPath, JSON.stringify({ pid: process.pid, at: Date.now() })).catch(() => undefined);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Live foreign controller holding this worktree, or null. Covers two
|
|
180
|
+
* controllers sharing one projects/ tree: whoever created/resumed the
|
|
181
|
+
* worktree last recorded its pid; GC (a different live pid) must not rip the
|
|
182
|
+
* tree out from under it. Our OWN pid never blocks (we are the GC). An
|
|
183
|
+
* orphaned worker process is not visible from the controller - the dirty
|
|
184
|
+
* guard remains that case's backstop (fails toward keep).
|
|
185
|
+
*/
|
|
186
|
+
async function worktreeInUseBy(wtPath) {
|
|
187
|
+
const lockPath = await taskLockPath(wtPath);
|
|
188
|
+
if (!lockPath) {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
const lock = JSON.parse(await fs.readFile(lockPath, "utf8"));
|
|
193
|
+
const pid = Number(lock.pid);
|
|
194
|
+
if (Number.isInteger(pid) && pid > 0 && pid !== process.pid && processAlive(pid)) {
|
|
195
|
+
return pid;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// missing/corrupt lock - cannot prove in-use; proceed.
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Collaboration contract: write tasks execute in a dedicated git worktree
|
|
205
|
+
* branched from HEAD. Reuses an existing worktree (resume-safe) so the
|
|
206
|
+
* checkpoint/retry path lands in the same tree.
|
|
207
|
+
*/
|
|
208
|
+
async function ensureTaskWorktree(repoId, taskId) {
|
|
209
|
+
const base = await repoDir(repoId);
|
|
210
|
+
const wtName = taskWorktreeDirName(repoId, taskId);
|
|
211
|
+
// wtName carries the teamauto/ level for the REL path; the physical dir is
|
|
212
|
+
// a SIBLING of the base checkout (path.join would nest teamauto/ twice).
|
|
213
|
+
const wtPath = path.join(path.dirname(base), path.basename(wtName));
|
|
214
|
+
if (!(await fs.access(path.join(wtPath, ".git")).then(() => true, () => false))) {
|
|
215
|
+
await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
|
|
216
|
+
logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
|
|
217
|
+
}
|
|
218
|
+
// Refresh the in-use sentinel on create AND resume (#173 follow-up 2).
|
|
219
|
+
await writeTaskLock(wtPath);
|
|
220
|
+
return wtPath;
|
|
221
|
+
}
|
|
222
|
+
/** Remove a task worktree and its local branch (terminal cleanup). */
|
|
223
|
+
async function removeTaskWorktree(repoId, taskId) {
|
|
224
|
+
const base = await repoDir(repoId);
|
|
225
|
+
const wtName = taskWorktreeDirName(repoId, taskId);
|
|
226
|
+
const wtPath = path.join(path.dirname(base), path.basename(wtName));
|
|
227
|
+
try {
|
|
228
|
+
if (await fs.access(wtPath).then(() => true, () => false)) {
|
|
229
|
+
await run(["worktree", "remove", "--force", wtPath], base).catch(async () => {
|
|
230
|
+
// Not a registered worktree anymore (stale admin dir / manual mv):
|
|
231
|
+
// prune registrations and delete the directory directly.
|
|
232
|
+
await run(["worktree", "prune"], base).catch(() => undefined);
|
|
233
|
+
await fs.rm(wtPath, { recursive: true, force: true });
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
await run(["branch", "-D", taskBranchName(taskId)], base).catch(() => undefined);
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
logger.warn(`TeamAuto: worktree cleanup failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Terminal-state removal with a delivery-safety check: delete the task
|
|
244
|
+
* worktree only when its work is either already on the remote (branch tip
|
|
245
|
+
* matches) or nonexistent (no commits of its own). Undelivered local work
|
|
246
|
+
* is retained and reported - never silently destroyed.
|
|
247
|
+
*/
|
|
248
|
+
async function safeRemoveTaskWorktree(repoId, taskId, deliveryOracle) {
|
|
249
|
+
const base = await repoDir(repoId);
|
|
250
|
+
const wtName = taskWorktreeDirName(repoId, taskId);
|
|
251
|
+
const wtPath = path.join(path.dirname(base), path.basename(wtName));
|
|
252
|
+
const branch = taskBranchName(taskId);
|
|
253
|
+
if (!(await fs.access(wtPath).then(() => true, () => false))) {
|
|
254
|
+
// Review F4: the dir is gone but a stale local branch can survive an
|
|
255
|
+
// earlier removal whose branch -D failed. Reap it when the remote tip
|
|
256
|
+
// still matches (work provably on the remote); otherwise leave it.
|
|
257
|
+
try {
|
|
258
|
+
const refs = await run(["ls-remote", "origin", `refs/heads/${branch}`], base);
|
|
259
|
+
const remoteTip = refs.split("\t")[0]?.trim() ?? "";
|
|
260
|
+
const localTip = remoteTip ? (await run(["rev-parse", branch], base).catch(() => "")).trim() : "";
|
|
261
|
+
if (remoteTip && localTip === remoteTip) {
|
|
262
|
+
await run(["branch", "-D", branch], base);
|
|
263
|
+
return { removed: true, reason: "worktree already gone; reaped stale branch (tip matches remote)" };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch { /* conservative: leave the branch */ }
|
|
267
|
+
return { removed: false, reason: "already gone" };
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
// #173 follow-up 2: in-use sentinel - a live foreign controller recorded
|
|
271
|
+
// in the task lock owns this tree; never remove under it.
|
|
272
|
+
const inUsePid = await worktreeInUseBy(wtPath);
|
|
273
|
+
if (inUsePid !== null) {
|
|
274
|
+
return { removed: false, reason: `retained: in use by live process (pid ${inUsePid})` };
|
|
275
|
+
}
|
|
276
|
+
// #173 follow-up 1: the dirty guard must cover BOTH removal paths. The
|
|
277
|
+
// tip-match branch used to remove without any dirty check, silently
|
|
278
|
+
// destroying post-delivery worker edits (small window, but real).
|
|
279
|
+
const dirty = await run(["status", "--porcelain"], wtPath).catch(() => "x");
|
|
280
|
+
if (dirty.trim()) {
|
|
281
|
+
return { removed: false, reason: "retained: dirty worktree (uncommitted changes)" };
|
|
282
|
+
}
|
|
283
|
+
const remoteRefs = await run(["ls-remote", "origin", `refs/heads/${branch}`], base);
|
|
284
|
+
const remoteTip = remoteRefs.split("\t")[0]?.trim() ?? "";
|
|
285
|
+
if (remoteTip) {
|
|
286
|
+
const localTip = (await run(["rev-parse", branch], base).catch(() => "")).trim();
|
|
287
|
+
if (localTip && localTip === remoteTip) {
|
|
288
|
+
await removeTaskWorktree(repoId, taskId);
|
|
289
|
+
return { removed: true, reason: "delivered (branch tip on remote)" };
|
|
290
|
+
}
|
|
291
|
+
return { removed: false, reason: "retained: local branch ahead of pushed tip (unpushed work)" };
|
|
292
|
+
}
|
|
293
|
+
// Branch never pushed (or deleted post-merge): the worktree is the only
|
|
294
|
+
// copy. Keep it when it carries its own commits; drop it when the worker
|
|
295
|
+
// never committed anything at all.
|
|
296
|
+
const info = await run(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).catch(() => "");
|
|
297
|
+
const defaultBranch = info.trim().replace(/^origin\//, "") || "main";
|
|
298
|
+
const own = await run(["rev-list", "--count", `HEAD`, "--not", `origin/${defaultBranch}`], wtPath).catch(() => null);
|
|
299
|
+
if (own === null) {
|
|
300
|
+
// Cannot prove emptiness (fetch state unknown) - conservative keep.
|
|
301
|
+
return { removed: false, reason: "retained: could not verify emptiness" };
|
|
302
|
+
}
|
|
303
|
+
if (Number(own.trim()) === 0) {
|
|
304
|
+
await removeTaskWorktree(repoId, taskId);
|
|
305
|
+
return { removed: true, reason: "no own commits, branch never pushed" };
|
|
306
|
+
}
|
|
307
|
+
// #173 follow-up 5: squash-merge + branch deletion re-leak. own > 0 with
|
|
308
|
+
// an empty ls-remote is ALSO the shape of a delivered-via-squash PR whose
|
|
309
|
+
// branch was auto-deleted (shas unreachable, content merged). Ask the
|
|
310
|
+
// oracle for positive proof (merged PR with exactly this head tip);
|
|
311
|
+
// anything less retains the worktree.
|
|
312
|
+
if (deliveryOracle) {
|
|
313
|
+
const headTip = (await run(["rev-parse", "HEAD"], wtPath).catch(() => "")).trim();
|
|
314
|
+
if (headTip && (await deliveryOracle(repoId, taskId, headTip).catch(() => false))) {
|
|
315
|
+
await removeTaskWorktree(repoId, taskId);
|
|
316
|
+
return { removed: true, reason: "delivered via merged PR (squash-merge, head tip matches)" };
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return { removed: false, reason: `retained: ${own.trim()} unpushed own commit(s)` };
|
|
320
|
+
}
|
|
321
|
+
catch (err) {
|
|
322
|
+
return { removed: false, reason: `retained: gc check failed (${err instanceof Error ? err.message : String(err)})` };
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Reconcile leftover task worktrees on disk: for every `<slug>__task-*`
|
|
327
|
+
* sibling whose task is terminal (or unknown), apply the delivery-safety
|
|
328
|
+
* removal. Heals the historical backlog that pre-dates terminal cleanup.
|
|
329
|
+
*/
|
|
330
|
+
async function gcTaskWorktrees(repoId, isTerminal, deliveryOracle) {
|
|
331
|
+
const base = await repoDir(repoId);
|
|
332
|
+
const siblings = path.dirname(base);
|
|
333
|
+
// taskWorktreeDirName(repoId, "x") = "teamauto/<slug>__task-x"; the
|
|
334
|
+
// physical dir is its basename, so the scan prefix is basename minus "x".
|
|
335
|
+
const withSentinel = path.basename(taskWorktreeDirName(repoId, "x"));
|
|
336
|
+
const prefix = withSentinel.slice(0, withSentinel.length - 1);
|
|
337
|
+
const removed = [];
|
|
338
|
+
const retained = [];
|
|
339
|
+
let stale = 0;
|
|
340
|
+
const apply = async (taskId) => {
|
|
341
|
+
const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle);
|
|
342
|
+
if (r.removed) {
|
|
343
|
+
removed.push(taskId);
|
|
344
|
+
logger.warn(`TeamAuto: worktree GC removed ${taskId} (${r.reason})`);
|
|
345
|
+
}
|
|
346
|
+
else if (r.reason.includes("already gone")) {
|
|
347
|
+
// #173 QA finding: dir already gone but a stale local branch survives
|
|
348
|
+
// (squash-merge leak face) - previously invisible in both the log and
|
|
349
|
+
// the activity line. Counted + logged now.
|
|
350
|
+
stale += 1;
|
|
351
|
+
logger.warn(`TeamAuto: worktree GC ${taskId}: worktree already gone (stale branch may remain)`);
|
|
352
|
+
}
|
|
353
|
+
else {
|
|
354
|
+
retained.push({ taskId, reason: r.reason });
|
|
355
|
+
logger.warn(`TeamAuto: worktree GC kept ${taskId}: ${r.reason}`);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
let entries = [];
|
|
359
|
+
try {
|
|
360
|
+
entries = (await fs.readdir(siblings)).filter((e) => e.startsWith(prefix));
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
entries = [];
|
|
364
|
+
}
|
|
365
|
+
const dirTaskIds = [];
|
|
366
|
+
for (const entry of entries) {
|
|
367
|
+
const taskId = entry.slice(prefix.length);
|
|
368
|
+
if (!taskId)
|
|
369
|
+
continue;
|
|
370
|
+
dirTaskIds.push(taskId);
|
|
371
|
+
if (!isTerminal(taskId))
|
|
372
|
+
continue; // active/resumable task - worktree is resume state
|
|
373
|
+
await apply(taskId);
|
|
374
|
+
}
|
|
375
|
+
// #173 QA finding: BRANCH-ONLY leaks - the worktree dir is already gone
|
|
376
|
+
// but the local teamclaw/task-* branch survives (e.g. an earlier removal
|
|
377
|
+
// whose branch -D failed, or the squash-merge stale-branch face). The
|
|
378
|
+
// directory enumeration above never sees them; enumerate the branches too
|
|
379
|
+
// so safeRemoveTaskWorktree can reap (tip on remote) or at least surface
|
|
380
|
+
// them in the stale count instead of leaking silently forever.
|
|
381
|
+
const branchPrefix = `${TEAMCLAW_BRANCH_PREFIX}task-`;
|
|
382
|
+
let branchRefs = [];
|
|
383
|
+
try {
|
|
384
|
+
branchRefs = (await run(["for-each-ref", "--format=%(refname:short)", `refs/heads/${branchPrefix}*`], base))
|
|
385
|
+
.split("\n")
|
|
386
|
+
.filter(Boolean);
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
branchRefs = [];
|
|
390
|
+
}
|
|
391
|
+
const seen = new Set(dirTaskIds);
|
|
392
|
+
for (const ref of branchRefs) {
|
|
393
|
+
const taskId = ref.slice(branchPrefix.length);
|
|
394
|
+
if (!taskId || seen.has(taskId))
|
|
395
|
+
continue;
|
|
396
|
+
if (!isTerminal(taskId))
|
|
397
|
+
continue;
|
|
398
|
+
await apply(taskId);
|
|
399
|
+
}
|
|
400
|
+
return { removed, retained, stale };
|
|
401
|
+
}
|
|
402
|
+
function taskWorktreeRelDir(repoId, taskId) {
|
|
403
|
+
return taskWorktreeDirName(repoId, taskId);
|
|
404
|
+
}
|
|
405
|
+
/** True when HEAD has commits beyond the base branch (worktree delivery). */
|
|
406
|
+
async function branchHasCommits(dir, baseBranch) {
|
|
407
|
+
try {
|
|
408
|
+
const out = await run(["rev-list", "--count", "HEAD", "--not", baseBranch], dir);
|
|
409
|
+
return Number(out.trim()) > 0;
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
// Base branch name unknown/unfetched - fall back to diff against first parent chain
|
|
413
|
+
try {
|
|
414
|
+
const root = await run(["rev-list", "--max-parents=0", "HEAD"], dir);
|
|
415
|
+
return root.trim().length > 0;
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
return false;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, safeRemoveTaskWorktree, gcTaskWorktrees, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
|
|
423
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { getActiveProfile } from "../profile-loader.js";
|
|
2
|
+
/**
|
|
3
|
+
* Joint full-review section definitions: which review sections exist and
|
|
4
|
+
* what each section focuses on. The ROLE SET is derived from the ACTIVE team
|
|
5
|
+
* profile at sweep time (Phase 2.3, P1 handover debt item 4): only sections
|
|
6
|
+
* whose role id is a role of the active profile are scheduled, replacing the
|
|
7
|
+
* old hardcoded role-id literal list + closed role union. software-rd keeps
|
|
8
|
+
* all three sections, so its sweeps are unchanged; a profile that carries
|
|
9
|
+
* none of the section roles simply produces no joint full-review candidates.
|
|
10
|
+
*/
|
|
11
|
+
const JOINT_REVIEW_SECTIONS = [
|
|
12
|
+
{
|
|
13
|
+
id: "architect",
|
|
14
|
+
focus: "architecture and structure: module boundaries, layering, README/docs accuracy, maintainability hotspots, dead or duplicated code paths",
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
id: "qa",
|
|
18
|
+
focus: "quality and tests: test coverage gaps, flaky-test hotspots, error-handling weaknesses, missing failure-path tests, CI blind spots",
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
id: "security-engineer",
|
|
22
|
+
focus: "security surface: dependency risks, secret handling, injection/validation gaps, auth-sensitive paths, unsafe defaults",
|
|
23
|
+
},
|
|
24
|
+
];
|
|
25
|
+
/**
|
|
26
|
+
* Joint-review sections whose roles exist in the ACTIVE profile, in section
|
|
27
|
+
* order (one candidate per role, one shared cycle). Derived per call so a
|
|
28
|
+
* profile switch flips the joint fan-out on the next sweep.
|
|
29
|
+
*/
|
|
30
|
+
export function resolveJointReviewSections() {
|
|
31
|
+
const activeRoleIds = new Set(getActiveProfile().roles.map((role) => role.id));
|
|
32
|
+
return JOINT_REVIEW_SECTIONS.filter((section) => activeRoleIds.has(section.id));
|
|
33
|
+
}
|
|
34
|
+
function matchesAny(text, keywords) {
|
|
35
|
+
const lower = text.toLowerCase();
|
|
36
|
+
return keywords.some((k) => k.trim() && lower.includes(k.trim().toLowerCase()));
|
|
37
|
+
}
|
|
38
|
+
function labelAllowed(issue, repo) {
|
|
39
|
+
const { include, exclude } = repo.policy.labelFilter;
|
|
40
|
+
if (exclude.some((l) => issue.labels.includes(l))) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (include.length && !include.some((l) => issue.labels.includes(l))) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
function keywordAllowed(title, repo) {
|
|
49
|
+
const { include, exclude } = repo.policy.keywordFilter;
|
|
50
|
+
if (exclude.length && matchesAny(title, exclude)) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
if (include.length && !matchesAny(title, include)) {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
const TEAMCLAW_MARKER_RE = /\[teamclaw(?::\w+)?\]/i;
|
|
59
|
+
function truncate(text, max) {
|
|
60
|
+
return text.length > max ? text.slice(0, max) + "..." : text;
|
|
61
|
+
}
|
|
62
|
+
export async function sweepRepo(repo, client, now = Date.now()) {
|
|
63
|
+
const [owner, name] = repo.id.split("/");
|
|
64
|
+
const issues = await client.listIssues(owner, name, repo.cursors.lastIssueSince, repo.cursors.etags);
|
|
65
|
+
const pulls = repo.policy.actions.prReview
|
|
66
|
+
? await client.listPulls(owner, name, repo.cursors.etags)
|
|
67
|
+
: [];
|
|
68
|
+
const candidates = [];
|
|
69
|
+
for (const issue of issues) {
|
|
70
|
+
// Dedup: seen map survives sweeps; a closed-then-reopened issue updates.
|
|
71
|
+
const key = `${repo.id}#issue-${issue.number}`;
|
|
72
|
+
const updatedAtMs = Date.parse(issue.updatedAt) || 0;
|
|
73
|
+
if ((repo.cursors.seen[key] ?? 0) >= updatedAtMs) {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
// NOTE: no first-sweep gate here. Gating candidates on "first sweep"
|
|
77
|
+
// combined with the dry-run not advancing cursors deadlocked repos in
|
|
78
|
+
// observe-only mode forever (zero candidates -> dryRunDone never set).
|
|
79
|
+
// Backlog protection comes from the per-sweep cap + one dry-run pass.
|
|
80
|
+
if (!labelAllowed(issue, repo) || !keywordAllowed(issue.title, repo)) {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (repo.policy.skipAssignedToHumans && issue.assignees.length > 0) {
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
// Never self-assign or review our own threads.
|
|
87
|
+
if (TEAMCLAW_MARKER_RE.test(issue.title) || TEAMCLAW_MARKER_RE.test(issue.body)) {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const base = {
|
|
91
|
+
repoId: repo.id,
|
|
92
|
+
key,
|
|
93
|
+
number: issue.number,
|
|
94
|
+
role: "qa",
|
|
95
|
+
writeMode: "read-only",
|
|
96
|
+
};
|
|
97
|
+
if (repo.policy.actions.issueReview) {
|
|
98
|
+
candidates.push({
|
|
99
|
+
...base,
|
|
100
|
+
kind: "issueReview",
|
|
101
|
+
title: truncate(`Review issue #${issue.number}: ${issue.title}`, 120),
|
|
102
|
+
reason: "new/updated issue needs triage",
|
|
103
|
+
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)}`,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
if (repo.policy.actions.takeOwnership && issue.state === "open") {
|
|
107
|
+
candidates.push({
|
|
108
|
+
...base,
|
|
109
|
+
kind: "takeOwnership",
|
|
110
|
+
role: "developer",
|
|
111
|
+
writeMode: "write",
|
|
112
|
+
title: truncate(`Take ownership of issue #${issue.number}: ${issue.title}`, 120),
|
|
113
|
+
reason: "unassigned issue eligible for autonomous ownership",
|
|
114
|
+
context: `Own and implement issue #${issue.number}: ${issue.title}\nLink: ${issue.htmlUrl}\n\nBody:\n${truncate(issue.body, 6000)}`,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
for (const pull of pulls) {
|
|
119
|
+
const key = `${repo.id}#pr-${pull.number}`;
|
|
120
|
+
const updatedAtMs = Date.parse(pull.updated_at) || 0;
|
|
121
|
+
if ((repo.cursors.seen[key] ?? 0) >= updatedAtMs) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
// See the issue-loop note: no first-sweep gate (deadlock source).
|
|
125
|
+
// Skip our own PRs and drafts.
|
|
126
|
+
if (pull.head.startsWith("teamclaw/") || pull.draft || TEAMCLAW_MARKER_RE.test(pull.title)) {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (repo.policy.actions.prReview) {
|
|
130
|
+
candidates.push({
|
|
131
|
+
repoId: repo.id,
|
|
132
|
+
key,
|
|
133
|
+
kind: "prReview",
|
|
134
|
+
number: pull.number,
|
|
135
|
+
role: "qa",
|
|
136
|
+
writeMode: "read-only",
|
|
137
|
+
title: truncate(`Review PR #${pull.number}: ${pull.title}`, 120),
|
|
138
|
+
reason: "new/updated pull request needs review",
|
|
139
|
+
context: `PR #${pull.number} by @${pull.user} (head: ${pull.head})\nLink: ${pull.htmlUrl}\n\nDescription:\n${truncate(pull.body, 4000)}`,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// Periodic full review (weekly/daily), independent of per-object cursors.
|
|
144
|
+
if (repo.policy.actions.fullReview !== "off") {
|
|
145
|
+
const intervalMs = repo.policy.actions.fullReview === "daily" ? 24 * 3600_000 : 7 * 24 * 3600_000;
|
|
146
|
+
// Interval-gated only (the old !firstSweep gate could never open for a
|
|
147
|
+
// repo whose first sweep observed nothing - see the deadlock note above).
|
|
148
|
+
if (now - repo.cursors.lastFullReviewAt >= intervalMs) {
|
|
149
|
+
const cycle = Math.floor(now / intervalMs);
|
|
150
|
+
// Joint review: one candidate per section role of the ACTIVE profile,
|
|
151
|
+
// one shared cycle. Each role's reply becomes a labeled section of a
|
|
152
|
+
// single umbrella review issue (the write-back reconciler groups by
|
|
153
|
+
// the cycle key).
|
|
154
|
+
for (const section of resolveJointReviewSections()) {
|
|
155
|
+
const role = section.id;
|
|
156
|
+
candidates.push({
|
|
157
|
+
repoId: repo.id,
|
|
158
|
+
key: `${repo.id}#fullreview-${cycle}-${role}`,
|
|
159
|
+
kind: "fullReview",
|
|
160
|
+
number: 0,
|
|
161
|
+
role,
|
|
162
|
+
writeMode: "read-only",
|
|
163
|
+
cycle,
|
|
164
|
+
title: `Full repository review (${role}): ${repo.id}`,
|
|
165
|
+
reason: `scheduled ${repo.policy.actions.fullReview} full review (joint, ${role} section)`,
|
|
166
|
+
context: [
|
|
167
|
+
`Perform the ${role} section of a joint full-repository review of ${repo.id}.`,
|
|
168
|
+
`Your focus: ${section.focus}.`,
|
|
169
|
+
"Other roles cover complementary areas in parallel - do NOT duplicate their scope; go deep on yours.",
|
|
170
|
+
"Your reply becomes the " + role + " section of the joint review issue on GitHub. Do not change code.",
|
|
171
|
+
].join("\n"),
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls };
|
|
177
|
+
}
|
|
178
|
+
/** Advance cursors after tasks were enqueued (or observed on first sweep). */
|
|
179
|
+
export function advanceCursors(repo, issues, pulls, now = Date.now()) {
|
|
180
|
+
for (const issue of issues) {
|
|
181
|
+
repo.cursors.seen[`${repo.id}#issue-${issue.number}`] = Date.parse(issue.updatedAt) || now;
|
|
182
|
+
}
|
|
183
|
+
for (const pull of pulls) {
|
|
184
|
+
repo.cursors.seen[`${repo.id}#pr-${pull.number}`] = Date.parse(pull.updated_at) || now;
|
|
185
|
+
}
|
|
186
|
+
// Cap the seen map so it cannot grow unbounded.
|
|
187
|
+
const entries = Object.entries(repo.cursors.seen);
|
|
188
|
+
if (entries.length > 2000) {
|
|
189
|
+
entries.sort((a, b) => a[1] - b[1]);
|
|
190
|
+
for (const [key] of entries.slice(0, entries.length - 2000)) {
|
|
191
|
+
delete repo.cursors.seen[key];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// `since` cursors track the newest observed object time, never the sweep's
|
|
195
|
+
// wall clock - objects updated between fetch and save must not fall behind
|
|
196
|
+
// the cursor forever.
|
|
197
|
+
let maxIssueUpdated = 0;
|
|
198
|
+
let maxPullUpdated = 0;
|
|
199
|
+
for (const issue of issues) {
|
|
200
|
+
maxIssueUpdated = Math.max(maxIssueUpdated, Date.parse(issue.updatedAt) || now);
|
|
201
|
+
}
|
|
202
|
+
for (const pull of pulls) {
|
|
203
|
+
maxPullUpdated = Math.max(maxPullUpdated, Date.parse(pull.updated_at) || now);
|
|
204
|
+
}
|
|
205
|
+
repo.cursors.lastIssueSince = Math.max(repo.cursors.lastIssueSince, maxIssueUpdated);
|
|
206
|
+
repo.cursors.lastPrSince = Math.max(repo.cursors.lastPrSince, maxPullUpdated);
|
|
207
|
+
}
|