@teamclaws/teamclaw 2026.11.2 → 2026.11.4

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 (38) hide show
  1. package/dist/src/controller/http-server.js +18 -0
  2. package/dist/src/controller/journal.js +68 -0
  3. package/dist/src/controller/provisioning/process-supervisor.js +58 -2
  4. package/dist/src/controller/provisioning-config.js +53 -0
  5. package/dist/src/controller/route-table.js +5 -0
  6. package/dist/src/controller/security.js +39 -0
  7. package/dist/src/controller/teamauto-routes.js +12 -0
  8. package/dist/src/controller/tunnel-manager.js +33 -1
  9. package/dist/src/controller/tunnel-routes.js +17 -1
  10. package/dist/src/controller/websocket.js +4 -0
  11. package/dist/src/controller/worker-provisioning.js +36 -0
  12. package/dist/src/state.js +77 -1
  13. package/dist/src/teamauto/github-client.js +39 -0
  14. package/dist/src/teamauto/scanner.js +9 -1
  15. package/dist/src/teamauto/scheduler.js +368 -17
  16. package/dist/src/teamauto/store.js +13 -0
  17. package/dist/src/ui/app.js +44 -0
  18. package/dist/src/ui/index.html +15 -0
  19. package/openclaw.plugin.json +1 -1
  20. package/package.json +1 -1
  21. package/src/controller/http-server.ts +18 -0
  22. package/src/controller/journal.ts +89 -0
  23. package/src/controller/provisioning/process-supervisor.ts +56 -2
  24. package/src/controller/provisioning-config.ts +54 -0
  25. package/src/controller/route-table.ts +5 -0
  26. package/src/controller/security.ts +40 -0
  27. package/src/controller/teamauto-routes.ts +12 -0
  28. package/src/controller/tunnel-manager.ts +34 -1
  29. package/src/controller/tunnel-routes.ts +18 -1
  30. package/src/controller/websocket.ts +5 -0
  31. package/src/controller/worker-provisioning.ts +34 -0
  32. package/src/state.ts +73 -2
  33. package/src/teamauto/github-client.ts +43 -0
  34. package/src/teamauto/scanner.ts +9 -1
  35. package/src/teamauto/scheduler.ts +372 -17
  36. package/src/teamauto/store.ts +40 -1
  37. package/src/ui/app.js +44 -0
  38. package/src/ui/index.html +15 -0
@@ -212,6 +212,7 @@ export function createControllerHttpServer(deps) {
212
212
  verifyUpgrade: createWebSocketUpgradeGuard({
213
213
  ...deps,
214
214
  isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
215
+ gateAllows: (req) => tunnelManagerSingleton?.gateAllows(req) ?? false,
215
216
  }),
216
217
  });
217
218
  // Plugin shutdown: kill the local connector and tear down the remote
@@ -227,6 +228,23 @@ export function createControllerHttpServer(deps) {
227
228
  void tunnelManagerSingleton.recover().catch((err) => {
228
229
  logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
229
230
  });
231
+ // Shutdown counterpart of the boot recover above: when the gateway process
232
+ // stops (SIGTERM/SIGINT - e.g. a config change restarting the plugin, or
233
+ // launchctl kickstart), detach() kills ONLY the local connector and keeps
234
+ // both tunnel-state.json and the remote relay tunnel alive, so the next
235
+ // boot's recover() reconnects the SAME tunnel. Without this, the
236
+ // connector's exit handler ran mid-shutdown, cleared the state file and
237
+ // DELETEd the relay tunnel - after which nothing could recover and the
238
+ // hostname served 530 (issue timeline: 2026-11-12, two consecutive
239
+ // restarts). Idempotent and safe to register repeatedly per http server.
240
+ for (const signal of ["SIGTERM", "SIGINT"]) {
241
+ process.on(signal, () => {
242
+ try {
243
+ tunnelManagerSingleton?.detach();
244
+ }
245
+ catch { /* best effort during shutdown */ }
246
+ });
247
+ }
230
248
  setTimeout(() => {
231
249
  const state = deps.getTeamState();
232
250
  const pendingCount = state
@@ -0,0 +1,68 @@
1
+ // Controller activity journal (#ui-blindness): an in-memory ring of recent
2
+ // controller-side events, plus a tail reader for the teamclaw-relevant slice
3
+ // of the host gateway log. The web UI's Activity tab polls the journal and
4
+ // follows the log tail so operators can SEE provisioning, sweeps, task
5
+ // routing and tunnel lifecycle without ssh-ing into logs.
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { sendJson } from "../protocol.js";
10
+ const RING_LIMIT = 400;
11
+ const ring = [];
12
+ /** Record a controller event into the ring (callers also broadcast it). */
13
+ export function journalRecord(source, type, summary) {
14
+ ring.push({ at: Date.now(), source, type, summary: summary.slice(0, 240) });
15
+ if (ring.length > RING_LIMIT)
16
+ ring.splice(0, ring.length - RING_LIMIT);
17
+ }
18
+ /** Summarize a broadcast WS event into the journal (best effort, never throws). */
19
+ export function journalFromWsEvent(event) {
20
+ try {
21
+ const t = String(event.type ?? "unknown");
22
+ if (t === "task:created" || t === "task:completed" || t === "task:updated" || t === "worker:online" || t === "worker:offline" || t === "team:config_updated" || t === "controller:run") {
23
+ journalRecord("ws", t, JSON.stringify(event.data ?? {}).slice(0, 200));
24
+ }
25
+ }
26
+ catch { /* journal must never break broadcasting */ }
27
+ }
28
+ export function journalSnapshot(limit = 200) {
29
+ return ring.slice(-Math.min(limit, RING_LIMIT));
30
+ }
31
+ // ---------------------------------------------------------------------------
32
+ // Host gateway log tail (read-only). The teamclaw plugin logs land in the
33
+ // openclaw gateway log; filter to the teamclaw-relevant lines.
34
+ // ---------------------------------------------------------------------------
35
+ const TEAMCLAW_LOG_FILTER = /TeamClaw|TeamAuto|Provisioner|ProvisionedWorker|TaskRouter|tunnel|Controller:/i;
36
+ function gatewayLogCandidates() {
37
+ const home = process.env.OPENCLAW_HOME || path.join(os.homedir(), ".openclaw");
38
+ return [
39
+ process.env.TEAMCLAW_GATEWAY_LOG,
40
+ path.join(home, "logs", "gateway.log"),
41
+ path.join(process.env.HOME ?? "", "Library", "Logs", "openclaw", "gateway.log"),
42
+ ].filter((p) => Boolean(p));
43
+ }
44
+ export function readGatewayLogTail(lines = 200, filter = true) {
45
+ for (const candidate of gatewayLogCandidates()) {
46
+ try {
47
+ const raw = fs.readFileSync(candidate, "utf8");
48
+ const all = raw.split("\n").filter((l) => l.trim().length > 0);
49
+ const picked = filter ? all.filter((l) => TEAMCLAW_LOG_FILTER.test(l)) : all;
50
+ return { path: candidate, lines: picked.slice(-lines) };
51
+ }
52
+ catch {
53
+ // try next candidate
54
+ }
55
+ }
56
+ return { path: null, lines: [] };
57
+ }
58
+ // Route handlers (bound in route-table.ts, appended at the table tail on the
59
+ // append-only precedent; both read-only GETs).
60
+ export function controllerJournalRoute({ res, requestUrl }) {
61
+ const limit = Math.min(Math.max(parseInt(requestUrl.searchParams.get("limit") ?? "200", 10) || 200, 1), 400);
62
+ sendJson(res, 200, { events: journalSnapshot(limit) });
63
+ }
64
+ export function controllerLogTailRoute({ res, requestUrl }) {
65
+ const lines = Math.min(Math.max(parseInt(requestUrl.searchParams.get("lines") ?? "200", 10) || 200, 1), 1000);
66
+ const unfiltered = requestUrl.searchParams.get("all") === "1";
67
+ sendJson(res, 200, readGatewayLogTail(lines, !unfiltered));
68
+ }
@@ -8,6 +8,7 @@ import fs from "node:fs/promises";
8
8
  import path from "node:path";
9
9
  import readline from "node:readline";
10
10
  import { spawn } from "node:child_process";
11
+ import { resolveControllerTeamclawEntryPath } from "../provisioning-config.js";
11
12
  import { resolveDefaultOpenClawConfigPath, resolveDefaultTeamClawRuntimeRootDir, } from "../../openclaw-workspace.js";
12
13
  import { pathExists, sanitizePathSegment } from "../../shared/utils.js";
13
14
  import { copyControllerAuthProfiles } from "../provisioning-config.js";
@@ -17,15 +18,39 @@ export class ProcessProvisioner {
17
18
  type = "process";
18
19
  logger;
19
20
  processByWorkerId = new Map();
20
- baseDirPromise;
21
+ baseDirPromise; // mutable: ensureBaseDir self-heal swaps it
21
22
  constructor(logger) {
22
23
  this.logger = logger;
23
24
  const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
24
25
  this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
25
26
  .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
26
27
  }
28
+ /**
29
+ * #watchdog (observer-found 2026-11-13, workers starved 2.3h+): the
30
+ * session baseDir is created ONCE in the constructor and cached - if an
31
+ * external cleanup removes it (gateway restarts / culling sweeps), every
32
+ * later launch's mkdtemp hits ENOENT (mkdtemp never creates parents),
33
+ * the provisioner cools down, and pending tasks starve until process
34
+ * restart. Self-heal: verify the cached dir still exists on every
35
+ * launch; on ENOENT, rebuild it and swap the cached promise.
36
+ */
37
+ async ensureBaseDir() {
38
+ const dir = await this.baseDirPromise;
39
+ try {
40
+ await fs.stat(dir);
41
+ return dir;
42
+ }
43
+ catch {
44
+ const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
45
+ const fresh = fs.mkdir(provisionedRoot, { recursive: true })
46
+ .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
47
+ this.baseDirPromise = fresh;
48
+ this.logger.warn?.(`TeamClaw: provisioner session dir vanished (${dir}) - rebuilt`);
49
+ return fresh;
50
+ }
51
+ }
27
52
  async launch(spec) {
28
- const baseDir = await this.baseDirPromise;
53
+ const baseDir = await this.ensureBaseDir();
29
54
  const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
30
55
  const stateDir = path.join(runtimeHomeDir, ".openclaw");
31
56
  const configPath = path.join(stateDir, "openclaw.json");
@@ -48,6 +73,37 @@ export class ProcessProvisioner {
48
73
  throw err;
49
74
  });
50
75
  await fs.writeFile(configPath, spec.configJson, { encoding: "utf8", mode: 0o600 });
76
+ // #task-stuck (13th layer, physical half): the worker sandbox has no
77
+ // teamclaw installation of its own, and entries.enabled does not resolve
78
+ // the plugin. Symlink the controller's teamclaw package into the
79
+ // sandbox's extensions/ dir - the host auto-discovers extensions/ - and
80
+ // mirror it into the config's plugins.load.paths so discovery sees the
81
+ // same physical path. Idempotent; failures are non-fatal (worker still
82
+ // boots, just without the plugin).
83
+ try {
84
+ const controllerEntry = resolveControllerTeamclawEntryPath();
85
+ if (controllerEntry) {
86
+ const pkgDir = path.dirname(path.dirname(controllerEntry)); // dist/index.js -> package root
87
+ const extDir = path.join(stateDir, "extensions");
88
+ await fs.mkdir(extDir, { recursive: true });
89
+ const linkPath = path.join(extDir, "teamclaw");
90
+ await fs.rm(linkPath, { force: true }).catch(() => undefined);
91
+ await fs.symlink(pkgDir, linkPath, "dir");
92
+ // Mirror into the written config (configJson was already serialized).
93
+ try {
94
+ const cfg = JSON.parse(await fs.readFile(configPath, "utf8"));
95
+ const plugins = (cfg.plugins ??= {});
96
+ const load = (plugins.load ??= { paths: [] });
97
+ if (Array.isArray(load.paths) && !load.paths.includes(linkPath))
98
+ load.paths.push(linkPath);
99
+ await fs.writeFile(configPath, JSON.stringify(cfg, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
100
+ }
101
+ catch { /* config mirror best-effort */ }
102
+ }
103
+ }
104
+ catch (e) {
105
+ this.logger.warn?.(`TeamClaw: could not link teamclaw into worker extensions: ${e instanceof Error ? e.message : String(e)}`);
106
+ }
51
107
  const gatewayEntrypoint = resolveGatewayEntrypoint();
52
108
  const child = spawn(process.execPath, [
53
109
  gatewayEntrypoint,
@@ -9,6 +9,39 @@ import path from "node:path";
9
9
  import JSON5 from "json5";
10
10
  import { resolveDefaultOpenClawConfigPath, resolveDefaultOpenClawStateDir, resolveDefaultAgentDir, resolveTeamClawAgentDir, resolveTeamClawAgentWorkspaceRootDir, TEAMCLAW_AGENT_ID, } from "../openclaw-workspace.js";
11
11
  import { cloneJson, pathExists, sanitizePathSegment } from "../shared/utils.js";
12
+ import os from "node:os";
13
+ import fsSync from "node:fs";
14
+ /**
15
+ * #task-stuck (13th layer): resolve the teamclaw entry the CONTROLLER is
16
+ * actually loading, so process workers can plugins.load the same physical
17
+ * path. Discovery order: openclaw npm projects generation dirs (newest
18
+ * mtime wins - that is what the host loaded), then the global node_modules
19
+ * install. Returns undefined when nothing resolvable exists.
20
+ */
21
+ export function resolveControllerTeamclawEntryPath() {
22
+ const candidates = [];
23
+ const home = process.env.OPENCLAW_HOME?.trim() || process.env.HOME?.trim() || os.homedir();
24
+ const projectsDir = path.join(home, ".openclaw", "npm", "projects");
25
+ try {
26
+ for (const proj of fsSync.readdirSync(projectsDir)) {
27
+ if (!proj.startsWith("teamclaws-teamclaw"))
28
+ continue;
29
+ candidates.push(path.join(projectsDir, proj, "node_modules", "@teamclaws", "teamclaw"));
30
+ }
31
+ }
32
+ catch { /* no projects dir */ }
33
+ candidates.push("/opt/homebrew/lib/node_modules/@teamclaws/teamclaw/dist/index.js", "/usr/local/lib/node_modules/@teamclaws/teamclaw/dist/index.js");
34
+ let best;
35
+ for (const p of candidates) {
36
+ try {
37
+ const m = fsSync.statSync(p).mtimeMs;
38
+ if (!best || m > best.m)
39
+ best = { p, m };
40
+ }
41
+ catch { /* candidate absent */ }
42
+ }
43
+ return best?.p;
44
+ }
12
45
  export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec) {
13
46
  const config = cloneJson(baseConfig);
14
47
  delete config.channels;
@@ -84,6 +117,26 @@ export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec)
84
117
  if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
85
118
  delete plugins.load;
86
119
  }
120
+ // #task-stuck (2026-11-13, 13th layer): a PROCESS worker sandbox has NO
121
+ // local teamclaw installation (no extensions dir, no npm registration),
122
+ // and entries.enabled alone does not make the host resolve the plugin -
123
+ // the worker gateway booted as bare openclaw (plugins: anthropic,
124
+ // memory-core) and never registered with the controller, so pending
125
+ // tasks sat unclaimed forever. Point plugins.load at the CONTROLLER's
126
+ // teamclaw entry (the npm project dir the controller itself loads from).
127
+ if (controllerConfig.workerProvisioningType === "process" || !controllerConfig.workerProvisioningType) {
128
+ const controllerEntryPath = resolveControllerTeamclawEntryPath();
129
+ if (controllerEntryPath) {
130
+ // Host schema: plugins.load = { paths: string[] } (object, not array).
131
+ const loadObj = ensureRecord(plugins).load;
132
+ const existing = ensureRecord(loadObj && typeof loadObj === "object" ? loadObj : {});
133
+ const paths = Array.isArray(existing.paths) ? existing.paths.filter((p) => typeof p === "string") : [];
134
+ if (!paths.includes(controllerEntryPath))
135
+ paths.push(controllerEntryPath);
136
+ existing.paths = paths;
137
+ plugins.load = existing;
138
+ }
139
+ }
87
140
  const entries = ensureRecord(plugins.entries);
88
141
  const teamclawEntry = ensureRecord(entries.teamclaw);
89
142
  teamclawEntry.enabled = true;
@@ -4,6 +4,7 @@ import { workspaceStatusRoute, workspaceChangeDirRoute, modelsConfigGetRoute, mo
4
4
  import { controllerManifestRoute, controllerRunsListRoute, projectDeleteRoute, controllerRunDeleteRoute, controllerIntakeRoute, } from "./controller-routes.js";
5
5
  import { teamStatsRoute, teamStatusRoute, teamRolesRoute, teamProfilesListRoute, teamProfileGetRoute, teamProfileSwitchRoute, archivedTeamsRoute, } from "./status-routes.js";
6
6
  import { teamConfigGetRoute, teamConfigPatchRoute } from "./config-routes.js";
7
+ import * as journalRoutes from "./journal.js";
7
8
  import { reportsListRoute, reportsSessionRoute, healthRoute, } from "./report-routes.js";
8
9
  import { handleTeamAutoActivityRequest, handleTeamAutoReposListRequest, handleTeamAutoRepoCandidatesRequest, handleTeamAutoRepoBindRequest, handleTeamAutoRepoItemRequest, } from "./teamauto-routes.js";
9
10
  import { handleRepoStatusRequest, handleRepoBundleRequest, repoImportRoute, } from "./repo-routes.js";
@@ -378,4 +379,8 @@ export const controllerRouteTable = [
378
379
  // (no path overlap with any earlier route).
379
380
  { method: "GET", path: "/api/v1/team/config", handler: teamConfigGetRoute },
380
381
  { method: "PATCH", path: "/api/v1/team/config", handler: teamConfigPatchRoute },
382
+ // Controller observability (#ui-blindness): event journal + gateway log
383
+ // tail for the web UI's Activity tab. Appended on the same precedent.
384
+ { method: "GET", path: "/api/v1/controller/journal", handler: journalRoutes.controllerJournalRoute },
385
+ { method: "GET", path: "/api/v1/controller/log-tail", handler: journalRoutes.controllerLogTailRoute },
381
386
  ];
@@ -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) {