@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
@@ -9,6 +9,7 @@ import path from "node:path";
9
9
  import readline from "node:readline";
10
10
  import { spawn, type ChildProcess } from "node:child_process";
11
11
  import type { PluginLogger } from "../../../api.js";
12
+ import { resolveControllerTeamclawEntryPath } from "../provisioning-config.js";
12
13
  import {
13
14
  resolveDefaultOpenClawConfigPath,
14
15
  resolveDefaultTeamClawRuntimeRootDir,
@@ -28,7 +29,7 @@ export class ProcessProvisioner implements WorkerProvisionerBackend {
28
29
  readonly type = "process" as const;
29
30
  private readonly logger: PluginLogger;
30
31
  private readonly processByWorkerId = new Map<string, ChildProcess>();
31
- private readonly baseDirPromise: Promise<string>;
32
+ private baseDirPromise: Promise<string>; // mutable: ensureBaseDir self-heal swaps it
32
33
 
33
34
  constructor(logger: PluginLogger) {
34
35
  this.logger = logger;
@@ -37,8 +38,32 @@ export class ProcessProvisioner implements WorkerProvisionerBackend {
37
38
  .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
38
39
  }
39
40
 
41
+ /**
42
+ * #watchdog (observer-found 2026-11-13, workers starved 2.3h+): the
43
+ * session baseDir is created ONCE in the constructor and cached - if an
44
+ * external cleanup removes it (gateway restarts / culling sweeps), every
45
+ * later launch's mkdtemp hits ENOENT (mkdtemp never creates parents),
46
+ * the provisioner cools down, and pending tasks starve until process
47
+ * restart. Self-heal: verify the cached dir still exists on every
48
+ * launch; on ENOENT, rebuild it and swap the cached promise.
49
+ */
50
+ private async ensureBaseDir(): Promise<string> {
51
+ const dir = await this.baseDirPromise;
52
+ try {
53
+ await fs.stat(dir);
54
+ return dir;
55
+ } catch {
56
+ const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
57
+ const fresh = fs.mkdir(provisionedRoot, { recursive: true })
58
+ .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
59
+ this.baseDirPromise = fresh;
60
+ this.logger.warn?.(`TeamClaw: provisioner session dir vanished (${dir}) - rebuilt`);
61
+ return fresh;
62
+ }
63
+ }
64
+
40
65
  async launch(spec: LaunchSpec): Promise<LaunchResult> {
41
- const baseDir = await this.baseDirPromise;
66
+ const baseDir = await this.ensureBaseDir();
42
67
  const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
43
68
  const stateDir = path.join(runtimeHomeDir, ".openclaw");
44
69
  const configPath = path.join(stateDir, "openclaw.json");
@@ -61,6 +86,35 @@ export class ProcessProvisioner implements WorkerProvisionerBackend {
61
86
  });
62
87
  await fs.writeFile(configPath, spec.configJson, { encoding: "utf8", mode: 0o600 });
63
88
 
89
+ // #task-stuck (13th layer, physical half): the worker sandbox has no
90
+ // teamclaw installation of its own, and entries.enabled does not resolve
91
+ // the plugin. Symlink the controller's teamclaw package into the
92
+ // sandbox's extensions/ dir - the host auto-discovers extensions/ - and
93
+ // mirror it into the config's plugins.load.paths so discovery sees the
94
+ // same physical path. Idempotent; failures are non-fatal (worker still
95
+ // boots, just without the plugin).
96
+ try {
97
+ const controllerEntry = resolveControllerTeamclawEntryPath();
98
+ if (controllerEntry) {
99
+ const pkgDir = path.dirname(path.dirname(controllerEntry)); // dist/index.js -> package root
100
+ const extDir = path.join(stateDir, "extensions");
101
+ await fs.mkdir(extDir, { recursive: true });
102
+ const linkPath = path.join(extDir, "teamclaw");
103
+ await fs.rm(linkPath, { force: true }).catch(() => undefined);
104
+ await fs.symlink(pkgDir, linkPath, "dir");
105
+ // Mirror into the written config (configJson was already serialized).
106
+ try {
107
+ const cfg = JSON.parse(await fs.readFile(configPath, "utf8"));
108
+ const plugins = (cfg.plugins ??= {});
109
+ const load = (plugins.load ??= { paths: [] });
110
+ if (Array.isArray(load.paths) && !load.paths.includes(linkPath)) load.paths.push(linkPath);
111
+ await fs.writeFile(configPath, JSON.stringify(cfg, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
112
+ } catch { /* config mirror best-effort */ }
113
+ }
114
+ } catch (e) {
115
+ this.logger.warn?.(`TeamClaw: could not link teamclaw into worker extensions: ${e instanceof Error ? e.message : String(e)}`);
116
+ }
117
+
64
118
  const gatewayEntrypoint = resolveGatewayEntrypoint();
65
119
  const child = spawn(process.execPath, [
66
120
  gatewayEntrypoint,
@@ -17,6 +17,41 @@ import {
17
17
  TEAMCLAW_AGENT_ID,
18
18
  } from "../openclaw-workspace.js";
19
19
  import { cloneJson, pathExists, sanitizePathSegment } from "../shared/utils.js";
20
+ import os from "node:os";
21
+ import fsSync from "node:fs";
22
+
23
+ /**
24
+ * #task-stuck (13th layer): resolve the teamclaw entry the CONTROLLER is
25
+ * actually loading, so process workers can plugins.load the same physical
26
+ * path. Discovery order: openclaw npm projects generation dirs (newest
27
+ * mtime wins - that is what the host loaded), then the global node_modules
28
+ * install. Returns undefined when nothing resolvable exists.
29
+ */
30
+ export function resolveControllerTeamclawEntryPath(): string | undefined {
31
+ const candidates: string[] = [];
32
+ const home = process.env.OPENCLAW_HOME?.trim() || process.env.HOME?.trim() || os.homedir();
33
+ const projectsDir = path.join(home, ".openclaw", "npm", "projects");
34
+ try {
35
+ for (const proj of fsSync.readdirSync(projectsDir)) {
36
+ if (!proj.startsWith("teamclaws-teamclaw")) continue;
37
+ candidates.push(
38
+ path.join(projectsDir, proj, "node_modules", "@teamclaws", "teamclaw"),
39
+ );
40
+ }
41
+ } catch { /* no projects dir */ }
42
+ candidates.push(
43
+ "/opt/homebrew/lib/node_modules/@teamclaws/teamclaw/dist/index.js",
44
+ "/usr/local/lib/node_modules/@teamclaws/teamclaw/dist/index.js",
45
+ );
46
+ let best: { p: string; m: number } | undefined;
47
+ for (const p of candidates) {
48
+ try {
49
+ const m = fsSync.statSync(p).mtimeMs;
50
+ if (!best || m > best.m) best = { p, m };
51
+ } catch { /* candidate absent */ }
52
+ }
53
+ return best?.p;
54
+ }
20
55
 
21
56
  export function buildProvisionedWorkerConfig(
22
57
  baseConfig: Record<string, unknown>,
@@ -108,6 +143,25 @@ export function buildProvisionedWorkerConfig(
108
143
  if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
109
144
  delete plugins.load;
110
145
  }
146
+ // #task-stuck (2026-11-13, 13th layer): a PROCESS worker sandbox has NO
147
+ // local teamclaw installation (no extensions dir, no npm registration),
148
+ // and entries.enabled alone does not make the host resolve the plugin -
149
+ // the worker gateway booted as bare openclaw (plugins: anthropic,
150
+ // memory-core) and never registered with the controller, so pending
151
+ // tasks sat unclaimed forever. Point plugins.load at the CONTROLLER's
152
+ // teamclaw entry (the npm project dir the controller itself loads from).
153
+ if (controllerConfig.workerProvisioningType === "process" || !controllerConfig.workerProvisioningType) {
154
+ const controllerEntryPath = resolveControllerTeamclawEntryPath();
155
+ if (controllerEntryPath) {
156
+ // Host schema: plugins.load = { paths: string[] } (object, not array).
157
+ const loadObj = ensureRecord(plugins).load;
158
+ const existing = ensureRecord(loadObj && typeof loadObj === "object" ? loadObj : {});
159
+ const paths = Array.isArray(existing.paths) ? existing.paths.filter((p) => typeof p === "string") : [];
160
+ if (!paths.includes(controllerEntryPath)) paths.push(controllerEntryPath);
161
+ existing.paths = paths;
162
+ plugins.load = existing;
163
+ }
164
+ }
111
165
  const entries = ensureRecord(plugins.entries);
112
166
  const teamclawEntry = ensureRecord(entries.teamclaw);
113
167
  teamclawEntry.enabled = true;
@@ -52,6 +52,8 @@ import {
52
52
  teamProfileSwitchRoute,
53
53
  archivedTeamsRoute,
54
54
  } from "./status-routes.js";
55
+ import { teamConfigGetRoute, teamConfigPatchRoute } from "./config-routes.js";
56
+ import * as journalRoutes from "./journal.js";
55
57
  import {
56
58
  reportsListRoute,
57
59
  reportsSessionRoute,
@@ -594,4 +596,13 @@ export const controllerRouteTable: readonly RouteDef[] = [
594
596
  // { context } (initial business context). The handler enforces the
595
597
  // transition-matrix 503 itself (see workflow-routes.ts).
596
598
  { method: "POST", path: /^\/api\/v1\/workflows\/[^/]+\/start$/, handler: workflowStartRoute },
599
+ // Hot worker-provisioning config (#hot-config): GET snapshot + PATCH
600
+ // hot-apply. Appended at the table tail on the same append-only precedent
601
+ // (no path overlap with any earlier route).
602
+ { method: "GET", path: "/api/v1/team/config", handler: teamConfigGetRoute },
603
+ { method: "PATCH", path: "/api/v1/team/config", handler: teamConfigPatchRoute },
604
+ // Controller observability (#ui-blindness): event journal + gateway log
605
+ // tail for the web UI's Activity tab. Appended on the same precedent.
606
+ { method: "GET", path: "/api/v1/controller/journal", handler: journalRoutes.controllerJournalRoute },
607
+ { method: "GET", path: "/api/v1/controller/log-tail", handler: journalRoutes.controllerLogTailRoute },
597
608
  ];
@@ -469,6 +469,30 @@ export function createSecurityMiddleware(deps: SecurityMiddlewareDeps): Security
469
469
  return true;
470
470
  }
471
471
 
472
+ // Loopback is the controller host itself: the desktop app, the web UI,
473
+ // provisioned workers registering/heart-beating, and the owner's own
474
+ // CLI/curl. Requiring device pairing from the SAME MACHINE broke all of
475
+ // them the moment protection turned on (provisioned workers 401'd their
476
+ // registration and the worker pool starved; the local desktop could not
477
+ // talk to its own gateway - reported as a UX defect 2026-11-12). Local
478
+ // peers stay first-party: tunnel traffic never earns loopback trust
479
+ // (classifySecurityPeer strips it via viaTunnel) and LAN peers still
480
+ // need a device token. When a loopback caller DOES present a valid
481
+ // device token, authenticate anyway so lastSeenAt keeps updating (the
482
+ // token may belong to a paired remote console the owner is driving).
483
+ // VIA-TUNNEL requests are ALSO exempt: cloudflared dials in from
484
+ // loopback (the tunnel IS a local connection), and their credential is
485
+ // the tunnel GATE TOKEN - http-server checks gateAllows for every
486
+ // tunnel request AFTER this gate. Pairing them is a category error: a
487
+ // visitor can never obtain a pairing code, so protection-on would just
488
+ // kill the tunnel with an unanswerable 401 (user design ruling
489
+ // 2026-11-12). LAN peers remain the pairing boundary.
490
+ if (peer.loopback || peer.viaTunnel) {
491
+ const authAny = authenticateDeviceToken(state, extractDeviceToken(req));
492
+ if (authAny) touchDeviceLastSeen(deps, authAny.device.id);
493
+ return true;
494
+ }
495
+
472
496
  const auth = authenticateDeviceToken(state, extractDeviceToken(req));
473
497
  if (!auth) {
474
498
  deps.logger.warn(`Controller: rejected unauthenticated ${req.method ?? "?"} ${pathname} from ${peer.ip}${peer.viaTunnel ? " (via tunnel)" : ""}`);
@@ -492,6 +516,7 @@ export function createSecurityMiddleware(deps: SecurityMiddlewareDeps): Security
492
516
  */
493
517
  export type WebSocketUpgradeGuardDeps = SecurityMiddlewareDeps & {
494
518
  isTunnelHost: (host: string | undefined) => boolean;
519
+ gateAllows?: (req: { headers: Record<string, unknown> }) => boolean;
495
520
  };
496
521
 
497
522
  export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (req: IncomingMessage) => boolean {
@@ -503,6 +528,21 @@ export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (r
503
528
  recordNonLanPeerSignal(deps, state, peer, "/ws");
504
529
  return true;
505
530
  }
531
+ // 8b03ed6 layering (user design ruling): loopback peers are first-party
532
+ // (the host itself - web UI, desktop, provisioned workers) and NEVER
533
+ // need a pairing token. The HTTP gate got this exemption; this WS guard
534
+ // missed it and rejected every loopback UI connection (92362 rejects,
535
+ // user-found: tasks UI stuck on pending because /ws never upgraded).
536
+ if (peer.loopback) {
537
+ return true;
538
+ }
539
+ // Tunnel-origin upgrades (cloudflared loopback + tunnel Host): the
540
+ // visitor holds the GATE token, not a pairing token - same layering
541
+ // as the HTTP gate (a device token here would be an unanswerable
542
+ // wall, 8b03ed6). Verify the gate cookie instead.
543
+ if (peer.viaTunnel && deps.gateAllows && deps.gateAllows(req)) {
544
+ return true;
545
+ }
506
546
  let token = extractDeviceToken(req);
507
547
  if (!token) {
508
548
  const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
@@ -102,6 +102,18 @@ export async function handleTeamAutoRepoItemRequest(
102
102
  let body: Record<string, unknown> = {};
103
103
  try { body = await parseJsonBody(req); } catch { /* empty */ }
104
104
  try {
105
+ // #269 (user report): the enabled flag used to be silently dropped
106
+ // here - the web UI's disable toggle returned 200 but never reached
107
+ // setRepoEnabled, so sweeps kept running. Wire it explicitly; the
108
+ // enable/disable path has different persistence semantics (pausedReason
109
+ // + timer reschedule) than the plain field patch below.
110
+ if (typeof body.enabled === "boolean" && Object.keys(body).every((k) => k === "enabled")) {
111
+ await teamAuto.setRepoEnabled(repoId, body.enabled);
112
+ const status = await teamAuto.getStatus();
113
+ const repo = (status?.repos ?? []).find((r: { id: string }) => r.id === repoId);
114
+ sendJson(res, 200, repo ?? { ok: true });
115
+ return true;
116
+ }
105
117
  const updated = await teamAuto.updateRepo(repoId, {
106
118
  schedule: typeof body.schedule === "string" ? body.schedule : undefined,
107
119
  maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
@@ -203,6 +203,9 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
203
203
  // an unexpected crash (which must clear the active state so /tunnel/status
204
204
  // never reports a dead tunnel as live).
205
205
  let userStopping = false;
206
+ // True while the gateway process itself is shutting down (detach()): the
207
+ // connector's death then is EXPECTED and must not tear down tunnel state.
208
+ let processShuttingDown = false;
206
209
  let startOp: { running: boolean; phase: string; detail: string | null } = { running: false, phase: "idle", detail: null };
207
210
  let installState: { running: boolean; phase: string; percent: number | null; detail: string | null } = { running: false, phase: "idle", percent: null, detail: null };
208
211
 
@@ -359,6 +362,14 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
359
362
  logger.warn(`TeamClaw tunnel: cloudflared exited (code ${code})`);
360
363
  if (child !== proc) return;
361
364
  child = null;
365
+ // During process shutdown (detach()) the connector dies WITH the
366
+ // gateway; that is expected, and tunnel-state.json must survive so the
367
+ // next boot's recover() can reconnect the SAME tunnel (gate cookies
368
+ // stay valid). Only a genuine mid-run crash clears state.
369
+ if (processShuttingDown) {
370
+ logger.info("TeamClaw tunnel: connector exited during process shutdown; state retained for recovery");
371
+ return;
372
+ }
362
373
  if (!userStopping && handle) {
363
374
  handle = null;
364
375
  lastError = `tunnel connector exited unexpectedly (code ${code ?? "null"})`;
@@ -386,6 +397,16 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
386
397
  // Unexpected exit (crash, network loss, cloudflared auto-kill): tear
387
398
  // the logical state down too, otherwise status() keeps reporting
388
399
  // active=true and the UI shows a dead tunnel as live forever.
400
+ // EXCEPTION - process shutdown: when the gateway itself is stopping,
401
+ // the connector dies by design (SIGTERM cascade). Clearing state (and
402
+ // worse, DELETE-ing the relay tunnel) at that moment destroyed the
403
+ // recovery chain: the next boot found no tunnel-state.json and never
404
+ // reconnected, leaving the CNAME live but 530. Keep both state and the
405
+ // relay tunnel; recover() owns them next boot.
406
+ if (processShuttingDown) {
407
+ logger.info("TeamClaw tunnel: connector exited during process shutdown; state retained for recovery");
408
+ return;
409
+ }
389
410
  if (!userStopping && handle) {
390
411
  const gone = handle;
391
412
  handle = null;
@@ -412,6 +433,18 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
412
433
  }
413
434
  }
414
435
 
436
+ // Process-lifecycle teardown: kill ONLY the local connector. The remote
437
+ // tunnel (relay) and tunnel-state.json both survive, so the next gateway
438
+ // boot's recover() reconnects the SAME tunnel (id/gate token/cookies all
439
+ // preserved). This is the shutdown-path counterpart to recover(); stop()
440
+ // remains the user-facing "turn it off" (full teardown + relay DELETE).
441
+ function detach(): void {
442
+ processShuttingDown = true;
443
+ stopConnector();
444
+ logger.info(handle ? "TeamClaw tunnel: detached connector for process shutdown (state retained; recover on next boot)" : "TeamClaw tunnel: shutdown detach (no active connector)");
445
+ handle = null;
446
+ }
447
+
415
448
  async function stop(): Promise<void> {
416
449
  userStopping = true;
417
450
  stopConnector();
@@ -584,7 +617,7 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
584
617
  }
585
618
 
586
619
 
587
- return { start: launchStart, startSelfHosted, startQuick, stop, recover, status, installCloudflared, isTunnelRequest, gateAllows };
620
+ return { start: launchStart, startSelfHosted, startQuick, stop, detach, recover, status, installCloudflared, isTunnelRequest, gateAllows };
588
621
  }
589
622
 
590
623
  export type TunnelManager = ReturnType<typeof createTunnelManager>;
@@ -119,6 +119,19 @@ export function createTunnelGateRoutes(tunnelManager: TunnelManager): readonly R
119
119
  }
120
120
 
121
121
  /** /api/v1/tunnel/* management API (direct requests only, never via tunnel). */
122
+ // Audit trail for every tunnel lifecycle call (#ghost-stop): the gateway's
123
+ // plugin log previously only showed the EFFECT ("stopped team-..."), never
124
+ // the caller, so a stop of unknown origin was undiagnosable (two such
125
+ // incidents: 2026-11-12 14:23 and 15:20). Log origin + user-agent on every
126
+ // mutating tunnel endpoint; status stays quiet (polled constantly).
127
+ function tunnelCaller(req: IncomingMessage): string {
128
+ const ua = String(req.headers["user-agent"] ?? "-");
129
+ const origin = String(req.headers.origin ?? "-");
130
+ const xff = String(req.headers["x-forwarded-for"] ?? "-");
131
+ const remote = req.socket.remoteAddress ?? "-";
132
+ return `caller=${remote} xff=${xff} origin=${origin} ua=${ua.slice(0, 120)}`;
133
+ }
134
+
122
135
  export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps: ControllerHttpDeps): readonly RouteDef[] {
123
136
  const { config, logger } = deps;
124
137
 
@@ -161,6 +174,7 @@ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps:
161
174
  if (!tunnelStartAllowedFrom(req, res)) {
162
175
  return;
163
176
  }
177
+ logger.info(`TeamClaw tunnel: start requested (${tunnelCaller(req)})`);
164
178
  const authStatus = await getGithubAuthManager(config, logger).getStatus();
165
179
  const account = authStatus.account;
166
180
  if (!account?.login) { sendError(res, 401, "GitHub login required to share a tunnel"); return; }
@@ -180,6 +194,7 @@ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps:
180
194
  if (!tunnelStartAllowedFrom(req, res)) {
181
195
  return;
182
196
  }
197
+ logger.info(`TeamClaw tunnel: start-self-hosted requested (${tunnelCaller(req)})`);
183
198
  let token = "";
184
199
  try {
185
200
  const body = await readFormBody(req) as { token?: unknown };
@@ -202,6 +217,7 @@ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps:
202
217
  if (!tunnelStartAllowedFrom(req, res)) {
203
218
  return;
204
219
  }
220
+ logger.info(`TeamClaw tunnel: start-quick requested (${tunnelCaller(req)})`);
205
221
  const r = tunnelManager.startQuick();
206
222
  if (!r.launched) { sendError(res, 400, r.error ?? "failed to start quick tunnel"); return; }
207
223
  sendJson(res, 202, { launched: true, status: tunnelManager.status() });
@@ -210,7 +226,8 @@ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps:
210
226
  {
211
227
  method: "POST",
212
228
  path: "/api/v1/tunnel/stop",
213
- handler: async ({ res }) => {
229
+ handler: async ({ req, res }) => {
230
+ logger.warn(`TeamClaw tunnel: STOP requested (${tunnelCaller(req)})`);
214
231
  await tunnelManager.stop();
215
232
  sendJson(res, 200, tunnelManager.status());
216
233
  },
@@ -1,6 +1,7 @@
1
1
  import { WebSocketServer, WebSocket } from "ws";
2
2
  import type { IncomingMessage, Server } from "node:http";
3
3
  import type { PluginLogger } from "../../api.js";
4
+ import { journalFromWsEvent } from "./journal.js";
4
5
 
5
6
  export type WsEvent =
6
7
  | { type: "worker:online"; data: unknown }
@@ -20,6 +21,7 @@ export type WsEvent =
20
21
  | { type: "project:deleted"; data: unknown }
21
22
  | { type: "requirement:complete"; data: unknown }
22
23
  | { type: "report:ready"; data: unknown }
24
+ | { type: "team:config_updated"; data: unknown }
23
25
  | { type: "teamauto:activity"; data: unknown }
24
26
  // Phase 2.2 (design sections 2.3/4): team profile switch lifecycle. Event
25
27
  // names follow the design document verbatim (dot-separated) rather than the
@@ -76,6 +78,10 @@ export class TeamWebSocketServer {
76
78
  broadcastUpdate(event: WsEvent): void {
77
79
  if (!this.wss) return;
78
80
 
81
+ // Every broadcast also lands in the controller journal so the web UI's
82
+ // Activity tab can backfill history after a reconnect (#ui-blindness).
83
+ journalFromWsEvent(event);
84
+
79
85
  const data = JSON.stringify(event);
80
86
  for (const client of this.wss.clients) {
81
87
  if (client.readyState === WebSocket.OPEN) {
@@ -55,6 +55,7 @@ import {
55
55
  loadOpenClawConfig,
56
56
  } from "./provisioning-config.js";
57
57
  import type { WorkerProvisionerBackend } from "./provisioning/backend-contract.js";
58
+ import { journalRecord } from "./journal.js";
58
59
  import {
59
60
  isDockerHostNetwork,
60
61
  requiresDedicatedHostPortsForProvisioner,
@@ -236,6 +237,7 @@ export class WorkerProvisioningManager {
236
237
  }
237
238
 
238
239
  this.deps.logger.info(`Provisioner: terminating managed worker ${workerId} (${reason})`);
240
+ journalRecord("provisioner", "terminated", `${workerId} (${reason})`);
239
241
  await this.terminateManagedWorker(workerId, reason, "terminated");
240
242
  }
241
243
 
@@ -424,6 +426,7 @@ export class WorkerProvisioningManager {
424
426
  );
425
427
  }
426
428
  this.deps.logger.info(`Provisioner: role ${role} needs ${demand} additional worker(s) (${reason})`);
429
+ journalRecord("provisioner", "demand", `${role} needs +${demand} (${reason})`);
427
430
  }
428
431
  for (let i = 0; i < demand; i += 1) {
429
432
  if (this.hasRecentProvisioningFailure(role)) {
@@ -465,6 +468,7 @@ export class WorkerProvisioningManager {
465
468
  continue;
466
469
  }
467
470
  this.deps.logger.info(`Provisioner: warming ${role} worker (${reason})`);
471
+ journalRecord("provisioner", "warming", `warming ${role} (${reason})`);
468
472
  await this.launchWorker(role);
469
473
  }
470
474
  }
@@ -661,8 +665,38 @@ export class WorkerProvisioningManager {
661
665
  });
662
666
 
663
667
  this.deps.logger.info(`Provisioner: launched ${role} worker ${workerId} via ${this.backend.type}`);
668
+ journalRecord("provisioner", "launched", `${role} ${workerId} via ${this.backend.type}`);
664
669
  } catch (err) {
665
670
  const message = err instanceof Error ? err.message : String(err);
671
+ // #stuck-classification: state-library lock family ("another gateway
672
+ // owns this state directory", "undergoing offline maintenance",
673
+ // "pending native opener", ENOENT mkdtemp on a vanished session) is
674
+ // self-healable by retiring the poisoned sandbox and re-launching on
675
+ // a fresh one. A bare cooldown would retry against the SAME stuck
676
+ // state forever (observed: hours of starvation, 2026-11-13).
677
+ const healable = /owns this state directory|undergoing offline maintenance|pending native opener|ENOENT.*mkdtemp/i.test(message);
678
+ if (healable && this.backend?.type === "process") {
679
+ this.deps.logger.warn(`Provisioner: state-library failure for ${workerId} - retiring the poisoned sandbox and retrying once on a fresh one...`);
680
+ try {
681
+ await this.terminateManagedWorker(workerId, `state-library self-heal: ${message.slice(0, 80)}`, "failed");
682
+ } catch { /* best-effort */ }
683
+ try {
684
+ await this.launchWorker(role);
685
+ return;
686
+ } catch (retryErr) {
687
+ const retryMessage = retryErr instanceof Error ? retryErr.message : String(retryErr);
688
+ this.deps.updateTeamState((state) => {
689
+ const record = ensureProvisioningState(state).workers[workerId];
690
+ if (record) {
691
+ record.status = "failed";
692
+ record.updatedAt = Date.now();
693
+ record.lastError = retryMessage;
694
+ }
695
+ });
696
+ this.deps.logger.warn(`Provisioner: self-heal retry also failed for ${workerId}: ${retryMessage}`);
697
+ return;
698
+ }
699
+ }
666
700
  this.deps.updateTeamState((state) => {
667
701
  const record = ensureProvisioningState(state).workers[workerId];
668
702
  if (!record) {
@@ -807,6 +807,53 @@ export async function updateTeamClawModelConfig(
807
807
  return { configPath };
808
808
  }
809
809
 
810
+ /**
811
+ * Persist hot-reloadable worker-provisioning fields into the host
812
+ * openclaw.json plugins.entries.teamclaw.config (read-modify-write, same
813
+ * pattern as updateTeamClawModelConfig). Only whitelisted fields are
814
+ * touched; unknown keys in the existing plugin config are preserved.
815
+ */
816
+ export async function updateTeamClawProvisioningConfig(
817
+ update: {
818
+ workerProvisioningMinPerRole?: number;
819
+ workerProvisioningMaxPerRole?: number;
820
+ workerProvisioningIdleTtlMs?: number;
821
+ },
822
+ logger?: { warn?: (message: string) => void },
823
+ env: NodeJS.ProcessEnv = process.env,
824
+ homedir: () => string = os.homedir,
825
+ ): Promise<{ configPath: string }> {
826
+ const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
827
+ let parsed: Record<string, unknown>;
828
+ try {
829
+ parsed = JSON5.parse(await fs.readFile(configPath, "utf8")) as Record<string, unknown>;
830
+ if (!isRecord(parsed)) {
831
+ throw new Error("host config is not an object");
832
+ }
833
+ } catch (err) {
834
+ throw new Error(`failed to read host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
835
+ }
836
+
837
+ const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
838
+ const pluginEntries = isRecord(plugins.entries) ? plugins.entries : {};
839
+ const teamclawPlugin = isRecord(pluginEntries[TEAMCLAW_AGENT_ID]) ? pluginEntries[TEAMCLAW_AGENT_ID] : { enabled: true };
840
+ const pluginConfig = isRecord((teamclawPlugin as { config?: unknown }).config)
841
+ ? { ...(teamclawPlugin as { config: Record<string, unknown> }).config }
842
+ : {};
843
+ for (const [key, value] of Object.entries(update)) {
844
+ if (typeof value === "number" && Number.isFinite(value)) {
845
+ pluginConfig[key] = value;
846
+ }
847
+ }
848
+ pluginEntries[TEAMCLAW_AGENT_ID] = { ...teamclawPlugin, config: pluginConfig };
849
+ plugins.entries = pluginEntries;
850
+ parsed.plugins = plugins;
851
+
852
+ await fs.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
853
+ logger?.warn?.("TeamClaw: worker provisioning config persisted (hot-reload applies to the running controller)");
854
+ return { configPath };
855
+ }
856
+
810
857
  /**
811
858
  * Resolve the `projects/` root inside the TeamClaw workspace.
812
859
  * Each orchestration run or ad-hoc task gets its own subdirectory here.
package/src/state.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  StartupProvisioningReadiness,
8
8
  TeamProvisioningState,
9
9
  TeamState,
10
+ TeamMessage,
10
11
  WorkerIdentity,
11
12
  } from "./types.js";
12
13
  import { validateRoleIdList } from "./roles.js";
@@ -240,6 +241,22 @@ async function writeFileAtomically(filePath: string, contents: string): Promise<
240
241
  // filesystems (e.g. network mounts) reject explicit chmod.
241
242
  }
242
243
  await fs.rename(tmpPath, filePath);
244
+ // #267-4 hygiene: crash/rename failures used to leave *.tmp-* siblings
245
+ // forever (observed: 16 residue files in the runtime dir). Best-effort
246
+ // sweep of same-prefix leftovers older than 1h - never throws.
247
+ try {
248
+ const dir = path.dirname(filePath);
249
+ const prefix = path.basename(filePath) + ".tmp-";
250
+ const stale = Date.now() - 3_600_000;
251
+ for (const name of await fs.readdir(dir)) {
252
+ if (!name.startsWith(prefix)) continue;
253
+ const full = path.join(dir, name);
254
+ const st = await fs.stat(full).catch(() => null);
255
+ if (st && st.mtimeMs < stale) await fs.unlink(full).catch(() => {});
256
+ }
257
+ } catch {
258
+ // Hygiene is best-effort: any fs failure here is silently ignored.
259
+ }
243
260
  }
244
261
 
245
262
  function enqueueAtomicWrite(filePath: string, contents: string): Promise<void> {
@@ -280,8 +297,7 @@ function errorMessage(error: unknown): string {
280
297
  return error instanceof Error ? error.message : String(error);
281
298
  }
282
299
 
283
- async function loadTeamState(teamName: string): Promise<TeamState | null> {
284
- // Review fix (Phase 1.6): the instance-scoped team-state.json is the
300
+ async function loadTeamState(teamName: string): Promise<TeamState | null> { // Review fix (Phase 1.6): the instance-scoped team-state.json is the
285
301
  // primary state file, and when it EXISTS it is authoritative. A
286
302
  // present-but-corrupt primary is a fatal error, never a silent fallback to
287
303
  // the legacy snapshot - falling back would rewind the team to the
@@ -290,6 +306,11 @@ async function loadTeamState(teamName: string): Promise<TeamState | null> {
290
306
  let primaryRaw: string | null = null;
291
307
  try {
292
308
  primaryRaw = await fs.readFile(teamStateFilePath(), "utf8");
309
+ // #270: baseline the mtime right after reading so a foreign write between
310
+ // load and our first save is detected (not blindly overwritten).
311
+ try {
312
+ teamStateMtime.set(teamStateFilePath(), (await fs.stat(teamStateFilePath())).mtimeMs);
313
+ } catch { /* stat race - next save re-baselines */ }
293
314
  } catch (error) {
294
315
  if (!isFileMissing(error)) {
295
316
  throw new Error(
@@ -330,6 +351,41 @@ async function loadTeamState(teamName: string): Promise<TeamState | null> {
330
351
  }
331
352
  }
332
353
 
354
+ // #270 lazy merge-on-write: last mtime this process observed for the team
355
+ // state file. A disk file NEWER than this stamp means another process wrote
356
+ // it (multi-gateway sharing one store) - the next save merges instead of
357
+ // blindly overwriting (which is how tasks "evaporated": 155/81 -> 135/72).
358
+ // Single-process cost: one stat() per save; the 24MB re-read+merge only
359
+ // happens when a foreign write is actually detected.
360
+ const teamStateMtime = new Map<string, number>();
361
+
362
+ /** #270: fold foreign keys back in. Key-level policy - keys present in the
363
+ * foreign snapshot but missing from OUR in-memory state are re-added (they
364
+ * were created by another process and a blind full-file write would erase
365
+ * them). Keys we hold locally always win (this process is the most recent
366
+ * writer for them). Messages union by id. */
367
+ function mergeForeignTeamState(state: TeamState, disk: Partial<TeamState>): void {
368
+ const recordKeys = ["workers", "tasks", "controllerRuns", "projects", "clarifications", "previews", "reports"] as const;
369
+ for (const key of recordKeys) {
370
+ const foreign = disk[key] as Record<string, unknown> | undefined;
371
+ if (!foreign || typeof foreign !== "object") continue;
372
+ const ours = (state[key] ?? {}) as Record<string, unknown>;
373
+ for (const [k, v] of Object.entries(foreign)) {
374
+ if (!(k in ours)) ours[k] = v;
375
+ }
376
+ (state as Record<string, unknown>)[key] = ours;
377
+ }
378
+ const foreignMsgs = Array.isArray(disk.messages) ? disk.messages : [];
379
+ if (foreignMsgs.length) {
380
+ const seen = new Set(state.messages.map((m) => m.id));
381
+ for (const m of foreignMsgs) {
382
+ if (m && typeof m === "object" && typeof (m as TeamMessage).id === "string" && !seen.has((m as TeamMessage).id)) {
383
+ state.messages.push(m as TeamMessage);
384
+ }
385
+ }
386
+ }
387
+ }
388
+
333
389
  async function saveTeamState(state: TeamState): Promise<void> {
334
390
  await ensureDir(STATE_DIR);
335
391
  const filePath = teamStateFilePath();
@@ -348,7 +404,22 @@ async function saveTeamState(state: TeamState): Promise<void> {
348
404
  state.projects = state.projects && typeof state.projects === "object"
349
405
  ? state.projects
350
406
  : {};
407
+ // #270: if the disk file is newer than what THIS process last observed,
408
+ // another gateway wrote it - fold its keys back in before overwriting.
409
+ try {
410
+ const st = await fs.stat(filePath);
411
+ const known = teamStateMtime.get(filePath);
412
+ if (known !== undefined && st.mtimeMs > known) {
413
+ const disk = JSON.parse(await fs.readFile(filePath, "utf8")) as Partial<TeamState>;
414
+ mergeForeignTeamState(state, disk);
415
+ }
416
+ } catch {
417
+ /* first save / stat race - proceed with a plain write */
418
+ }
351
419
  await enqueueAtomicWrite(filePath, `${JSON.stringify(state, null, 2)}\n`);
420
+ try {
421
+ teamStateMtime.set(filePath, (await fs.stat(filePath)).mtimeMs);
422
+ } catch { /* renamed away mid-write - next save re-baselines */ }
352
423
  }
353
424
 
354
425
  // ---------------------------------------------------------------------------