@teamclaws/teamclaw 2026.8.0 → 2026.11.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.
Files changed (149) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +412 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-capacity.js +14 -0
  7. package/dist/src/controller/controller-intake.js +895 -0
  8. package/dist/src/controller/controller-planning.js +813 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +624 -0
  11. package/dist/src/controller/controller-tools.js +587 -0
  12. package/dist/src/controller/delivery-report.js +458 -0
  13. package/dist/src/controller/github-auth.js +564 -0
  14. package/dist/src/controller/http-server.js +284 -0
  15. package/dist/src/controller/kickoff-orchestrator.js +246 -0
  16. package/dist/src/controller/managed-gateway-process.js +286 -0
  17. package/dist/src/controller/message-delivery.js +28 -0
  18. package/dist/src/controller/message-router.js +38 -0
  19. package/dist/src/controller/message-routes.js +114 -0
  20. package/dist/src/controller/orchestration-manifest.js +151 -0
  21. package/dist/src/controller/preview-manager.js +586 -0
  22. package/dist/src/controller/preview-proxy.js +98 -0
  23. package/dist/src/controller/profile-switch.js +289 -0
  24. package/dist/src/controller/project-registry.js +294 -0
  25. package/dist/src/controller/prompt-injector.js +197 -0
  26. package/dist/src/controller/repo-routes.js +63 -0
  27. package/dist/src/controller/role-inference.js +246 -0
  28. package/dist/src/controller/route-table.js +1353 -0
  29. package/dist/src/controller/task-assignment.js +508 -0
  30. package/dist/src/controller/task-cleanup.js +258 -0
  31. package/dist/src/controller/task-execution.js +240 -0
  32. package/dist/src/controller/task-results.js +461 -0
  33. package/dist/src/controller/task-router.js +137 -0
  34. package/dist/src/controller/task-routes.js +703 -0
  35. package/dist/src/controller/teamauto-routes.js +124 -0
  36. package/dist/src/controller/tunnel-manager.js +548 -0
  37. package/dist/src/controller/ui-assets.js +68 -0
  38. package/dist/src/controller/websocket.js +42 -0
  39. package/dist/src/controller/worker-provisioning.js +1674 -0
  40. package/dist/src/controller/worker-routes.js +188 -0
  41. package/dist/src/discovery.js +86 -0
  42. package/dist/src/git-collaboration.js +694 -0
  43. package/dist/src/identity.js +132 -0
  44. package/dist/src/install-defaults.js +1 -0
  45. package/dist/src/interaction-contracts.js +531 -0
  46. package/dist/src/networking.js +91 -0
  47. package/dist/src/openclaw-workspace.js +925 -0
  48. package/dist/src/profile-loader.js +486 -0
  49. package/dist/src/profiles/banking.json +178 -0
  50. package/dist/src/profiles/crossborder-ecom.json +253 -0
  51. package/dist/src/profiles/insurance.json +157 -0
  52. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  53. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  54. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  55. package/dist/src/profiles/schema.json +201 -0
  56. package/dist/src/profiles/securities.json +137 -0
  57. package/dist/src/profiles/software-rd.json +264 -0
  58. package/dist/src/profiles/trading-co.json +200 -0
  59. package/dist/src/prompt-policy.js +386 -0
  60. package/dist/src/protocol.js +58 -0
  61. package/dist/src/role-ids.js +29 -0
  62. package/dist/src/roles.js +390 -0
  63. package/dist/src/session-roles.js +14 -0
  64. package/dist/src/state.js +361 -0
  65. package/dist/src/task-executor.js +1023 -0
  66. package/dist/src/teamauto/github-client.js +210 -0
  67. package/dist/src/teamauto/norms.js +85 -0
  68. package/dist/src/teamauto/repo-sync.js +423 -0
  69. package/dist/src/teamauto/scanner.js +207 -0
  70. package/dist/src/teamauto/schedule.js +123 -0
  71. package/dist/src/teamauto/scheduler.js +907 -0
  72. package/dist/src/teamauto/store.js +133 -0
  73. package/dist/src/types.js +290 -0
  74. package/dist/src/ui/app.js +4860 -0
  75. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  76. package/dist/src/ui/github-login.html +296 -0
  77. package/dist/src/ui/index.html +447 -0
  78. package/dist/src/ui/style.css +2805 -0
  79. package/dist/src/worker/http-handler.js +146 -0
  80. package/dist/src/worker/message-queue.js +24 -0
  81. package/dist/src/worker/prompt-injector.js +78 -0
  82. package/dist/src/worker/skill-installer.js +255 -0
  83. package/dist/src/worker/tools.js +541 -0
  84. package/dist/src/worker/worker-service.js +307 -0
  85. package/dist/src/workspace-browser.js +269 -0
  86. package/openclaw.plugin.json +28 -1
  87. package/package.json +3 -2
  88. package/src/config.ts +33 -2
  89. package/src/controller/clarification-routes.ts +404 -0
  90. package/src/controller/controller-intake.ts +1113 -0
  91. package/src/controller/controller-planning.ts +1029 -0
  92. package/src/controller/controller-runs.ts +239 -0
  93. package/src/controller/controller-service.ts +295 -41
  94. package/src/controller/controller-tools.ts +11 -7
  95. package/src/controller/http-server.ts +294 -6971
  96. package/src/controller/kickoff-orchestrator.ts +70 -7
  97. package/src/controller/message-delivery.ts +49 -0
  98. package/src/controller/message-routes.ts +137 -0
  99. package/src/controller/orchestration-manifest.ts +6 -29
  100. package/src/controller/preview-proxy.ts +127 -0
  101. package/src/controller/profile-switch.ts +366 -0
  102. package/src/controller/project-registry.ts +361 -0
  103. package/src/controller/prompt-injector.ts +23 -8
  104. package/src/controller/repo-routes.ts +91 -0
  105. package/src/controller/role-inference.ts +260 -22
  106. package/src/controller/route-table.ts +1616 -0
  107. package/src/controller/task-assignment.ts +618 -0
  108. package/src/controller/task-cleanup.ts +344 -0
  109. package/src/controller/task-execution.ts +356 -0
  110. package/src/controller/task-results.ts +544 -0
  111. package/src/controller/task-router.ts +98 -6
  112. package/src/controller/task-routes.ts +812 -0
  113. package/src/controller/teamauto-routes.ts +121 -0
  114. package/src/controller/ui-assets.ts +70 -0
  115. package/src/controller/websocket.ts +13 -1
  116. package/src/controller/worker-provisioning.ts +32 -4
  117. package/src/controller/worker-routes.ts +241 -0
  118. package/src/identity.ts +3 -2
  119. package/src/interaction-contracts.ts +7 -7
  120. package/src/openclaw-workspace.ts +44 -18
  121. package/src/profile-loader.ts +650 -0
  122. package/src/profiles/banking.json +178 -0
  123. package/src/profiles/crossborder-ecom.json +253 -0
  124. package/src/profiles/insurance.json +157 -0
  125. package/src/profiles/knowledge/hs-structure.md +97 -0
  126. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  127. package/src/profiles/knowledge/vat-principles.md +85 -0
  128. package/src/profiles/schema.json +201 -0
  129. package/src/profiles/securities.json +137 -0
  130. package/src/profiles/software-rd.json +264 -0
  131. package/src/profiles/trading-co.json +200 -0
  132. package/src/prompt-policy.ts +27 -13
  133. package/src/role-ids.ts +31 -0
  134. package/src/roles.ts +60 -14
  135. package/src/session-roles.ts +14 -0
  136. package/src/state.ts +236 -9
  137. package/src/task-executor.ts +7 -18
  138. package/src/teamauto/github-client.ts +21 -0
  139. package/src/teamauto/repo-sync.ts +246 -6
  140. package/src/teamauto/scanner.ts +47 -13
  141. package/src/teamauto/scheduler.ts +259 -16
  142. package/src/teamauto/store.ts +12 -0
  143. package/src/types.ts +133 -16
  144. package/src/ui/app.js +592 -24
  145. package/src/ui/index.html +44 -11
  146. package/src/ui/style.css +194 -0
  147. package/src/worker/prompt-injector.ts +48 -8
  148. package/src/worker/skill-installer.ts +3 -1
  149. package/src/worker/worker-service.ts +83 -3
package/src/state.ts CHANGED
@@ -2,12 +2,18 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
4
  import type {
5
+ RoleDefinition,
5
6
  RoleId,
6
7
  StartupProvisioningReadiness,
7
8
  TeamProvisioningState,
8
9
  TeamState,
9
10
  WorkerIdentity,
10
11
  } from "./types.js";
12
+ import { validateRoleIdList } from "./roles.js";
13
+ // Phase 1.6: the legacy-state profileId migration defaults to the loader's
14
+ // software-rd baseline id (single literal source). profile-loader has no
15
+ // runtime edge back into this module, so no cycle.
16
+ import { SOFTWARE_RD_PROFILE_ID } from "./profile-loader.js";
11
17
 
12
18
  const STATE_VERSION = 2;
13
19
 
@@ -67,6 +73,26 @@ function migrateState(raw: unknown): TeamState | null {
67
73
  // startupReadiness was already optional and handled by normalizeStartupReadiness above.
68
74
  state.version = STATE_VERSION;
69
75
 
76
+ // Phase 1.6 (design 2.3): legacy states carry no profileId; default them
77
+ // to the software-rd baseline. Idempotent - states saved by this build
78
+ // already carry the field and pass through unchanged.
79
+ if (typeof state.profileId !== "string" || !state.profileId.trim()) {
80
+ state.profileId = SOFTWARE_RD_PROFILE_ID;
81
+ }
82
+
83
+ // Phase 2.1: a malformed persisted transition is dropped (treated as "no
84
+ // switch in progress"). Aborting a corrupt switch keeps the previous team
85
+ // fully intact - the safe failure mode; the user can re-issue the switch.
86
+ if (state.transition !== undefined) {
87
+ const transition = state.transition as Record<string, unknown>;
88
+ const phaseOk = transition?.phase === "draining" || transition?.phase === "archiving" || transition?.phase === "warming";
89
+ const targetOk = typeof transition?.targetProfileId === "string" && Boolean(transition.targetProfileId.trim());
90
+ const startedAtOk = typeof transition?.startedAt === "number";
91
+ if (!phaseOk || !targetOk || !startedAtOk) {
92
+ delete state.transition;
93
+ }
94
+ }
95
+
70
96
  return state as unknown as TeamState;
71
97
  }
72
98
 
@@ -101,9 +127,9 @@ function normalizeStartupReadiness(value: unknown): StartupProvisioningReadiness
101
127
  const startedAt = typeof record.startedAt === "number" ? record.startedAt : undefined;
102
128
  const checkedAt = typeof record.checkedAt === "number" ? record.checkedAt : undefined;
103
129
  const attempts = typeof record.attempts === "number" && record.attempts >= 0 ? Math.floor(record.attempts) : 0;
104
- const requiredRoles = Array.isArray(record.requiredRoles)
105
- ? record.requiredRoles.filter((entry): entry is string => typeof entry === "string")
106
- : [];
130
+ // Phase 0.3: persisted requiredRoles are untrusted; filter through the
131
+ // shared guard so corrupted state cannot inject arbitrary role strings.
132
+ const requiredRoles = validateRoleIdList(record.requiredRoles);
107
133
  const readyWorkerIds = Array.isArray(record.readyWorkerIds)
108
134
  ? record.readyWorkerIds.filter((entry): entry is string => typeof entry === "string")
109
135
  : [];
@@ -116,7 +142,7 @@ function normalizeStartupReadiness(value: unknown): StartupProvisioningReadiness
116
142
  startedAt,
117
143
  checkedAt,
118
144
  attempts,
119
- requiredRoles: requiredRoles as RoleId[],
145
+ requiredRoles,
120
146
  readyWorkerIds,
121
147
  message,
122
148
  };
@@ -145,12 +171,76 @@ function enqueueAtomicWrite(filePath: string, contents: string): Promise<void> {
145
171
  });
146
172
  }
147
173
 
174
+ // Phase 1.6 (design section 2.3): the persisted state file name is decoupled
175
+ // from teamName. TeamClaw is single-instance-single-team per state dir, so a
176
+ // fixed instance-scoped file name IS the instance identity - renaming a team
177
+ // no longer orphans the old `<teamName>-team-state.json` (the collision risk
178
+ // called out in the design). The legacy teamName-named file is still read as
179
+ // a one-time migration source; the next save writes the new name and the
180
+ // legacy file is simply never consulted again.
181
+ const TEAM_STATE_FILE = "team-state.json";
182
+
183
+ function teamStateFilePath(): string {
184
+ return path.join(STATE_DIR, TEAM_STATE_FILE);
185
+ }
186
+
187
+ function legacyTeamStateFilePath(teamName: string): string {
188
+ return path.join(STATE_DIR, `${teamName}-team-state.json`);
189
+ }
190
+
191
+ function isFileMissing(error: unknown): boolean {
192
+ return (error as NodeJS.ErrnoException)?.code === "ENOENT";
193
+ }
194
+
195
+ function errorMessage(error: unknown): string {
196
+ return error instanceof Error ? error.message : String(error);
197
+ }
198
+
148
199
  async function loadTeamState(teamName: string): Promise<TeamState | null> {
149
- const filePath = path.join(STATE_DIR, `${teamName}-team-state.json`);
200
+ // Review fix (Phase 1.6): the instance-scoped team-state.json is the
201
+ // primary state file, and when it EXISTS it is authoritative. A
202
+ // present-but-corrupt primary is a fatal error, never a silent fallback to
203
+ // the legacy snapshot - falling back would rewind the team to the
204
+ // pre-migration state and lose everything saved since. Only a MISSING
205
+ // primary (ENOENT) falls through to the one-time legacy read.
206
+ let primaryRaw: string | null = null;
150
207
  try {
151
- const raw = await fs.readFile(filePath, "utf8");
152
- const parsed = JSON.parse(raw);
153
- return migrateState(parsed);
208
+ primaryRaw = await fs.readFile(teamStateFilePath(), "utf8");
209
+ } catch (error) {
210
+ if (!isFileMissing(error)) {
211
+ throw new Error(
212
+ `TeamClaw cannot read the persisted team state ${teamStateFilePath()}: ${errorMessage(error)}`,
213
+ );
214
+ }
215
+ }
216
+
217
+ if (primaryRaw !== null) {
218
+ let parsed: unknown;
219
+ try {
220
+ parsed = JSON.parse(primaryRaw);
221
+ } catch (error) {
222
+ throw new Error(
223
+ `TeamClaw team state file ${teamStateFilePath()} is not valid JSON (${errorMessage(error)}). `
224
+ + "Refusing to start with a fresh team over a corrupt state file - fix or remove the file manually.",
225
+ );
226
+ }
227
+ const migrated = migrateState(parsed);
228
+ if (!migrated) {
229
+ throw new Error(
230
+ `TeamClaw team state file ${teamStateFilePath()} exists but is not a valid team state. `
231
+ + "Refusing to start with a fresh team over an unusable state file - fix or remove the file manually.",
232
+ );
233
+ }
234
+ return migrated;
235
+ }
236
+
237
+ // Primary absent: one-time legacy fallback (pre-Phase-1.6 file name).
238
+ // Lenient by design, matching the pre-Phase-1.6 single-file behavior: a
239
+ // missing or corrupt legacy file simply means first initialization, and a
240
+ // corrupt legacy file is never overwritten (saves go to the new name).
241
+ try {
242
+ const legacyRaw = await fs.readFile(legacyTeamStateFilePath(teamName), "utf8");
243
+ return migrateState(JSON.parse(legacyRaw));
154
244
  } catch {
155
245
  return null;
156
246
  }
@@ -158,7 +248,7 @@ async function loadTeamState(teamName: string): Promise<TeamState | null> {
158
248
 
159
249
  async function saveTeamState(state: TeamState): Promise<void> {
160
250
  await ensureDir(STATE_DIR);
161
- const filePath = path.join(STATE_DIR, `${state.teamName}-team-state.json`);
251
+ const filePath = teamStateFilePath();
162
252
  state.version = STATE_VERSION;
163
253
  state.updatedAt = Date.now();
164
254
  state.provisioning = state.provisioning && typeof state.provisioning === "object"
@@ -177,6 +267,140 @@ async function saveTeamState(state: TeamState): Promise<void> {
177
267
  await enqueueAtomicWrite(filePath, `${JSON.stringify(state, null, 2)}\n`);
178
268
  }
179
269
 
270
+ // ---------------------------------------------------------------------------
271
+ // Team profile switch archive (Phase 2.1, design section 2.3 step 3).
272
+ //
273
+ // Switching profiles seals the WHOLE previous TeamState (tasks,
274
+ // clarifications, messages, previews, repo, projects, controllerRuns,
275
+ // reports) into state-dir/archived/<profileId>-<timestamp>.json together with
276
+ // an embedded snapshot of the profile's roles - so an archived banking team
277
+ // keeps its original role vocabulary even after the profile package evolves
278
+ // (design 2.2: archive queries must not suffer terminology drift). v1 only
279
+ // lists archive metadata; the full payload stays queryable offline.
280
+ // ---------------------------------------------------------------------------
281
+
282
+ const ARCHIVED_TEAMS_DIR_NAME = "archived";
283
+ const ARCHIVE_FILE_RE = /^([a-z0-9-]+)-(\d+)\.json$/;
284
+
285
+ /** Embedded profile snapshot stored alongside the archived team state. */
286
+ export type ArchivedTeamProfileSnapshot = {
287
+ id: string;
288
+ name: string;
289
+ nameZh?: string;
290
+ version: string;
291
+ roles: RoleDefinition[];
292
+ };
293
+
294
+ export type ArchivedTeamEnvelope = {
295
+ archivedAt: number;
296
+ profile: ArchivedTeamProfileSnapshot;
297
+ team: TeamState;
298
+ };
299
+
300
+ export type ArchivedTeamSummary = {
301
+ /** Archive file name (unique id for v1 metadata listing purposes). */
302
+ file: string;
303
+ profileId: string;
304
+ profileName: string;
305
+ teamName: string;
306
+ archivedAt: number;
307
+ taskCount: number;
308
+ };
309
+
310
+ function archivedTeamsDirPath(): string {
311
+ return path.join(STATE_DIR, ARCHIVED_TEAMS_DIR_NAME);
312
+ }
313
+
314
+ function parseArchiveFileName(name: string): { profileId: string; timestamp: number } | null {
315
+ const match = ARCHIVE_FILE_RE.exec(name);
316
+ if (!match) {
317
+ return null;
318
+ }
319
+ const timestamp = Number(match[2]);
320
+ return Number.isFinite(timestamp) ? { profileId: match[1]!, timestamp } : null;
321
+ }
322
+
323
+ /**
324
+ * Seal the given TeamState into the archive directory (design 2.3 step 3).
325
+ * Returns the archive file path. The write is atomic; the envelope embeds the
326
+ * profile snapshot so the archive is self-contained.
327
+ */
328
+ async function archiveTeamState(
329
+ state: TeamState,
330
+ profileSnapshot: ArchivedTeamProfileSnapshot,
331
+ ): Promise<string> {
332
+ const dir = archivedTeamsDirPath();
333
+ await ensureDir(dir);
334
+ const fileName = `${state.profileId}-${Date.now()}.json`;
335
+ const filePath = path.join(dir, fileName);
336
+ const envelope: ArchivedTeamEnvelope = {
337
+ archivedAt: Date.now(),
338
+ profile: profileSnapshot,
339
+ team: state,
340
+ };
341
+ await enqueueAtomicWrite(filePath, `${JSON.stringify(envelope, null, 2)}\n`);
342
+ return filePath;
343
+ }
344
+
345
+ /** List archived teams (newest first). Unreadable entries are skipped. */
346
+ async function listArchivedTeams(): Promise<ArchivedTeamSummary[]> {
347
+ let files: string[];
348
+ try {
349
+ files = await fs.readdir(archivedTeamsDirPath());
350
+ } catch {
351
+ return [];
352
+ }
353
+ const summaries: ArchivedTeamSummary[] = [];
354
+ for (const name of files.sort().reverse()) {
355
+ if (!name.endsWith(".json") || !parseArchiveFileName(name)) {
356
+ continue;
357
+ }
358
+ try {
359
+ const raw = await fs.readFile(path.join(archivedTeamsDirPath(), name), "utf8");
360
+ const parsed = JSON.parse(raw) as ArchivedTeamEnvelope;
361
+ if (!parsed?.team || typeof parsed.team !== "object") {
362
+ continue;
363
+ }
364
+ summaries.push({
365
+ file: name,
366
+ profileId: parsed.profile?.id ?? parsed.team.profileId ?? "unknown",
367
+ profileName: parsed.profile?.name ?? "",
368
+ teamName: typeof parsed.team.teamName === "string" ? parsed.team.teamName : "",
369
+ archivedAt: typeof parsed.archivedAt === "number" ? parsed.archivedAt : 0,
370
+ taskCount: parsed.team.tasks && typeof parsed.team.tasks === "object"
371
+ ? Object.keys(parsed.team.tasks).length
372
+ : 0,
373
+ });
374
+ } catch {
375
+ // Skip unreadable/corrupt archive files - listing must never fail the API.
376
+ }
377
+ }
378
+ return summaries;
379
+ }
380
+
381
+ /**
382
+ * Crash-resume helper (design 2.3): find an archive file written for the
383
+ * given (source) profileId at or after `startedAt` - the persisted
384
+ * transition.startedAt. Existence of such a file means the switch already got
385
+ * past the archive step, so a restart must jump straight to building the new
386
+ * team instead of re-draining.
387
+ */
388
+ async function findTeamSwitchArchive(profileId: string, startedAt: number): Promise<string | null> {
389
+ let files: string[];
390
+ try {
391
+ files = await fs.readdir(archivedTeamsDirPath());
392
+ } catch {
393
+ return null;
394
+ }
395
+ for (const name of files.sort().reverse()) {
396
+ const parsed = parseArchiveFileName(name);
397
+ if (parsed && parsed.profileId === profileId && parsed.timestamp >= startedAt) {
398
+ return path.join(archivedTeamsDirPath(), name);
399
+ }
400
+ }
401
+ return null;
402
+ }
403
+
180
404
  async function loadWorkerIdentity(): Promise<WorkerIdentity | null> {
181
405
  const filePath = path.join(STATE_DIR, "worker-identity.json");
182
406
  try {
@@ -215,6 +439,9 @@ export {
215
439
  STATE_DIR,
216
440
  loadTeamState,
217
441
  saveTeamState,
442
+ archiveTeamState,
443
+ listArchivedTeams,
444
+ findTeamSwitchArchive,
218
445
  loadWorkerIdentity,
219
446
  saveWorkerIdentity,
220
447
  clearWorkerIdentity,
@@ -1,3 +1,4 @@
1
+ import { normalizeSessionRole } from "./session-roles.js";
1
2
  import type { OpenClawPluginApi, PluginLogger } from "../api.js";
2
3
  import {
3
4
  buildDeliverableMetadataPolicy,
@@ -11,14 +12,13 @@ import {
11
12
  resolveTeamClawWorkspaceDir,
12
13
  resolveTeamClawProjectsDir,
13
14
  } from "./openclaw-workspace.js";
14
- import { getRole } from "./roles.js";
15
+ // Phase 1.3: the executor role prompt comes from the active TeamProfile.
16
+ import { getActiveRole } from "./profile-loader.js";
15
17
  import type { RoleId, TaskAssignmentPayload, TaskExecutionEventInput, WorkerTaskResultContract } from "./types.js";
16
18
 
17
- const TEAMCLAW_ROLE_IDS_TEXT = [
18
- "pm", "architect", "developer", "qa",
19
- "release-engineer", "infra-engineer", "devops", "security-engineer",
20
- "designer", "marketing", "data-engineer",
21
- ];
19
+ // Phase 1.2: the local TEAMCLAW_ROLE_IDS_TEXT copy that used to live here was
20
+ // dead code (no references) and duplicated the canonical role id list; the
21
+ // shared text is exported from prompt-policy.ts (TEAMCLAW_ROLE_IDS_TEXT).
22
22
 
23
23
  const SESSION_PROGRESS_POLL_INTERVAL_MS = 1000;
24
24
  /** Checkpoint heartbeat cadence (resume support). */
@@ -84,7 +84,7 @@ export type RoleTaskExecutorDeps = {
84
84
 
85
85
  export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
86
86
  const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent, reportCheckpoint } = deps;
87
- const roleDef = getRole(role);
87
+ const roleDef = getActiveRole(role);
88
88
  const roleSystemPrompt = roleDef
89
89
  ? roleDef.systemPrompt
90
90
  : `You are a ${role} in a virtual software team. Complete the assigned task.`;
@@ -812,17 +812,6 @@ function getNewSessionProgressEntries(
812
812
  return entries.slice(overlap);
813
813
  }
814
814
 
815
- function normalizeSessionRole(value: unknown): string {
816
- if (typeof value !== "string") {
817
- return "";
818
- }
819
- const normalized = value.trim().toLowerCase().replace(/[-\s]+/g, "_");
820
- if (normalized === "toolresult") {
821
- return "tool_result";
822
- }
823
- return normalized;
824
- }
825
-
826
815
  function renderSessionMessage(message: Record<string, unknown>, role: string): { message: string; stream: string } {
827
816
  const content = message.content;
828
817
  if (typeof content === "string") {
@@ -232,6 +232,27 @@ export function createGithubClient(auth: GithubAuthManager) {
232
232
  return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };
233
233
  },
234
234
 
235
+ /**
236
+ * Worktree-GC delivery oracle (#173 follow-up 5): after a squash merge +
237
+ * branch deletion, ls-remote for the task branch is empty and the local
238
+ * rev-list own-count never drains (squash shas differ from the branch
239
+ * commits). True only on positive proof: a PR from this exact branch whose
240
+ * head tip is EXACTLY the given sha was merged. A closed-unmerged PR, a
241
+ * head-tip mismatch (worker committed after the push), or any API failure
242
+ * resolves false - the GC then retains the worktree (fails toward keep).
243
+ */
244
+ async prHeadDelivered(owner: string, repo: string, branch: string, headTip: string): Promise<boolean> {
245
+ const data = await getJson<unknown[]>(
246
+ `/repos/${owner}/${repo}/pulls?state=all&head=${encodeURIComponent(`${owner}:${branch}`)}`,
247
+ );
248
+ if (!Array.isArray(data) || data.length === 0) {
249
+ return false;
250
+ }
251
+ const pr = data[0] as Record<string, unknown>;
252
+ const headSha = String((pr.head as { sha?: string } | undefined)?.sha ?? "");
253
+ return Boolean(pr.merged) && headSha === headTip;
254
+ },
255
+
235
256
  /** Repos the logged-in user can select in the TeamAuto bind picker. */
236
257
  async listUserRepos(): Promise<{ id: string; fullName: string; private: boolean; pushedAt: string | null }[]> {
237
258
  const data = await getJson<unknown[]>("/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&per_page=100");
@@ -10,6 +10,21 @@ const exec = promisify(execFile);
10
10
 
11
11
  export const TEAMCLAW_BRANCH_PREFIX = "teamclaw/";
12
12
 
13
+ /**
14
+ * Delivery oracle for worktree GC (#173 follow-up 5): after a squash merge +
15
+ * branch deletion the task branch's commits never become reachable from
16
+ * origin/<default> (different shas, same content), so ls-remote is empty and
17
+ * the local rev-list own-count never drains. The scheduler supplies an oracle
18
+ * that asks GitHub whether a PR carrying EXACTLY this head tip was merged.
19
+ * Returns true only on positive proof; any error must resolve false (fail
20
+ * toward keep).
21
+ */
22
+ export type TaskDeliveryOracle = (
23
+ repoId: string,
24
+ taskId: string,
25
+ headTip: string,
26
+ ) => Promise<boolean>;
27
+
13
28
  /** TaskInfo.projectDir slug for a bound repo (relative to the projects dir). */
14
29
  export function teamAutoProjectDir(repoId: string): string {
15
30
  return `teamauto/${repoSlugToDirName(repoId)}`;
@@ -158,6 +173,65 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
158
173
  return `teamclaw/task-${taskId.replace(/[^\w-]/g, "")}`;
159
174
  }
160
175
 
176
+ // ---------- in-use sentinel (#173 follow-up 2) ----------
177
+
178
+ // The lock lives in the per-worktree git ADMIN dir, never inside the worktree
179
+ // tree: a file in the tree would dirty `git status --porcelain` and wedge the
180
+ // GC dirty guard. The admin dir is removed together with the worktree.
181
+ const TASK_LOCK_NAME = "teamclaw-task-lock.json";
182
+
183
+ async function taskLockPath(wtPath: string): Promise<string | null> {
184
+ try {
185
+ const out = (await run(["rev-parse", "--git-dir"], wtPath)).trim();
186
+ return path.join(path.resolve(wtPath, out), TASK_LOCK_NAME);
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+
192
+ function processAlive(pid: number): boolean {
193
+ try {
194
+ process.kill(pid, 0);
195
+ return true;
196
+ } catch (err) {
197
+ // EPERM: alive but owned by another user - treat as in use.
198
+ return (err as NodeJS.ErrnoException).code === "EPERM";
199
+ }
200
+ }
201
+
202
+ async function writeTaskLock(wtPath: string): Promise<void> {
203
+ const lockPath = await taskLockPath(wtPath);
204
+ if (!lockPath) {
205
+ return;
206
+ }
207
+ await fs.writeFile(lockPath, JSON.stringify({ pid: process.pid, at: Date.now() })).catch(() => undefined);
208
+ }
209
+
210
+ /**
211
+ * Live foreign controller holding this worktree, or null. Covers two
212
+ * controllers sharing one projects/ tree: whoever created/resumed the
213
+ * worktree last recorded its pid; GC (a different live pid) must not rip the
214
+ * tree out from under it. Our OWN pid never blocks (we are the GC). An
215
+ * orphaned worker process is not visible from the controller - the dirty
216
+ * guard remains that case's backstop (fails toward keep).
217
+ */
218
+ async function worktreeInUseBy(wtPath: string): Promise<number | null> {
219
+ const lockPath = await taskLockPath(wtPath);
220
+ if (!lockPath) {
221
+ return null;
222
+ }
223
+ try {
224
+ const lock = JSON.parse(await fs.readFile(lockPath, "utf8")) as { pid?: number };
225
+ const pid = Number(lock.pid);
226
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid && processAlive(pid)) {
227
+ return pid;
228
+ }
229
+ } catch {
230
+ // missing/corrupt lock - cannot prove in-use; proceed.
231
+ }
232
+ return null;
233
+ }
234
+
161
235
  /**
162
236
  * Collaboration contract: write tasks execute in a dedicated git worktree
163
237
  * branched from HEAD. Reuses an existing worktree (resume-safe) so the
@@ -169,11 +243,12 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
169
243
  // wtName carries the teamauto/ level for the REL path; the physical dir is
170
244
  // a SIBLING of the base checkout (path.join would nest teamauto/ twice).
171
245
  const wtPath = path.join(path.dirname(base), path.basename(wtName));
172
- if (await fs.access(path.join(wtPath, ".git")).then(() => true, () => false)) {
173
- return wtPath; // resume case
246
+ if (!(await fs.access(path.join(wtPath, ".git")).then(() => true, () => false))) {
247
+ await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
248
+ logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
174
249
  }
175
- await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
176
- logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
250
+ // Refresh the in-use sentinel on create AND resume (#173 follow-up 2).
251
+ await writeTaskLock(wtPath);
177
252
  return wtPath;
178
253
  }
179
254
 
@@ -184,7 +259,12 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
184
259
  const wtPath = path.join(path.dirname(base), path.basename(wtName));
185
260
  try {
186
261
  if (await fs.access(wtPath).then(() => true, () => false)) {
187
- await run(["worktree", "remove", "--force", wtPath], base);
262
+ await run(["worktree", "remove", "--force", wtPath], base).catch(async () => {
263
+ // Not a registered worktree anymore (stale admin dir / manual mv):
264
+ // prune registrations and delete the directory directly.
265
+ await run(["worktree", "prune"], base).catch(() => undefined);
266
+ await fs.rm(wtPath, { recursive: true, force: true });
267
+ });
188
268
  }
189
269
  await run(["branch", "-D", taskBranchName(taskId)], base).catch(() => undefined);
190
270
  } catch (err) {
@@ -192,6 +272,166 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
192
272
  }
193
273
  }
194
274
 
275
+ /**
276
+ * Terminal-state removal with a delivery-safety check: delete the task
277
+ * worktree only when its work is either already on the remote (branch tip
278
+ * matches) or nonexistent (no commits of its own). Undelivered local work
279
+ * is retained and reported - never silently destroyed.
280
+ */
281
+ async function safeRemoveTaskWorktree(
282
+ repoId: string,
283
+ taskId: string,
284
+ deliveryOracle?: TaskDeliveryOracle,
285
+ ): Promise<{ removed: boolean; reason: string }> {
286
+ const base = await repoDir(repoId);
287
+ const wtName = taskWorktreeDirName(repoId, taskId);
288
+ const wtPath = path.join(path.dirname(base), path.basename(wtName));
289
+ const branch = taskBranchName(taskId);
290
+ if (!(await fs.access(wtPath).then(() => true, () => false))) {
291
+ // Review F4: the dir is gone but a stale local branch can survive an
292
+ // earlier removal whose branch -D failed. Reap it when the remote tip
293
+ // still matches (work provably on the remote); otherwise leave it.
294
+ try {
295
+ const refs = await run(["ls-remote", "origin", `refs/heads/${branch}`], base);
296
+ const remoteTip = refs.split("\t")[0]?.trim() ?? "";
297
+ const localTip = remoteTip ? (await run(["rev-parse", branch], base).catch(() => "")).trim() : "";
298
+ if (remoteTip && localTip === remoteTip) {
299
+ await run(["branch", "-D", branch], base);
300
+ return { removed: true, reason: "worktree already gone; reaped stale branch (tip matches remote)" };
301
+ }
302
+ } catch { /* conservative: leave the branch */ }
303
+ return { removed: false, reason: "already gone" };
304
+ }
305
+ try {
306
+ // #173 follow-up 2: in-use sentinel - a live foreign controller recorded
307
+ // in the task lock owns this tree; never remove under it.
308
+ const inUsePid = await worktreeInUseBy(wtPath);
309
+ if (inUsePid !== null) {
310
+ return { removed: false, reason: `retained: in use by live process (pid ${inUsePid})` };
311
+ }
312
+ // #173 follow-up 1: the dirty guard must cover BOTH removal paths. The
313
+ // tip-match branch used to remove without any dirty check, silently
314
+ // destroying post-delivery worker edits (small window, but real).
315
+ const dirty = await run(["status", "--porcelain"], wtPath).catch(() => "x");
316
+ if (dirty.trim()) {
317
+ return { removed: false, reason: "retained: dirty worktree (uncommitted changes)" };
318
+ }
319
+ const remoteRefs = await run(["ls-remote", "origin", `refs/heads/${branch}`], base);
320
+ const remoteTip = remoteRefs.split("\t")[0]?.trim() ?? "";
321
+ if (remoteTip) {
322
+ const localTip = (await run(["rev-parse", branch], base).catch(() => "")).trim();
323
+ if (localTip && localTip === remoteTip) {
324
+ await removeTaskWorktree(repoId, taskId);
325
+ return { removed: true, reason: "delivered (branch tip on remote)" };
326
+ }
327
+ return { removed: false, reason: "retained: local branch ahead of pushed tip (unpushed work)" };
328
+ }
329
+ // Branch never pushed (or deleted post-merge): the worktree is the only
330
+ // copy. Keep it when it carries its own commits; drop it when the worker
331
+ // never committed anything at all.
332
+ const info = await run(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).catch(() => "");
333
+ const defaultBranch = info.trim().replace(/^origin\//, "") || "main";
334
+ const own = await run(["rev-list", "--count", `HEAD`, "--not", `origin/${defaultBranch}`], wtPath).catch(() => null);
335
+ if (own === null) {
336
+ // Cannot prove emptiness (fetch state unknown) - conservative keep.
337
+ return { removed: false, reason: "retained: could not verify emptiness" };
338
+ }
339
+ if (Number(own.trim()) === 0) {
340
+ await removeTaskWorktree(repoId, taskId);
341
+ return { removed: true, reason: "no own commits, branch never pushed" };
342
+ }
343
+ // #173 follow-up 5: squash-merge + branch deletion re-leak. own > 0 with
344
+ // an empty ls-remote is ALSO the shape of a delivered-via-squash PR whose
345
+ // branch was auto-deleted (shas unreachable, content merged). Ask the
346
+ // oracle for positive proof (merged PR with exactly this head tip);
347
+ // anything less retains the worktree.
348
+ if (deliveryOracle) {
349
+ const headTip = (await run(["rev-parse", "HEAD"], wtPath).catch(() => "")).trim();
350
+ if (headTip && (await deliveryOracle(repoId, taskId, headTip).catch(() => false))) {
351
+ await removeTaskWorktree(repoId, taskId);
352
+ return { removed: true, reason: "delivered via merged PR (squash-merge, head tip matches)" };
353
+ }
354
+ }
355
+ return { removed: false, reason: `retained: ${own.trim()} unpushed own commit(s)` };
356
+ } catch (err) {
357
+ return { removed: false, reason: `retained: gc check failed (${err instanceof Error ? err.message : String(err)})` };
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Reconcile leftover task worktrees on disk: for every `<slug>__task-*`
363
+ * sibling whose task is terminal (or unknown), apply the delivery-safety
364
+ * removal. Heals the historical backlog that pre-dates terminal cleanup.
365
+ */
366
+ async function gcTaskWorktrees(
367
+ repoId: string,
368
+ isTerminal: (taskId: string) => boolean,
369
+ deliveryOracle?: TaskDeliveryOracle,
370
+ ): Promise<{ removed: string[]; retained: { taskId: string; reason: string }[]; stale: number }> {
371
+ const base = await repoDir(repoId);
372
+ const siblings = path.dirname(base);
373
+ // taskWorktreeDirName(repoId, "x") = "teamauto/<slug>__task-x"; the
374
+ // physical dir is its basename, so the scan prefix is basename minus "x".
375
+ const withSentinel = path.basename(taskWorktreeDirName(repoId, "x"));
376
+ const prefix = withSentinel.slice(0, withSentinel.length - 1);
377
+ const removed: string[] = [];
378
+ const retained: { taskId: string; reason: string }[] = [];
379
+ let stale = 0;
380
+ const apply = async (taskId: string): Promise<void> => {
381
+ const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle);
382
+ if (r.removed) {
383
+ removed.push(taskId);
384
+ logger.warn(`TeamAuto: worktree GC removed ${taskId} (${r.reason})`);
385
+ } else if (r.reason.includes("already gone")) {
386
+ // #173 QA finding: dir already gone but a stale local branch survives
387
+ // (squash-merge leak face) - previously invisible in both the log and
388
+ // the activity line. Counted + logged now.
389
+ stale += 1;
390
+ logger.warn(`TeamAuto: worktree GC ${taskId}: worktree already gone (stale branch may remain)`);
391
+ } else {
392
+ retained.push({ taskId, reason: r.reason });
393
+ logger.warn(`TeamAuto: worktree GC kept ${taskId}: ${r.reason}`);
394
+ }
395
+ };
396
+ let entries: string[] = [];
397
+ try {
398
+ entries = (await fs.readdir(siblings)).filter((e) => e.startsWith(prefix));
399
+ } catch {
400
+ entries = [];
401
+ }
402
+ const dirTaskIds: string[] = [];
403
+ for (const entry of entries) {
404
+ const taskId = entry.slice(prefix.length);
405
+ if (!taskId) continue;
406
+ dirTaskIds.push(taskId);
407
+ if (!isTerminal(taskId)) continue; // active/resumable task - worktree is resume state
408
+ await apply(taskId);
409
+ }
410
+ // #173 QA finding: BRANCH-ONLY leaks - the worktree dir is already gone
411
+ // but the local teamclaw/task-* branch survives (e.g. an earlier removal
412
+ // whose branch -D failed, or the squash-merge stale-branch face). The
413
+ // directory enumeration above never sees them; enumerate the branches too
414
+ // so safeRemoveTaskWorktree can reap (tip on remote) or at least surface
415
+ // them in the stale count instead of leaking silently forever.
416
+ const branchPrefix = `${TEAMCLAW_BRANCH_PREFIX}task-`;
417
+ let branchRefs: string[] = [];
418
+ try {
419
+ branchRefs = (await run(["for-each-ref", "--format=%(refname:short)", `refs/heads/${branchPrefix}*`], base))
420
+ .split("\n")
421
+ .filter(Boolean);
422
+ } catch {
423
+ branchRefs = [];
424
+ }
425
+ const seen = new Set(dirTaskIds);
426
+ for (const ref of branchRefs) {
427
+ const taskId = ref.slice(branchPrefix.length);
428
+ if (!taskId || seen.has(taskId)) continue;
429
+ if (!isTerminal(taskId)) continue;
430
+ await apply(taskId);
431
+ }
432
+ return { removed, retained, stale };
433
+ }
434
+
195
435
  function taskWorktreeRelDir(repoId: string, taskId: string): string {
196
436
  return taskWorktreeDirName(repoId, taskId);
197
437
  }
@@ -212,7 +452,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
212
452
  }
213
453
  }
214
454
 
215
- return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
455
+ return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, safeRemoveTaskWorktree, gcTaskWorktrees, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
216
456
  }
217
457
 
218
458
  export type TeamAutoRepoSync = ReturnType<typeof createRepoSync>;