@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/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,9 +73,87 @@ 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
+
96
+ // Issue #23: device-pairing security state (additive optional field). No
97
+ // `security` key = protection off (L0 zero-friction default). A malformed
98
+ // persisted shape is sanitized in place, mirroring the transition policy
99
+ // above: devices without a usable identity/tokenHash are dropped (such a
100
+ // device could never authenticate again anyway), and malformed pairing
101
+ // codes / observation records are discarded.
102
+ if (state.security !== undefined) {
103
+ const security = state.security as Record<string, unknown>;
104
+ if (!security || typeof security !== "object" || Array.isArray(security)) {
105
+ delete state.security;
106
+ } else {
107
+ if (security.enabledAt !== undefined && typeof security.enabledAt !== "number") {
108
+ delete security.enabledAt;
109
+ }
110
+ security.devices = Array.isArray(security.devices)
111
+ ? security.devices.filter(isValidPersistedSecurityDevice)
112
+ : [];
113
+ if (security.pairingCode !== undefined) {
114
+ const pairingCode = security.pairingCode as Record<string, unknown>;
115
+ const codeOk = typeof pairingCode?.code === "string" && /^[A-Z2-7]{8}$/.test(pairingCode.code);
116
+ const expiresOk = typeof pairingCode?.expiresAt === "number";
117
+ const purposeOk = typeof pairingCode?.purpose === "string" && Boolean(pairingCode.purpose.trim());
118
+ const usedOk = pairingCode?.usedAt === undefined || typeof pairingCode.usedAt === "number";
119
+ if (!codeOk || !expiresOk || !purposeOk || !usedOk) {
120
+ delete security.pairingCode;
121
+ }
122
+ }
123
+ if (security.lastNonLanPeer !== undefined) {
124
+ const observation = security.lastNonLanPeer as Record<string, unknown>;
125
+ if (
126
+ typeof observation?.ip !== "string" ||
127
+ typeof observation?.at !== "number" ||
128
+ typeof observation?.path !== "string"
129
+ ) {
130
+ delete security.lastNonLanPeer;
131
+ }
132
+ }
133
+ }
134
+ }
135
+
70
136
  return state as unknown as TeamState;
71
137
  }
72
138
 
139
+ /**
140
+ * Issue #23: persisted-device structural guard for the migration above. A
141
+ * device needs a non-empty id, a sha256-hex tokenHash (64 lowercase hex
142
+ * chars) and a creation timestamp; anything else is corrupt state and is
143
+ * dropped rather than half-loaded.
144
+ */
145
+ function isValidPersistedSecurityDevice(entry: unknown): boolean {
146
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
147
+ return false;
148
+ }
149
+ const device = entry as Record<string, unknown>;
150
+ return (
151
+ typeof device.id === "string" && Boolean(device.id.trim()) &&
152
+ typeof device.tokenHash === "string" && /^[0-9a-f]{64}$/.test(device.tokenHash) &&
153
+ typeof device.createdAt === "number"
154
+ );
155
+ }
156
+
73
157
  function resolvePluginStateDir(): string {
74
158
  const explicitStateDir = process.env.OPENCLAW_STATE_DIR?.trim();
75
159
  if (explicitStateDir) {
@@ -101,9 +185,9 @@ function normalizeStartupReadiness(value: unknown): StartupProvisioningReadiness
101
185
  const startedAt = typeof record.startedAt === "number" ? record.startedAt : undefined;
102
186
  const checkedAt = typeof record.checkedAt === "number" ? record.checkedAt : undefined;
103
187
  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
- : [];
188
+ // Phase 0.3: persisted requiredRoles are untrusted; filter through the
189
+ // shared guard so corrupted state cannot inject arbitrary role strings.
190
+ const requiredRoles = validateRoleIdList(record.requiredRoles);
107
191
  const readyWorkerIds = Array.isArray(record.readyWorkerIds)
108
192
  ? record.readyWorkerIds.filter((entry): entry is string => typeof entry === "string")
109
193
  : [];
@@ -116,7 +200,7 @@ function normalizeStartupReadiness(value: unknown): StartupProvisioningReadiness
116
200
  startedAt,
117
201
  checkedAt,
118
202
  attempts,
119
- requiredRoles: requiredRoles as RoleId[],
203
+ requiredRoles,
120
204
  readyWorkerIds,
121
205
  message,
122
206
  };
@@ -126,9 +210,35 @@ async function ensureDir(dir: string): Promise<void> {
126
210
  await fs.mkdir(dir, { recursive: true });
127
211
  }
128
212
 
213
+ /**
214
+ * Issue #255 P1-4: every file written through this helper is controller
215
+ * state that can carry plaintext secrets - team-state.json holds the device
216
+ * pairingCode and each provisioned worker's launchToken, the archived team
217
+ * envelopes and worker-identity.json ride the same path. Writes are now
218
+ * owner-only (0600), matching the github-auth.ts auth-store precedent:
219
+ * - the tmp file is created with mode 0600 and the rename carries that
220
+ * mode onto the final path, and
221
+ * - an existing file from an older build (created 0644 by this same
222
+ * helper before the mode existed) is pre-tightened before the rewrite
223
+ * (#242 process-supervisor pattern: chmod first, ENOENT tolerated for
224
+ * first writes).
225
+ */
129
226
  async function writeFileAtomically(filePath: string, contents: string): Promise<void> {
130
227
  const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
131
- await fs.writeFile(tmpPath, contents, "utf8");
228
+ try {
229
+ await fs.chmod(filePath, 0o600);
230
+ } catch (error) {
231
+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {
232
+ throw error;
233
+ }
234
+ }
235
+ await fs.writeFile(tmpPath, contents, { encoding: "utf8", mode: 0o600 });
236
+ try {
237
+ await fs.chmod(tmpPath, 0o600);
238
+ } catch {
239
+ // Best-effort: the write itself already requested mode 0600; some
240
+ // filesystems (e.g. network mounts) reject explicit chmod.
241
+ }
132
242
  await fs.rename(tmpPath, filePath);
133
243
  }
134
244
 
@@ -145,12 +255,76 @@ function enqueueAtomicWrite(filePath: string, contents: string): Promise<void> {
145
255
  });
146
256
  }
147
257
 
258
+ // Phase 1.6 (design section 2.3): the persisted state file name is decoupled
259
+ // from teamName. TeamClaw is single-instance-single-team per state dir, so a
260
+ // fixed instance-scoped file name IS the instance identity - renaming a team
261
+ // no longer orphans the old `<teamName>-team-state.json` (the collision risk
262
+ // called out in the design). The legacy teamName-named file is still read as
263
+ // a one-time migration source; the next save writes the new name and the
264
+ // legacy file is simply never consulted again.
265
+ const TEAM_STATE_FILE = "team-state.json";
266
+
267
+ function teamStateFilePath(): string {
268
+ return path.join(STATE_DIR, TEAM_STATE_FILE);
269
+ }
270
+
271
+ function legacyTeamStateFilePath(teamName: string): string {
272
+ return path.join(STATE_DIR, `${teamName}-team-state.json`);
273
+ }
274
+
275
+ function isFileMissing(error: unknown): boolean {
276
+ return (error as NodeJS.ErrnoException)?.code === "ENOENT";
277
+ }
278
+
279
+ function errorMessage(error: unknown): string {
280
+ return error instanceof Error ? error.message : String(error);
281
+ }
282
+
148
283
  async function loadTeamState(teamName: string): Promise<TeamState | null> {
149
- const filePath = path.join(STATE_DIR, `${teamName}-team-state.json`);
284
+ // Review fix (Phase 1.6): the instance-scoped team-state.json is the
285
+ // primary state file, and when it EXISTS it is authoritative. A
286
+ // present-but-corrupt primary is a fatal error, never a silent fallback to
287
+ // the legacy snapshot - falling back would rewind the team to the
288
+ // pre-migration state and lose everything saved since. Only a MISSING
289
+ // primary (ENOENT) falls through to the one-time legacy read.
290
+ let primaryRaw: string | null = null;
150
291
  try {
151
- const raw = await fs.readFile(filePath, "utf8");
152
- const parsed = JSON.parse(raw);
153
- return migrateState(parsed);
292
+ primaryRaw = await fs.readFile(teamStateFilePath(), "utf8");
293
+ } catch (error) {
294
+ if (!isFileMissing(error)) {
295
+ throw new Error(
296
+ `TeamClaw cannot read the persisted team state ${teamStateFilePath()}: ${errorMessage(error)}`,
297
+ );
298
+ }
299
+ }
300
+
301
+ if (primaryRaw !== null) {
302
+ let parsed: unknown;
303
+ try {
304
+ parsed = JSON.parse(primaryRaw);
305
+ } catch (error) {
306
+ throw new Error(
307
+ `TeamClaw team state file ${teamStateFilePath()} is not valid JSON (${errorMessage(error)}). `
308
+ + "Refusing to start with a fresh team over a corrupt state file - fix or remove the file manually.",
309
+ );
310
+ }
311
+ const migrated = migrateState(parsed);
312
+ if (!migrated) {
313
+ throw new Error(
314
+ `TeamClaw team state file ${teamStateFilePath()} exists but is not a valid team state. `
315
+ + "Refusing to start with a fresh team over an unusable state file - fix or remove the file manually.",
316
+ );
317
+ }
318
+ return migrated;
319
+ }
320
+
321
+ // Primary absent: one-time legacy fallback (pre-Phase-1.6 file name).
322
+ // Lenient by design, matching the pre-Phase-1.6 single-file behavior: a
323
+ // missing or corrupt legacy file simply means first initialization, and a
324
+ // corrupt legacy file is never overwritten (saves go to the new name).
325
+ try {
326
+ const legacyRaw = await fs.readFile(legacyTeamStateFilePath(teamName), "utf8");
327
+ return migrateState(JSON.parse(legacyRaw));
154
328
  } catch {
155
329
  return null;
156
330
  }
@@ -158,7 +332,7 @@ async function loadTeamState(teamName: string): Promise<TeamState | null> {
158
332
 
159
333
  async function saveTeamState(state: TeamState): Promise<void> {
160
334
  await ensureDir(STATE_DIR);
161
- const filePath = path.join(STATE_DIR, `${state.teamName}-team-state.json`);
335
+ const filePath = teamStateFilePath();
162
336
  state.version = STATE_VERSION;
163
337
  state.updatedAt = Date.now();
164
338
  state.provisioning = state.provisioning && typeof state.provisioning === "object"
@@ -177,6 +351,145 @@ async function saveTeamState(state: TeamState): Promise<void> {
177
351
  await enqueueAtomicWrite(filePath, `${JSON.stringify(state, null, 2)}\n`);
178
352
  }
179
353
 
354
+ // ---------------------------------------------------------------------------
355
+ // Team profile switch archive (Phase 2.1, design section 2.3 step 3).
356
+ //
357
+ // Switching profiles seals the WHOLE previous TeamState (tasks,
358
+ // clarifications, messages, previews, repo, projects, controllerRuns,
359
+ // reports) into state-dir/archived/<profileId>-<timestamp>.json together with
360
+ // an embedded snapshot of the profile's roles - so an archived banking team
361
+ // keeps its original role vocabulary even after the profile package evolves
362
+ // (design 2.2: archive queries must not suffer terminology drift). v1 only
363
+ // lists archive metadata; the full payload stays queryable offline.
364
+ // ---------------------------------------------------------------------------
365
+
366
+ const ARCHIVED_TEAMS_DIR_NAME = "archived";
367
+ const ARCHIVE_FILE_RE = /^([a-z0-9-]+)-(\d+)(?:-([a-z0-9]+))?\.json$/;
368
+
369
+ /** Embedded profile snapshot stored alongside the archived team state. */
370
+ export type ArchivedTeamProfileSnapshot = {
371
+ id: string;
372
+ name: string;
373
+ nameZh?: string;
374
+ version: string;
375
+ roles: RoleDefinition[];
376
+ };
377
+
378
+ export type ArchivedTeamEnvelope = {
379
+ archivedAt: number;
380
+ profile: ArchivedTeamProfileSnapshot;
381
+ team: TeamState;
382
+ };
383
+
384
+ export type ArchivedTeamSummary = {
385
+ /** Archive file name (unique id for v1 metadata listing purposes). */
386
+ file: string;
387
+ profileId: string;
388
+ profileName: string;
389
+ teamName: string;
390
+ archivedAt: number;
391
+ taskCount: number;
392
+ };
393
+
394
+ function archivedTeamsDirPath(): string {
395
+ return path.join(STATE_DIR, ARCHIVED_TEAMS_DIR_NAME);
396
+ }
397
+
398
+ function parseArchiveFileName(name: string): { profileId: string; timestamp: number } | null {
399
+ const match = ARCHIVE_FILE_RE.exec(name);
400
+ if (!match) {
401
+ return null;
402
+ }
403
+ const timestamp = Number(match[2]);
404
+ return Number.isFinite(timestamp) ? { profileId: match[1]!, timestamp } : null;
405
+ }
406
+
407
+ /**
408
+ * Seal the given TeamState into the archive directory (design 2.3 step 3).
409
+ * Returns the archive file path. The write is atomic; the envelope embeds the
410
+ * profile snapshot so the archive is self-contained.
411
+ */
412
+ async function archiveTeamState(
413
+ state: TeamState,
414
+ profileSnapshot: ArchivedTeamProfileSnapshot,
415
+ ): Promise<string> {
416
+ const dir = archivedTeamsDirPath();
417
+ await ensureDir(dir);
418
+ // #251: a short random suffix disambiguates same-millisecond archives
419
+ // (two switches inside one ms would otherwise silently overwrite each
420
+ // other). Capture groups 1/2 keep their original semantics; group 3 is
421
+ // the optional suffix, so pre-#251 archive names still parse.
422
+ const suffix = Math.random().toString(36).slice(2, 8).padEnd(6, "0");
423
+ const fileName = `${state.profileId}-${Date.now()}-${suffix}.json`;
424
+ const filePath = path.join(dir, fileName);
425
+ const envelope: ArchivedTeamEnvelope = {
426
+ archivedAt: Date.now(),
427
+ profile: profileSnapshot,
428
+ team: state,
429
+ };
430
+ await enqueueAtomicWrite(filePath, `${JSON.stringify(envelope, null, 2)}\n`);
431
+ return filePath;
432
+ }
433
+
434
+ /** List archived teams (newest first). Unreadable entries are skipped. */
435
+ async function listArchivedTeams(): Promise<ArchivedTeamSummary[]> {
436
+ let files: string[];
437
+ try {
438
+ files = await fs.readdir(archivedTeamsDirPath());
439
+ } catch {
440
+ return [];
441
+ }
442
+ const summaries: ArchivedTeamSummary[] = [];
443
+ for (const name of files.sort().reverse()) {
444
+ if (!name.endsWith(".json") || !parseArchiveFileName(name)) {
445
+ continue;
446
+ }
447
+ try {
448
+ const raw = await fs.readFile(path.join(archivedTeamsDirPath(), name), "utf8");
449
+ const parsed = JSON.parse(raw) as ArchivedTeamEnvelope;
450
+ if (!parsed?.team || typeof parsed.team !== "object") {
451
+ continue;
452
+ }
453
+ summaries.push({
454
+ file: name,
455
+ profileId: parsed.profile?.id ?? parsed.team.profileId ?? "unknown",
456
+ profileName: parsed.profile?.name ?? "",
457
+ teamName: typeof parsed.team.teamName === "string" ? parsed.team.teamName : "",
458
+ archivedAt: typeof parsed.archivedAt === "number" ? parsed.archivedAt : 0,
459
+ taskCount: parsed.team.tasks && typeof parsed.team.tasks === "object"
460
+ ? Object.keys(parsed.team.tasks).length
461
+ : 0,
462
+ });
463
+ } catch {
464
+ // Skip unreadable/corrupt archive files - listing must never fail the API.
465
+ }
466
+ }
467
+ return summaries;
468
+ }
469
+
470
+ /**
471
+ * Crash-resume helper (design 2.3): find an archive file written for the
472
+ * given (source) profileId at or after `startedAt` - the persisted
473
+ * transition.startedAt. Existence of such a file means the switch already got
474
+ * past the archive step, so a restart must jump straight to building the new
475
+ * team instead of re-draining.
476
+ */
477
+ async function findTeamSwitchArchive(profileId: string, startedAt: number): Promise<string | null> {
478
+ let files: string[];
479
+ try {
480
+ files = await fs.readdir(archivedTeamsDirPath());
481
+ } catch {
482
+ return null;
483
+ }
484
+ for (const name of files.sort().reverse()) {
485
+ const parsed = parseArchiveFileName(name);
486
+ if (parsed && parsed.profileId === profileId && parsed.timestamp >= startedAt) {
487
+ return path.join(archivedTeamsDirPath(), name);
488
+ }
489
+ }
490
+ return null;
491
+ }
492
+
180
493
  async function loadWorkerIdentity(): Promise<WorkerIdentity | null> {
181
494
  const filePath = path.join(STATE_DIR, "worker-identity.json");
182
495
  try {
@@ -215,6 +528,9 @@ export {
215
528
  STATE_DIR,
216
529
  loadTeamState,
217
530
  saveTeamState,
531
+ archiveTeamState,
532
+ listArchivedTeams,
533
+ findTeamSwitchArchive,
218
534
  loadWorkerIdentity,
219
535
  saveWorkerIdentity,
220
536
  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") {
@@ -1,4 +1,5 @@
1
- import type { GithubAuthManager } from "../controller/github-auth.js";
1
+ // Issue #226 W5: cross-subsystem contract lives in the shared layer now.
2
+ import type { GithubAuthManager } from "../shared/github-auth.js";
2
3
 
3
4
  /**
4
5
  * Minimal GitHub REST client for TeamAuto: ETag-conditional GETs, light
@@ -232,6 +233,27 @@ export function createGithubClient(auth: GithubAuthManager) {
232
233
  return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };
233
234
  },
234
235
 
236
+ /**
237
+ * Worktree-GC delivery oracle (#173 follow-up 5): after a squash merge +
238
+ * branch deletion, ls-remote for the task branch is empty and the local
239
+ * rev-list own-count never drains (squash shas differ from the branch
240
+ * commits). True only on positive proof: a PR from this exact branch whose
241
+ * head tip is EXACTLY the given sha was merged. A closed-unmerged PR, a
242
+ * head-tip mismatch (worker committed after the push), or any API failure
243
+ * resolves false - the GC then retains the worktree (fails toward keep).
244
+ */
245
+ async prHeadDelivered(owner: string, repo: string, branch: string, headTip: string): Promise<boolean> {
246
+ const data = await getJson<unknown[]>(
247
+ `/repos/${owner}/${repo}/pulls?state=all&head=${encodeURIComponent(`${owner}:${branch}`)}`,
248
+ );
249
+ if (!Array.isArray(data) || data.length === 0) {
250
+ return false;
251
+ }
252
+ const pr = data[0] as Record<string, unknown>;
253
+ const headSha = String((pr.head as { sha?: string } | undefined)?.sha ?? "");
254
+ return Boolean(pr.merged) && headSha === headTip;
255
+ },
256
+
235
257
  /** Repos the logged-in user can select in the TeamAuto bind picker. */
236
258
  async listUserRepos(): Promise<{ id: string; fullName: string; private: boolean; pushedAt: string | null }[]> {
237
259
  const data = await getJson<unknown[]>("/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&per_page=100");