@teamclaws/teamclaw 2026.8.1 → 2026.11.1

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 (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
package/dist/src/state.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
+ import { validateRoleIdList } from "./roles.js";
5
+ // Phase 1.6: the legacy-state profileId migration defaults to the loader's
6
+ // software-rd baseline id (single literal source). profile-loader has no
7
+ // runtime edge back into this module, so no cycle.
8
+ import { SOFTWARE_RD_PROFILE_ID } from "./profile-loader.js";
4
9
  const STATE_VERSION = 2;
5
10
  function migrateState(raw) {
6
11
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
@@ -49,8 +54,79 @@ function migrateState(raw) {
49
54
  // Version 1 → 2: no new required fields beyond `version` itself.
50
55
  // startupReadiness was already optional and handled by normalizeStartupReadiness above.
51
56
  state.version = STATE_VERSION;
57
+ // Phase 1.6 (design 2.3): legacy states carry no profileId; default them
58
+ // to the software-rd baseline. Idempotent - states saved by this build
59
+ // already carry the field and pass through unchanged.
60
+ if (typeof state.profileId !== "string" || !state.profileId.trim()) {
61
+ state.profileId = SOFTWARE_RD_PROFILE_ID;
62
+ }
63
+ // Phase 2.1: a malformed persisted transition is dropped (treated as "no
64
+ // switch in progress"). Aborting a corrupt switch keeps the previous team
65
+ // fully intact - the safe failure mode; the user can re-issue the switch.
66
+ if (state.transition !== undefined) {
67
+ const transition = state.transition;
68
+ const phaseOk = transition?.phase === "draining" || transition?.phase === "archiving" || transition?.phase === "warming";
69
+ const targetOk = typeof transition?.targetProfileId === "string" && Boolean(transition.targetProfileId.trim());
70
+ const startedAtOk = typeof transition?.startedAt === "number";
71
+ if (!phaseOk || !targetOk || !startedAtOk) {
72
+ delete state.transition;
73
+ }
74
+ }
75
+ // Issue #23: device-pairing security state (additive optional field). No
76
+ // `security` key = protection off (L0 zero-friction default). A malformed
77
+ // persisted shape is sanitized in place, mirroring the transition policy
78
+ // above: devices without a usable identity/tokenHash are dropped (such a
79
+ // device could never authenticate again anyway), and malformed pairing
80
+ // codes / observation records are discarded.
81
+ if (state.security !== undefined) {
82
+ const security = state.security;
83
+ if (!security || typeof security !== "object" || Array.isArray(security)) {
84
+ delete state.security;
85
+ }
86
+ else {
87
+ if (security.enabledAt !== undefined && typeof security.enabledAt !== "number") {
88
+ delete security.enabledAt;
89
+ }
90
+ security.devices = Array.isArray(security.devices)
91
+ ? security.devices.filter(isValidPersistedSecurityDevice)
92
+ : [];
93
+ if (security.pairingCode !== undefined) {
94
+ const pairingCode = security.pairingCode;
95
+ const codeOk = typeof pairingCode?.code === "string" && /^[A-Z2-7]{8}$/.test(pairingCode.code);
96
+ const expiresOk = typeof pairingCode?.expiresAt === "number";
97
+ const purposeOk = typeof pairingCode?.purpose === "string" && Boolean(pairingCode.purpose.trim());
98
+ const usedOk = pairingCode?.usedAt === undefined || typeof pairingCode.usedAt === "number";
99
+ if (!codeOk || !expiresOk || !purposeOk || !usedOk) {
100
+ delete security.pairingCode;
101
+ }
102
+ }
103
+ if (security.lastNonLanPeer !== undefined) {
104
+ const observation = security.lastNonLanPeer;
105
+ if (typeof observation?.ip !== "string" ||
106
+ typeof observation?.at !== "number" ||
107
+ typeof observation?.path !== "string") {
108
+ delete security.lastNonLanPeer;
109
+ }
110
+ }
111
+ }
112
+ }
52
113
  return state;
53
114
  }
115
+ /**
116
+ * Issue #23: persisted-device structural guard for the migration above. A
117
+ * device needs a non-empty id, a sha256-hex tokenHash (64 lowercase hex
118
+ * chars) and a creation timestamp; anything else is corrupt state and is
119
+ * dropped rather than half-loaded.
120
+ */
121
+ function isValidPersistedSecurityDevice(entry) {
122
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
123
+ return false;
124
+ }
125
+ const device = entry;
126
+ return (typeof device.id === "string" && Boolean(device.id.trim()) &&
127
+ typeof device.tokenHash === "string" && /^[0-9a-f]{64}$/.test(device.tokenHash) &&
128
+ typeof device.createdAt === "number");
129
+ }
54
130
  function resolvePluginStateDir() {
55
131
  const explicitStateDir = process.env.OPENCLAW_STATE_DIR?.trim();
56
132
  if (explicitStateDir) {
@@ -78,9 +154,9 @@ function normalizeStartupReadiness(value) {
78
154
  const startedAt = typeof record.startedAt === "number" ? record.startedAt : undefined;
79
155
  const checkedAt = typeof record.checkedAt === "number" ? record.checkedAt : undefined;
80
156
  const attempts = typeof record.attempts === "number" && record.attempts >= 0 ? Math.floor(record.attempts) : 0;
81
- const requiredRoles = Array.isArray(record.requiredRoles)
82
- ? record.requiredRoles.filter((entry) => typeof entry === "string")
83
- : [];
157
+ // Phase 0.3: persisted requiredRoles are untrusted; filter through the
158
+ // shared guard so corrupted state cannot inject arbitrary role strings.
159
+ const requiredRoles = validateRoleIdList(record.requiredRoles);
84
160
  const readyWorkerIds = Array.isArray(record.readyWorkerIds)
85
161
  ? record.readyWorkerIds.filter((entry) => typeof entry === "string")
86
162
  : [];
@@ -93,7 +169,7 @@ function normalizeStartupReadiness(value) {
93
169
  startedAt,
94
170
  checkedAt,
95
171
  attempts,
96
- requiredRoles: requiredRoles,
172
+ requiredRoles,
97
173
  readyWorkerIds,
98
174
  message,
99
175
  };
@@ -101,9 +177,37 @@ function normalizeStartupReadiness(value) {
101
177
  async function ensureDir(dir) {
102
178
  await fs.mkdir(dir, { recursive: true });
103
179
  }
180
+ /**
181
+ * Issue #255 P1-4: every file written through this helper is controller
182
+ * state that can carry plaintext secrets - team-state.json holds the device
183
+ * pairingCode and each provisioned worker's launchToken, the archived team
184
+ * envelopes and worker-identity.json ride the same path. Writes are now
185
+ * owner-only (0600), matching the github-auth.ts auth-store precedent:
186
+ * - the tmp file is created with mode 0600 and the rename carries that
187
+ * mode onto the final path, and
188
+ * - an existing file from an older build (created 0644 by this same
189
+ * helper before the mode existed) is pre-tightened before the rewrite
190
+ * (#242 process-supervisor pattern: chmod first, ENOENT tolerated for
191
+ * first writes).
192
+ */
104
193
  async function writeFileAtomically(filePath, contents) {
105
194
  const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
106
- await fs.writeFile(tmpPath, contents, "utf8");
195
+ try {
196
+ await fs.chmod(filePath, 0o600);
197
+ }
198
+ catch (error) {
199
+ if (error?.code !== "ENOENT") {
200
+ throw error;
201
+ }
202
+ }
203
+ await fs.writeFile(tmpPath, contents, { encoding: "utf8", mode: 0o600 });
204
+ try {
205
+ await fs.chmod(tmpPath, 0o600);
206
+ }
207
+ catch {
208
+ // Best-effort: the write itself already requested mode 0600; some
209
+ // filesystems (e.g. network mounts) reject explicit chmod.
210
+ }
107
211
  await fs.rename(tmpPath, filePath);
108
212
  }
109
213
  function enqueueAtomicWrite(filePath, contents) {
@@ -118,12 +222,65 @@ function enqueueAtomicWrite(filePath, contents) {
118
222
  }
119
223
  });
120
224
  }
225
+ // Phase 1.6 (design section 2.3): the persisted state file name is decoupled
226
+ // from teamName. TeamClaw is single-instance-single-team per state dir, so a
227
+ // fixed instance-scoped file name IS the instance identity - renaming a team
228
+ // no longer orphans the old `<teamName>-team-state.json` (the collision risk
229
+ // called out in the design). The legacy teamName-named file is still read as
230
+ // a one-time migration source; the next save writes the new name and the
231
+ // legacy file is simply never consulted again.
232
+ const TEAM_STATE_FILE = "team-state.json";
233
+ function teamStateFilePath() {
234
+ return path.join(STATE_DIR, TEAM_STATE_FILE);
235
+ }
236
+ function legacyTeamStateFilePath(teamName) {
237
+ return path.join(STATE_DIR, `${teamName}-team-state.json`);
238
+ }
239
+ function isFileMissing(error) {
240
+ return error?.code === "ENOENT";
241
+ }
242
+ function errorMessage(error) {
243
+ return error instanceof Error ? error.message : String(error);
244
+ }
121
245
  async function loadTeamState(teamName) {
122
- const filePath = path.join(STATE_DIR, `${teamName}-team-state.json`);
246
+ // Review fix (Phase 1.6): the instance-scoped team-state.json is the
247
+ // primary state file, and when it EXISTS it is authoritative. A
248
+ // present-but-corrupt primary is a fatal error, never a silent fallback to
249
+ // the legacy snapshot - falling back would rewind the team to the
250
+ // pre-migration state and lose everything saved since. Only a MISSING
251
+ // primary (ENOENT) falls through to the one-time legacy read.
252
+ let primaryRaw = null;
123
253
  try {
124
- const raw = await fs.readFile(filePath, "utf8");
125
- const parsed = JSON.parse(raw);
126
- return migrateState(parsed);
254
+ primaryRaw = await fs.readFile(teamStateFilePath(), "utf8");
255
+ }
256
+ catch (error) {
257
+ if (!isFileMissing(error)) {
258
+ throw new Error(`TeamClaw cannot read the persisted team state ${teamStateFilePath()}: ${errorMessage(error)}`);
259
+ }
260
+ }
261
+ if (primaryRaw !== null) {
262
+ let parsed;
263
+ try {
264
+ parsed = JSON.parse(primaryRaw);
265
+ }
266
+ catch (error) {
267
+ throw new Error(`TeamClaw team state file ${teamStateFilePath()} is not valid JSON (${errorMessage(error)}). `
268
+ + "Refusing to start with a fresh team over a corrupt state file - fix or remove the file manually.");
269
+ }
270
+ const migrated = migrateState(parsed);
271
+ if (!migrated) {
272
+ throw new Error(`TeamClaw team state file ${teamStateFilePath()} exists but is not a valid team state. `
273
+ + "Refusing to start with a fresh team over an unusable state file - fix or remove the file manually.");
274
+ }
275
+ return migrated;
276
+ }
277
+ // Primary absent: one-time legacy fallback (pre-Phase-1.6 file name).
278
+ // Lenient by design, matching the pre-Phase-1.6 single-file behavior: a
279
+ // missing or corrupt legacy file simply means first initialization, and a
280
+ // corrupt legacy file is never overwritten (saves go to the new name).
281
+ try {
282
+ const legacyRaw = await fs.readFile(legacyTeamStateFilePath(teamName), "utf8");
283
+ return migrateState(JSON.parse(legacyRaw));
127
284
  }
128
285
  catch {
129
286
  return null;
@@ -131,7 +288,7 @@ async function loadTeamState(teamName) {
131
288
  }
132
289
  async function saveTeamState(state) {
133
290
  await ensureDir(STATE_DIR);
134
- const filePath = path.join(STATE_DIR, `${state.teamName}-team-state.json`);
291
+ const filePath = teamStateFilePath();
135
292
  state.version = STATE_VERSION;
136
293
  state.updatedAt = Date.now();
137
294
  state.provisioning = state.provisioning && typeof state.provisioning === "object"
@@ -149,6 +306,113 @@ async function saveTeamState(state) {
149
306
  : {};
150
307
  await enqueueAtomicWrite(filePath, `${JSON.stringify(state, null, 2)}\n`);
151
308
  }
309
+ // ---------------------------------------------------------------------------
310
+ // Team profile switch archive (Phase 2.1, design section 2.3 step 3).
311
+ //
312
+ // Switching profiles seals the WHOLE previous TeamState (tasks,
313
+ // clarifications, messages, previews, repo, projects, controllerRuns,
314
+ // reports) into state-dir/archived/<profileId>-<timestamp>.json together with
315
+ // an embedded snapshot of the profile's roles - so an archived banking team
316
+ // keeps its original role vocabulary even after the profile package evolves
317
+ // (design 2.2: archive queries must not suffer terminology drift). v1 only
318
+ // lists archive metadata; the full payload stays queryable offline.
319
+ // ---------------------------------------------------------------------------
320
+ const ARCHIVED_TEAMS_DIR_NAME = "archived";
321
+ const ARCHIVE_FILE_RE = /^([a-z0-9-]+)-(\d+)(?:-([a-z0-9]+))?\.json$/;
322
+ function archivedTeamsDirPath() {
323
+ return path.join(STATE_DIR, ARCHIVED_TEAMS_DIR_NAME);
324
+ }
325
+ function parseArchiveFileName(name) {
326
+ const match = ARCHIVE_FILE_RE.exec(name);
327
+ if (!match) {
328
+ return null;
329
+ }
330
+ const timestamp = Number(match[2]);
331
+ return Number.isFinite(timestamp) ? { profileId: match[1], timestamp } : null;
332
+ }
333
+ /**
334
+ * Seal the given TeamState into the archive directory (design 2.3 step 3).
335
+ * Returns the archive file path. The write is atomic; the envelope embeds the
336
+ * profile snapshot so the archive is self-contained.
337
+ */
338
+ async function archiveTeamState(state, profileSnapshot) {
339
+ const dir = archivedTeamsDirPath();
340
+ await ensureDir(dir);
341
+ // #251: a short random suffix disambiguates same-millisecond archives
342
+ // (two switches inside one ms would otherwise silently overwrite each
343
+ // other). Capture groups 1/2 keep their original semantics; group 3 is
344
+ // the optional suffix, so pre-#251 archive names still parse.
345
+ const suffix = Math.random().toString(36).slice(2, 8).padEnd(6, "0");
346
+ const fileName = `${state.profileId}-${Date.now()}-${suffix}.json`;
347
+ const filePath = path.join(dir, fileName);
348
+ const envelope = {
349
+ archivedAt: Date.now(),
350
+ profile: profileSnapshot,
351
+ team: state,
352
+ };
353
+ await enqueueAtomicWrite(filePath, `${JSON.stringify(envelope, null, 2)}\n`);
354
+ return filePath;
355
+ }
356
+ /** List archived teams (newest first). Unreadable entries are skipped. */
357
+ async function listArchivedTeams() {
358
+ let files;
359
+ try {
360
+ files = await fs.readdir(archivedTeamsDirPath());
361
+ }
362
+ catch {
363
+ return [];
364
+ }
365
+ const summaries = [];
366
+ for (const name of files.sort().reverse()) {
367
+ if (!name.endsWith(".json") || !parseArchiveFileName(name)) {
368
+ continue;
369
+ }
370
+ try {
371
+ const raw = await fs.readFile(path.join(archivedTeamsDirPath(), name), "utf8");
372
+ const parsed = JSON.parse(raw);
373
+ if (!parsed?.team || typeof parsed.team !== "object") {
374
+ continue;
375
+ }
376
+ summaries.push({
377
+ file: name,
378
+ profileId: parsed.profile?.id ?? parsed.team.profileId ?? "unknown",
379
+ profileName: parsed.profile?.name ?? "",
380
+ teamName: typeof parsed.team.teamName === "string" ? parsed.team.teamName : "",
381
+ archivedAt: typeof parsed.archivedAt === "number" ? parsed.archivedAt : 0,
382
+ taskCount: parsed.team.tasks && typeof parsed.team.tasks === "object"
383
+ ? Object.keys(parsed.team.tasks).length
384
+ : 0,
385
+ });
386
+ }
387
+ catch {
388
+ // Skip unreadable/corrupt archive files - listing must never fail the API.
389
+ }
390
+ }
391
+ return summaries;
392
+ }
393
+ /**
394
+ * Crash-resume helper (design 2.3): find an archive file written for the
395
+ * given (source) profileId at or after `startedAt` - the persisted
396
+ * transition.startedAt. Existence of such a file means the switch already got
397
+ * past the archive step, so a restart must jump straight to building the new
398
+ * team instead of re-draining.
399
+ */
400
+ async function findTeamSwitchArchive(profileId, startedAt) {
401
+ let files;
402
+ try {
403
+ files = await fs.readdir(archivedTeamsDirPath());
404
+ }
405
+ catch {
406
+ return null;
407
+ }
408
+ for (const name of files.sort().reverse()) {
409
+ const parsed = parseArchiveFileName(name);
410
+ if (parsed && parsed.profileId === profileId && parsed.timestamp >= startedAt) {
411
+ return path.join(archivedTeamsDirPath(), name);
412
+ }
413
+ }
414
+ return null;
415
+ }
152
416
  async function loadWorkerIdentity() {
153
417
  const filePath = path.join(STATE_DIR, "worker-identity.json");
154
418
  try {
@@ -180,4 +444,4 @@ async function clearWorkerIdentity() {
180
444
  // ignore
181
445
  }
182
446
  }
183
- export { STATE_DIR, loadTeamState, saveTeamState, loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity, };
447
+ export { STATE_DIR, loadTeamState, saveTeamState, archiveTeamState, listArchivedTeams, findTeamSwitchArchive, loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity, };
@@ -1,11 +1,11 @@
1
+ import { normalizeSessionRole } from "./session-roles.js";
1
2
  import { buildDeliverableMetadataPolicy, buildResultContractGuidance, buildTaskExecutionRules, buildVerificationPolicy, buildWorkerMemoryContractRules, } from "./prompt-policy.js";
2
3
  import { buildTeamClawProjectWorkspacePath, resolveTeamClawWorkspaceDir, resolveTeamClawProjectsDir, } from "./openclaw-workspace.js";
3
- import { getRole } from "./roles.js";
4
- const TEAMCLAW_ROLE_IDS_TEXT = [
5
- "pm", "architect", "developer", "qa",
6
- "release-engineer", "infra-engineer", "devops", "security-engineer",
7
- "designer", "marketing", "data-engineer",
8
- ];
4
+ // Phase 1.3: the executor role prompt comes from the active TeamProfile.
5
+ import { getActiveRole } from "./profile-loader.js";
6
+ // Phase 1.2: the local TEAMCLAW_ROLE_IDS_TEXT copy that used to live here was
7
+ // dead code (no references) and duplicated the canonical role id list; the
8
+ // shared text is exported from prompt-policy.ts (TEAMCLAW_ROLE_IDS_TEXT).
9
9
  const SESSION_PROGRESS_POLL_INTERVAL_MS = 1000;
10
10
  /** Checkpoint heartbeat cadence (resume support). */
11
11
  const CHECKPOINT_EMIT_INTERVAL_MS = 15_000;
@@ -23,7 +23,7 @@ const TOOL_CALL_BLOCK_TYPES = new Set(["tool_use", "toolcall", "tool_call"]);
23
23
  const TOOL_RESULT_BLOCK_TYPES = new Set(["tool_result", "tool_result_error"]);
24
24
  export function createRoleTaskExecutor(deps) {
25
25
  const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent, reportCheckpoint } = deps;
26
- const roleDef = getRole(role);
26
+ const roleDef = getActiveRole(role);
27
27
  const roleSystemPrompt = roleDef
28
28
  ? roleDef.systemPrompt
29
29
  : `You are a ${role} in a virtual software team. Complete the assigned task.`;
@@ -666,16 +666,6 @@ function getNewSessionProgressEntries(entries, previousFingerprints) {
666
666
  }
667
667
  return entries.slice(overlap);
668
668
  }
669
- function normalizeSessionRole(value) {
670
- if (typeof value !== "string") {
671
- return "";
672
- }
673
- const normalized = value.trim().toLowerCase().replace(/[-\s]+/g, "_");
674
- if (normalized === "toolresult") {
675
- return "tool_result";
676
- }
677
- return normalized;
678
- }
679
669
  function renderSessionMessage(message, role) {
680
670
  const content = message.content;
681
671
  if (typeof content === "string") {
@@ -172,6 +172,24 @@ export function createGithubClient(auth) {
172
172
  const item = data;
173
173
  return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };
174
174
  },
175
+ /**
176
+ * Worktree-GC delivery oracle (#173 follow-up 5): after a squash merge +
177
+ * branch deletion, ls-remote for the task branch is empty and the local
178
+ * rev-list own-count never drains (squash shas differ from the branch
179
+ * commits). True only on positive proof: a PR from this exact branch whose
180
+ * head tip is EXACTLY the given sha was merged. A closed-unmerged PR, a
181
+ * head-tip mismatch (worker committed after the push), or any API failure
182
+ * resolves false - the GC then retains the worktree (fails toward keep).
183
+ */
184
+ async prHeadDelivered(owner, repo, branch, headTip) {
185
+ const data = await getJson(`/repos/${owner}/${repo}/pulls?state=all&head=${encodeURIComponent(`${owner}:${branch}`)}`);
186
+ if (!Array.isArray(data) || data.length === 0) {
187
+ return false;
188
+ }
189
+ const pr = data[0];
190
+ const headSha = String(pr.head?.sha ?? "");
191
+ return Boolean(pr.merged) && headSha === headTip;
192
+ },
175
193
  /** Repos the logged-in user can select in the TeamAuto bind picker. */
176
194
  async listUserRepos() {
177
195
  const data = await getJson("/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&per_page=100");