@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
@@ -0,0 +1,289 @@
1
+ import { saveTeamState, archiveTeamState, findTeamSwitchArchive } from "../state.js";
2
+ import { BUILTIN_PROFILES, getActiveProfile, hasProfile, setActiveProfileId, } from "../profile-loader.js";
3
+ import { ensureControllerGitRepo } from "../git-collaboration.js";
4
+ // ===========================================================================
5
+ // Team profile switch (Phase 2.1, vertical-team-profiles-design.md 2.3).
6
+ //
7
+ // Six-step semantics of POST /api/v1/team/profile:
8
+ // 0. validate profileId + reject concurrent switches (409) [endpoint]
9
+ // 1. transition = { draining, target, startedAt }; persisted + WS event
10
+ // 2. graceful drain of in-flight tasks (timeout -> force-collect),
11
+ // terminate workers [drainTeam...]
12
+ // 3. archive the WHOLE TeamState + roles snapshot [state.ts]
13
+ // 4. fresh capability-conditioned TeamState for the target
14
+ // 5. warm the target profile's warmupRoles [provisioner]
15
+ // 6. clear transition, persist, broadcast team.switch_completed
16
+ // ===========================================================================
17
+ const SWITCH_DRAIN_POLL_INTERVAL_MS = 500;
18
+ function sleepForSwitchDrain(ms) {
19
+ return new Promise((resolve) => setTimeout(resolve, ms));
20
+ }
21
+ function taskInFlightForDrain(task) {
22
+ return Boolean(task.assignedWorkerId) && (task.status === "assigned" || task.status === "in_progress");
23
+ }
24
+ /**
25
+ * Design 2.3 step 2: graceful drain. Waits until no task is assigned /
26
+ * in-progress any more (in-flight workers report results through their
27
+ * normal endpoints, which stay open during the transition), then returns.
28
+ * On timeout the remaining in-flight tasks are force-collected (failed with
29
+ * an explicit error so the archive records the forced end) and all workers
30
+ * are marked offline. Managed workers are terminated by the caller through
31
+ * the provisioning manager's onWorkerRemoved (the terminateManagedWorker
32
+ * single point); external workers observe 409 heartbeats and back off.
33
+ */
34
+ async function drainTeamForProfileSwitch(deps) {
35
+ const { config, logger, getTeamState, updateTeamState } = deps;
36
+ const deadline = Date.now() + config.teamSwitchDrainTimeoutMs;
37
+ while (Date.now() < deadline) {
38
+ const state = getTeamState();
39
+ if (!state || !Object.values(state.tasks).some(taskInFlightForDrain)) {
40
+ return { timedOut: false, forceCollected: [] };
41
+ }
42
+ await sleepForSwitchDrain(SWITCH_DRAIN_POLL_INTERVAL_MS);
43
+ }
44
+ const forceCollected = [];
45
+ updateTeamState((state) => {
46
+ for (const task of Object.values(state.tasks)) {
47
+ if (taskInFlightForDrain(task)) {
48
+ task.status = "failed";
49
+ task.error = `team profile switch drain timeout (${config.teamSwitchDrainTimeoutMs}ms) - in-flight task force-collected into the team archive`;
50
+ task.updatedAt = Date.now();
51
+ forceCollected.push(task.id);
52
+ }
53
+ }
54
+ for (const worker of Object.values(state.workers)) {
55
+ worker.status = "offline";
56
+ worker.currentTaskId = undefined;
57
+ }
58
+ });
59
+ logger.warn(`Controller: profile switch drain timed out after ${config.teamSwitchDrainTimeoutMs}ms - force-collected ${forceCollected.length} in-flight task(s)`);
60
+ return { timedOut: true, forceCollected };
61
+ }
62
+ /**
63
+ * Run switch steps 2-6 (step 1 - setting and persisting the transition -
64
+ * belongs to the POST endpoint / crash resume). Exported so the controller
65
+ * startup chain can resume an interrupted switch with the same semantics.
66
+ */
67
+ export async function executeTeamProfileSwitch(deps, targetProfileId, options = {}) {
68
+ const { config, logger, getTeamState, updateTeamState, wsServer, workerProvisioningManager } = deps;
69
+ const target = BUILTIN_PROFILES.get(targetProfileId);
70
+ if (!target) {
71
+ throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
72
+ }
73
+ const setPhase = (phase) => {
74
+ updateTeamState((state) => {
75
+ if (state.transition?.targetProfileId === targetProfileId) {
76
+ state.transition.phase = phase;
77
+ }
78
+ });
79
+ };
80
+ if (!options.skipArchive) {
81
+ // Step 2: drain in-flight work, then stop every worker.
82
+ setPhase("draining");
83
+ workerProvisioningManager?.setReconcileSuspended(true);
84
+ const drain = await drainTeamForProfileSwitch(deps);
85
+ for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
86
+ if (workerProvisioningManager?.hasManagedWorker(workerId)) {
87
+ await workerProvisioningManager
88
+ .onWorkerRemoved(workerId, `team profile switch to "${targetProfileId}"`)
89
+ .catch((err) => logger.warn(`Controller: failed to terminate managed worker ${workerId} during profile switch: ${String(err)}`));
90
+ }
91
+ }
92
+ // Capability teardown for subsystems the target profile switches off
93
+ // (minimal Phase 2.3 preview; the full 404 short-circuit lands in 2.3).
94
+ // NOTE: teardown is one-directional at runtime. Switching a capability
95
+ // back ON does not (re)start its subsystem here - TeamAuto scheduling
96
+ // and preview restoration are wired at controller startup only, so an
97
+ // off -> on switch (e.g. minimal-bank -> software-rd) takes effect for
98
+ // those subsystems after the next gateway restart.
99
+ if (!target.capabilities.teamauto) {
100
+ const scheduler = deps.getTeamAutoScheduler?.() ?? null;
101
+ if (scheduler) {
102
+ try {
103
+ await scheduler.stop();
104
+ }
105
+ catch { /* scheduler already stopped */ }
106
+ }
107
+ }
108
+ if (!target.capabilities.runnablePreview && deps.previewManager) {
109
+ try {
110
+ await deps.previewManager.stopAll();
111
+ }
112
+ catch { /* previews already stopped */ }
113
+ }
114
+ // Step 3: archive the whole previous TeamState with a roles snapshot.
115
+ // The phase flip is persisted BEFORE the archive write so a crash between
116
+ // the two leaves an unambiguous "archive may exist" state for the resume
117
+ // path (file existence check).
118
+ setPhase("archiving");
119
+ const sourceState = getTeamState();
120
+ if (sourceState) {
121
+ await saveTeamState(sourceState);
122
+ const sourceProfile = getActiveProfile();
123
+ await archiveTeamState(sourceState, {
124
+ id: sourceProfile.id,
125
+ name: sourceProfile.name,
126
+ nameZh: sourceProfile.nameZh,
127
+ version: sourceProfile.version,
128
+ roles: sourceProfile.roles,
129
+ });
130
+ logger.info(`Controller: archived team "${sourceState.teamName}" (profile ${sourceProfile.id}, `
131
+ + `${Object.keys(sourceState.tasks).length} task(s))${drain.timedOut ? " after drain timeout" : ""}`);
132
+ }
133
+ }
134
+ // Step 4: fresh TeamState for the target profile, conditioned on its
135
+ // capability switches (design 2.3: banking omits repo/previews/reports).
136
+ // setActiveProfileId and the state mutation below are both synchronous, so
137
+ // no request can observe the new state against the old profile.
138
+ const repoState = target.capabilities.git
139
+ ? await ensureControllerGitRepo(config, logger).catch((err) => {
140
+ logger.warn(`Controller: failed to prepare git collaboration repo for profile "${target.id}": ${err instanceof Error ? err.message : String(err)}`);
141
+ return null;
142
+ })
143
+ : null;
144
+ setActiveProfileId(target.id);
145
+ const newCreatedAt = Date.now();
146
+ updateTeamState((state) => {
147
+ state.profileId = target.id;
148
+ state.teamName = target.name;
149
+ state.workers = {};
150
+ state.tasks = {};
151
+ state.controllerRuns = {};
152
+ state.projects = {};
153
+ state.messages = [];
154
+ state.clarifications = {};
155
+ state.provisioning = { workers: {} };
156
+ if (target.capabilities.git && repoState) {
157
+ state.repo = repoState;
158
+ }
159
+ else {
160
+ delete state.repo;
161
+ }
162
+ if (target.capabilities.runnablePreview) {
163
+ state.previews = {};
164
+ }
165
+ else {
166
+ delete state.previews;
167
+ }
168
+ if (target.capabilities.deliveryReview) {
169
+ state.reports = {};
170
+ }
171
+ else {
172
+ delete state.reports;
173
+ }
174
+ state.createdAt = newCreatedAt;
175
+ });
176
+ await saveTeamState(getTeamState());
177
+ // Step 5: warm the new profile's warmupRoles through the provisioning
178
+ // pipeline (launch dispatch; registration/readiness tracking continues in
179
+ // the background exactly like a cold start).
180
+ setPhase("warming");
181
+ await saveTeamState(getTeamState());
182
+ workerProvisioningManager?.setReconcileSuspended(false);
183
+ if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
184
+ await workerProvisioningManager
185
+ .warmRolesForTeamSwitch(target.warmupRoles, `profile switch warmup (${target.id})`)
186
+ .catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
187
+ }
188
+ // Step 6: settle - clear the transition, persist, announce.
189
+ updateTeamState((state) => {
190
+ delete state.transition;
191
+ });
192
+ await saveTeamState(getTeamState());
193
+ wsServer.broadcastUpdate({ type: "team.switch_completed", data: { profileId: target.id } });
194
+ logger.info(`Controller: team profile switch to "${target.id}" completed`);
195
+ }
196
+ /**
197
+ * Design 2.3 crash semantics: on controller startup, an unfinished persisted
198
+ * transition is resumed idempotently. If the archive file for this switch
199
+ * already exists AND the phase is at/after "archiving", jump straight to
200
+ * building the new team (skipArchive); otherwise re-run the drain from
201
+ * scratch (drain is idempotent - a completed drain simply finds no in-flight
202
+ * tasks). Returns true when a transition was resumed.
203
+ */
204
+ // No team.switch_failed broadcast on this path: startup resume runs before
205
+ // the HTTP/WS listeners exist, so there are no clients to receive it - a
206
+ // failed resume surfaces through the fatal startup path instead (#201 review
207
+ // note, recorded for external reviewers).
208
+ export async function resumeTeamProfileSwitch(deps) {
209
+ const state = deps.getTeamState();
210
+ const transition = state?.transition;
211
+ if (!state || !transition) {
212
+ return false;
213
+ }
214
+ if (!hasProfile(transition.targetProfileId)) {
215
+ // Same red line as restoring an unknown profileId (design 2.2): a team
216
+ // mid-switch to an unavailable profile must never silently land on a
217
+ // different profile.
218
+ throw new Error(`Controller: interrupted team profile switch references profile "${transition.targetProfileId}", which is not available in this installation. `);
219
+ }
220
+ deps.logger.info(`Controller: resuming interrupted team profile switch to "${transition.targetProfileId}" (phase: ${transition.phase}, started at ${new Date(transition.startedAt).toISOString()})`);
221
+ // A persisted state whose profileId already equals the target means step 4
222
+ // flipped the team identity onto the NEW team. Step 4 strictly follows the
223
+ // completed archive write in the same execution (the archive file lands
224
+ // atomically before step 4 runs), so that flip PROVES the archive exists.
225
+ // This covers both phase "warming" and the ghost-archive window between
226
+ // the step-4 flip reaching disk and the warming phase persisting - on disk
227
+ // that window reads as (phase "archiving", profileId = target), where
228
+ // looking up the SOURCE-named archive file with state.profileId would miss
229
+ // it and a re-drain would seal the already-emptied NEW team as a ghost
230
+ // archive entry. (Alternative considered: persisting a sourceProfileId on
231
+ // the transition - rejected; this flip predicate is the identical proof
232
+ // without transition-shape or migration churn, and it also degrades the
233
+ // manually-corrupted (draining, target) combination the same safe way.)
234
+ const step4Flipped = state.profileId === transition.targetProfileId;
235
+ const archiveExists = step4Flipped
236
+ || transition.phase === "warming"
237
+ || Boolean(await findTeamSwitchArchive(state.profileId, transition.startedAt));
238
+ const phaseAtOrAfterArchive = transition.phase === "archiving" || transition.phase === "warming";
239
+ await executeTeamProfileSwitch(deps, transition.targetProfileId, {
240
+ skipArchive: archiveExists && (phaseAtOrAfterArchive || step4Flipped),
241
+ });
242
+ return true;
243
+ }
244
+ /**
245
+ * Fire-and-forget switch execution launched by POST /api/v1/team/profile
246
+ * after step 1 (transition persisted + switch_started broadcast). Owns the
247
+ * failure path: worst-case archive-preservation detection, the
248
+ * team.switch_failed broadcast, and unwedging the transition.
249
+ */
250
+ export function startTeamProfileSwitch(deps, state, profileId, previousProfileId) {
251
+ const { logger, wsServer, updateTeamState, getTeamState } = deps;
252
+ void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
253
+ const detail = err instanceof Error ? err.message : String(err);
254
+ logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
255
+ // Never leave the team wedged in a transition: clear it so whichever
256
+ // team the state now holds keeps serving and the switch can be
257
+ // re-issued. The archive (if step 3 ran) keeps the previous team. Also
258
+ // lift the provisioning reconcile suspension so the manager keeps
259
+ // operating for whichever team survived.
260
+ deps.workerProvisioningManager?.setReconcileSuspended(false);
261
+ // Honest worst case for the failure payload: once the step-3 archive
262
+ // write has landed (or step 4 already flipped the team identity - which
263
+ // strictly proves the archive landed), the state on disk may be
264
+ // partially switched and a restart is the reliable recovery. Detect
265
+ // with the same resume-path predicate: a source-named archive file at
266
+ // or after the transition's startedAt.
267
+ const transition = state.transition;
268
+ let archivePreserved = state.profileId === profileId;
269
+ if (!archivePreserved && transition) {
270
+ archivePreserved = Boolean(await findTeamSwitchArchive(previousProfileId, transition.startedAt).catch(() => null));
271
+ }
272
+ const reason = archivePreserved
273
+ ? `${detail} (archive preserved, team state may be partially switched, restart recommended)`
274
+ : detail;
275
+ // Broadcast BEFORE clearing the transition: the web switcher releases
276
+ // its loading/confirm state on this event instead of silently timing
277
+ // out on the reconcile fallback.
278
+ wsServer.broadcastUpdate({
279
+ type: "team.switch_failed",
280
+ data: { previousProfileId, targetProfileId: profileId, reason },
281
+ });
282
+ updateTeamState((s) => {
283
+ if (s.transition?.targetProfileId === profileId) {
284
+ delete s.transition;
285
+ }
286
+ });
287
+ void saveTeamState(getTeamState()).catch(() => undefined);
288
+ });
289
+ }
@@ -0,0 +1,294 @@
1
+ import { deriveStableProjectKey } from "../openclaw-workspace.js";
2
+ import { normalizeControllerIntakeSessionKey } from "./task-execution.js";
3
+ const EXISTING_PROJECT_REUSE_HINT_RE = /\b(existing|optimi(?:s|z)e|optimi(?:s|z)ation|improvement|enhanc(?:e|ement)|follow[- ]?up|extend|update|bugfix|bug fix)\b/iu;
4
+ const GENERIC_PROJECT_FOLLOW_UP_RE = /\b(continue|continuing|next step|what else|what's next|follow[- ]?up|more|remaining)\b|继续|接下来|下一步|还有哪些|还可以做什么/u;
5
+ const PROJECT_MATCH_STOPWORDS = new Set([
6
+ "a",
7
+ "an",
8
+ "and",
9
+ "app",
10
+ "application",
11
+ "build",
12
+ "complete",
13
+ "existing",
14
+ "follow",
15
+ "for",
16
+ "hub",
17
+ "improvement",
18
+ "improvements",
19
+ "internal",
20
+ "optimization",
21
+ "product",
22
+ "project",
23
+ "requirement",
24
+ "request",
25
+ "studio",
26
+ "system",
27
+ "the",
28
+ "this",
29
+ "up",
30
+ "update",
31
+ "web",
32
+ ]);
33
+ export function resolveExistingProjectIdentityFromMessage(message, state) {
34
+ const normalizedMessage = normalizeProjectMatchingText(message);
35
+ if (!normalizedMessage) {
36
+ return undefined;
37
+ }
38
+ const explicitAlias = normalizeProjectMatchingText(extractExplicitProjectNameHint(message) ?? "");
39
+ let best = null;
40
+ const candidates = collectExistingProjectCandidates(state);
41
+ for (const candidate of candidates) {
42
+ const normalizedAliases = Array.from(candidate.aliases)
43
+ .map((alias) => normalizeProjectMatchingText(alias))
44
+ .filter(Boolean)
45
+ .reduce((acc, alias) => {
46
+ acc.push(alias);
47
+ return acc;
48
+ }, []);
49
+ const hasExplicitAliasMatch = explicitAlias
50
+ ? normalizedAliases.some((alias) => alias.includes(explicitAlias) || explicitAlias.includes(alias))
51
+ : false;
52
+ if (explicitAlias && !hasExplicitAliasMatch) {
53
+ continue;
54
+ }
55
+ const aliasScore = normalizedAliases
56
+ .reduce((score, alias) => {
57
+ if (!alias) {
58
+ return score;
59
+ }
60
+ return normalizedMessage.includes(alias)
61
+ ? Math.max(score, alias.split(" ").length + 10)
62
+ : score;
63
+ }, 0);
64
+ const tokenScore = scoreProjectTokenOverlap(normalizedMessage, candidate.searchText);
65
+ const totalScore = Math.max(aliasScore, tokenScore);
66
+ if (totalScore < 2) {
67
+ continue;
68
+ }
69
+ if (!best || totalScore > best.score || (totalScore === best.score && candidate.updatedAt > best.updatedAt)) {
70
+ best = {
71
+ projectId: candidate.projectId,
72
+ projectDir: candidate.projectDir,
73
+ score: totalScore,
74
+ updatedAt: candidate.updatedAt,
75
+ };
76
+ }
77
+ }
78
+ if (best) {
79
+ return { projectId: best.projectId, projectDir: best.projectDir };
80
+ }
81
+ if ((EXISTING_PROJECT_REUSE_HINT_RE.test(message) || GENERIC_PROJECT_FOLLOW_UP_RE.test(message)) && candidates.length === 1) {
82
+ return {
83
+ projectId: candidates[0]?.projectId,
84
+ projectDir: candidates[0]?.projectDir,
85
+ };
86
+ }
87
+ return undefined;
88
+ }
89
+ export function collectExistingProjectCandidates(state) {
90
+ const byProjectDir = new Map();
91
+ const addCandidate = (projectDir, text, updatedAt, alias, projectId) => {
92
+ if (!projectDir) {
93
+ return;
94
+ }
95
+ const entry = byProjectDir.get(projectDir) ?? { projectId, aliases: new Set(), texts: [], updatedAt: 0 };
96
+ if (!entry.projectId && projectId) {
97
+ entry.projectId = projectId;
98
+ }
99
+ if (text && text.trim()) {
100
+ entry.texts.push(text);
101
+ }
102
+ if (alias && alias.trim()) {
103
+ entry.aliases.add(alias.trim());
104
+ }
105
+ entry.updatedAt = Math.max(entry.updatedAt, updatedAt);
106
+ byProjectDir.set(projectDir, entry);
107
+ };
108
+ for (const project of Object.values(state?.projects ?? {})) {
109
+ addCandidate(project.projectDir, project.summary, project.updatedAt, project.id, project.id);
110
+ for (const alias of project.aliases ?? []) {
111
+ addCandidate(project.projectDir, alias, project.updatedAt, alias, project.id);
112
+ }
113
+ }
114
+ for (const run of Object.values(state?.controllerRuns ?? {})) {
115
+ addCandidate(run.projectDir, run.request, run.updatedAt, extractProjectAliasFromText(run.request), run.projectId);
116
+ addCandidate(run.projectDir, run.title, run.updatedAt, extractProjectAliasFromText(run.title), run.projectId);
117
+ addCandidate(run.projectDir, run.manifest?.projectName, run.updatedAt, run.manifest?.projectName, run.projectId);
118
+ }
119
+ for (const task of Object.values(state?.tasks ?? {})) {
120
+ addCandidate(task.projectDir, task.title, task.updatedAt, extractProjectAliasFromText(task.title), task.projectId);
121
+ addCandidate(task.projectDir, task.description, task.updatedAt, extractProjectAliasFromText(task.description), task.projectId);
122
+ addCandidate(task.projectDir, task.resultContract?.summary, task.updatedAt, null, task.projectId);
123
+ }
124
+ return Array.from(byProjectDir.entries()).map(([projectDir, entry]) => ({
125
+ projectId: entry.projectId,
126
+ projectDir,
127
+ aliases: entry.aliases,
128
+ searchText: entry.texts.join("\n"),
129
+ updatedAt: entry.updatedAt,
130
+ }));
131
+ }
132
+ export function extractExplicitProjectNameHint(text) {
133
+ const value = String(text ?? "");
134
+ const namedMatch = value.match(/(?:品牌|brand|project\s*name|产品名|名字)\s*[::]?\s*[`"'“”]?([a-z][a-z0-9_-]{1,39})[`"'“”]?/iu);
135
+ if (namedMatch?.[1]) {
136
+ return deriveStableProjectKey(namedMatch[1]);
137
+ }
138
+ const inlineNames = Array.from(value.matchAll(/`([a-z][a-z0-9_-]{1,39})`/giu))
139
+ .map((match) => deriveStableProjectKey(match[1]))
140
+ .filter(Boolean);
141
+ return inlineNames.length === 1 ? inlineNames[0] : undefined;
142
+ }
143
+ export function findProjectRecordByDir(state, projectDir) {
144
+ if (!state || !projectDir) {
145
+ return undefined;
146
+ }
147
+ return Object.values(state.projects ?? {}).find((project) => project.projectDir === projectDir);
148
+ }
149
+ export function syncProjectRegistryEntry(state, input) {
150
+ state.projects = state.projects && typeof state.projects === "object" ? state.projects : {};
151
+ let normalizedProjectId = deriveStableProjectKey(input.projectId ?? "");
152
+ let existing = normalizedProjectId ? state.projects[normalizedProjectId] : undefined;
153
+ const byDir = findProjectRecordByDir(state, input.projectDir);
154
+ if (!existing && byDir) {
155
+ existing = byDir;
156
+ }
157
+ if (!existing && input.projectDir) {
158
+ normalizedProjectId = normalizedProjectId || deriveStableProjectKey(input.projectDir);
159
+ if (normalizedProjectId) {
160
+ existing = {
161
+ id: normalizedProjectId,
162
+ projectDir: input.projectDir,
163
+ aliases: [],
164
+ createdAt: input.updatedAt,
165
+ updatedAt: input.updatedAt,
166
+ lastUsedAt: input.updatedAt,
167
+ };
168
+ state.projects[normalizedProjectId] = existing;
169
+ }
170
+ }
171
+ if (!existing) {
172
+ return { projectId: normalizedProjectId || undefined, projectDir: input.projectDir };
173
+ }
174
+ if (normalizedProjectId && existing.id !== normalizedProjectId && !state.projects[normalizedProjectId]) {
175
+ delete state.projects[existing.id];
176
+ existing.id = normalizedProjectId;
177
+ state.projects[normalizedProjectId] = existing;
178
+ }
179
+ if (!existing.projectDir && input.projectDir) {
180
+ existing.projectDir = input.projectDir;
181
+ }
182
+ const aliasSet = new Set(existing.aliases ?? []);
183
+ aliasSet.add(existing.id);
184
+ if (existing.projectDir) {
185
+ aliasSet.add(existing.projectDir);
186
+ }
187
+ for (const alias of input.aliases ?? []) {
188
+ const normalizedAlias = deriveStableProjectKey(String(alias ?? ""));
189
+ if (normalizedAlias) {
190
+ aliasSet.add(normalizedAlias);
191
+ }
192
+ }
193
+ existing.aliases = Array.from(aliasSet);
194
+ existing.summary = input.summary || existing.summary;
195
+ existing.updatedAt = Math.max(existing.updatedAt || 0, input.updatedAt);
196
+ existing.lastUsedAt = Math.max(existing.lastUsedAt || 0, input.updatedAt);
197
+ return { projectId: existing.id, projectDir: existing.projectDir };
198
+ }
199
+ export function resolveProjectIdentityForSession(sessionKey, state) {
200
+ const runId = findLatestControllerRunIdForSession(sessionKey, state, { preferActive: true });
201
+ if (!runId) {
202
+ return undefined;
203
+ }
204
+ const run = state?.controllerRuns[runId];
205
+ if (!run) {
206
+ return undefined;
207
+ }
208
+ const project = findProjectRecordByDir(state, run.projectDir);
209
+ return {
210
+ projectId: run.projectId ?? project?.id,
211
+ projectDir: run.projectDir ?? project?.projectDir,
212
+ };
213
+ }
214
+ export function resolveProjectIdentityForTaskId(taskId, state) {
215
+ const task = state?.tasks?.[taskId];
216
+ if (!task) {
217
+ return undefined;
218
+ }
219
+ const project = findProjectRecordByDir(state, task.projectDir);
220
+ return {
221
+ projectId: task.projectId ?? project?.id,
222
+ projectDir: task.projectDir ?? project?.projectDir,
223
+ };
224
+ }
225
+ export function extractProjectAliasFromText(text) {
226
+ const firstMeaningfulLine = String(text ?? "")
227
+ .split(/\n+/u)
228
+ .map((line) => line.replace(/^#+\s*/u, "").trim())
229
+ .find(Boolean);
230
+ if (!firstMeaningfulLine) {
231
+ return null;
232
+ }
233
+ const normalized = firstMeaningfulLine
234
+ .replace(/^(product|optimization)\s+requirement[::]\s*/iu, "")
235
+ .replace(/^implement\s+/iu, "")
236
+ .replace(/^design\s+/iu, "")
237
+ .replace(/^enhance\s+/iu, "")
238
+ .replace(/^qa[:\s-]+/iu, "")
239
+ .replace(/\s+(architecture|application|web app|workflows?|improvements?)$/iu, "")
240
+ .trim();
241
+ if (normalized.length < 4 || normalized.length > 80) {
242
+ return null;
243
+ }
244
+ return normalized;
245
+ }
246
+ export function normalizeProjectMatchingText(text) {
247
+ return text
248
+ .toLowerCase()
249
+ .replace(/[`*_#:[\]()/\\-]+/gu, " ")
250
+ .replace(/\s+/gu, " ")
251
+ .trim();
252
+ }
253
+ export function scoreProjectTokenOverlap(message, candidateText) {
254
+ const messageTokens = tokenizeProjectMatchingText(message);
255
+ if (messageTokens.size === 0) {
256
+ return 0;
257
+ }
258
+ const candidateTokens = tokenizeProjectMatchingText(candidateText);
259
+ let overlap = 0;
260
+ for (const token of candidateTokens) {
261
+ if (messageTokens.has(token)) {
262
+ overlap += 1;
263
+ }
264
+ }
265
+ return overlap;
266
+ }
267
+ export function tokenizeProjectMatchingText(text) {
268
+ return new Set(normalizeProjectMatchingText(text)
269
+ .split(" ")
270
+ .map((token) => token.trim())
271
+ .filter((token) => token.length >= 4 && !PROJECT_MATCH_STOPWORDS.has(token)));
272
+ }
273
+ export function isActiveControllerRun(run) {
274
+ return run.status === "pending" || run.status === "running";
275
+ }
276
+ export function findLatestControllerRunIdForSession(sessionKey, state, options) {
277
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
278
+ const matchingRuns = Object.values(state?.controllerRuns ?? {})
279
+ .filter((run) => normalizeControllerIntakeSessionKey(run.sessionKey) === normalizedSessionKey)
280
+ .sort((left, right) => {
281
+ if (options?.preferActive) {
282
+ const leftScore = isActiveControllerRun(left) ? 1 : 0;
283
+ const rightScore = isActiveControllerRun(right) ? 1 : 0;
284
+ if (leftScore !== rightScore) {
285
+ return rightScore - leftScore;
286
+ }
287
+ }
288
+ return right.updatedAt - left.updatedAt;
289
+ });
290
+ return matchingRuns[0]?.id ?? null;
291
+ }
292
+ export function resolveProjectDirForSession(sessionKey, state) {
293
+ return resolveProjectIdentityForSession(sessionKey, state)?.projectDir;
294
+ }