@teamclaws/teamclaw 2026.4.4 → 2026.5.0

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.
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import http from "node:http";
4
4
  import zlib from "node:zlib";
5
+ import { execFileSync } from "node:child_process";
5
6
  import type { IncomingMessage, ServerResponse } from "node:http";
6
7
  import type { OpenClawPluginApi, PluginLogger } from "../../api.js";
7
8
  import type {
@@ -51,6 +52,9 @@ import { TeamWebSocketServer } from "./websocket.js";
51
52
  import type { WorkerProvisioningManager } from "./worker-provisioning.js";
52
53
  import type { PreviewManager } from "./preview-manager.js";
53
54
  import { createControllerPromptInjector } from "./prompt-injector.js";
55
+ import { getGithubAuthManager } from "./github-auth.js";
56
+ import { createGithubClient } from "../teamauto/github-client.js";
57
+ import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
54
58
  import { buildControllerNoWorkersMessage, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
55
59
  import { generateDeliveryReport, isSessionComplete, renderReportHtml, type DeliveryReport } from "./delivery-report.js";
56
60
  import {
@@ -93,6 +97,8 @@ export type ControllerHttpDeps = {
93
97
  previewManager?: PreviewManager;
94
98
  /** Late-bound kickoff handler for automatic team kickoff on complex projects. */
95
99
  getKickoffHandler?: () => KickoffHandler | undefined;
100
+ /** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
101
+ getTeamAutoScheduler?: () => TeamAutoScheduler | null;
96
102
  };
97
103
 
98
104
  const MAX_TASK_EXECUTION_EVENTS = 250;
@@ -3460,6 +3466,22 @@ function scheduleProvisioningReconcile(deps: ControllerHttpDeps, reason: string)
3460
3466
  void deps.workerProvisioningManager?.requestReconcile(reason);
3461
3467
  }
3462
3468
 
3469
+ /** Collaboration contract helpers: at most ONE active write task per repo checkout. */
3470
+ function taskWriteRoot(task: TaskInfo): string | null {
3471
+ if (task.writeMode === "read-only" || !task.projectDir) { return null; }
3472
+ return task.projectDir.split("__task-")[0] ?? task.projectDir;
3473
+ }
3474
+
3475
+ function activeWriteRoots(state: TeamState): Set<string> {
3476
+ const roots = new Set<string>();
3477
+ for (const t of Object.values(state.tasks)) {
3478
+ if (t.status !== "assigned" && t.status !== "in_progress") { continue; }
3479
+ const root = taskWriteRoot(t);
3480
+ if (root) { roots.add(root); }
3481
+ }
3482
+ return roots;
3483
+ }
3484
+
3463
3485
  function broadcastTaskExecutionEvent(
3464
3486
  taskId: string,
3465
3487
  task: TaskInfo,
@@ -3566,6 +3588,9 @@ function serveStaticFile(res: ServerResponse, filePath: string, contentType: str
3566
3588
  res.writeHead(200, {
3567
3589
  "Content-Type": contentType,
3568
3590
  "Access-Control-Allow-Origin": "*",
3591
+ // UI assets change with every plugin deploy on a localhost controller;
3592
+ // always revalidate so browsers never stick to a stale app.js.
3593
+ "Cache-Control": "no-cache",
3569
3594
  });
3570
3595
  res.end(content);
3571
3596
  } catch {
@@ -3869,6 +3894,18 @@ function projectHasMeaningfulFileChanges(
3869
3894
  if (!fs.existsSync(projectRoot)) {
3870
3895
  return false;
3871
3896
  }
3897
+ // Collaboration contract: write tasks deliver in a dedicated worktree.
3898
+ // An mtime scan is the wrong test there (committed files keep old mtimes
3899
+ // and the gate may run before the flush) - ask git instead: does HEAD carry
3900
+ // commits beyond the remote refs?
3901
+ if (task.projectDir.includes("__task-")) {
3902
+ try {
3903
+ const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], { cwd: projectRoot }).toString();
3904
+ return Number(out.trim()) > 0;
3905
+ } catch {
3906
+ return false;
3907
+ }
3908
+ }
3872
3909
  const threshold = Math.max(task.startedAt ?? 0, task.createdAt ?? 0) - 1000;
3873
3910
  const stack = [projectRoot];
3874
3911
  while (stack.length > 0) {
@@ -4403,7 +4440,7 @@ async function dispatchTaskToWorker(
4403
4440
  worker: WorkerInfo,
4404
4441
  deps: ControllerHttpDeps,
4405
4442
  ): Promise<void> {
4406
- const { getTeamState } = deps;
4443
+ const { getTeamState, logger, updateTeamState } = deps;
4407
4444
  const state = getTeamState();
4408
4445
  const task = state?.tasks[taskId];
4409
4446
  if (!task) {
@@ -4416,22 +4453,49 @@ async function dispatchTaskToWorker(
4416
4453
  try { fs.mkdirSync(projectPath, { recursive: true }); } catch { /* best-effort */ }
4417
4454
  }
4418
4455
 
4456
+ // Collaboration contract: WRITE tasks execute in a task-scoped git worktree
4457
+ // (branch teamclaw/task-<id>) so parallel roles never share a dirty checkout;
4458
+ // delivery happens via push + PR in the write-back reconciler.
4459
+ let assignmentProjectDir = task.projectDir;
4460
+ if (task.writeMode === "write" && task.projectDir?.startsWith("teamauto/") && !task.projectDir.includes("__task-")) {
4461
+ const scheduler = deps.getTeamAutoScheduler?.();
4462
+ if (scheduler) {
4463
+ const repoId = task.projectDir.slice("teamauto/".length).replace(/__/g, "/");
4464
+ try {
4465
+ assignmentProjectDir = await scheduler.ensureWriteWorktree(repoId, taskId);
4466
+ updateTeamState((s) => {
4467
+ const t = s.tasks[taskId];
4468
+ if (t) { t.projectDir = assignmentProjectDir; }
4469
+ });
4470
+ logger.info(`Controller: write task ${taskId} -> worktree projects/${assignmentProjectDir}`);
4471
+ } catch (err) {
4472
+ logger.warn(`Controller: worktree setup failed for ${taskId}, falling back to shared checkout: ${String(err)}`);
4473
+ }
4474
+ }
4475
+ }
4476
+
4419
4477
  const sharedWorkspace = deps.workerProvisioningManager?.isSharedWorkspaceWorker(worker.id)
4420
4478
  || false;
4421
4479
  const repoState = await refreshControllerRepoState(deps);
4422
4480
  const repoInfo = buildRepoSyncInfo(repoState, sharedWorkspace);
4423
4481
  const description = buildTaskAssignmentDescription(task, state ?? null, repoInfo);
4424
4482
  const recommendedSkills = resolveRecommendedSkillsForRole(task.assignedRole, task.recommendedSkills ?? []);
4425
- const executionIdentity = buildTaskExecutionIdentity(task.id, worker.id);
4483
+ // Resume support: reuse the interrupted execution's session so the worker
4484
+ // continues the same persisted OpenClaw conversation instead of starting over.
4485
+ const executionIdentity = (task.checkpoint?.sessionKey)
4486
+ ? { executionSessionKey: task.checkpoint.sessionKey, executionIdempotencyKey: buildTaskExecutionIdentity(task.id, worker.id).executionIdempotencyKey }
4487
+ : buildTaskExecutionIdentity(task.id, worker.id);
4426
4488
  const assignment: TaskAssignmentPayload = {
4427
4489
  taskId: task.id,
4428
4490
  title: task.title,
4429
4491
  description,
4430
4492
  priority: task.priority,
4431
4493
  recommendedSkills,
4432
- projectDir: task.projectDir,
4494
+ projectDir: assignmentProjectDir,
4433
4495
  executionSessionKey: executionIdentity.executionSessionKey,
4434
4496
  executionIdempotencyKey: executionIdentity.executionIdempotencyKey,
4497
+ checkpoint: task.checkpoint,
4498
+ resumeAttempt: task.resumeAttempt,
4435
4499
  repo: repoInfo,
4436
4500
  teamContext: buildTaskContextSnapshot(task, state ?? null),
4437
4501
  };
@@ -4518,7 +4582,7 @@ async function assignTaskToWorker(
4518
4582
  return deps.getTeamState()?.tasks[taskId];
4519
4583
  }
4520
4584
 
4521
- async function autoAssignPendingTasks(
4585
+ export async function autoAssignPendingTasks(
4522
4586
  deps: ControllerHttpDeps,
4523
4587
  preferredWorkerId?: string,
4524
4588
  ): Promise<TaskInfo[]> {
@@ -4544,9 +4608,16 @@ async function autoAssignPendingTasks(
4544
4608
  break;
4545
4609
  }
4546
4610
 
4611
+ // Collaboration contract: serialize write tasks per repo checkout - a
4612
+ // second writer on the same root waits until the active one settles.
4613
+ const busyWriteRoots = activeWriteRoots(state);
4547
4614
  const candidateAssignments = taskRouter
4548
4615
  .autoAssignPendingTasks(state.tasks, state.workers)
4549
- .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`));
4616
+ .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`))
4617
+ .filter(({ task }) => {
4618
+ const root = taskWriteRoot(task);
4619
+ return !(root && busyWriteRoots.has(root));
4620
+ });
4550
4621
 
4551
4622
  const nextAssignment = (
4552
4623
  (preferredWorkerId
@@ -4630,6 +4701,41 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
4630
4701
  return server;
4631
4702
  }
4632
4703
 
4704
+ function resolveRequestOrigin(req: IncomingMessage, config: PluginConfig): string {
4705
+ const host = req.headers.host;
4706
+ if (typeof host === "string" && host.trim()) {
4707
+ return `http://${host.trim()}`;
4708
+ }
4709
+ return `http://127.0.0.1:${config.port}`;
4710
+ }
4711
+
4712
+ function escapeHtmlText(value: string): string {
4713
+ return value
4714
+ .replace(/&/g, "&amp;")
4715
+ .replace(/</g, "&lt;")
4716
+ .replace(/>/g, "&gt;")
4717
+ .replace(/"/g, "&quot;")
4718
+ .replace(/'/g, "&#39;");
4719
+ }
4720
+
4721
+ function sendGithubCallbackHtml(res: ServerResponse, statusCode: number, title: string, message: string): void {
4722
+ const html = [
4723
+ "<!DOCTYPE html><html><head><meta charset=\"utf-8\">",
4724
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
4725
+ `<title>${escapeHtmlText(title)}</title>`,
4726
+ "<style>body{font-family:-apple-system,system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:#0f1117;color:#e6e8ee}main{max-width:520px;padding:32px 40px;border:1px solid #2a2f3a;border-radius:14px;background:#161923;text-align:center}h1{font-size:20px;margin:0 0 10px}p{margin:6px 0;color:#a8b0c0;line-height:1.6}</style>",
4727
+ "</head><body><main>",
4728
+ `<h1>${escapeHtmlText(title)}</h1>`,
4729
+ `<p>${escapeHtmlText(message)}</p>`,
4730
+ "</main></body></html>",
4731
+ ].join("");
4732
+ res.writeHead(statusCode, {
4733
+ "Content-Type": "text/html; charset=utf-8",
4734
+ "Content-Length": Buffer.byteLength(html),
4735
+ });
4736
+ res.end(html);
4737
+ }
4738
+
4633
4739
  async function handleRequest(
4634
4740
  req: IncomingMessage,
4635
4741
  res: ServerResponse,
@@ -4654,6 +4760,13 @@ async function handleRequest(
4654
4760
  return;
4655
4761
  }
4656
4762
 
4763
+ // Standalone GitHub device-login page (big user code + prefilled link + polling).
4764
+ if (req.method === "GET" && (pathname === "/ui/auth/github" || pathname === "/ui/auth/github/")) {
4765
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
4766
+ serveStaticFile(res, path.join(uiPath, "github-login.html"), "text/html; charset=utf-8");
4767
+ return;
4768
+ }
4769
+
4657
4770
  if (req.method === "GET" && pathname.startsWith("/ui/")) {
4658
4771
  const uiPath = path.join(import.meta.dirname, "..", "ui");
4659
4772
  const file = pathname.slice(4); // remove "/ui/"
@@ -4673,6 +4786,191 @@ async function handleRequest(
4673
4786
  return;
4674
4787
  }
4675
4788
 
4789
+ // ==================== TeamAuto ====================
4790
+
4791
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
4792
+
4793
+ if (req.method === "GET" && pathname === "/api/v1/teamauto/activity") {
4794
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4795
+ try {
4796
+ const activity = await teamAuto.getActivity();
4797
+ sendJson(res, 200, { activity });
4798
+ } catch (err) {
4799
+ sendError(res, 500, err instanceof Error ? err.message : "failed to load activity");
4800
+ }
4801
+ return;
4802
+ }
4803
+
4804
+ if (req.method === "GET" && pathname === "/api/v1/teamauto/repos") {
4805
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4806
+ try {
4807
+ sendJson(res, 200, await teamAuto.getStatus());
4808
+ } catch (err) {
4809
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read TeamAuto status");
4810
+ }
4811
+ return;
4812
+ }
4813
+
4814
+ // Selectable repos for the bind picker (the logged-in GitHub account's).
4815
+ if (req.method === "GET" && pathname === "/api/v1/teamauto/repo-candidates") {
4816
+ try {
4817
+ const auth = getGithubAuthManager(config, logger);
4818
+ const candidates = await createGithubClient(auth).listUserRepos();
4819
+ sendJson(res, 200, { candidates });
4820
+ } catch (err) {
4821
+ sendError(res, 400, err instanceof Error ? err.message : "failed to list repositories");
4822
+ }
4823
+ return;
4824
+ }
4825
+
4826
+ if (req.method === "POST" && pathname === "/api/v1/teamauto/repos") {
4827
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4828
+ let body: Record<string, unknown> = {};
4829
+ try { body = await parseJsonBody(req); } catch { /* empty body */ }
4830
+ const repo = typeof body.repo === "string" ? body.repo : "";
4831
+ if (!repo) { sendError(res, 400, "repo (owner/name) is required"); return; }
4832
+ try {
4833
+ const created = await teamAuto.addRepo(repo, {
4834
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
4835
+ keywordInclude: Array.isArray(body.keywordInclude) ? body.keywordInclude.filter((k): k is string => typeof k === "string") : undefined,
4836
+ keywordExclude: Array.isArray(body.keywordExclude) ? body.keywordExclude.filter((k): k is string => typeof k === "string") : undefined,
4837
+ });
4838
+ sendJson(res, 201, created);
4839
+ } catch (err) {
4840
+ sendError(res, 400, err instanceof Error ? err.message : "failed to bind repo");
4841
+ }
4842
+ return;
4843
+ }
4844
+
4845
+ if (pathname.startsWith("/api/v1/teamauto/repos/")) {
4846
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4847
+ const repoId = decodeURIComponent(pathname.slice("/api/v1/teamauto/repos/".length).replace(/\/sweep$/, ""));
4848
+ const isSweep = pathname.endsWith("/sweep");
4849
+ if (req.method === "DELETE" && !isSweep) {
4850
+ try { await teamAuto.removeRepo(repoId); sendJson(res, 200, { ok: true }); }
4851
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to unbind"); }
4852
+ return;
4853
+ }
4854
+ if (req.method === "PATCH" && !isSweep) {
4855
+ let body: Record<string, unknown> = {};
4856
+ try { body = await parseJsonBody(req); } catch { /* empty */ }
4857
+ try {
4858
+ const updated = await teamAuto.updateRepo(repoId, {
4859
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
4860
+ maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
4861
+ fullReview: body.fullReview === "off" || body.fullReview === "weekly" || body.fullReview === "daily" ? body.fullReview : undefined,
4862
+ takeOwnership: typeof body.takeOwnership === "boolean" ? body.takeOwnership : undefined,
4863
+ });
4864
+ sendJson(res, 200, updated);
4865
+ } catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to update"); }
4866
+ return;
4867
+ }
4868
+ if (req.method === "POST" && isSweep) {
4869
+ try { sendJson(res, 200, { summary: await teamAuto.runSweepNow(repoId, true) }); }
4870
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "sweep failed"); }
4871
+ return;
4872
+ }
4873
+ }
4874
+
4875
+ // ==================== GitHub Auth ====================
4876
+
4877
+ if (req.method === "GET" && pathname === "/api/v1/auth/github/status") {
4878
+ try {
4879
+ const status = await getGithubAuthManager(config, logger).getStatus(resolveRequestOrigin(req, config));
4880
+ sendJson(res, 200, status);
4881
+ } catch (err) {
4882
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read GitHub login status");
4883
+ }
4884
+ return;
4885
+ }
4886
+
4887
+ if (req.method === "POST" && pathname === "/api/v1/auth/github/login") {
4888
+ let flow: string | undefined;
4889
+ try {
4890
+ const body = await parseJsonBody(req) as { flow?: unknown };
4891
+ if (typeof body?.flow === "string") {
4892
+ flow = body.flow.trim();
4893
+ }
4894
+ } catch {
4895
+ // No body or invalid body: fall through to the default (device) flow.
4896
+ }
4897
+ const manager = getGithubAuthManager(config, logger);
4898
+ try {
4899
+ const loginPageUrl = resolveRequestOrigin(req, config).replace(/\/+$/, "") + "/ui/auth/github";
4900
+ if (flow === "web") {
4901
+ // Web flow needs a client secret for the code exchange; the device
4902
+ // flow (default) is fully secretless.
4903
+ const start = manager.beginLogin(resolveRequestOrigin(req, config));
4904
+ sendJson(res, 200, { mode: "web", loginPageUrl, ...start });
4905
+ } else {
4906
+ const start = await manager.beginDeviceLogin();
4907
+ // authorizeUrl intentionally points at our standalone login page so
4908
+ // older UI clients that just open response.authorizeUrl land on the
4909
+ // device-code page instead of a dead web-flow URL.
4910
+ sendJson(res, 200, { mode: "device", loginPageUrl, authorizeUrl: loginPageUrl, ...start });
4911
+ }
4912
+ logger.info(`Controller: GitHub login flow started (${flow === "web" ? "web" : "device"})`);
4913
+ } catch (err) {
4914
+ sendError(res, 400, err instanceof Error ? err.message : "failed to start GitHub login");
4915
+ }
4916
+ return;
4917
+ }
4918
+
4919
+ if (req.method === "GET" && pathname === "/api/v1/auth/github/callback") {
4920
+ const callbackError = requestUrl.searchParams.get("error");
4921
+ if (callbackError) {
4922
+ const description = requestUrl.searchParams.get("error_description") ?? "";
4923
+ logger.warn(`Controller: GitHub login was denied (${callbackError})`);
4924
+ sendGithubCallbackHtml(
4925
+ res,
4926
+ 400,
4927
+ "GitHub login failed",
4928
+ `Authorization was denied: ${callbackError}${description ? ` (${description})` : ""}`,
4929
+ );
4930
+ return;
4931
+ }
4932
+ const code = requestUrl.searchParams.get("code") ?? "";
4933
+ const state = requestUrl.searchParams.get("state") ?? "";
4934
+ try {
4935
+ const account = await getGithubAuthManager(config, logger).completeLogin({
4936
+ code: code || undefined,
4937
+ state: state || undefined,
4938
+ });
4939
+ logger.info(`Controller: GitHub login completed for @${account.login}`);
4940
+ sendGithubCallbackHtml(
4941
+ res,
4942
+ 200,
4943
+ "GitHub login successful",
4944
+ `Signed in as @${account.login}(GitHub 登录成功,可关闭本页返回 TeamClaw)。`,
4945
+ );
4946
+ } catch (err) {
4947
+ const message = err instanceof Error ? err.message : String(err);
4948
+ logger.warn(`Controller: GitHub login callback failed: ${message}`);
4949
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `${message}`);
4950
+ }
4951
+ return;
4952
+ }
4953
+
4954
+ if (req.method === "POST" && pathname === "/api/v1/auth/github/logout") {
4955
+ try {
4956
+ await getGithubAuthManager(config, logger).logout();
4957
+ sendJson(res, 200, { ok: true });
4958
+ } catch (err) {
4959
+ sendError(res, 500, err instanceof Error ? err.message : "failed to sign out of GitHub");
4960
+ }
4961
+ return;
4962
+ }
4963
+
4964
+ if (req.method === "POST" && pathname === "/api/v1/auth/github/refresh") {
4965
+ try {
4966
+ const store = await getGithubAuthManager(config, logger).forceRefresh();
4967
+ sendJson(res, 200, { ok: true, account: store.account, expiresAt: store.expiresAt });
4968
+ } catch (err) {
4969
+ sendError(res, 400, err instanceof Error ? err.message : "failed to refresh the GitHub token");
4970
+ }
4971
+ return;
4972
+ }
4973
+
4676
4974
  // ==================== Workspace Browser ====================
4677
4975
 
4678
4976
  if (req.method === "GET" && pathname === "/api/v1/workspace/status") {
@@ -5419,6 +5717,40 @@ function computeTeamStats(state: TeamState): TeamStatsResponse {
5419
5717
  return;
5420
5718
  }
5421
5719
 
5720
+ // POST /api/v1/tasks/:id/checkpoint - worker persists an execution progress
5721
+ // snapshot so an interrupted task can resume instead of restarting.
5722
+ if (req.method === "POST" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/checkpoint$/)) {
5723
+ const taskId = pathname.split("/")[4];
5724
+ let body: Record<string, unknown> = {};
5725
+ try { body = await parseJsonBody(req); } catch { sendError(res, 400, "invalid JSON body"); return; }
5726
+ const lastAssistantMessage = typeof body.lastAssistantMessage === "string" ? body.lastAssistantMessage.slice(0, 8000) : "";
5727
+ const progressNote = typeof body.progressNote === "string" ? body.progressNote.slice(0, 1000) : "";
5728
+ const sessionKey = typeof body.sessionKey === "string" ? body.sessionKey : "";
5729
+ if (!lastAssistantMessage && !progressNote) {
5730
+ sendError(res, 400, "lastAssistantMessage or progressNote is required");
5731
+ return;
5732
+ }
5733
+ const updated = updateTeamState((s) => {
5734
+ const task = s.tasks[taskId];
5735
+ if (!task) { return; }
5736
+ const prev = task.checkpoint;
5737
+ const notes = [...(prev?.progressNotes ?? [])];
5738
+ if (progressNote && !notes.includes(progressNote)) { notes.push(progressNote); }
5739
+ task.checkpoint = {
5740
+ updatedAt: Date.now(),
5741
+ attempt: prev?.attempt ?? 0,
5742
+ sessionKey: sessionKey || prev?.sessionKey || "",
5743
+ lastAssistantMessage: lastAssistantMessage || prev?.lastAssistantMessage || "",
5744
+ progressNotes: notes.slice(-10),
5745
+ };
5746
+ task.updatedAt = Date.now();
5747
+ });
5748
+ const task = updated?.tasks[taskId];
5749
+ if (!task) { sendError(res, 404, "task not found"); return; }
5750
+ sendJson(res, 200, { ok: true, updatedAt: task.checkpoint?.updatedAt });
5751
+ return;
5752
+ }
5753
+
5422
5754
  // POST /api/v1/tasks/:id/result-contract
5423
5755
  if (req.method === "POST" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/result-contract$/)) {
5424
5756
  const taskId = pathname.split("/")[4]!;
@@ -20,6 +20,7 @@ const TEAMCLAW_ROLE_IDS = new Set<RoleId>([
20
20
  "security-engineer",
21
21
  "designer",
22
22
  "marketing",
23
+ "data-engineer",
23
24
  ]);
24
25
 
25
26
  export function normalizeManifestRoleList(raw: unknown): RoleId[] {
@@ -21,6 +21,8 @@ const TEAMCLAW_ROLE_IDS_TEXT = [
21
21
  ];
22
22
 
23
23
  const SESSION_PROGRESS_POLL_INTERVAL_MS = 1000;
24
+ /** Checkpoint heartbeat cadence (resume support). */
25
+ const CHECKPOINT_EMIT_INTERVAL_MS = 15_000;
24
26
  const SESSION_PROGRESS_MESSAGE_LIMIT = 200;
25
27
  const MAX_SESSION_PROGRESS_MESSAGE_CHARS = 4000;
26
28
  const RUN_WAIT_SLICE_MS = 30_000;
@@ -76,10 +78,12 @@ export type RoleTaskExecutorDeps = {
76
78
  getSessionKey: (assignment: TaskAssignmentPayload) => string;
77
79
  getIdempotencyKey?: (assignment: TaskAssignmentPayload) => string;
78
80
  reportExecutionEvent?: (taskId: string, event: TaskExecutionEventInput) => Promise<void> | void;
81
+ /** Persist a resumable progress snapshot (throttled by the executor). */
82
+ reportCheckpoint?: (taskId: string, checkpoint: { lastAssistantMessage: string; progressNote?: string; sessionKey: string }) => Promise<void> | void;
79
83
  };
80
84
 
81
85
  export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
82
- const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent } = deps;
86
+ const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent, reportCheckpoint } = deps;
83
87
  const roleDef = getRole(role);
84
88
  const roleSystemPrompt = roleDef
85
89
  ? roleDef.systemPrompt
@@ -143,6 +147,8 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
143
147
  }
144
148
 
145
149
  try {
150
+ // Checkpoint heartbeat state for resume support.
151
+ let lastCheckpointAt = 0;
146
152
  const runResult = await runtime.subagent.run(buildSubagentRunOptions({
147
153
  sessionKey,
148
154
  message: taskMessage,
@@ -291,6 +297,16 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
291
297
  }
292
298
  if (entry.stream === "assistant") {
293
299
  progressSnapshot.lastAssistantMessage = entry.message;
300
+ // Checkpoint heartbeat: persist the latest assistant turn so an
301
+ // interrupted execution resumes with fresh context (max once per
302
+ // CHECKPOINT_EMIT_INTERVAL_MS to bound controller write load).
303
+ if (reportCheckpoint && Date.now() - lastCheckpointAt >= CHECKPOINT_EMIT_INTERVAL_MS) {
304
+ lastCheckpointAt = Date.now();
305
+ void Promise.resolve(reportCheckpoint(taskId, {
306
+ lastAssistantMessage: entry.message.slice(0, 8000),
307
+ sessionKey,
308
+ })).catch(() => { /* checkpointing is best-effort */ });
309
+ }
294
310
  }
295
311
  await emitExecutionEvent({
296
312
  type: "progress",