@teamclaws/teamclaw 2026.11.1 → 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.
Files changed (45) hide show
  1. package/cli.mjs +96 -11
  2. package/dist/index.js +7 -0
  3. package/dist/src/controller/config-routes.js +138 -0
  4. package/dist/src/controller/http-server.js +18 -0
  5. package/dist/src/controller/journal.js +68 -0
  6. package/dist/src/controller/provisioning/process-supervisor.js +58 -2
  7. package/dist/src/controller/provisioning-config.js +53 -0
  8. package/dist/src/controller/route-table.js +11 -0
  9. package/dist/src/controller/security.js +39 -0
  10. package/dist/src/controller/teamauto-routes.js +12 -0
  11. package/dist/src/controller/tunnel-manager.js +33 -1
  12. package/dist/src/controller/tunnel-routes.js +17 -1
  13. package/dist/src/controller/websocket.js +4 -0
  14. package/dist/src/controller/worker-provisioning.js +36 -0
  15. package/dist/src/openclaw-workspace.js +36 -0
  16. package/dist/src/state.js +77 -1
  17. package/dist/src/teamauto/github-client.js +33 -0
  18. package/dist/src/teamauto/scanner.js +30 -3
  19. package/dist/src/teamauto/scheduler.js +300 -18
  20. package/dist/src/teamauto/store.js +9 -0
  21. package/dist/src/ui/app.js +188 -11
  22. package/dist/src/ui/index.html +38 -0
  23. package/index.ts +8 -0
  24. package/openclaw.plugin.json +1 -1
  25. package/package.json +1 -1
  26. package/src/controller/config-routes.ts +152 -0
  27. package/src/controller/http-server.ts +18 -0
  28. package/src/controller/journal.ts +89 -0
  29. package/src/controller/provisioning/process-supervisor.ts +56 -2
  30. package/src/controller/provisioning-config.ts +54 -0
  31. package/src/controller/route-table.ts +11 -0
  32. package/src/controller/security.ts +40 -0
  33. package/src/controller/teamauto-routes.ts +12 -0
  34. package/src/controller/tunnel-manager.ts +34 -1
  35. package/src/controller/tunnel-routes.ts +18 -1
  36. package/src/controller/websocket.ts +6 -0
  37. package/src/controller/worker-provisioning.ts +34 -0
  38. package/src/openclaw-workspace.ts +47 -0
  39. package/src/state.ts +73 -2
  40. package/src/teamauto/github-client.ts +36 -0
  41. package/src/teamauto/scanner.ts +31 -4
  42. package/src/teamauto/scheduler.ts +303 -18
  43. package/src/teamauto/store.ts +36 -1
  44. package/src/ui/app.js +188 -11
  45. package/src/ui/index.html +38 -0
@@ -399,6 +399,30 @@ export function createSecurityMiddleware(deps) {
399
399
  if (isSecurityExemptPath(req.method ?? "", pathname)) {
400
400
  return true;
401
401
  }
402
+ // Loopback is the controller host itself: the desktop app, the web UI,
403
+ // provisioned workers registering/heart-beating, and the owner's own
404
+ // CLI/curl. Requiring device pairing from the SAME MACHINE broke all of
405
+ // them the moment protection turned on (provisioned workers 401'd their
406
+ // registration and the worker pool starved; the local desktop could not
407
+ // talk to its own gateway - reported as a UX defect 2026-11-12). Local
408
+ // peers stay first-party: tunnel traffic never earns loopback trust
409
+ // (classifySecurityPeer strips it via viaTunnel) and LAN peers still
410
+ // need a device token. When a loopback caller DOES present a valid
411
+ // device token, authenticate anyway so lastSeenAt keeps updating (the
412
+ // token may belong to a paired remote console the owner is driving).
413
+ // VIA-TUNNEL requests are ALSO exempt: cloudflared dials in from
414
+ // loopback (the tunnel IS a local connection), and their credential is
415
+ // the tunnel GATE TOKEN - http-server checks gateAllows for every
416
+ // tunnel request AFTER this gate. Pairing them is a category error: a
417
+ // visitor can never obtain a pairing code, so protection-on would just
418
+ // kill the tunnel with an unanswerable 401 (user design ruling
419
+ // 2026-11-12). LAN peers remain the pairing boundary.
420
+ if (peer.loopback || peer.viaTunnel) {
421
+ const authAny = authenticateDeviceToken(state, extractDeviceToken(req));
422
+ if (authAny)
423
+ touchDeviceLastSeen(deps, authAny.device.id);
424
+ return true;
425
+ }
402
426
  const auth = authenticateDeviceToken(state, extractDeviceToken(req));
403
427
  if (!auth) {
404
428
  deps.logger.warn(`Controller: rejected unauthenticated ${req.method ?? "?"} ${pathname} from ${peer.ip}${peer.viaTunnel ? " (via tunnel)" : ""}`);
@@ -418,6 +442,21 @@ export function createWebSocketUpgradeGuard(deps) {
418
442
  recordNonLanPeerSignal(deps, state, peer, "/ws");
419
443
  return true;
420
444
  }
445
+ // 8b03ed6 layering (user design ruling): loopback peers are first-party
446
+ // (the host itself - web UI, desktop, provisioned workers) and NEVER
447
+ // need a pairing token. The HTTP gate got this exemption; this WS guard
448
+ // missed it and rejected every loopback UI connection (92362 rejects,
449
+ // user-found: tasks UI stuck on pending because /ws never upgraded).
450
+ if (peer.loopback) {
451
+ return true;
452
+ }
453
+ // Tunnel-origin upgrades (cloudflared loopback + tunnel Host): the
454
+ // visitor holds the GATE token, not a pairing token - same layering
455
+ // as the HTTP gate (a device token here would be an unanswerable
456
+ // wall, 8b03ed6). Verify the gate cookie instead.
457
+ if (peer.viaTunnel && deps.gateAllows && deps.gateAllows(req)) {
458
+ return true;
459
+ }
421
460
  let token = extractDeviceToken(req);
422
461
  if (!token) {
423
462
  const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
@@ -98,6 +98,18 @@ export async function handleTeamAutoRepoItemRequest(deps, req, res, pathname) {
98
98
  }
99
99
  catch { /* empty */ }
100
100
  try {
101
+ // #269 (user report): the enabled flag used to be silently dropped
102
+ // here - the web UI's disable toggle returned 200 but never reached
103
+ // setRepoEnabled, so sweeps kept running. Wire it explicitly; the
104
+ // enable/disable path has different persistence semantics (pausedReason
105
+ // + timer reschedule) than the plain field patch below.
106
+ if (typeof body.enabled === "boolean" && Object.keys(body).every((k) => k === "enabled")) {
107
+ await teamAuto.setRepoEnabled(repoId, body.enabled);
108
+ const status = await teamAuto.getStatus();
109
+ const repo = (status?.repos ?? []).find((r) => r.id === repoId);
110
+ sendJson(res, 200, repo ?? { ok: true });
111
+ return true;
112
+ }
101
113
  const updated = await teamAuto.updateRepo(repoId, {
102
114
  schedule: typeof body.schedule === "string" ? body.schedule : undefined,
103
115
  maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
@@ -178,6 +178,9 @@ export function createTunnelManager(deps) {
178
178
  // an unexpected crash (which must clear the active state so /tunnel/status
179
179
  // never reports a dead tunnel as live).
180
180
  let userStopping = false;
181
+ // True while the gateway process itself is shutting down (detach()): the
182
+ // connector's death then is EXPECTED and must not tear down tunnel state.
183
+ let processShuttingDown = false;
181
184
  let startOp = { running: false, phase: "idle", detail: null };
182
185
  let installState = { running: false, phase: "idle", percent: null, detail: null };
183
186
  function isTunnelRequest(hostHeader) {
@@ -339,6 +342,14 @@ export function createTunnelManager(deps) {
339
342
  if (child !== proc)
340
343
  return;
341
344
  child = null;
345
+ // During process shutdown (detach()) the connector dies WITH the
346
+ // gateway; that is expected, and tunnel-state.json must survive so the
347
+ // next boot's recover() can reconnect the SAME tunnel (gate cookies
348
+ // stay valid). Only a genuine mid-run crash clears state.
349
+ if (processShuttingDown) {
350
+ logger.info("TeamClaw tunnel: connector exited during process shutdown; state retained for recovery");
351
+ return;
352
+ }
342
353
  if (!userStopping && handle) {
343
354
  handle = null;
344
355
  lastError = `tunnel connector exited unexpectedly (code ${code ?? "null"})`;
@@ -366,6 +377,16 @@ export function createTunnelManager(deps) {
366
377
  // Unexpected exit (crash, network loss, cloudflared auto-kill): tear
367
378
  // the logical state down too, otherwise status() keeps reporting
368
379
  // active=true and the UI shows a dead tunnel as live forever.
380
+ // EXCEPTION - process shutdown: when the gateway itself is stopping,
381
+ // the connector dies by design (SIGTERM cascade). Clearing state (and
382
+ // worse, DELETE-ing the relay tunnel) at that moment destroyed the
383
+ // recovery chain: the next boot found no tunnel-state.json and never
384
+ // reconnected, leaving the CNAME live but 530. Keep both state and the
385
+ // relay tunnel; recover() owns them next boot.
386
+ if (processShuttingDown) {
387
+ logger.info("TeamClaw tunnel: connector exited during process shutdown; state retained for recovery");
388
+ return;
389
+ }
369
390
  if (!userStopping && handle) {
370
391
  const gone = handle;
371
392
  handle = null;
@@ -390,6 +411,17 @@ export function createTunnelManager(deps) {
390
411
  child = null;
391
412
  }
392
413
  }
414
+ // Process-lifecycle teardown: kill ONLY the local connector. The remote
415
+ // tunnel (relay) and tunnel-state.json both survive, so the next gateway
416
+ // boot's recover() reconnects the SAME tunnel (id/gate token/cookies all
417
+ // preserved). This is the shutdown-path counterpart to recover(); stop()
418
+ // remains the user-facing "turn it off" (full teardown + relay DELETE).
419
+ function detach() {
420
+ processShuttingDown = true;
421
+ stopConnector();
422
+ logger.info(handle ? "TeamClaw tunnel: detached connector for process shutdown (state retained; recover on next boot)" : "TeamClaw tunnel: shutdown detach (no active connector)");
423
+ handle = null;
424
+ }
393
425
  async function stop() {
394
426
  userStopping = true;
395
427
  stopConnector();
@@ -562,7 +594,7 @@ export function createTunnelManager(deps) {
562
594
  job.then((r) => finish(r.ok ? "done" : "error", r.detail), (e) => finish("error", String(e)));
563
595
  return job;
564
596
  }
565
- return { start: launchStart, startSelfHosted, startQuick, stop, recover, status, installCloudflared, isTunnelRequest, gateAllows };
597
+ return { start: launchStart, startSelfHosted, startQuick, stop, detach, recover, status, installCloudflared, isTunnelRequest, gateAllows };
566
598
  }
567
599
  export function gatePageHtml(hostname, wrong) {
568
600
  return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TeamClaw Tunnel</title>
@@ -101,6 +101,18 @@ export function createTunnelGateRoutes(tunnelManager) {
101
101
  ];
102
102
  }
103
103
  /** /api/v1/tunnel/* management API (direct requests only, never via tunnel). */
104
+ // Audit trail for every tunnel lifecycle call (#ghost-stop): the gateway's
105
+ // plugin log previously only showed the EFFECT ("stopped team-..."), never
106
+ // the caller, so a stop of unknown origin was undiagnosable (two such
107
+ // incidents: 2026-11-12 14:23 and 15:20). Log origin + user-agent on every
108
+ // mutating tunnel endpoint; status stays quiet (polled constantly).
109
+ function tunnelCaller(req) {
110
+ const ua = String(req.headers["user-agent"] ?? "-");
111
+ const origin = String(req.headers.origin ?? "-");
112
+ const xff = String(req.headers["x-forwarded-for"] ?? "-");
113
+ const remote = req.socket.remoteAddress ?? "-";
114
+ return `caller=${remote} xff=${xff} origin=${origin} ua=${ua.slice(0, 120)}`;
115
+ }
104
116
  export function createTunnelManagementRoutes(tunnelManager, deps) {
105
117
  const { config, logger } = deps;
106
118
  // Issue #222 (coordinated scope): creating a public tunnel is an
@@ -141,6 +153,7 @@ export function createTunnelManagementRoutes(tunnelManager, deps) {
141
153
  if (!tunnelStartAllowedFrom(req, res)) {
142
154
  return;
143
155
  }
156
+ logger.info(`TeamClaw tunnel: start requested (${tunnelCaller(req)})`);
144
157
  const authStatus = await getGithubAuthManager(config, logger).getStatus();
145
158
  const account = authStatus.account;
146
159
  if (!account?.login) {
@@ -163,6 +176,7 @@ export function createTunnelManagementRoutes(tunnelManager, deps) {
163
176
  if (!tunnelStartAllowedFrom(req, res)) {
164
177
  return;
165
178
  }
179
+ logger.info(`TeamClaw tunnel: start-self-hosted requested (${tunnelCaller(req)})`);
166
180
  let token = "";
167
181
  try {
168
182
  const body = await readFormBody(req);
@@ -192,6 +206,7 @@ export function createTunnelManagementRoutes(tunnelManager, deps) {
192
206
  if (!tunnelStartAllowedFrom(req, res)) {
193
207
  return;
194
208
  }
209
+ logger.info(`TeamClaw tunnel: start-quick requested (${tunnelCaller(req)})`);
195
210
  const r = tunnelManager.startQuick();
196
211
  if (!r.launched) {
197
212
  sendError(res, 400, r.error ?? "failed to start quick tunnel");
@@ -203,7 +218,8 @@ export function createTunnelManagementRoutes(tunnelManager, deps) {
203
218
  {
204
219
  method: "POST",
205
220
  path: "/api/v1/tunnel/stop",
206
- handler: async ({ res }) => {
221
+ handler: async ({ req, res }) => {
222
+ logger.warn(`TeamClaw tunnel: STOP requested (${tunnelCaller(req)})`);
207
223
  await tunnelManager.stop();
208
224
  sendJson(res, 200, tunnelManager.status());
209
225
  },
@@ -1,4 +1,5 @@
1
1
  import { WebSocketServer, WebSocket } from "ws";
2
+ import { journalFromWsEvent } from "./journal.js";
2
3
  export class TeamWebSocketServer {
3
4
  wss = null;
4
5
  logger;
@@ -24,6 +25,9 @@ export class TeamWebSocketServer {
24
25
  broadcastUpdate(event) {
25
26
  if (!this.wss)
26
27
  return;
28
+ // Every broadcast also lands in the controller journal so the web UI's
29
+ // Activity tab can backfill history after a reconnect (#ui-blindness).
30
+ journalFromWsEvent(event);
27
31
  const data = JSON.stringify(event);
28
32
  for (const client of this.wss.clients) {
29
33
  if (client.readyState === WebSocket.OPEN) {
@@ -30,6 +30,7 @@ import { getActiveRoleIds, getActiveDefaultRole } from "../profile-loader.js";
30
30
  import { inferTaskRole } from "./role-inference.js";
31
31
  import { cloneJson, sleep } from "../shared/utils.js";
32
32
  import { appendNoProxyEntries, buildProvisionedWorkspaceDir, buildProvisionedWorkerConfig, getConfiguredWorkerWorkspaceDir, loadOpenClawConfig, } from "./provisioning-config.js";
33
+ import { journalRecord } from "./journal.js";
33
34
  import { isDockerHostNetwork, requiresDedicatedHostPortsForProvisioner, } from "./provisioning/backend-contract.js";
34
35
  import { ProcessProvisioner } from "./provisioning/process-supervisor.js";
35
36
  import { DockerProvisioner } from "./provisioning/docker.js";
@@ -177,6 +178,7 @@ export class WorkerProvisioningManager {
177
178
  return;
178
179
  }
179
180
  this.deps.logger.info(`Provisioner: terminating managed worker ${workerId} (${reason})`);
181
+ journalRecord("provisioner", "terminated", `${workerId} (${reason})`);
180
182
  await this.terminateManagedWorker(workerId, reason, "terminated");
181
183
  }
182
184
  /** Phase 2.1: suspend/resume the reconcile loop during a team profile switch. */
@@ -335,6 +337,7 @@ export class WorkerProvisioningManager {
335
337
  this.deps.logger.info(`Provisioner: allowing role ${role} because pending task demand exists outside configured workerProvisioningRoles`);
336
338
  }
337
339
  this.deps.logger.info(`Provisioner: role ${role} needs ${demand} additional worker(s) (${reason})`);
340
+ journalRecord("provisioner", "demand", `${role} needs +${demand} (${reason})`);
338
341
  }
339
342
  for (let i = 0; i < demand; i += 1) {
340
343
  if (this.hasRecentProvisioningFailure(role)) {
@@ -372,6 +375,7 @@ export class WorkerProvisioningManager {
372
375
  continue;
373
376
  }
374
377
  this.deps.logger.info(`Provisioner: warming ${role} worker (${reason})`);
378
+ journalRecord("provisioner", "warming", `warming ${role} (${reason})`);
375
379
  await this.launchWorker(role);
376
380
  }
377
381
  }
@@ -533,9 +537,41 @@ export class WorkerProvisioningManager {
533
537
  record.updatedAt = Date.now();
534
538
  });
535
539
  this.deps.logger.info(`Provisioner: launched ${role} worker ${workerId} via ${this.backend.type}`);
540
+ journalRecord("provisioner", "launched", `${role} ${workerId} via ${this.backend.type}`);
536
541
  }
537
542
  catch (err) {
538
543
  const message = err instanceof Error ? err.message : String(err);
544
+ // #stuck-classification: state-library lock family ("another gateway
545
+ // owns this state directory", "undergoing offline maintenance",
546
+ // "pending native opener", ENOENT mkdtemp on a vanished session) is
547
+ // self-healable by retiring the poisoned sandbox and re-launching on
548
+ // a fresh one. A bare cooldown would retry against the SAME stuck
549
+ // state forever (observed: hours of starvation, 2026-11-13).
550
+ const healable = /owns this state directory|undergoing offline maintenance|pending native opener|ENOENT.*mkdtemp/i.test(message);
551
+ if (healable && this.backend?.type === "process") {
552
+ this.deps.logger.warn(`Provisioner: state-library failure for ${workerId} - retiring the poisoned sandbox and retrying once on a fresh one...`);
553
+ try {
554
+ await this.terminateManagedWorker(workerId, `state-library self-heal: ${message.slice(0, 80)}`, "failed");
555
+ }
556
+ catch { /* best-effort */ }
557
+ try {
558
+ await this.launchWorker(role);
559
+ return;
560
+ }
561
+ catch (retryErr) {
562
+ const retryMessage = retryErr instanceof Error ? retryErr.message : String(retryErr);
563
+ this.deps.updateTeamState((state) => {
564
+ const record = ensureProvisioningState(state).workers[workerId];
565
+ if (record) {
566
+ record.status = "failed";
567
+ record.updatedAt = Date.now();
568
+ record.lastError = retryMessage;
569
+ }
570
+ });
571
+ this.deps.logger.warn(`Provisioner: self-heal retry also failed for ${workerId}: ${retryMessage}`);
572
+ return;
573
+ }
574
+ }
539
575
  this.deps.updateTeamState((state) => {
540
576
  const record = ensureProvisioningState(state).workers[workerId];
541
577
  if (!record) {
@@ -655,6 +655,42 @@ export async function updateTeamClawModelConfig(update, logger, env = process.en
655
655
  logger?.warn?.("TeamClaw: model config updated (hot-reload applies; restart the gateway if a change does not take effect)");
656
656
  return { configPath };
657
657
  }
658
+ /**
659
+ * Persist hot-reloadable worker-provisioning fields into the host
660
+ * openclaw.json plugins.entries.teamclaw.config (read-modify-write, same
661
+ * pattern as updateTeamClawModelConfig). Only whitelisted fields are
662
+ * touched; unknown keys in the existing plugin config are preserved.
663
+ */
664
+ export async function updateTeamClawProvisioningConfig(update, logger, env = process.env, homedir = os.homedir) {
665
+ const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
666
+ let parsed;
667
+ try {
668
+ parsed = JSON5.parse(await fs.readFile(configPath, "utf8"));
669
+ if (!isRecord(parsed)) {
670
+ throw new Error("host config is not an object");
671
+ }
672
+ }
673
+ catch (err) {
674
+ throw new Error(`failed to read host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
675
+ }
676
+ const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
677
+ const pluginEntries = isRecord(plugins.entries) ? plugins.entries : {};
678
+ const teamclawPlugin = isRecord(pluginEntries[TEAMCLAW_AGENT_ID]) ? pluginEntries[TEAMCLAW_AGENT_ID] : { enabled: true };
679
+ const pluginConfig = isRecord(teamclawPlugin.config)
680
+ ? { ...teamclawPlugin.config }
681
+ : {};
682
+ for (const [key, value] of Object.entries(update)) {
683
+ if (typeof value === "number" && Number.isFinite(value)) {
684
+ pluginConfig[key] = value;
685
+ }
686
+ }
687
+ pluginEntries[TEAMCLAW_AGENT_ID] = { ...teamclawPlugin, config: pluginConfig };
688
+ plugins.entries = pluginEntries;
689
+ parsed.plugins = plugins;
690
+ await fs.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
691
+ logger?.warn?.("TeamClaw: worker provisioning config persisted (hot-reload applies to the running controller)");
692
+ return { configPath };
693
+ }
658
694
  /**
659
695
  * Resolve the `projects/` root inside the TeamClaw workspace.
660
696
  * Each orchestration run or ad-hoc task gets its own subdirectory here.
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`, {
@@ -65,6 +65,19 @@ export async function sweepRepo(repo, client, now = Date.now()) {
65
65
  const pulls = repo.policy.actions.prReview
66
66
  ? await client.listPulls(owner, name, repo.cursors.etags)
67
67
  : [];
68
+ // #265: the commits leg was dead code (listCommits had zero callers,
69
+ // lastCommitSha never advanced) - the designed third signal source never
70
+ // ran. Wire it as an observation-only feed: fetch, filter past the cursor,
71
+ // and surface the delta. Cursor advance happens in advanceCursors (with
72
+ // the other legs, so dry-run semantics stay intact); it produces no task
73
+ // candidates (issue/pull policies stay the sole candidate sources).
74
+ const commits = await client.listCommits(owner, name, repo.cursors.lastCommitSha);
75
+ // Newest-first feed: when the cursor is set, stop the delta at the first
76
+ // entry whose sha equals it (that commit and everything after is already
77
+ // known). An unset cursor means first sweep: observe only, report nothing.
78
+ const newCommits = repo.cursors.lastCommitSha
79
+ ? commits.slice(0, (() => { const i = commits.findIndex((c) => c.sha === repo.cursors.lastCommitSha); return i === -1 ? commits.length : i; })())
80
+ : [];
68
81
  const candidates = [];
69
82
  for (const issue of issues) {
70
83
  // Dedup: seen map survives sweeps; a closed-then-reopened issue updates.
@@ -94,7 +107,15 @@ export async function sweepRepo(repo, client, now = Date.now()) {
94
107
  role: "qa",
95
108
  writeMode: "read-only",
96
109
  };
97
- if (repo.policy.actions.issueReview) {
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) {
98
119
  candidates.push({
99
120
  ...base,
100
121
  kind: "issueReview",
@@ -173,16 +194,22 @@ export async function sweepRepo(repo, client, now = Date.now()) {
173
194
  }
174
195
  }
175
196
  }
176
- return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls };
197
+ return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls, newCommits, commits };
177
198
  }
178
199
  /** Advance cursors after tasks were enqueued (or observed on first sweep). */
179
- export function advanceCursors(repo, issues, pulls, now = Date.now()) {
200
+ export function advanceCursors(repo, issues, pulls, now = Date.now(), commits = []) {
180
201
  for (const issue of issues) {
181
202
  repo.cursors.seen[`${repo.id}#issue-${issue.number}`] = Date.parse(issue.updatedAt) || now;
182
203
  }
183
204
  for (const pull of pulls) {
184
205
  repo.cursors.seen[`${repo.id}#pr-${pull.number}`] = Date.parse(pull.updated_at) || now;
185
206
  }
207
+ // Commit cursor: the feed is newest-first, so when anything came back the
208
+ // HEAD entry IS the new cursor. Empty feed keeps the old cursor (nothing
209
+ // new to advance to).
210
+ if (commits.length > 0) {
211
+ repo.cursors.lastCommitSha = commits[0].sha;
212
+ }
186
213
  // Cap the seen map so it cannot grow unbounded.
187
214
  const entries = Object.entries(repo.cursors.seen);
188
215
  if (entries.length > 2000) {