@teamclaws/teamclaw 2026.11.6 → 2026.11.7
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 +17 -11
- package/dist/src/config.js +3 -3
- package/dist/src/controller/http-server.js +2 -2
- package/dist/src/controller/managed-gateway-process.js +17 -1
- package/dist/src/controller/provisioning/process-supervisor.js +11 -0
- package/dist/src/controller/route-table.js +2 -2
- package/dist/src/controller/security.js +30 -15
- package/dist/src/controller/task-assignment.js +62 -1
- package/dist/src/controller/task-routes.js +39 -2
- package/dist/src/controller/tunnel-manager.js +11 -0
- package/dist/src/controller/tunnel-routes.js +11 -0
- package/dist/src/controller/workspace-routes.js +16 -2
- package/dist/src/teamauto/github-client.js +19 -0
- package/dist/src/teamauto/repo-sync.js +96 -22
- package/dist/src/teamauto/scheduler.js +458 -36
- package/dist/src/teamauto/store.js +125 -3
- package/dist/src/types.js +5 -3
- package/dist/src/ui/app.js +2 -2
- package/dist/src/worker/worker-service.js +13 -1
- package/dist/src/workspace-browser.js +14 -0
- package/openclaw.plugin.json +5 -5
- package/package.json +4 -2
- package/src/config.ts +3 -3
- package/src/controller/http-server.ts +2 -2
- package/src/controller/managed-gateway-process.ts +17 -1
- package/src/controller/provisioning/process-supervisor.ts +11 -0
- package/src/controller/route-table.ts +2 -2
- package/src/controller/security.ts +30 -15
- package/src/controller/task-assignment.ts +58 -1
- package/src/controller/task-routes.ts +39 -1
- package/src/controller/tunnel-manager.ts +12 -1
- package/src/controller/tunnel-routes.ts +11 -0
- package/src/controller/workspace-routes.ts +17 -2
- package/src/teamauto/github-client.ts +21 -1
- package/src/teamauto/repo-sync.ts +85 -21
- package/src/teamauto/scheduler.ts +434 -33
- package/src/teamauto/store.ts +133 -3
- package/src/types.ts +9 -7
- package/src/ui/app.js +2 -2
- package/src/worker/worker-service.ts +15 -1
- package/src/workspace-browser.ts +15 -0
|
@@ -69,6 +69,7 @@ import {
|
|
|
69
69
|
} from "./controller-planning.js";
|
|
70
70
|
import {
|
|
71
71
|
ControllerIntakeSwitchInProgressError,
|
|
72
|
+
isStillWaitingResponse,
|
|
72
73
|
runControllerIntake,
|
|
73
74
|
} from "./controller-intake.js";
|
|
74
75
|
import {
|
|
@@ -579,7 +580,7 @@ export async function handleTaskResultRequest(deps: ControllerTaskDomainDeps, re
|
|
|
579
580
|
const { logger, getTeamState, updateTeamState } = deps;
|
|
580
581
|
const taskId = pathname.split("/")[4]!;
|
|
581
582
|
const body = await parseJsonBody(req);
|
|
582
|
-
|
|
583
|
+
let result = typeof body.result === "string" ? body.result : "";
|
|
583
584
|
let error = typeof body.error === "string" ? body.error : undefined;
|
|
584
585
|
const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
|
|
585
586
|
const currentTask = getTeamState()?.tasks[taskId];
|
|
@@ -668,6 +669,43 @@ export async function handleTaskResultRequest(deps: ControllerTaskDomainDeps, re
|
|
|
668
669
|
}
|
|
669
670
|
|
|
670
671
|
const gatedTask = getTeamState()?.tasks[taskId];
|
|
672
|
+
// #5767 fourth hole: a worker that never produced work can "complete" by
|
|
673
|
+
// submitting the waiting SENTINEL as its result (live: f12efcdb completed
|
|
674
|
+
// with `TEAMCLAW_STILL_WAITING`). The sentinel means "not done yet" - it
|
|
675
|
+
// must never satisfy completion. Reject with an empty stored result so the
|
|
676
|
+
// failed-without-result semantics apply (terminal write-back, claim
|
|
677
|
+
// recovery re-opens the issue, the next sweep retries).
|
|
678
|
+
if (!error && gatedTask && isStillWaitingResponse(result)) {
|
|
679
|
+
error = "Task submitted the TEAMCLAW_STILL_WAITING placeholder as its result - the task is still waiting, not complete. Result discarded; the issue will be re-opened for the next sweep.";
|
|
680
|
+
recordTaskExecutionEvent(taskId, {
|
|
681
|
+
type: "warning",
|
|
682
|
+
phase: "completion_gate",
|
|
683
|
+
source: "controller",
|
|
684
|
+
status: "failed",
|
|
685
|
+
message: error,
|
|
686
|
+
workerId,
|
|
687
|
+
role: gatedTask.assignedRole,
|
|
688
|
+
}, deps);
|
|
689
|
+
result = "";
|
|
690
|
+
}
|
|
691
|
+
// #5770 leg A: a MID-FLIGHT narration is not a final result either (live:
|
|
692
|
+
// "Tree is clean. Now implementing the fix - first the helper in ...").
|
|
693
|
+
// Present-progressive openers mean the work has NOT finished; accepting
|
|
694
|
+
// them completes a task with zero product. Reject like the sentinel -
|
|
695
|
+
// fresh attempt on the next sweep once the worker actually finishes.
|
|
696
|
+
if (!error && gatedTask && /\b(?:now|currently|next)\s+(?:implementing|working on|fixing|writing|adding|refactoring|investigating|starting)\b/i.test(result.slice(0, 400))) {
|
|
697
|
+
error = "Task submitted a mid-flight narration (present-progressive) as its result - the work is still in progress, not complete. Result discarded; the issue will be re-opened for the next sweep.";
|
|
698
|
+
recordTaskExecutionEvent(taskId, {
|
|
699
|
+
type: "warning",
|
|
700
|
+
phase: "completion_gate",
|
|
701
|
+
source: "controller",
|
|
702
|
+
status: "failed",
|
|
703
|
+
message: error,
|
|
704
|
+
workerId,
|
|
705
|
+
role: gatedTask.assignedRole,
|
|
706
|
+
}, deps);
|
|
707
|
+
result = "";
|
|
708
|
+
}
|
|
671
709
|
if (
|
|
672
710
|
!error
|
|
673
711
|
&& gatedTask
|
|
@@ -193,7 +193,7 @@ function gateCookieValue(gateToken: string, tunnelId: string): string {
|
|
|
193
193
|
return createHash("sha256").update(`${gateToken}:${tunnelId}`).digest("hex").slice(0, 32);
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
-
export function createTunnelManager(deps: { logger: PluginLogger; localPort: number }) {
|
|
196
|
+
export function createTunnelManager(deps: { logger: PluginLogger; localPort: number; isProtectionOn?: () => boolean }) {
|
|
197
197
|
const { logger } = deps;
|
|
198
198
|
let child: ChildProcess | null = null;
|
|
199
199
|
let handle: TunnelHandle | null = null;
|
|
@@ -470,6 +470,17 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
|
|
|
470
470
|
if (handle) return handle;
|
|
471
471
|
const st = readTunnelState();
|
|
472
472
|
if (!st || st.tunnelId === "quick") return null; // one-off, not recoverable
|
|
473
|
+
// ClawHub security review 2026.11.6 (finding 4): a self-hosted tunnel's
|
|
474
|
+
// custom hostname never matches the built-in gate suffixes, so its
|
|
475
|
+
// traffic arrives as a loopback peer and inherits trusted-host access.
|
|
476
|
+
// Device protection is the only thing standing between that public
|
|
477
|
+
// ingress and the API - do not reconnect one while protection is off;
|
|
478
|
+
// drop the stale state so the owner re-enables deliberately.
|
|
479
|
+
if (st.tunnelId === "self-hosted" && deps.isProtectionOn && !deps.isProtectionOn()) {
|
|
480
|
+
logger.warn("TeamClaw tunnel: NOT recovering the previous self-hosted tunnel - device protection is off and a custom-domain tunnel bypasses the sharing gate; enable device pairing (POST /api/v1/security/enable) and start it again from the Tunnel page");
|
|
481
|
+
clearTunnelState();
|
|
482
|
+
return null;
|
|
483
|
+
}
|
|
473
484
|
const bin = findCloudflared();
|
|
474
485
|
if (!bin) {
|
|
475
486
|
logger.warn("TeamClaw tunnel: previous share found but cloudflared is not installed; not recovering");
|
|
@@ -194,6 +194,17 @@ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps:
|
|
|
194
194
|
if (!tunnelStartAllowedFrom(req, res)) {
|
|
195
195
|
return;
|
|
196
196
|
}
|
|
197
|
+
// ClawHub security review 2026.11.6 (finding 4): a self-hosted
|
|
198
|
+
// tunnel's custom hostname is outside the built-in gate, so its
|
|
199
|
+
// requests arrive as trusted loopback peers. Without device
|
|
200
|
+
// protection that is unauthenticated public access to the API.
|
|
201
|
+
if (!isProtectionOn(deps.getTeamState())) {
|
|
202
|
+
sendJson(res, 409, {
|
|
203
|
+
error: "device protection must be enabled before starting a self-hosted tunnel",
|
|
204
|
+
hint: "A custom-domain tunnel bypasses the sharing gate (its hostname is not *.teamclaw.dev), so every request reaches this controller as a trusted local peer. Enable device pairing first (POST /api/v1/security/enable from the controller host), then start the tunnel. Managed (*.teamclaw.dev) tunnels are gate-protected and unaffected.",
|
|
205
|
+
});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
197
208
|
logger.info(`TeamClaw tunnel: start-self-hosted requested (${tunnelCaller(req)})`);
|
|
198
209
|
let token = "";
|
|
199
210
|
try {
|
|
@@ -29,6 +29,9 @@ function workspaceRequestErrorMessage(err: unknown): string {
|
|
|
29
29
|
return err instanceof Error ? err.message : "Workspace request failed";
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
// Active content the raw route must sandbox on direct navigation (finding 6).
|
|
33
|
+
const ACTIVE_CONTENT_TYPES = new Set(["text/html; charset=utf-8", "image/svg+xml"]);
|
|
34
|
+
|
|
32
35
|
function workspaceStatusRoute(ctx: RouteContext): void {
|
|
33
36
|
const { res } = ctx;
|
|
34
37
|
sendJson(res, 200, {
|
|
@@ -193,7 +196,15 @@ async function workspaceRawFileRoute(ctx: RouteContext): Promise<void> {
|
|
|
193
196
|
try {
|
|
194
197
|
const relativePath = decodeURIComponent(rawPathname);
|
|
195
198
|
const file = await readWorkspaceRawFile(relativePath);
|
|
196
|
-
|
|
199
|
+
// ClawHub security review 2026.11.6 (finding 6): HTML/SVG served with
|
|
200
|
+
// their active MIME type under the controller origin execute with the
|
|
201
|
+
// owner's session on DIRECT navigation (the preview iframe's sandbox
|
|
202
|
+
// attribute does not travel with the "Open Raw" link). A response-level
|
|
203
|
+
// CSP sandbox without allow-same-origin gives the document an opaque
|
|
204
|
+
// origin even on top-level navigation: scripts may run (the preview
|
|
205
|
+
// already allows that) but cannot read controller cookies or call
|
|
206
|
+
// /api/v1/* same-origin. Mirrors the iframe flags byte for byte.
|
|
207
|
+
const headers: Record<string, string> = {
|
|
197
208
|
"Content-Type": file.contentType,
|
|
198
209
|
"Cache-Control": "no-store",
|
|
199
210
|
// Issue #23 security review follow-up: honor a CORS origin the
|
|
@@ -202,7 +213,11 @@ async function workspaceRawFileRoute(ctx: RouteContext): Promise<void> {
|
|
|
202
213
|
// historical "*" byte for byte (shared helper, see protocol.ts).
|
|
203
214
|
"Access-Control-Allow-Origin": pinnedCorsAllowOrigin(res),
|
|
204
215
|
"X-Content-Type-Options": "nosniff",
|
|
205
|
-
}
|
|
216
|
+
};
|
|
217
|
+
if (ACTIVE_CONTENT_TYPES.has(file.contentType)) {
|
|
218
|
+
headers["Content-Security-Policy"] = "sandbox allow-scripts allow-forms";
|
|
219
|
+
}
|
|
220
|
+
res.writeHead(200, headers);
|
|
206
221
|
res.end(file.content);
|
|
207
222
|
} catch (err) {
|
|
208
223
|
sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
|
|
@@ -215,6 +215,25 @@ export function createGithubClient(auth: GithubAuthManager) {
|
|
|
215
215
|
});
|
|
216
216
|
},
|
|
217
217
|
|
|
218
|
+
/** #5785: PRs (any state) whose head is exactly this branch - the
|
|
219
|
+
* PR-face evidence surface. The settle audit asks "did this WRITE task's
|
|
220
|
+
* PR ever come into existence", which no comment surface can answer (an
|
|
221
|
+
* issue direct-post masks the missing PR). Mirrors the sentinel's
|
|
222
|
+
* pulls?head= REST probe. */
|
|
223
|
+
async listPullsByHead(owner: string, repo: string, branch: string): Promise<Array<{ number: number; state: string; htmlUrl: string }>> {
|
|
224
|
+
const { data } = await request("GET", `/repos/${owner}/${repo}/pulls?head=${encodeURIComponent(`${owner}:${branch}`)}&state=all&per_page=10`);
|
|
225
|
+
if (!Array.isArray(data)) {
|
|
226
|
+
return [];
|
|
227
|
+
}
|
|
228
|
+
return (data as Record<string, unknown>[])
|
|
229
|
+
.map((raw) => ({
|
|
230
|
+
number: Number(raw.number ?? 0),
|
|
231
|
+
state: String(raw.state ?? ""),
|
|
232
|
+
htmlUrl: String(raw.html_url ?? ""),
|
|
233
|
+
}))
|
|
234
|
+
.filter((p) => p.number > 0);
|
|
235
|
+
},
|
|
236
|
+
|
|
218
237
|
async listCommits(owner: string, repo: string, sinceSha: string): Promise<{ sha: string; message: string }[]> {
|
|
219
238
|
const suffix = sinceSha ? `?sha=${encodeURIComponent(sinceSha)}` : "?per_page=20";
|
|
220
239
|
void suffix;
|
|
@@ -297,13 +316,14 @@ export function createGithubClient(auth: GithubAuthManager) {
|
|
|
297
316
|
|
|
298
317
|
/** #claim-dequeue: comments on an issue since a timestamp, for the
|
|
299
318
|
* dequeue-time external-collaboration check (authors + times only). */
|
|
300
|
-
async getIssueCommentsSince(owner: string, repo: string, issueNumber: number, sinceIso: string): Promise<Array<{ user: string; createdAt: string }>> {
|
|
319
|
+
async getIssueCommentsSince(owner: string, repo: string, issueNumber: number, sinceIso: string): Promise<Array<{ user: string; createdAt: string; body: string }>> {
|
|
301
320
|
try {
|
|
302
321
|
const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}/comments?since=${encodeURIComponent(sinceIso)}&per_page=20`);
|
|
303
322
|
if (!Array.isArray(data)) return [];
|
|
304
323
|
return (data as Record<string, unknown>[]).map((c) => ({
|
|
305
324
|
user: String((c.user as { login?: string } | undefined)?.login ?? ""),
|
|
306
325
|
createdAt: String(c.created_at ?? ""),
|
|
326
|
+
body: String(c.body ?? ""),
|
|
307
327
|
})).filter((c) => c.user);
|
|
308
328
|
} catch {
|
|
309
329
|
return []; // listing failed - degrade to assignee check only
|
|
@@ -155,17 +155,51 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
|
|
|
155
155
|
await run(["checkout", "-B", name], dir);
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
+
/** #5815: deliverable must mean commits beyond the REMOTE base tip. A
|
|
159
|
+
* stale local baseline makes a zero-commit branch look deliverable; the
|
|
160
|
+
* PR then 422s (zero diff) deterministically six times. */
|
|
161
|
+
async function branchHasCommits(dir: string, defaultBranch?: string, cloneUrl?: string): Promise<boolean> {
|
|
162
|
+
if (!defaultBranch) return false;
|
|
163
|
+
try {
|
|
164
|
+
if (cloneUrl) {
|
|
165
|
+
const authed = await tokenizedUrl(cloneUrl);
|
|
166
|
+
await run(["fetch", authed, defaultBranch], dir).catch(() => {});
|
|
167
|
+
} else {
|
|
168
|
+
await run(["fetch", "origin", defaultBranch], dir).catch(() => {});
|
|
169
|
+
}
|
|
170
|
+
const out = await run(["rev-list", "--count", `origin/${defaultBranch}..HEAD`], dir);
|
|
171
|
+
return Number(out.trim()) > 0;
|
|
172
|
+
} catch {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** #5815: is the branch an ancestor of the remote base (zero-diff shape)? */
|
|
178
|
+
async function branchIsAncestorOfRemoteBase(dir: string, branch: string, defaultBranch: string): Promise<boolean> {
|
|
179
|
+
await run(["fetch", "origin", defaultBranch], dir).catch(() => {});
|
|
180
|
+
const head = (await run(["rev-parse", `origin/${branch}`], dir).catch(() => "")).trim();
|
|
181
|
+
const base = (await run(["rev-parse", `origin/${defaultBranch}`], dir).catch(() => "")).trim();
|
|
182
|
+
if (!head || !base) return false;
|
|
183
|
+
return run(["merge-base", "--is-ancestor", head, base], dir).then(() => true, () => false);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** #5788: does the branch exist on the remote? (422 disambiguation probe) */
|
|
187
|
+
async function branchExistsRemotely(dir: string, branch: string): Promise<boolean> {
|
|
188
|
+
const out = await run(["ls-remote", "origin", `refs/heads/${branch}`], dir).catch(() => "");
|
|
189
|
+
return out.trim().length > 0;
|
|
190
|
+
}
|
|
191
|
+
|
|
158
192
|
async function commitAll(dir: string, message: string, authorName: string, authorEmail: string): Promise<boolean> {
|
|
159
193
|
const status = await run(["status", "--porcelain"], dir);
|
|
160
194
|
if (!status.trim()) {
|
|
161
195
|
return false;
|
|
162
196
|
}
|
|
163
197
|
await run(["add", "-A"], dir);
|
|
164
|
-
await run(["-c", `user.name=${authorName}`, "-c", `user.email=${authorEmail}`, "commit", "-m", message], dir);
|
|
198
|
+
await run(["-c", `user.name=${authorName}`, "-c", `user.email=${authorEmail}`, "-c", "core.hooksPath=", "commit", "-m", message], dir);
|
|
165
199
|
return true;
|
|
166
200
|
}
|
|
167
201
|
|
|
168
|
-
async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string): Promise<{ alreadyDelivered: boolean }> {
|
|
202
|
+
async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string, onPushError?: (msg: string) => void): Promise<{ alreadyDelivered: boolean }> {
|
|
169
203
|
const authed = await tokenizedUrl(cloneUrl);
|
|
170
204
|
// #stale-base follow-up: the remote task branch may ALREADY carry the
|
|
171
205
|
// delivery (previous incarnation pushed it; the PR got merged). Blindly
|
|
@@ -187,10 +221,25 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
|
|
|
187
221
|
} catch { /* branch absent remotely or fetch failed - plain push below */ }
|
|
188
222
|
try {
|
|
189
223
|
await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
|
|
224
|
+
// #5788: verify the push LANDED - a "successful" push whose ref is
|
|
225
|
+
// missing remotely (auth edge, proxy quirk) strands the branch exactly
|
|
226
|
+
// like a failed one, and createPR would 422 on the missing head.
|
|
227
|
+
const ls = await run(["ls-remote", authed, `refs/heads/${branch}`], dir).catch(() => "");
|
|
228
|
+
const localHead = (await run(["rev-parse", "HEAD"], dir)).trim();
|
|
229
|
+
if (ls && localHead && !ls.includes(localHead)) {
|
|
230
|
+
const msg = `post-push ref verification failed: remote refs/heads/${branch} does not contain local HEAD ${localHead.slice(0, 8)}`;
|
|
231
|
+
logger.warn(`TeamAuto: ${msg}`);
|
|
232
|
+
try { onPushError?.(msg); } catch { /* observability only */ }
|
|
233
|
+
throw new Error(msg);
|
|
234
|
+
}
|
|
190
235
|
return { alreadyDelivered: false };
|
|
191
236
|
} catch (err) {
|
|
192
237
|
const msg = err instanceof Error ? err.message : String(err);
|
|
193
238
|
logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${msg}`);
|
|
239
|
+
// #5788: the push leg was the ONLY delivery step with zero activity
|
|
240
|
+
// surface - its failure only ever showed as downstream createPR 422
|
|
241
|
+
// noise (two stranded self-fix legs). Surface it via the callback.
|
|
242
|
+
try { onPushError?.(msg); } catch { /* observability only */ }
|
|
194
243
|
// #5651 (ggcode, 2026-11-15): a NON-FAST-FORWARD rejection is
|
|
195
244
|
// deterministic - the generic retry ladder burned 6 attempts / ~25min
|
|
196
245
|
// on it twice (#5268 family). The task branch is exclusively ours, so
|
|
@@ -299,13 +348,14 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
|
|
|
299
348
|
// wtName carries the teamauto/ level for the REL path; the physical dir is
|
|
300
349
|
// a SIBLING of the base checkout (path.join would nest teamauto/ twice).
|
|
301
350
|
const wtPath = path.join(path.dirname(base), path.basename(wtName));
|
|
302
|
-
|
|
351
|
+
const wtExists = await fs.access(path.join(wtPath, ".git")).then(() => true, () => false);
|
|
352
|
+
if (!wtExists) {
|
|
303
353
|
// #stale-base (user report 2026-11-14): ensureCloned (fetch + reset to
|
|
304
354
|
// the default-branch tip) only ran at BIND time (learnNorms), so the
|
|
305
355
|
// base checkout's HEAD drifted days behind origin/main and EVERY new
|
|
306
356
|
// task worktree branched from stale code. Refresh the base right
|
|
307
357
|
// before creating a new branch off it - same fetch+reset as
|
|
308
|
-
// ensureCloned.
|
|
358
|
+
// ensureCloned.
|
|
309
359
|
if (defaultBranch && cloneUrl) {
|
|
310
360
|
try {
|
|
311
361
|
const authed = await tokenizedUrl(cloneUrl);
|
|
@@ -317,6 +367,36 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
|
|
|
317
367
|
}
|
|
318
368
|
await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
|
|
319
369
|
logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
|
|
370
|
+
} else {
|
|
371
|
+
// #resume-sync (user 2026-11-18): a RESUMED task (retry / review
|
|
372
|
+
// follow-up) used to continue on the ORIGINAL base untouched - the
|
|
373
|
+
// comment above explicitly left resume paths stale. On repos that
|
|
374
|
+
// move fast, a worktree alive for hours is guaranteed behind, all
|
|
375
|
+
// retried work lands on a superseded base, and the divergence only
|
|
376
|
+
// surfaces at push (single-shot #5651 rebase self-heal or dead
|
|
377
|
+
// letter). Sync BEFORE resuming: fetch the main tree, count how far
|
|
378
|
+
// behind this branch is, rebase when behind (dirty trees via
|
|
379
|
+
// autostash). Best-effort: on any failure we continue on the current
|
|
380
|
+
// base exactly as before - delivery-time self-heal still applies.
|
|
381
|
+
try {
|
|
382
|
+
await run(["fetch", "origin", "+refs/heads/main:refs/remotes/origin/main"], base).catch(async () => {
|
|
383
|
+
const db = defaultBranch || (await run(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).then((o) => o.trim(), () => ""));
|
|
384
|
+
if (db) await run(["fetch", "origin", `+refs/heads/${db}:refs/remotes/origin/${db}`], base);
|
|
385
|
+
});
|
|
386
|
+
const behindOut = await run(["rev-list", "--count", "HEAD..origin/main"], wtPath).catch(() => "");
|
|
387
|
+
const behind = Number(behindOut.trim()) || 0;
|
|
388
|
+
if (behind > 0) {
|
|
389
|
+
logger.warn(`TeamAuto: resume-sync ${repoId}#${taskId}: branch is ${behind} commit(s) behind main - rebasing before work continues`);
|
|
390
|
+
try {
|
|
391
|
+
await run(["rebase", "--autostash", "origin/main"], wtPath);
|
|
392
|
+
} catch (rebaseErr) {
|
|
393
|
+
await run(["rebase", "--abort"], wtPath).catch(() => {});
|
|
394
|
+
logger.warn(`TeamAuto: resume-sync rebase failed for ${repoId}#${taskId} (continuing on current base; delivery-time self-heal applies): ${rebaseErr instanceof Error ? rebaseErr.message : String(rebaseErr)}`);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
} catch (err) {
|
|
398
|
+
logger.warn(`TeamAuto: resume-sync skipped for ${repoId}#${taskId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
399
|
+
}
|
|
320
400
|
}
|
|
321
401
|
// Refresh the in-use sentinel on create AND resume (#173 follow-up 2).
|
|
322
402
|
await writeTaskLock(wtPath);
|
|
@@ -533,23 +613,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
|
|
|
533
613
|
return taskWorktreeDirName(repoId, taskId);
|
|
534
614
|
}
|
|
535
615
|
|
|
536
|
-
|
|
537
|
-
async function branchHasCommits(dir: string, baseBranch: string): Promise<boolean> {
|
|
538
|
-
try {
|
|
539
|
-
const out = await run(["rev-list", "--count", "HEAD", "--not", baseBranch], dir);
|
|
540
|
-
return Number(out.trim()) > 0;
|
|
541
|
-
} catch {
|
|
542
|
-
// Base branch name unknown/unfetched - fall back to diff against first parent chain
|
|
543
|
-
try {
|
|
544
|
-
const root = await run(["rev-list", "--max-parents=0", "HEAD"], dir);
|
|
545
|
-
return root.trim().length > 0;
|
|
546
|
-
} catch {
|
|
547
|
-
return false;
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, safeRemoveTaskWorktree, gcTaskWorktrees, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
|
|
616
|
+
return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, branchExistsRemotely, branchIsAncestorOfRemoteBase, ensureTaskWorktree, removeTaskWorktree, safeRemoveTaskWorktree, gcTaskWorktrees, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
|
|
553
617
|
}
|
|
554
618
|
|
|
555
619
|
export type TeamAutoRepoSync = ReturnType<typeof createRepoSync>;
|