@teamclaws/teamclaw 2026.8.1 → 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 (125) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/src/config.js +33 -2
  3. package/dist/src/controller/clarification-routes.js +315 -0
  4. package/dist/src/controller/controller-intake.js +895 -0
  5. package/dist/src/controller/controller-planning.js +813 -0
  6. package/dist/src/controller/controller-runs.js +175 -0
  7. package/dist/src/controller/controller-service.js +271 -40
  8. package/dist/src/controller/controller-tools.js +11 -6
  9. package/dist/src/controller/http-server.js +256 -6004
  10. package/dist/src/controller/kickoff-orchestrator.js +32 -6
  11. package/dist/src/controller/message-delivery.js +28 -0
  12. package/dist/src/controller/message-routes.js +114 -0
  13. package/dist/src/controller/orchestration-manifest.js +6 -28
  14. package/dist/src/controller/preview-proxy.js +98 -0
  15. package/dist/src/controller/profile-switch.js +289 -0
  16. package/dist/src/controller/project-registry.js +294 -0
  17. package/dist/src/controller/prompt-injector.js +19 -9
  18. package/dist/src/controller/repo-routes.js +63 -0
  19. package/dist/src/controller/role-inference.js +231 -20
  20. package/dist/src/controller/route-table.js +1353 -0
  21. package/dist/src/controller/task-assignment.js +508 -0
  22. package/dist/src/controller/task-cleanup.js +258 -0
  23. package/dist/src/controller/task-execution.js +240 -0
  24. package/dist/src/controller/task-results.js +461 -0
  25. package/dist/src/controller/task-router.js +74 -4
  26. package/dist/src/controller/task-routes.js +703 -0
  27. package/dist/src/controller/teamauto-routes.js +124 -0
  28. package/dist/src/controller/ui-assets.js +68 -0
  29. package/dist/src/controller/worker-provisioning.js +30 -4
  30. package/dist/src/controller/worker-routes.js +188 -0
  31. package/dist/src/identity.js +3 -2
  32. package/dist/src/interaction-contracts.js +7 -7
  33. package/dist/src/openclaw-workspace.js +40 -18
  34. package/dist/src/profile-loader.js +486 -0
  35. package/dist/src/profiles/banking.json +178 -0
  36. package/dist/src/profiles/crossborder-ecom.json +253 -0
  37. package/dist/src/profiles/insurance.json +157 -0
  38. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  39. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  40. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  41. package/dist/src/profiles/schema.json +201 -0
  42. package/dist/src/profiles/securities.json +137 -0
  43. package/dist/src/profiles/software-rd.json +264 -0
  44. package/dist/src/profiles/trading-co.json +200 -0
  45. package/dist/src/prompt-policy.js +26 -13
  46. package/dist/src/role-ids.js +29 -0
  47. package/dist/src/roles.js +54 -13
  48. package/dist/src/session-roles.js +14 -0
  49. package/dist/src/state.js +188 -10
  50. package/dist/src/task-executor.js +7 -17
  51. package/dist/src/teamauto/github-client.js +18 -0
  52. package/dist/src/teamauto/repo-sync.js +228 -6
  53. package/dist/src/teamauto/scanner.js +40 -12
  54. package/dist/src/teamauto/scheduler.js +231 -12
  55. package/dist/src/types.js +62 -15
  56. package/dist/src/ui/app.js +592 -24
  57. package/dist/src/ui/index.html +44 -11
  58. package/dist/src/ui/style.css +194 -0
  59. package/dist/src/worker/prompt-injector.js +44 -8
  60. package/dist/src/worker/skill-installer.js +3 -1
  61. package/dist/src/worker/worker-service.js +76 -3
  62. package/openclaw.plugin.json +28 -1
  63. package/package.json +3 -2
  64. package/src/config.ts +33 -2
  65. package/src/controller/clarification-routes.ts +404 -0
  66. package/src/controller/controller-intake.ts +1113 -0
  67. package/src/controller/controller-planning.ts +1029 -0
  68. package/src/controller/controller-runs.ts +239 -0
  69. package/src/controller/controller-service.ts +295 -41
  70. package/src/controller/controller-tools.ts +11 -7
  71. package/src/controller/http-server.ts +294 -6971
  72. package/src/controller/kickoff-orchestrator.ts +70 -7
  73. package/src/controller/message-delivery.ts +49 -0
  74. package/src/controller/message-routes.ts +137 -0
  75. package/src/controller/orchestration-manifest.ts +6 -29
  76. package/src/controller/preview-proxy.ts +127 -0
  77. package/src/controller/profile-switch.ts +366 -0
  78. package/src/controller/project-registry.ts +361 -0
  79. package/src/controller/prompt-injector.ts +23 -8
  80. package/src/controller/repo-routes.ts +91 -0
  81. package/src/controller/role-inference.ts +260 -22
  82. package/src/controller/route-table.ts +1616 -0
  83. package/src/controller/task-assignment.ts +618 -0
  84. package/src/controller/task-cleanup.ts +344 -0
  85. package/src/controller/task-execution.ts +356 -0
  86. package/src/controller/task-results.ts +544 -0
  87. package/src/controller/task-router.ts +98 -6
  88. package/src/controller/task-routes.ts +812 -0
  89. package/src/controller/teamauto-routes.ts +121 -0
  90. package/src/controller/ui-assets.ts +70 -0
  91. package/src/controller/websocket.ts +13 -1
  92. package/src/controller/worker-provisioning.ts +32 -4
  93. package/src/controller/worker-routes.ts +241 -0
  94. package/src/identity.ts +3 -2
  95. package/src/interaction-contracts.ts +7 -7
  96. package/src/openclaw-workspace.ts +44 -18
  97. package/src/profile-loader.ts +650 -0
  98. package/src/profiles/banking.json +178 -0
  99. package/src/profiles/crossborder-ecom.json +253 -0
  100. package/src/profiles/insurance.json +157 -0
  101. package/src/profiles/knowledge/hs-structure.md +97 -0
  102. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  103. package/src/profiles/knowledge/vat-principles.md +85 -0
  104. package/src/profiles/schema.json +201 -0
  105. package/src/profiles/securities.json +137 -0
  106. package/src/profiles/software-rd.json +264 -0
  107. package/src/profiles/trading-co.json +200 -0
  108. package/src/prompt-policy.ts +27 -13
  109. package/src/role-ids.ts +31 -0
  110. package/src/roles.ts +60 -14
  111. package/src/session-roles.ts +14 -0
  112. package/src/state.ts +236 -9
  113. package/src/task-executor.ts +7 -18
  114. package/src/teamauto/github-client.ts +21 -0
  115. package/src/teamauto/repo-sync.ts +246 -6
  116. package/src/teamauto/scanner.ts +47 -13
  117. package/src/teamauto/scheduler.ts +259 -16
  118. package/src/teamauto/store.ts +12 -0
  119. package/src/types.ts +133 -16
  120. package/src/ui/app.js +592 -24
  121. package/src/ui/index.html +44 -11
  122. package/src/ui/style.css +194 -0
  123. package/src/worker/prompt-injector.ts +48 -8
  124. package/src/worker/skill-installer.ts +3 -1
  125. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,366 @@
1
+ // PR-A of issue #204 (http-server monolith split): the team profile switch
2
+ // state machine extracted verbatim from controller/http-server.ts. Zero
3
+ // behavior change - the POST /api/v1/team/profile route shell and the
4
+ // controller startup chain (controller-service.ts) call these functions with
5
+ // the same deps object as before. This module must NEVER import http-server
6
+ // (the reverse edge exists: http-server -> profile-switch); ws broadcasts,
7
+ // state persistence and provisioning all arrive through the deps slice below.
8
+ import type { PluginLogger } from "../../api.js";
9
+ import type {
10
+ PluginConfig,
11
+ TaskInfo,
12
+ TeamState,
13
+ } from "../types.js";
14
+ import { saveTeamState, archiveTeamState, findTeamSwitchArchive } from "../state.js";
15
+ import {
16
+ BUILTIN_PROFILES,
17
+ getActiveProfile,
18
+ hasProfile,
19
+ setActiveProfileId,
20
+ } from "../profile-loader.js";
21
+ import { ensureControllerGitRepo } from "../git-collaboration.js";
22
+ import type { TeamWebSocketServer } from "./websocket.js";
23
+ import type { WorkerProvisioningManager } from "./worker-provisioning.js";
24
+ import type { PreviewManager } from "./preview-manager.js";
25
+ import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
26
+
27
+ /**
28
+ * Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
29
+ * the fields the switch machine reads. http-server and controller-service
30
+ * keep passing their full ControllerHttpDeps object; TypeScript structural
31
+ * typing accepts it, so no call site changes beyond the import path.
32
+ */
33
+ export type TeamProfileSwitchDeps = {
34
+ config: PluginConfig;
35
+ logger: PluginLogger;
36
+ getTeamState: () => TeamState | null;
37
+ updateTeamState: (updater: (state: TeamState) => void) => TeamState;
38
+ wsServer: TeamWebSocketServer;
39
+ workerProvisioningManager?: WorkerProvisioningManager | null;
40
+ previewManager?: PreviewManager;
41
+ /** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
42
+ getTeamAutoScheduler?: () => TeamAutoScheduler | null;
43
+ };
44
+
45
+ // ===========================================================================
46
+ // Team profile switch (Phase 2.1, vertical-team-profiles-design.md 2.3).
47
+ //
48
+ // Six-step semantics of POST /api/v1/team/profile:
49
+ // 0. validate profileId + reject concurrent switches (409) [endpoint]
50
+ // 1. transition = { draining, target, startedAt }; persisted + WS event
51
+ // 2. graceful drain of in-flight tasks (timeout -> force-collect),
52
+ // terminate workers [drainTeam...]
53
+ // 3. archive the WHOLE TeamState + roles snapshot [state.ts]
54
+ // 4. fresh capability-conditioned TeamState for the target
55
+ // 5. warm the target profile's warmupRoles [provisioner]
56
+ // 6. clear transition, persist, broadcast team.switch_completed
57
+ // ===========================================================================
58
+
59
+ const SWITCH_DRAIN_POLL_INTERVAL_MS = 500;
60
+
61
+ function sleepForSwitchDrain(ms: number): Promise<void> {
62
+ return new Promise((resolve) => setTimeout(resolve, ms));
63
+ }
64
+
65
+ function taskInFlightForDrain(task: TaskInfo): boolean {
66
+ return Boolean(task.assignedWorkerId) && (task.status === "assigned" || task.status === "in_progress");
67
+ }
68
+
69
+ /**
70
+ * Design 2.3 step 2: graceful drain. Waits until no task is assigned /
71
+ * in-progress any more (in-flight workers report results through their
72
+ * normal endpoints, which stay open during the transition), then returns.
73
+ * On timeout the remaining in-flight tasks are force-collected (failed with
74
+ * an explicit error so the archive records the forced end) and all workers
75
+ * are marked offline. Managed workers are terminated by the caller through
76
+ * the provisioning manager's onWorkerRemoved (the terminateManagedWorker
77
+ * single point); external workers observe 409 heartbeats and back off.
78
+ */
79
+ async function drainTeamForProfileSwitch(
80
+ deps: TeamProfileSwitchDeps,
81
+ ): Promise<{ timedOut: boolean; forceCollected: string[] }> {
82
+ const { config, logger, getTeamState, updateTeamState } = deps;
83
+ const deadline = Date.now() + config.teamSwitchDrainTimeoutMs;
84
+ while (Date.now() < deadline) {
85
+ const state = getTeamState();
86
+ if (!state || !Object.values(state.tasks).some(taskInFlightForDrain)) {
87
+ return { timedOut: false, forceCollected: [] };
88
+ }
89
+ await sleepForSwitchDrain(SWITCH_DRAIN_POLL_INTERVAL_MS);
90
+ }
91
+
92
+ const forceCollected: string[] = [];
93
+ updateTeamState((state) => {
94
+ for (const task of Object.values(state.tasks)) {
95
+ if (taskInFlightForDrain(task)) {
96
+ task.status = "failed";
97
+ task.error = `team profile switch drain timeout (${config.teamSwitchDrainTimeoutMs}ms) - in-flight task force-collected into the team archive`;
98
+ task.updatedAt = Date.now();
99
+ forceCollected.push(task.id);
100
+ }
101
+ }
102
+ for (const worker of Object.values(state.workers)) {
103
+ worker.status = "offline";
104
+ worker.currentTaskId = undefined;
105
+ }
106
+ });
107
+ logger.warn(
108
+ `Controller: profile switch drain timed out after ${config.teamSwitchDrainTimeoutMs}ms - force-collected ${forceCollected.length} in-flight task(s)`,
109
+ );
110
+ return { timedOut: true, forceCollected };
111
+ }
112
+
113
+ export type TeamProfileSwitchOptions = {
114
+ /**
115
+ * Crash resume (design 2.3): the archive file for this switch already
116
+ * exists, so skip the drain+archive steps (2-3) and rebuild the new team
117
+ * directly (steps 4-6).
118
+ */
119
+ skipArchive?: boolean;
120
+ };
121
+
122
+ /**
123
+ * Run switch steps 2-6 (step 1 - setting and persisting the transition -
124
+ * belongs to the POST endpoint / crash resume). Exported so the controller
125
+ * startup chain can resume an interrupted switch with the same semantics.
126
+ */
127
+ export async function executeTeamProfileSwitch(
128
+ deps: TeamProfileSwitchDeps,
129
+ targetProfileId: string,
130
+ options: TeamProfileSwitchOptions = {},
131
+ ): Promise<void> {
132
+ const { config, logger, getTeamState, updateTeamState, wsServer, workerProvisioningManager } = deps;
133
+ const target = BUILTIN_PROFILES.get(targetProfileId);
134
+ if (!target) {
135
+ throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
136
+ }
137
+ const setPhase = (phase: "draining" | "archiving" | "warming"): void => {
138
+ updateTeamState((state) => {
139
+ if (state.transition?.targetProfileId === targetProfileId) {
140
+ state.transition.phase = phase;
141
+ }
142
+ });
143
+ };
144
+
145
+ if (!options.skipArchive) {
146
+ // Step 2: drain in-flight work, then stop every worker.
147
+ setPhase("draining");
148
+ workerProvisioningManager?.setReconcileSuspended(true);
149
+ const drain = await drainTeamForProfileSwitch(deps);
150
+ for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
151
+ if (workerProvisioningManager?.hasManagedWorker(workerId)) {
152
+ await workerProvisioningManager
153
+ .onWorkerRemoved(workerId, `team profile switch to "${targetProfileId}"`)
154
+ .catch((err) => logger.warn(`Controller: failed to terminate managed worker ${workerId} during profile switch: ${String(err)}`));
155
+ }
156
+ }
157
+ // Capability teardown for subsystems the target profile switches off
158
+ // (minimal Phase 2.3 preview; the full 404 short-circuit lands in 2.3).
159
+ // NOTE: teardown is one-directional at runtime. Switching a capability
160
+ // back ON does not (re)start its subsystem here - TeamAuto scheduling
161
+ // and preview restoration are wired at controller startup only, so an
162
+ // off -> on switch (e.g. minimal-bank -> software-rd) takes effect for
163
+ // those subsystems after the next gateway restart.
164
+ if (!target.capabilities.teamauto) {
165
+ const scheduler = deps.getTeamAutoScheduler?.() ?? null;
166
+ if (scheduler) {
167
+ try {
168
+ await scheduler.stop();
169
+ } catch { /* scheduler already stopped */ }
170
+ }
171
+ }
172
+ if (!target.capabilities.runnablePreview && deps.previewManager) {
173
+ try {
174
+ await deps.previewManager.stopAll();
175
+ } catch { /* previews already stopped */ }
176
+ }
177
+
178
+ // Step 3: archive the whole previous TeamState with a roles snapshot.
179
+ // The phase flip is persisted BEFORE the archive write so a crash between
180
+ // the two leaves an unambiguous "archive may exist" state for the resume
181
+ // path (file existence check).
182
+ setPhase("archiving");
183
+ const sourceState = getTeamState();
184
+ if (sourceState) {
185
+ await saveTeamState(sourceState);
186
+ const sourceProfile = getActiveProfile();
187
+ await archiveTeamState(sourceState, {
188
+ id: sourceProfile.id,
189
+ name: sourceProfile.name,
190
+ nameZh: sourceProfile.nameZh,
191
+ version: sourceProfile.version,
192
+ roles: sourceProfile.roles,
193
+ });
194
+ logger.info(
195
+ `Controller: archived team "${sourceState.teamName}" (profile ${sourceProfile.id}, `
196
+ + `${Object.keys(sourceState.tasks).length} task(s))${drain.timedOut ? " after drain timeout" : ""}`,
197
+ );
198
+ }
199
+ }
200
+
201
+ // Step 4: fresh TeamState for the target profile, conditioned on its
202
+ // capability switches (design 2.3: banking omits repo/previews/reports).
203
+ // setActiveProfileId and the state mutation below are both synchronous, so
204
+ // no request can observe the new state against the old profile.
205
+ const repoState = target.capabilities.git
206
+ ? await ensureControllerGitRepo(config, logger).catch((err) => {
207
+ logger.warn(`Controller: failed to prepare git collaboration repo for profile "${target.id}": ${err instanceof Error ? err.message : String(err)}`);
208
+ return null;
209
+ })
210
+ : null;
211
+ setActiveProfileId(target.id);
212
+ const newCreatedAt = Date.now();
213
+ updateTeamState((state) => {
214
+ state.profileId = target.id;
215
+ state.teamName = target.name;
216
+ state.workers = {};
217
+ state.tasks = {};
218
+ state.controllerRuns = {};
219
+ state.projects = {};
220
+ state.messages = [];
221
+ state.clarifications = {};
222
+ state.provisioning = { workers: {} };
223
+ if (target.capabilities.git && repoState) {
224
+ state.repo = repoState;
225
+ } else {
226
+ delete state.repo;
227
+ }
228
+ if (target.capabilities.runnablePreview) {
229
+ state.previews = {};
230
+ } else {
231
+ delete state.previews;
232
+ }
233
+ if (target.capabilities.deliveryReview) {
234
+ state.reports = {};
235
+ } else {
236
+ delete state.reports;
237
+ }
238
+ state.createdAt = newCreatedAt;
239
+ });
240
+ await saveTeamState(getTeamState()!);
241
+
242
+ // Step 5: warm the new profile's warmupRoles through the provisioning
243
+ // pipeline (launch dispatch; registration/readiness tracking continues in
244
+ // the background exactly like a cold start).
245
+ setPhase("warming");
246
+ await saveTeamState(getTeamState()!);
247
+ workerProvisioningManager?.setReconcileSuspended(false);
248
+ if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
249
+ await workerProvisioningManager
250
+ .warmRolesForTeamSwitch(target.warmupRoles, `profile switch warmup (${target.id})`)
251
+ .catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
252
+ }
253
+
254
+ // Step 6: settle - clear the transition, persist, announce.
255
+ updateTeamState((state) => {
256
+ delete state.transition;
257
+ });
258
+ await saveTeamState(getTeamState()!);
259
+ wsServer.broadcastUpdate({ type: "team.switch_completed", data: { profileId: target.id } });
260
+ logger.info(`Controller: team profile switch to "${target.id}" completed`);
261
+ }
262
+
263
+ /**
264
+ * Design 2.3 crash semantics: on controller startup, an unfinished persisted
265
+ * transition is resumed idempotently. If the archive file for this switch
266
+ * already exists AND the phase is at/after "archiving", jump straight to
267
+ * building the new team (skipArchive); otherwise re-run the drain from
268
+ * scratch (drain is idempotent - a completed drain simply finds no in-flight
269
+ * tasks). Returns true when a transition was resumed.
270
+ */
271
+ // No team.switch_failed broadcast on this path: startup resume runs before
272
+ // the HTTP/WS listeners exist, so there are no clients to receive it - a
273
+ // failed resume surfaces through the fatal startup path instead (#201 review
274
+ // note, recorded for external reviewers).
275
+ export async function resumeTeamProfileSwitch(deps: TeamProfileSwitchDeps): Promise<boolean> {
276
+ const state = deps.getTeamState();
277
+ const transition = state?.transition;
278
+ if (!state || !transition) {
279
+ return false;
280
+ }
281
+ if (!hasProfile(transition.targetProfileId)) {
282
+ // Same red line as restoring an unknown profileId (design 2.2): a team
283
+ // mid-switch to an unavailable profile must never silently land on a
284
+ // different profile.
285
+ throw new Error(
286
+ `Controller: interrupted team profile switch references profile "${transition.targetProfileId}", which is not available in this installation. `,
287
+ );
288
+ }
289
+ deps.logger.info(
290
+ `Controller: resuming interrupted team profile switch to "${transition.targetProfileId}" (phase: ${transition.phase}, started at ${new Date(transition.startedAt).toISOString()})`,
291
+ );
292
+ // A persisted state whose profileId already equals the target means step 4
293
+ // flipped the team identity onto the NEW team. Step 4 strictly follows the
294
+ // completed archive write in the same execution (the archive file lands
295
+ // atomically before step 4 runs), so that flip PROVES the archive exists.
296
+ // This covers both phase "warming" and the ghost-archive window between
297
+ // the step-4 flip reaching disk and the warming phase persisting - on disk
298
+ // that window reads as (phase "archiving", profileId = target), where
299
+ // looking up the SOURCE-named archive file with state.profileId would miss
300
+ // it and a re-drain would seal the already-emptied NEW team as a ghost
301
+ // archive entry. (Alternative considered: persisting a sourceProfileId on
302
+ // the transition - rejected; this flip predicate is the identical proof
303
+ // without transition-shape or migration churn, and it also degrades the
304
+ // manually-corrupted (draining, target) combination the same safe way.)
305
+ const step4Flipped = state.profileId === transition.targetProfileId;
306
+ const archiveExists = step4Flipped
307
+ || transition.phase === "warming"
308
+ || Boolean(await findTeamSwitchArchive(state.profileId, transition.startedAt));
309
+ const phaseAtOrAfterArchive = transition.phase === "archiving" || transition.phase === "warming";
310
+ await executeTeamProfileSwitch(deps, transition.targetProfileId, {
311
+ skipArchive: archiveExists && (phaseAtOrAfterArchive || step4Flipped),
312
+ });
313
+ return true;
314
+ }
315
+
316
+ /**
317
+ * Fire-and-forget switch execution launched by POST /api/v1/team/profile
318
+ * after step 1 (transition persisted + switch_started broadcast). Owns the
319
+ * failure path: worst-case archive-preservation detection, the
320
+ * team.switch_failed broadcast, and unwedging the transition.
321
+ */
322
+ export function startTeamProfileSwitch(
323
+ deps: TeamProfileSwitchDeps,
324
+ state: TeamState,
325
+ profileId: string,
326
+ previousProfileId: string,
327
+ ): void {
328
+ const { logger, wsServer, updateTeamState, getTeamState } = deps;
329
+ void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
330
+ const detail = err instanceof Error ? err.message : String(err);
331
+ logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
332
+ // Never leave the team wedged in a transition: clear it so whichever
333
+ // team the state now holds keeps serving and the switch can be
334
+ // re-issued. The archive (if step 3 ran) keeps the previous team. Also
335
+ // lift the provisioning reconcile suspension so the manager keeps
336
+ // operating for whichever team survived.
337
+ deps.workerProvisioningManager?.setReconcileSuspended(false);
338
+ // Honest worst case for the failure payload: once the step-3 archive
339
+ // write has landed (or step 4 already flipped the team identity - which
340
+ // strictly proves the archive landed), the state on disk may be
341
+ // partially switched and a restart is the reliable recovery. Detect
342
+ // with the same resume-path predicate: a source-named archive file at
343
+ // or after the transition's startedAt.
344
+ const transition = state.transition;
345
+ let archivePreserved = state.profileId === profileId;
346
+ if (!archivePreserved && transition) {
347
+ archivePreserved = Boolean(await findTeamSwitchArchive(previousProfileId, transition.startedAt).catch(() => null));
348
+ }
349
+ const reason = archivePreserved
350
+ ? `${detail} (archive preserved, team state may be partially switched, restart recommended)`
351
+ : detail;
352
+ // Broadcast BEFORE clearing the transition: the web switcher releases
353
+ // its loading/confirm state on this event instead of silently timing
354
+ // out on the reconcile fallback.
355
+ wsServer.broadcastUpdate({
356
+ type: "team.switch_failed",
357
+ data: { previousProfileId, targetProfileId: profileId, reason },
358
+ });
359
+ updateTeamState((s) => {
360
+ if (s.transition?.targetProfileId === profileId) {
361
+ delete s.transition;
362
+ }
363
+ });
364
+ void saveTeamState(getTeamState()!).catch(() => undefined);
365
+ });
366
+ }