@teamclaws/teamclaw 2026.11.2 → 2026.11.3
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/dist/src/controller/http-server.js +18 -0
- package/dist/src/controller/journal.js +68 -0
- package/dist/src/controller/provisioning/process-supervisor.js +58 -2
- package/dist/src/controller/provisioning-config.js +53 -0
- package/dist/src/controller/route-table.js +5 -0
- package/dist/src/controller/security.js +39 -0
- package/dist/src/controller/teamauto-routes.js +12 -0
- package/dist/src/controller/tunnel-manager.js +33 -1
- package/dist/src/controller/tunnel-routes.js +17 -1
- package/dist/src/controller/websocket.js +4 -0
- package/dist/src/controller/worker-provisioning.js +36 -0
- package/dist/src/state.js +77 -1
- package/dist/src/teamauto/github-client.js +33 -0
- package/dist/src/teamauto/scanner.js +9 -1
- package/dist/src/teamauto/scheduler.js +292 -17
- package/dist/src/teamauto/store.js +9 -0
- package/dist/src/ui/app.js +44 -0
- package/dist/src/ui/index.html +15 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/src/controller/http-server.ts +18 -0
- package/src/controller/journal.ts +89 -0
- package/src/controller/provisioning/process-supervisor.ts +56 -2
- package/src/controller/provisioning-config.ts +54 -0
- package/src/controller/route-table.ts +5 -0
- package/src/controller/security.ts +40 -0
- package/src/controller/teamauto-routes.ts +12 -0
- package/src/controller/tunnel-manager.ts +34 -1
- package/src/controller/tunnel-routes.ts +18 -1
- package/src/controller/websocket.ts +5 -0
- package/src/controller/worker-provisioning.ts +34 -0
- package/src/state.ts +73 -2
- package/src/teamauto/github-client.ts +36 -0
- package/src/teamauto/scanner.ts +9 -1
- package/src/teamauto/scheduler.ts +295 -17
- package/src/teamauto/store.ts +31 -1
- package/src/ui/app.js +44 -0
- package/src/ui/index.html +15 -0
package/dist/src/state.js
CHANGED
|
@@ -209,6 +209,25 @@ async function writeFileAtomically(filePath, contents) {
|
|
|
209
209
|
// filesystems (e.g. network mounts) reject explicit chmod.
|
|
210
210
|
}
|
|
211
211
|
await fs.rename(tmpPath, filePath);
|
|
212
|
+
// #267-4 hygiene: crash/rename failures used to leave *.tmp-* siblings
|
|
213
|
+
// forever (observed: 16 residue files in the runtime dir). Best-effort
|
|
214
|
+
// sweep of same-prefix leftovers older than 1h - never throws.
|
|
215
|
+
try {
|
|
216
|
+
const dir = path.dirname(filePath);
|
|
217
|
+
const prefix = path.basename(filePath) + ".tmp-";
|
|
218
|
+
const stale = Date.now() - 3_600_000;
|
|
219
|
+
for (const name of await fs.readdir(dir)) {
|
|
220
|
+
if (!name.startsWith(prefix))
|
|
221
|
+
continue;
|
|
222
|
+
const full = path.join(dir, name);
|
|
223
|
+
const st = await fs.stat(full).catch(() => null);
|
|
224
|
+
if (st && st.mtimeMs < stale)
|
|
225
|
+
await fs.unlink(full).catch(() => { });
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
// Hygiene is best-effort: any fs failure here is silently ignored.
|
|
230
|
+
}
|
|
212
231
|
}
|
|
213
232
|
function enqueueAtomicWrite(filePath, contents) {
|
|
214
233
|
const previous = writeQueues.get(filePath) ?? Promise.resolve();
|
|
@@ -243,7 +262,6 @@ function errorMessage(error) {
|
|
|
243
262
|
return error instanceof Error ? error.message : String(error);
|
|
244
263
|
}
|
|
245
264
|
async function loadTeamState(teamName) {
|
|
246
|
-
// Review fix (Phase 1.6): the instance-scoped team-state.json is the
|
|
247
265
|
// primary state file, and when it EXISTS it is authoritative. A
|
|
248
266
|
// present-but-corrupt primary is a fatal error, never a silent fallback to
|
|
249
267
|
// the legacy snapshot - falling back would rewind the team to the
|
|
@@ -252,6 +270,12 @@ async function loadTeamState(teamName) {
|
|
|
252
270
|
let primaryRaw = null;
|
|
253
271
|
try {
|
|
254
272
|
primaryRaw = await fs.readFile(teamStateFilePath(), "utf8");
|
|
273
|
+
// #270: baseline the mtime right after reading so a foreign write between
|
|
274
|
+
// load and our first save is detected (not blindly overwritten).
|
|
275
|
+
try {
|
|
276
|
+
teamStateMtime.set(teamStateFilePath(), (await fs.stat(teamStateFilePath())).mtimeMs);
|
|
277
|
+
}
|
|
278
|
+
catch { /* stat race - next save re-baselines */ }
|
|
255
279
|
}
|
|
256
280
|
catch (error) {
|
|
257
281
|
if (!isFileMissing(error)) {
|
|
@@ -286,6 +310,41 @@ async function loadTeamState(teamName) {
|
|
|
286
310
|
return null;
|
|
287
311
|
}
|
|
288
312
|
}
|
|
313
|
+
// #270 lazy merge-on-write: last mtime this process observed for the team
|
|
314
|
+
// state file. A disk file NEWER than this stamp means another process wrote
|
|
315
|
+
// it (multi-gateway sharing one store) - the next save merges instead of
|
|
316
|
+
// blindly overwriting (which is how tasks "evaporated": 155/81 -> 135/72).
|
|
317
|
+
// Single-process cost: one stat() per save; the 24MB re-read+merge only
|
|
318
|
+
// happens when a foreign write is actually detected.
|
|
319
|
+
const teamStateMtime = new Map();
|
|
320
|
+
/** #270: fold foreign keys back in. Key-level policy - keys present in the
|
|
321
|
+
* foreign snapshot but missing from OUR in-memory state are re-added (they
|
|
322
|
+
* were created by another process and a blind full-file write would erase
|
|
323
|
+
* them). Keys we hold locally always win (this process is the most recent
|
|
324
|
+
* writer for them). Messages union by id. */
|
|
325
|
+
function mergeForeignTeamState(state, disk) {
|
|
326
|
+
const recordKeys = ["workers", "tasks", "controllerRuns", "projects", "clarifications", "previews", "reports"];
|
|
327
|
+
for (const key of recordKeys) {
|
|
328
|
+
const foreign = disk[key];
|
|
329
|
+
if (!foreign || typeof foreign !== "object")
|
|
330
|
+
continue;
|
|
331
|
+
const ours = (state[key] ?? {});
|
|
332
|
+
for (const [k, v] of Object.entries(foreign)) {
|
|
333
|
+
if (!(k in ours))
|
|
334
|
+
ours[k] = v;
|
|
335
|
+
}
|
|
336
|
+
state[key] = ours;
|
|
337
|
+
}
|
|
338
|
+
const foreignMsgs = Array.isArray(disk.messages) ? disk.messages : [];
|
|
339
|
+
if (foreignMsgs.length) {
|
|
340
|
+
const seen = new Set(state.messages.map((m) => m.id));
|
|
341
|
+
for (const m of foreignMsgs) {
|
|
342
|
+
if (m && typeof m === "object" && typeof m.id === "string" && !seen.has(m.id)) {
|
|
343
|
+
state.messages.push(m);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
289
348
|
async function saveTeamState(state) {
|
|
290
349
|
await ensureDir(STATE_DIR);
|
|
291
350
|
const filePath = teamStateFilePath();
|
|
@@ -304,7 +363,24 @@ async function saveTeamState(state) {
|
|
|
304
363
|
state.projects = state.projects && typeof state.projects === "object"
|
|
305
364
|
? state.projects
|
|
306
365
|
: {};
|
|
366
|
+
// #270: if the disk file is newer than what THIS process last observed,
|
|
367
|
+
// another gateway wrote it - fold its keys back in before overwriting.
|
|
368
|
+
try {
|
|
369
|
+
const st = await fs.stat(filePath);
|
|
370
|
+
const known = teamStateMtime.get(filePath);
|
|
371
|
+
if (known !== undefined && st.mtimeMs > known) {
|
|
372
|
+
const disk = JSON.parse(await fs.readFile(filePath, "utf8"));
|
|
373
|
+
mergeForeignTeamState(state, disk);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
/* first save / stat race - proceed with a plain write */
|
|
378
|
+
}
|
|
307
379
|
await enqueueAtomicWrite(filePath, `${JSON.stringify(state, null, 2)}\n`);
|
|
380
|
+
try {
|
|
381
|
+
teamStateMtime.set(filePath, (await fs.stat(filePath)).mtimeMs);
|
|
382
|
+
}
|
|
383
|
+
catch { /* renamed away mid-write - next save re-baselines */ }
|
|
308
384
|
}
|
|
309
385
|
// ---------------------------------------------------------------------------
|
|
310
386
|
// Team profile switch archive (Phase 2.1, design section 2.3 step 3).
|
|
@@ -15,7 +15,13 @@ export class GithubClientError extends Error {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
export function createGithubClient(auth) {
|
|
18
|
+
// #267-3: cumulative API-call counters; runSweep reads etagStats() before/
|
|
19
|
+
// after each sweep and stores the DELTA on the repo's sweep record, so the
|
|
20
|
+
// shared client still yields correct per-repo attribution (sweeps are
|
|
21
|
+
// serialized by the sweeping set).
|
|
22
|
+
const etagCounters = { calls: 0, hits: 0 };
|
|
18
23
|
async function request(method, urlPath, options = {}) {
|
|
24
|
+
etagCounters.calls += 1;
|
|
19
25
|
const headers = {
|
|
20
26
|
...(await auth.getAuthHeaders()),
|
|
21
27
|
"User-Agent": USER_AGENT,
|
|
@@ -57,6 +63,9 @@ export function createGithubClient(auth) {
|
|
|
57
63
|
const message = data?.message ?? `HTTP ${response.status}`;
|
|
58
64
|
throw new GithubClientError(message, response.status);
|
|
59
65
|
}
|
|
66
|
+
if (response.status >= 200 && response.status < 300) {
|
|
67
|
+
etagCounters.hits += 1; // #267-3: "hits" = calls that returned fresh data (non-304 successes)
|
|
68
|
+
}
|
|
60
69
|
return { status: response.status, data, notModified: false };
|
|
61
70
|
}
|
|
62
71
|
async function getJson(urlPath, etags) {
|
|
@@ -65,6 +74,10 @@ export function createGithubClient(auth) {
|
|
|
65
74
|
}
|
|
66
75
|
return {
|
|
67
76
|
request,
|
|
77
|
+
/** #267-3: cumulative etag/API counters (see etagCounters above). */
|
|
78
|
+
etagStats() {
|
|
79
|
+
return { ...etagCounters };
|
|
80
|
+
},
|
|
68
81
|
async getRepoInfo(owner, repo) {
|
|
69
82
|
const data = await getJson(`/repos/${owner}/${repo}`);
|
|
70
83
|
if (!data) {
|
|
@@ -164,6 +177,26 @@ export function createGithubClient(auth) {
|
|
|
164
177
|
async assignIssue(owner, repo, issueNumber, assignee) {
|
|
165
178
|
await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees: [assignee] } });
|
|
166
179
|
},
|
|
180
|
+
/** Fresh issue state for claim-time re-checks (#268): the scan-time
|
|
181
|
+
* assignee snapshot is seconds stale by enqueue time - a human may have
|
|
182
|
+
* self-assigned in between, and claiming over a human is worse than not
|
|
183
|
+
* claiming. */
|
|
184
|
+
async getIssue(owner, repo, issueNumber) {
|
|
185
|
+
const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}`);
|
|
186
|
+
const raw = data;
|
|
187
|
+
return {
|
|
188
|
+
assignees: Array.isArray(raw.assignees) ? raw.assignees.map((a) => String(a.login ?? "")).filter(Boolean) : [],
|
|
189
|
+
state: String(raw.state ?? "open"),
|
|
190
|
+
updatedAt: String(raw.updated_at ?? ""),
|
|
191
|
+
};
|
|
192
|
+
},
|
|
193
|
+
/** Login of the authenticated account (#268): the assignee string for
|
|
194
|
+
* self-claiming. Kept here (not on the auth manager) so the claim path
|
|
195
|
+
* stays client-only. */
|
|
196
|
+
async getAuthenticatedUser() {
|
|
197
|
+
const { data } = await request("GET", "/user");
|
|
198
|
+
return { login: String(data.login ?? "") };
|
|
199
|
+
},
|
|
167
200
|
/** Open a PR from a task worktree branch (collaboration contract delivery). */
|
|
168
201
|
async createPullRequest(owner, repo, head, base, title, body) {
|
|
169
202
|
const { data } = await request("POST", `/repos/${owner}/${repo}/pulls`, {
|
|
@@ -107,7 +107,15 @@ export async function sweepRepo(repo, client, now = Date.now()) {
|
|
|
107
107
|
role: "qa",
|
|
108
108
|
writeMode: "read-only",
|
|
109
109
|
};
|
|
110
|
-
|
|
110
|
+
// #269 6th case (ggcode#4785): an issue eligible for BOTH actions got
|
|
111
|
+
// two tasks in the same sweep, each delivering its own comment - the
|
|
112
|
+
// delivery layer correctly treats them as independent entries. Collapse
|
|
113
|
+
// at the source: when ownership applies (open + enabled) it wins and
|
|
114
|
+
// subsumes the triage read; issueReview fires only when ownership is
|
|
115
|
+
// disabled for this repo (or the issue is closed and un-reviewable via
|
|
116
|
+
// ownership, e.g. follow-up triage on a closed issue).
|
|
117
|
+
const ownershipApplies = repo.policy.actions.takeOwnership && issue.state === "open";
|
|
118
|
+
if (repo.policy.actions.issueReview && !ownershipApplies) {
|
|
111
119
|
candidates.push({
|
|
112
120
|
...base,
|
|
113
121
|
kind: "issueReview",
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
2
3
|
// Phase 2.3/2.5 (cross-review adopted suggestion): manual-proposal roles
|
|
3
4
|
// validate against the ACTIVE profile and default to its defaultRole instead
|
|
4
5
|
// of hardcoded software role literals.
|
|
@@ -7,8 +8,9 @@ import { createGithubClient } from "./github-client.js";
|
|
|
7
8
|
import { learnNorms, renderNormsBlock } from "./norms.js";
|
|
8
9
|
import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
|
|
9
10
|
import { nextFireMs } from "./schedule.js";
|
|
11
|
+
import { resolveTeamAutoPaths } from "./store.js";
|
|
10
12
|
import { advanceCursors, sweepRepo } from "./scanner.js";
|
|
11
|
-
import { consumeDailyBudget, defaultCursors, defaultPolicy, loadTeamAutoStore, pushTeamAutoActivity, saveTeamAutoStore, } from "./store.js";
|
|
13
|
+
import { consumeDailyBudget, defaultCursors, defaultPolicy, loadTeamAutoStore, pushTeamAutoActivity, saveTeamAutoStore, pushSweepRecord, } from "./store.js";
|
|
12
14
|
/**
|
|
13
15
|
* TeamAuto scheduler: per-repo cron sweeps -> TeamClaw tasks -> GitHub
|
|
14
16
|
* write-backs. Fully autonomous per the user's decisions (TEAMAUTO_DESIGN.md):
|
|
@@ -47,15 +49,49 @@ export function hardAttemptCount(state, candidate) {
|
|
|
47
49
|
const marker = idempotencyMarker(candidate);
|
|
48
50
|
return Object.values(state.tasks).filter((t) => t.description.includes(marker) && t.status === "failed" && !(t.error && TRANSIENT_FAILURE_RE.test(t.error))).length;
|
|
49
51
|
}
|
|
50
|
-
/** Auto-pause retry backoff
|
|
52
|
+
/** Auto-pause retry backoff for classes where a fast retry is useless or
|
|
53
|
+
* harmful: 30m after the 1st failure, doubling, capped at 4h. auth needs a
|
|
54
|
+
* human re-login; ratelimited retried early just re-triggers the limit. */
|
|
51
55
|
export const SWEEP_RETRY_BASE_MINUTES = 30;
|
|
52
56
|
export const SWEEP_RETRY_MAX_MINUTES = 240;
|
|
53
57
|
export function sweepBackoffMinutes(failures) {
|
|
54
58
|
return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
|
|
55
59
|
}
|
|
60
|
+
/** Sweep-timeout report: a transient "fetch failed" sat a full 30m before
|
|
61
|
+
* its first retry - a seconds-long network blip cost half an hour of repo
|
|
62
|
+
* idle time. Network-class failures get a fast ladder: 1m, 2m, 4m... capped
|
|
63
|
+
* at 15m. The cap means a genuinely-down network converges to one attempt
|
|
64
|
+
* per 15m (slower than the old ladder's first step, so we never hammer),
|
|
65
|
+
* but a single blip costs one minute instead of thirty. */
|
|
66
|
+
export const SWEEP_NETWORK_RETRY_BASE_MINUTES = 1;
|
|
67
|
+
export const SWEEP_NETWORK_RETRY_MAX_MINUTES = 15;
|
|
68
|
+
export function sweepNetworkBackoffMinutes(failures) {
|
|
69
|
+
return Math.min(SWEEP_NETWORK_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_NETWORK_RETRY_MAX_MINUTES);
|
|
70
|
+
}
|
|
71
|
+
/** Class-aware dispatch: the retry ladder a failure class deserves. */
|
|
72
|
+
export function sweepBackoffMinutesFor(failClass, failures) {
|
|
73
|
+
return failClass === "network" ? sweepNetworkBackoffMinutes(failures) : sweepBackoffMinutes(failures);
|
|
74
|
+
}
|
|
75
|
+
/** Timer floor when arming the retry ladder: a just-missed due time must not
|
|
76
|
+
* fire at 0ms (tight failure/retry loop protection). */
|
|
77
|
+
export const SWEEP_RETRY_FLOOR_MS = 5_000;
|
|
56
78
|
/** Epoch ms when an auto-paused repo becomes due for its next retry attempt. */
|
|
57
|
-
export function sweepRetryDueAt(failures, lastErrorAt) {
|
|
58
|
-
return lastErrorAt +
|
|
79
|
+
export function sweepRetryDueAt(failures, lastErrorAt, failClass = "network") {
|
|
80
|
+
return lastErrorAt + sweepBackoffMinutesFor(failClass, failures) * 60_000;
|
|
81
|
+
}
|
|
82
|
+
/** In-place network retries: a transient "fetch failed"/"terminated" is
|
|
83
|
+
* retried immediately INSIDE the sweep invocation (user report 2026-11-14:
|
|
84
|
+
* "sweep failed[network] (auto-retry in ~30min): fetch failed" - the repo
|
|
85
|
+
* idled half an hour on a blip that a 5s retry would have survived). 10
|
|
86
|
+
* attempts with a 3s..30s delay ladder (~2.5min worst case) before the
|
|
87
|
+
* failure is recorded and the pause/backoff path takes over. Non-network
|
|
88
|
+
* classes (auth, ratelimited) never retry in place - retrying is useless
|
|
89
|
+
* or harmful. */
|
|
90
|
+
export const SWEEP_INPLACE_RETRIES = 10;
|
|
91
|
+
export const SWEEP_INPLACE_DELAY_BASE_MS = 3_000;
|
|
92
|
+
export const SWEEP_INPLACE_DELAY_MAX_MS = 30_000;
|
|
93
|
+
export function sweepInplaceDelayMs(attempt) {
|
|
94
|
+
return Math.min(SWEEP_INPLACE_DELAY_BASE_MS * 2 ** Math.max(0, attempt - 1), SWEEP_INPLACE_DELAY_MAX_MS);
|
|
59
95
|
}
|
|
60
96
|
/**
|
|
61
97
|
* Issue #24: max write-back delivery attempts before the entry is marked
|
|
@@ -79,9 +115,33 @@ export function writebackBackoffMs(attempts) {
|
|
|
79
115
|
export function writebackRetryDueAt(attempts, lastErrorAt) {
|
|
80
116
|
return lastErrorAt + writebackBackoffMs(attempts);
|
|
81
117
|
}
|
|
82
|
-
|
|
118
|
+
export function classifySweepError(err) {
|
|
119
|
+
const cause = err?.cause ?? err;
|
|
120
|
+
const status = Number(cause?.status ?? 0);
|
|
121
|
+
if (status === 401)
|
|
122
|
+
return "auth";
|
|
123
|
+
if (status === 403 || status === 429)
|
|
124
|
+
return "ratelimited";
|
|
125
|
+
return "network";
|
|
126
|
+
}
|
|
127
|
+
/** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not.
|
|
128
|
+
* Accept BOTH the legacy prefix ("sweep failed: ...") and the #267 classified
|
|
129
|
+
* format ("sweep failed[network]: ...") - the classified format broke the old
|
|
130
|
+
* startsWith("sweep failed:") check, so successful sweeps could never clear
|
|
131
|
+
* the pause and the retry timer never re-armed (all four repos stuck paused
|
|
132
|
+
* after the 12:30 restart-window failures; found 2026-11-12). */
|
|
83
133
|
export function isAutoPause(reason) {
|
|
84
|
-
|
|
134
|
+
if (!reason)
|
|
135
|
+
return false;
|
|
136
|
+
return /^sweep failed(\[[^\]]*\])?:/.test(reason);
|
|
137
|
+
}
|
|
138
|
+
/** Recover the fail class from a persisted auto-pause reason
|
|
139
|
+
* ("sweep failed[network]: ..."). Legacy/unparsable reasons default to the
|
|
140
|
+
* fast network ladder - a wrong guess only retries sooner, and the ladder
|
|
141
|
+
* itself still caps the attempt rate, so the default is safe. */
|
|
142
|
+
export function failClassFromPauseReason(reason) {
|
|
143
|
+
const m = reason?.match(/^sweep failed\[([^\]]*)\]/);
|
|
144
|
+
return m && (m[1] === "auth" || m[1] === "ratelimited" || m[1] === "network") ? m[1] : "network";
|
|
85
145
|
}
|
|
86
146
|
export function createTeamAutoScheduler(deps) {
|
|
87
147
|
const { logger, auth } = deps;
|
|
@@ -99,6 +159,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
99
159
|
*/
|
|
100
160
|
function markWritebackFailure(store, entry, message, options = {}) {
|
|
101
161
|
entry.error = message;
|
|
162
|
+
entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
|
|
102
163
|
entry.attempts = (entry.attempts ?? 0) + 1;
|
|
103
164
|
entry.lastErrorAt = Date.now();
|
|
104
165
|
entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
|
|
@@ -336,8 +397,35 @@ export function createTeamAutoScheduler(deps) {
|
|
|
336
397
|
return "sweep already in progress";
|
|
337
398
|
}
|
|
338
399
|
sweeping.add(repo.id);
|
|
400
|
+
const sweepStartedAt = Date.now();
|
|
401
|
+
const etagBefore = client.etagStats();
|
|
339
402
|
try {
|
|
340
|
-
|
|
403
|
+
// #sweep-inplace: transient network failures retry IN PLACE (see
|
|
404
|
+
// SWEEP_INPLACE_RETRIES) - only a network blip that survives ~2.5min of
|
|
405
|
+
// retrying reaches the failure-recording path below.
|
|
406
|
+
let swept;
|
|
407
|
+
let lastNetworkErr;
|
|
408
|
+
for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
|
|
409
|
+
try {
|
|
410
|
+
swept = await sweepRepo(repo, client);
|
|
411
|
+
break;
|
|
412
|
+
}
|
|
413
|
+
catch (err) {
|
|
414
|
+
if (classifySweepError(err) !== "network") {
|
|
415
|
+
throw err;
|
|
416
|
+
}
|
|
417
|
+
lastNetworkErr = err;
|
|
418
|
+
const message0 = err instanceof Error ? err.message : String(err);
|
|
419
|
+
logger.warn(`TeamAuto: sweep ${repo.id} network error (attempt ${attempt}/${SWEEP_INPLACE_RETRIES}): ${message0}`);
|
|
420
|
+
if (attempt < SWEEP_INPLACE_RETRIES) {
|
|
421
|
+
await new Promise((resolve) => setTimeout(resolve, sweepInplaceDelayMs(attempt)));
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
if (!swept) {
|
|
426
|
+
throw lastNetworkErr;
|
|
427
|
+
}
|
|
428
|
+
const { candidates, issues, pulls, newCommits, commits } = swept;
|
|
341
429
|
const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
|
|
342
430
|
if (dryRun) {
|
|
343
431
|
// One observing pass, then act. Flip unconditionally - flipping only
|
|
@@ -382,6 +470,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
382
470
|
}
|
|
383
471
|
else if (taskId) {
|
|
384
472
|
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
|
|
473
|
+
claimIssue(repo, candidate); // #268: visible claim at enqueue time
|
|
385
474
|
const action = candidate.kind === "prReview"
|
|
386
475
|
? "prComment"
|
|
387
476
|
: candidate.kind === "fullReview"
|
|
@@ -407,6 +496,8 @@ export function createTeamAutoScheduler(deps) {
|
|
|
407
496
|
}
|
|
408
497
|
repo.sweepFailures = 0;
|
|
409
498
|
repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
|
|
499
|
+
const etagAfter = client.etagStats();
|
|
500
|
+
pushSweepRecord(repo, { at: Date.now(), ok: true, summary: repo.lastSweepSummary ?? "sweep complete", durationMs: Date.now() - sweepStartedAt, etagCalls: Math.max(0, etagAfter.calls - etagBefore.calls), etag304Hits: Math.max(0, etagAfter.hits - etagBefore.hits) });
|
|
410
501
|
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
|
|
411
502
|
await saveTeamAutoStore(s);
|
|
412
503
|
if (created > 0) {
|
|
@@ -426,8 +517,11 @@ export function createTeamAutoScheduler(deps) {
|
|
|
426
517
|
repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
|
|
427
518
|
repo.lastSweepErrorAt = Date.now();
|
|
428
519
|
repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
|
|
429
|
-
|
|
430
|
-
|
|
520
|
+
const failClass = classifySweepError(err);
|
|
521
|
+
repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
|
|
522
|
+
const etagAfter = client.etagStats();
|
|
523
|
+
pushSweepRecord(repo, { at: Date.now(), ok: false, summary: `sweep failed[${failClass}]: ${message}`, failClass, durationMs: Date.now() - sweepStartedAt, etagCalls: Math.max(0, etagAfter.calls - etagBefore.calls), etag304Hits: Math.max(0, etagAfter.hits - etagBefore.hits) });
|
|
524
|
+
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
|
|
431
525
|
await saveTeamAutoStore(s).catch(() => { });
|
|
432
526
|
logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
|
|
433
527
|
return `error: ${message}`;
|
|
@@ -543,8 +637,68 @@ export function createTeamAutoScheduler(deps) {
|
|
|
543
637
|
return "duplicate-active-skipped";
|
|
544
638
|
}
|
|
545
639
|
// ---------- write-back reconciler ----------
|
|
640
|
+
// #269: the 20s interval fires `void reconcileWritebacks()` fire-and-forget,
|
|
641
|
+
// and a slow delivery (worktree ensure + commit + PR > 20s) let the next
|
|
642
|
+
// tick re-read the same pending entries before doneAt landed - same
|
|
643
|
+
// comment delivered twice (ggcode#5480, byte-identical pair). Two-layer
|
|
644
|
+
// fix: serialize the whole pass (guard below) + intent-first inFlightAt
|
|
645
|
+
// persisted BEFORE dispatch so even a concurrent caller cannot re-send.
|
|
646
|
+
let reconcileInFlight = false;
|
|
546
647
|
async function reconcileWritebacks() {
|
|
547
|
-
|
|
648
|
+
if (reconcileInFlight) {
|
|
649
|
+
return; // a pass is still delivering - never overlap (#269)
|
|
650
|
+
}
|
|
651
|
+
// #269 recurrence (23:40 CST): MULTIPLE gateway processes share one
|
|
652
|
+
// ~/.openclaw store (launchctl service + spawned gateways). In-process
|
|
653
|
+
// guards cannot see another process's deliveries - each kept its
|
|
654
|
+
// startup-cached store and delivered the same pending row (3s apart,
|
|
655
|
+
// two "issueComment ok" for one task). Cross-process mutex: an atomic
|
|
656
|
+
// mkdir lock dir next to the store file; stale (>5min) locks are
|
|
657
|
+
// taken over (crashed holder).
|
|
658
|
+
const { storeFile } = resolveTeamAutoPaths();
|
|
659
|
+
const lockDir = `${storeFile}.reconcile-lock`;
|
|
660
|
+
let locked = false;
|
|
661
|
+
try {
|
|
662
|
+
try {
|
|
663
|
+
await fs.mkdir(lockDir);
|
|
664
|
+
locked = true;
|
|
665
|
+
}
|
|
666
|
+
catch {
|
|
667
|
+
// Held - unless stale (holder crashed mid-pass).
|
|
668
|
+
try {
|
|
669
|
+
const st = await fs.stat(lockDir);
|
|
670
|
+
if (Date.now() - st.mtimeMs > 300_000) {
|
|
671
|
+
await fs.rm(lockDir, { recursive: true, force: true });
|
|
672
|
+
await fs.mkdir(lockDir);
|
|
673
|
+
locked = true;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
catch { /* racing takeover - someone else won; skip this pass */ }
|
|
677
|
+
}
|
|
678
|
+
if (!locked) {
|
|
679
|
+
return; // another PROCESS is mid-reconcile; our next tick re-tries
|
|
680
|
+
}
|
|
681
|
+
reconcileInFlight = true;
|
|
682
|
+
try {
|
|
683
|
+
await doReconcileWritebacks();
|
|
684
|
+
}
|
|
685
|
+
finally {
|
|
686
|
+
reconcileInFlight = false;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
finally {
|
|
690
|
+
if (locked) {
|
|
691
|
+
await fs.rm(lockDir, { recursive: true, force: true }).catch(() => { });
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
async function doReconcileWritebacks() {
|
|
696
|
+
// #269 recurrence: re-read the store from disk EVERY pass - the
|
|
697
|
+
// closure cache is a startup snapshot that never sees another
|
|
698
|
+
// process's persisted inFlightAt/doneAt, which is exactly how the
|
|
699
|
+
// 23:40 double delivery happened.
|
|
700
|
+
store = await loadTeamAutoStore();
|
|
701
|
+
const s = store;
|
|
548
702
|
const state0 = deps.getTeamState();
|
|
549
703
|
// Dead letters: entries whose task is gone or failed without a result can
|
|
550
704
|
// never deliver - drop them instead of accumulating forever.
|
|
@@ -602,7 +756,30 @@ export function createTeamAutoScheduler(deps) {
|
|
|
602
756
|
}
|
|
603
757
|
}
|
|
604
758
|
}
|
|
605
|
-
|
|
759
|
+
// #269: reset stale in-flight intents (crashed mid-dispatch) so they
|
|
760
|
+
// re-enter the pending set instead of wedging forever.
|
|
761
|
+
for (const w of s.writebacks) {
|
|
762
|
+
if (w.inFlightAt && !w.doneAt && Date.now() - w.inFlightAt > 600_000) {
|
|
763
|
+
w.inFlightAt = undefined;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
const pendingAll = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt && !w.inFlightAt);
|
|
767
|
+
// #269 per-target dedupe (delivery side): cap at ONE entry per target
|
|
768
|
+
// key per pass, so N pending rows aimed at the same issue/PR cannot
|
|
769
|
+
// burst N same-second comments even if they somehow slipped the enqueue
|
|
770
|
+
// check (e.g. pre-fix stores). Deferred rows simply ride the next 20s
|
|
771
|
+
// pass. Null-target create* rows key on taskId: each is a distinct
|
|
772
|
+
// create intent and must never be merged.
|
|
773
|
+
const seenTarget = new Set();
|
|
774
|
+
const pending = [];
|
|
775
|
+
for (const w of pendingAll) {
|
|
776
|
+
const key = w.targetId != null ? `${w.action}|${w.repoId}|${w.targetId}` : `${w.action}|${w.taskId}`;
|
|
777
|
+
if (seenTarget.has(key)) {
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
seenTarget.add(key);
|
|
781
|
+
pending.push(w);
|
|
782
|
+
}
|
|
606
783
|
if (!pending.length) {
|
|
607
784
|
return;
|
|
608
785
|
}
|
|
@@ -611,6 +788,11 @@ export function createTeamAutoScheduler(deps) {
|
|
|
611
788
|
return;
|
|
612
789
|
}
|
|
613
790
|
for (const entry of pending) {
|
|
791
|
+
// #269 intent-first: persist the dispatch intent BEFORE any await so
|
|
792
|
+
// an overlapping pass (or a future guard-less caller) filters this
|
|
793
|
+
// entry out instead of re-delivering it.
|
|
794
|
+
entry.inFlightAt = Date.now();
|
|
795
|
+
await saveTeamAutoStore(s);
|
|
614
796
|
const task = state.tasks[entry.taskId];
|
|
615
797
|
if (!task || (task.status !== "completed" && task.status !== "failed")) {
|
|
616
798
|
continue;
|
|
@@ -649,6 +831,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
649
831
|
// push its branch, open a PR, and attach the link to the reply.
|
|
650
832
|
const repoId = entry.repoId;
|
|
651
833
|
const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
|
|
834
|
+
let prDeliveryFailed = false;
|
|
652
835
|
if (isTeamAutoWrite) {
|
|
653
836
|
try {
|
|
654
837
|
const info = await client.getRepoInfo(repoId.split("/")[0], repoId.split("/")[1]);
|
|
@@ -670,11 +853,24 @@ export function createTeamAutoScheduler(deps) {
|
|
|
670
853
|
}
|
|
671
854
|
catch (prErr) {
|
|
672
855
|
markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
|
|
856
|
+
// #269 4th recurrence (ggcode#5524): a failed PR step must abort
|
|
857
|
+
// the WHOLE entry this pass. The old fall-through posted the
|
|
858
|
+
// link-less comment anyway, set doneAt, and the #24 cleanup
|
|
859
|
+
// cleared the error - a partial delivery masked as success.
|
|
860
|
+
// The retry pass then delivered the WITH-link comment too:
|
|
861
|
+
// two comments 2s apart. Fail atomically instead: the entry
|
|
862
|
+
// keeps its failed state + backoff and replays BOTH steps
|
|
863
|
+
// (PR first, then comment) on the next attempt.
|
|
864
|
+
prDeliveryFailed = true;
|
|
673
865
|
}
|
|
674
866
|
}
|
|
867
|
+
if (prDeliveryFailed) {
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
675
870
|
if (entry.action === "issueComment" && entry.targetId) {
|
|
676
871
|
await client.postIssueComment(owner, name, entry.targetId, body);
|
|
677
872
|
entry.doneAt = Date.now();
|
|
873
|
+
entry.inFlightAt = undefined;
|
|
678
874
|
writebackDone = true;
|
|
679
875
|
// Our own comment bumps the issue's updatedAt, which the scanner
|
|
680
876
|
// treats as new activity - advance the seen cursor so we do not
|
|
@@ -688,6 +884,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
688
884
|
else if (entry.action === "prComment" && entry.targetId) {
|
|
689
885
|
await client.postPullReviewComment(owner, name, entry.targetId, body);
|
|
690
886
|
entry.doneAt = Date.now();
|
|
887
|
+
entry.inFlightAt = undefined;
|
|
691
888
|
writebackDone = true;
|
|
692
889
|
const prRepo = s.repos.find((r) => r.id === entry.repoId);
|
|
693
890
|
if (prRepo) {
|
|
@@ -705,12 +902,14 @@ export function createTeamAutoScheduler(deps) {
|
|
|
705
902
|
await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
|
|
706
903
|
entry.targetId = umbrella.targetId;
|
|
707
904
|
entry.doneAt = Date.now();
|
|
905
|
+
entry.inFlightAt = undefined;
|
|
708
906
|
writebackDone = true;
|
|
709
907
|
}
|
|
710
908
|
else if (entry.targetId == null) {
|
|
711
909
|
const number = await client.createIssue(owner, name, `[teamclaw:fullreview] Joint full review - ${entry.repoId}`, `Joint multi-role full review (cycle ${entry.cycleKey}). Each role appends its section as a comment below.\n\n${sectionBody}`, ["teamclaw", "teamclaw:fullreview"]);
|
|
712
910
|
entry.targetId = number;
|
|
713
911
|
entry.doneAt = Date.now();
|
|
912
|
+
entry.inFlightAt = undefined;
|
|
714
913
|
writebackDone = true;
|
|
715
914
|
}
|
|
716
915
|
}
|
|
@@ -718,6 +917,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
718
917
|
const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
|
|
719
918
|
entry.targetId = number;
|
|
720
919
|
entry.doneAt = Date.now();
|
|
920
|
+
entry.inFlightAt = undefined;
|
|
721
921
|
writebackDone = true;
|
|
722
922
|
}
|
|
723
923
|
}
|
|
@@ -748,10 +948,75 @@ export function createTeamAutoScheduler(deps) {
|
|
|
748
948
|
if (s.writebacks.some((w) => w.taskId === taskId)) {
|
|
749
949
|
return;
|
|
750
950
|
}
|
|
951
|
+
// #269 per-target dedupe (enqueue side): a second registration for
|
|
952
|
+
// the SAME target + action with no doneAt yet is a duplicate in the
|
|
953
|
+
// making - the delivery pass would fan out two comments onto one
|
|
954
|
+
// target. Skip it; the pending original still delivers the content.
|
|
955
|
+
// targetId null (create* actions) cannot be target-deduped pre-delivery
|
|
956
|
+
// and is excluded by the taskId check above.
|
|
957
|
+
if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
751
960
|
s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
|
|
752
961
|
void saveTeamAutoStore(s);
|
|
753
962
|
}).catch(() => { });
|
|
754
963
|
}
|
|
964
|
+
/** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
|
|
965
|
+
* assignIssue was dead code and registerWriteback had no assign action, so
|
|
966
|
+
* claims existed only in internal state - humans could not see the bot had
|
|
967
|
+
* picked an issue up (collision risk), contradicting the design decision
|
|
968
|
+
* that identity presents as the logged-in account's activity.
|
|
969
|
+
* Fired at ENQUEUE time: a claim is a placeholder declaration; posting it
|
|
970
|
+
* at completion would leave the whole execution window claim-invisible.
|
|
971
|
+
* Best-effort, never blocks the task. Review notes (#268):
|
|
972
|
+
* (a) re-check assignees at claim time (the scan snapshot is seconds
|
|
973
|
+
* stale - a human may have self-assigned in between);
|
|
974
|
+
* (b) stamp cursors.seen with NOW + 60s on BOTH success paths (assign
|
|
975
|
+
* AND fallback comment) because our own write bumps the issue's
|
|
976
|
+
* updated_at - a bare-assign stamp would lose the scanner's
|
|
977
|
+
* `seen >= updatedAt` comparison next sweep and re-candidate the
|
|
978
|
+
* issue we just claimed (self-triggering loop). */
|
|
979
|
+
function claimIssue(repo, candidate) {
|
|
980
|
+
if (candidate.kind !== "takeOwnership" || !candidate.number) {
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
void (async () => {
|
|
984
|
+
const [owner, name] = repo.id.split("/");
|
|
985
|
+
const client = createGithubClient(auth);
|
|
986
|
+
try {
|
|
987
|
+
const fresh = await client.getIssue(owner, name, candidate.number);
|
|
988
|
+
if (fresh.state !== "open") {
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (repo.policy.skipAssignedToHumans && fresh.assignees.length > 0) {
|
|
992
|
+
recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claim skipped: issue #${candidate.number} gained an assignee since scan` });
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
const { login } = await client.getAuthenticatedUser();
|
|
996
|
+
try {
|
|
997
|
+
await client.assignIssue(owner, name, candidate.number, login);
|
|
998
|
+
recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} as @${login}` });
|
|
999
|
+
}
|
|
1000
|
+
catch {
|
|
1001
|
+
// Fallback: a visible claim comment carries the same placeholder
|
|
1002
|
+
// semantics when the App lacks the assignees write surface.
|
|
1003
|
+
await client.postIssueComment(owner, name, candidate.number, `TeamClaw (teamclaw/developer, @${login}) has taken ownership of this issue and is implementing it autonomously - a PR will follow.`);
|
|
1004
|
+
recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
|
|
1005
|
+
}
|
|
1006
|
+
const s = await ensureStore();
|
|
1007
|
+
const freshRepo = s.repos.find((r) => r.id === repo.id);
|
|
1008
|
+
if (freshRepo) {
|
|
1009
|
+
// +60s guard: our own write (assign or comment) bumps updated_at;
|
|
1010
|
+
// see helper doc.
|
|
1011
|
+
freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
|
|
1012
|
+
await saveTeamAutoStore(s);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
catch (err) {
|
|
1016
|
+
logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
|
|
1017
|
+
}
|
|
1018
|
+
})();
|
|
1019
|
+
}
|
|
755
1020
|
// ---------- scheduling loop ----------
|
|
756
1021
|
function scheduleRepo(repo) {
|
|
757
1022
|
const previous = timers.get(repo.id);
|
|
@@ -763,12 +1028,22 @@ export function createTeamAutoScheduler(deps) {
|
|
|
763
1028
|
return;
|
|
764
1029
|
}
|
|
765
1030
|
let delay;
|
|
766
|
-
|
|
767
|
-
|
|
1031
|
+
// Auto-paused repos arm the RETRY ladder, not the regular schedule: the
|
|
1032
|
+
// retry-due check used to ride the next regular tick, so "auto-retry in
|
|
1033
|
+
// ~1min" for a network blip really meant "at the next hourly tick".
|
|
1034
|
+
// While paused, retry at the class-aware backoff; a successful sweep
|
|
1035
|
+
// clears pausedReason and restores the regular schedule below.
|
|
1036
|
+
if (isAutoPause(repo.pausedReason) && repo.lastSweepErrorAt) {
|
|
1037
|
+
delay = Math.max(SWEEP_RETRY_FLOOR_MS, sweepRetryDueAt(repo.sweepFailures ?? 1, repo.lastSweepErrorAt, failClassFromPauseReason(repo.pausedReason)) - Date.now());
|
|
768
1038
|
}
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
1039
|
+
else {
|
|
1040
|
+
try {
|
|
1041
|
+
delay = nextFireMs(repo.schedule);
|
|
1042
|
+
}
|
|
1043
|
+
catch (err) {
|
|
1044
|
+
logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
772
1047
|
}
|
|
773
1048
|
const timer = setTimeout(() => {
|
|
774
1049
|
void (async () => {
|
|
@@ -776,7 +1051,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
776
1051
|
const s = await ensureStore();
|
|
777
1052
|
const fresh = s.repos.find((r) => r.id === repo.id);
|
|
778
1053
|
const retryDue = fresh
|
|
779
|
-
? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
|
|
1054
|
+
? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0, failClassFromPauseReason(fresh.pausedReason))
|
|
780
1055
|
: false;
|
|
781
1056
|
if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
|
|
782
1057
|
await runSweep(fresh, false);
|