claude-flow 3.77.1 → 3.77.2

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 (43) hide show
  1. package/.claude/helpers/hook-handler.cjs +85 -5
  2. package/README.md +12 -2
  3. package/node_modules/@claude-flow/plugin-agent-federation/README.md +18 -0
  4. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.d.ts +4 -1
  5. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.d.ts.map +1 -1
  6. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js +11 -0
  7. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js.map +1 -1
  8. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.d.ts +29 -0
  9. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.d.ts.map +1 -0
  10. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.js +96 -0
  11. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.js.map +1 -0
  12. package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.d.ts.map +1 -1
  13. package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.js +3 -0
  14. package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.js.map +1 -1
  15. package/package.json +8 -5
  16. package/v3/@claude-flow/cli/README.md +5 -0
  17. package/v3/@claude-flow/cli/bin/cli.js +8 -3
  18. package/v3/@claude-flow/cli/dist/src/commands/init.js +8 -1
  19. package/v3/@claude-flow/cli/dist/src/commands/session.js +2 -1
  20. package/v3/@claude-flow/cli/dist/src/commands/workflow.js +2 -1
  21. package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +85 -5
  22. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.js +26 -25
  23. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +161 -157
  24. package/v3/@claude-flow/cli/dist/src/mcp-tools/claims-tools.js +257 -258
  25. package/v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.js +48 -29
  26. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +6 -0
  27. package/v3/@claude-flow/cli/dist/src/mcp-tools/locked-json-store.d.ts +20 -0
  28. package/v3/@claude-flow/cli/dist/src/mcp-tools/locked-json-store.js +99 -0
  29. package/v3/@claude-flow/cli/dist/src/mcp-tools/managed-agent-tools.js +51 -7
  30. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +19 -9
  31. package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.js +299 -270
  32. package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.js +245 -215
  33. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +5 -4
  34. package/v3/@claude-flow/cli/dist/src/missions/schemas.d.ts +38 -38
  35. package/v3/@claude-flow/cli/dist/src/mods/command-registry/schema.d.ts +210 -210
  36. package/v3/@claude-flow/cli/dist/src/services/managed-run-store.d.ts +11 -0
  37. package/v3/@claude-flow/cli/dist/src/services/managed-run-store.js +125 -3
  38. package/v3/@claude-flow/cli/dist/src/services/policy-runtime.d.ts +3 -0
  39. package/v3/@claude-flow/cli/dist/src/services/policy-runtime.js +3 -1
  40. package/v3/@claude-flow/cli/package.json +9 -6
  41. package/v3/@claude-flow/guidance/package.json +1 -0
  42. package/.claude/.proven-config-version +0 -1
  43. package/.claude/proven-config.json +0 -42
@@ -9,8 +9,8 @@
9
9
  import { getProjectCwd } from './types.js';
10
10
  import { readClaimsStore } from '../services/claims-store.js';
11
11
  import { validateIdentifier, validateText } from './validate-input.js';
12
+ import { saved, unchanged, updateJsonStore } from './locked-json-store.js';
12
13
  // File-based persistence
13
- import { existsSync, writeFileSync, mkdirSync } from 'fs';
14
14
  import { resolve } from 'path';
15
15
  const CLAIMS_DIR = '.claude-flow/claims';
16
16
  const CLAIMS_FILE = 'claims.json';
@@ -18,18 +18,13 @@ const DEFAULT_MAX_CLAIMS = 5;
18
18
  function getClaimsPath() {
19
19
  return resolve(getProjectCwd(), CLAIMS_DIR, CLAIMS_FILE);
20
20
  }
21
- function ensureClaimsDir() {
22
- const dir = resolve(getProjectCwd(), CLAIMS_DIR);
23
- if (!existsSync(dir)) {
24
- mkdirSync(dir, { recursive: true });
25
- }
26
- }
27
21
  function loadClaims() {
28
22
  return readClaimsStore(getClaimsPath());
29
23
  }
30
- function saveClaims(store) {
31
- ensureClaimsDir();
32
- writeFileSync(getClaimsPath(), JSON.stringify(store, null, 2), 'utf-8');
24
+ /** Every write goes through here: the check and the change run under the
25
+ * claims lock, so two processes cannot both win the same issue. */
26
+ function updateClaims(mutate) {
27
+ return updateJsonStore(getClaimsPath(), loadClaims, mutate, 'claims');
33
28
  }
34
29
  function formatClaimant(claimant) {
35
30
  return claimant.type === 'human'
@@ -104,34 +99,34 @@ export const claimsTools = [
104
99
  if (!claimant) {
105
100
  return { success: false, error: 'Invalid claimant format. Use "human:userId:name" or "agent:agentId:agentType"' };
106
101
  }
107
- const store = loadClaims();
108
- // Check if already claimed
109
- if (store.claims[issueId]) {
110
- const existing = store.claims[issueId];
111
- return {
112
- success: false,
113
- error: `Issue already claimed by ${formatClaimant(existing.claimant)}`,
114
- existingClaim: existing,
102
+ return updateClaims((store) => {
103
+ // Check if already claimed
104
+ if (store.claims[issueId]) {
105
+ const existing = store.claims[issueId];
106
+ return unchanged({
107
+ success: false,
108
+ error: `Issue already claimed by ${formatClaimant(existing.claimant)}`,
109
+ existingClaim: existing,
110
+ });
111
+ }
112
+ const now = new Date().toISOString();
113
+ const claim = {
114
+ issueId,
115
+ claimant,
116
+ claimedAt: now,
117
+ status: 'active',
118
+ statusChangedAt: now,
119
+ progress: 0,
120
+ context,
121
+ expiresAt: ttlMs !== undefined ? new Date(Date.now() + ttlMs).toISOString() : undefined,
115
122
  };
116
- }
117
- const now = new Date().toISOString();
118
- const claim = {
119
- issueId,
120
- claimant,
121
- claimedAt: now,
122
- status: 'active',
123
- statusChangedAt: now,
124
- progress: 0,
125
- context,
126
- expiresAt: ttlMs !== undefined ? new Date(Date.now() + ttlMs).toISOString() : undefined,
127
- };
128
- store.claims[issueId] = claim;
129
- saveClaims(store);
130
- return {
131
- success: true,
132
- claim,
133
- message: `Issue ${issueId} claimed by ${formatClaimant(claimant)}`,
134
- };
123
+ store.claims[issueId] = claim;
124
+ return saved({
125
+ success: true,
126
+ claim,
127
+ message: `Issue ${issueId} claimed by ${formatClaimant(claimant)}`,
128
+ });
129
+ });
135
130
  },
136
131
  },
137
132
  {
@@ -179,24 +174,24 @@ export const claimsTools = [
179
174
  if (!claimant) {
180
175
  return { success: false, error: 'Invalid claimant format' };
181
176
  }
182
- const store = loadClaims();
183
- const claim = store.claims[issueId];
184
- if (!claim) {
185
- return { success: false, error: 'Issue is not claimed' };
186
- }
187
- // Verify ownership
188
- if (formatClaimant(claim.claimant) !== formatClaimant(claimant)) {
189
- return { success: false, error: 'Only the current claimant can release' };
190
- }
191
- delete store.claims[issueId];
192
- delete store.stealable[issueId];
193
- saveClaims(store);
194
- return {
195
- success: true,
196
- message: `Issue ${issueId} released`,
197
- reason,
198
- previousClaim: claim,
199
- };
177
+ return updateClaims((store) => {
178
+ const claim = store.claims[issueId];
179
+ if (!claim) {
180
+ return unchanged({ success: false, error: 'Issue is not claimed' });
181
+ }
182
+ // Verify ownership
183
+ if (formatClaimant(claim.claimant) !== formatClaimant(claimant)) {
184
+ return unchanged({ success: false, error: 'Only the current claimant can release' });
185
+ }
186
+ delete store.claims[issueId];
187
+ delete store.stealable[issueId];
188
+ return saved({
189
+ success: true,
190
+ message: `Issue ${issueId} released`,
191
+ reason,
192
+ previousClaim: claim,
193
+ });
194
+ });
200
195
  },
201
196
  },
202
197
  {
@@ -260,35 +255,35 @@ export const claimsTools = [
260
255
  if (!from || !to) {
261
256
  return { success: false, error: 'Invalid claimant format' };
262
257
  }
263
- const store = loadClaims();
264
- const claim = store.claims[issueId];
265
- if (!claim) {
266
- return { success: false, error: 'Issue is not claimed' };
267
- }
268
- if (formatClaimant(claim.claimant) !== formatClaimant(from)) {
269
- return { success: false, error: 'Only the current claimant can request handoff' };
270
- }
271
- const now = new Date().toISOString();
272
- claim.status = 'handoff-pending';
273
- claim.statusChangedAt = now;
274
- claim.handoffTo = to;
275
- claim.handoffReason = reason;
276
- // Optional: keep the progress recorded with claims_status when it is
277
- // left out, and clamp it to 0-100 the same way claims_status does.
278
- if (progress !== undefined) {
279
- claim.progress = Math.min(100, Math.max(0, progress));
280
- }
281
- // A claim being handed to a named claimant is no longer up for grabs:
282
- // drop it from the list claims_stealable and claims_steal read, so it
283
- // cannot be stolen while the handoff is pending or after it is accepted.
284
- delete store.stealable[issueId];
285
- store.claims[issueId] = claim;
286
- saveClaims(store);
287
- return {
288
- success: true,
289
- claim,
290
- message: `Handoff requested from ${formatClaimant(from)} to ${formatClaimant(to)}`,
291
- };
258
+ return updateClaims((store) => {
259
+ const claim = store.claims[issueId];
260
+ if (!claim) {
261
+ return unchanged({ success: false, error: 'Issue is not claimed' });
262
+ }
263
+ if (formatClaimant(claim.claimant) !== formatClaimant(from)) {
264
+ return unchanged({ success: false, error: 'Only the current claimant can request handoff' });
265
+ }
266
+ const now = new Date().toISOString();
267
+ claim.status = 'handoff-pending';
268
+ claim.statusChangedAt = now;
269
+ claim.handoffTo = to;
270
+ claim.handoffReason = reason;
271
+ // Optional: keep the progress recorded with claims_status when it is
272
+ // left out, and clamp it to 0-100 the same way claims_status does.
273
+ if (progress !== undefined) {
274
+ claim.progress = Math.min(100, Math.max(0, progress));
275
+ }
276
+ // A claim being handed to a named claimant is no longer up for grabs:
277
+ // drop it from the list claims_stealable and claims_steal read, so it
278
+ // cannot be stolen while the handoff is pending or after it is accepted.
279
+ delete store.stealable[issueId];
280
+ store.claims[issueId] = claim;
281
+ return saved({
282
+ success: true,
283
+ claim,
284
+ message: `Handoff requested from ${formatClaimant(from)} to ${formatClaimant(to)}`,
285
+ });
286
+ });
292
287
  },
293
288
  },
294
289
  {
@@ -326,32 +321,32 @@ export const claimsTools = [
326
321
  if (!claimant) {
327
322
  return { success: false, error: 'Invalid claimant format' };
328
323
  }
329
- const store = loadClaims();
330
- const claim = store.claims[issueId];
331
- if (!claim) {
332
- return { success: false, error: 'Issue is not claimed' };
333
- }
334
- if (claim.status !== 'handoff-pending') {
335
- return { success: false, error: 'No pending handoff for this issue' };
336
- }
337
- if (!claim.handoffTo || formatClaimant(claim.handoffTo) !== formatClaimant(claimant)) {
338
- return { success: false, error: 'You are not the target of this handoff' };
339
- }
340
- const previousOwner = claim.claimant;
341
- const now = new Date().toISOString();
342
- claim.claimant = claimant;
343
- claim.status = 'active';
344
- claim.statusChangedAt = now;
345
- claim.handoffTo = undefined;
346
- claim.handoffReason = undefined;
347
- store.claims[issueId] = claim;
348
- saveClaims(store);
349
- return {
350
- success: true,
351
- claim,
352
- previousOwner,
353
- message: `Handoff accepted. ${formatClaimant(claimant)} now owns issue ${issueId}`,
354
- };
324
+ return updateClaims((store) => {
325
+ const claim = store.claims[issueId];
326
+ if (!claim) {
327
+ return unchanged({ success: false, error: 'Issue is not claimed' });
328
+ }
329
+ if (claim.status !== 'handoff-pending') {
330
+ return unchanged({ success: false, error: 'No pending handoff for this issue' });
331
+ }
332
+ if (!claim.handoffTo || formatClaimant(claim.handoffTo) !== formatClaimant(claimant)) {
333
+ return unchanged({ success: false, error: 'You are not the target of this handoff' });
334
+ }
335
+ const previousOwner = claim.claimant;
336
+ const now = new Date().toISOString();
337
+ claim.claimant = claimant;
338
+ claim.status = 'active';
339
+ claim.statusChangedAt = now;
340
+ claim.handoffTo = undefined;
341
+ claim.handoffReason = undefined;
342
+ store.claims[issueId] = claim;
343
+ return saved({
344
+ success: true,
345
+ claim,
346
+ previousOwner,
347
+ message: `Handoff accepted. ${formatClaimant(claimant)} now owns issue ${issueId}`,
348
+ });
349
+ });
355
350
  },
356
351
  },
357
352
  {
@@ -396,31 +391,31 @@ export const claimsTools = [
396
391
  if (!v.valid)
397
392
  return { success: false, error: v.error };
398
393
  }
399
- const store = loadClaims();
400
- const claim = store.claims[issueId];
401
- if (!claim) {
402
- return { success: false, error: 'Issue is not claimed' };
403
- }
404
- const now = new Date().toISOString();
405
- claim.status = status;
406
- claim.statusChangedAt = now;
407
- if (status === 'blocked') {
408
- claim.blockReason = note;
409
- }
410
- if (progress !== undefined) {
411
- claim.progress = Math.min(100, Math.max(0, progress));
412
- }
413
- // claims_status never sets 'stealable', so a claim it updates is no
414
- // longer up for grabs: drop it from the list claims_stealable and
415
- // claims_steal read.
416
- delete store.stealable[issueId];
417
- store.claims[issueId] = claim;
418
- saveClaims(store);
419
- return {
420
- success: true,
421
- claim,
422
- message: `Issue ${issueId} status updated to ${status}`,
423
- };
394
+ return updateClaims((store) => {
395
+ const claim = store.claims[issueId];
396
+ if (!claim) {
397
+ return unchanged({ success: false, error: 'Issue is not claimed' });
398
+ }
399
+ const now = new Date().toISOString();
400
+ claim.status = status;
401
+ claim.statusChangedAt = now;
402
+ if (status === 'blocked') {
403
+ claim.blockReason = note;
404
+ }
405
+ if (progress !== undefined) {
406
+ claim.progress = Math.min(100, Math.max(0, progress));
407
+ }
408
+ // claims_status never sets 'stealable', so a claim it updates is no
409
+ // longer up for grabs: drop it from the list claims_stealable and
410
+ // claims_steal read.
411
+ delete store.stealable[issueId];
412
+ store.claims[issueId] = claim;
413
+ return saved({
414
+ success: true,
415
+ claim,
416
+ message: `Issue ${issueId} status updated to ${status}`,
417
+ });
418
+ });
424
419
  },
425
420
  },
426
421
  {
@@ -521,29 +516,29 @@ export const claimsTools = [
521
516
  if (!v.valid)
522
517
  return { success: false, error: v.error };
523
518
  }
524
- const store = loadClaims();
525
- const claim = store.claims[issueId];
526
- if (!claim) {
527
- return { success: false, error: 'Issue is not claimed' };
528
- }
529
- const now = new Date().toISOString();
530
- claim.status = 'stealable';
531
- claim.statusChangedAt = now;
532
- store.stealable[issueId] = {
533
- reason,
534
- stealableAt: now,
535
- preferredTypes,
536
- progress: claim.progress,
537
- context,
538
- };
539
- store.claims[issueId] = claim;
540
- saveClaims(store);
541
- return {
542
- success: true,
543
- claim,
544
- stealableInfo: store.stealable[issueId],
545
- message: `Issue ${issueId} marked as stealable (${reason})`,
546
- };
519
+ return updateClaims((store) => {
520
+ const claim = store.claims[issueId];
521
+ if (!claim) {
522
+ return unchanged({ success: false, error: 'Issue is not claimed' });
523
+ }
524
+ const now = new Date().toISOString();
525
+ claim.status = 'stealable';
526
+ claim.statusChangedAt = now;
527
+ store.stealable[issueId] = {
528
+ reason,
529
+ stealableAt: now,
530
+ preferredTypes,
531
+ progress: claim.progress,
532
+ context,
533
+ };
534
+ store.claims[issueId] = claim;
535
+ return saved({
536
+ success: true,
537
+ claim,
538
+ stealableInfo: store.stealable[issueId],
539
+ message: `Issue ${issueId} marked as stealable (${reason})`,
540
+ });
541
+ });
547
542
  },
548
543
  },
549
544
  {
@@ -581,42 +576,42 @@ export const claimsTools = [
581
576
  if (!stealer) {
582
577
  return { success: false, error: 'Invalid claimant format' };
583
578
  }
584
- const store = loadClaims();
585
- const claim = store.claims[issueId];
586
- const stealableInfo = store.stealable[issueId];
587
- if (!claim) {
588
- return { success: false, error: 'Issue is not claimed' };
589
- }
590
- if (!stealableInfo) {
591
- return { success: false, error: 'Issue is not stealable' };
592
- }
593
- // Check preferred types
594
- if (stealableInfo.preferredTypes && stealableInfo.preferredTypes.length > 0) {
595
- if (stealer.type === 'agent' && !stealableInfo.preferredTypes.includes(stealer.agentType)) {
596
- return {
597
- success: false,
598
- error: `Issue prefers agent types: ${stealableInfo.preferredTypes.join(', ')}`,
599
- };
579
+ return updateClaims((store) => {
580
+ const claim = store.claims[issueId];
581
+ const stealableInfo = store.stealable[issueId];
582
+ if (!claim) {
583
+ return unchanged({ success: false, error: 'Issue is not claimed' });
600
584
  }
601
- }
602
- const previousOwner = claim.claimant;
603
- const now = new Date().toISOString();
604
- claim.claimant = stealer;
605
- claim.status = 'active';
606
- claim.statusChangedAt = now;
607
- // The context given to claims_mark-stealable is the handoff note for the
608
- // stealer; without one, keep the context recorded with the claim.
609
- claim.context = stealableInfo.context ?? claim.context;
610
- delete store.stealable[issueId];
611
- store.claims[issueId] = claim;
612
- saveClaims(store);
613
- return {
614
- success: true,
615
- claim,
616
- previousOwner,
617
- stealableInfo,
618
- message: `Issue ${issueId} stolen by ${formatClaimant(stealer)}`,
619
- };
585
+ if (!stealableInfo) {
586
+ return unchanged({ success: false, error: 'Issue is not stealable' });
587
+ }
588
+ // Check preferred types
589
+ if (stealableInfo.preferredTypes && stealableInfo.preferredTypes.length > 0) {
590
+ if (stealer.type === 'agent' && !stealableInfo.preferredTypes.includes(stealer.agentType)) {
591
+ return unchanged({
592
+ success: false,
593
+ error: `Issue prefers agent types: ${stealableInfo.preferredTypes.join(', ')}`,
594
+ });
595
+ }
596
+ }
597
+ const previousOwner = claim.claimant;
598
+ const now = new Date().toISOString();
599
+ claim.claimant = stealer;
600
+ claim.status = 'active';
601
+ claim.statusChangedAt = now;
602
+ // The context given to claims_mark-stealable is the handoff note for the
603
+ // stealer; without one, keep the context recorded with the claim.
604
+ claim.context = stealableInfo.context ?? claim.context;
605
+ delete store.stealable[issueId];
606
+ store.claims[issueId] = claim;
607
+ return saved({
608
+ success: true,
609
+ claim,
610
+ previousOwner,
611
+ stealableInfo,
612
+ message: `Issue ${issueId} stolen by ${formatClaimant(stealer)}`,
613
+ });
614
+ });
620
615
  },
621
616
  },
622
617
  {
@@ -809,77 +804,81 @@ export const claimsTools = [
809
804
  handler: async (input) => {
810
805
  const dryRun = input.dryRun !== false;
811
806
  const targetUtilization = input.targetUtilization || 0.7;
812
- const store = loadClaims();
813
- // Completed claims are not load, as in claims_load.
814
- const openAgentClaims = Object.values(store.claims).filter(isOpenAgentClaim);
815
- // Group by agent
816
- const agentLoads = new Map();
817
- for (const claim of openAgentClaims) {
818
- const key = claim.claimant.agentId;
819
- if (!agentLoads.has(key)) {
820
- agentLoads.set(key, { agentId: key, agentType: claim.claimant.agentType, claims: [] });
807
+ // The moves are planned from the same locked read they are applied to.
808
+ return updateClaims((store) => {
809
+ // Completed claims are not load, as in claims_load.
810
+ const openAgentClaims = Object.values(store.claims).filter(isOpenAgentClaim);
811
+ // Group by agent
812
+ const agentLoads = new Map();
813
+ for (const claim of openAgentClaims) {
814
+ const key = claim.claimant.agentId;
815
+ if (!agentLoads.has(key)) {
816
+ agentLoads.set(key, { agentId: key, agentType: claim.claimant.agentType, claims: [] });
817
+ }
818
+ agentLoads.get(key).claims.push(claim);
821
819
  }
822
- agentLoads.get(key).claims.push(claim);
823
- }
824
- const loads = Array.from(agentLoads.values());
825
- const maxClaims = DEFAULT_MAX_CLAIMS;
826
- const avgLoad = loads.length > 0
827
- ? loads.reduce((sum, l) => sum + l.claims.length, 0) / loads.length
828
- : 0;
829
- const overloaded = loads.filter(l => l.claims.length > maxClaims * targetUtilization * 1.5);
830
- const underloaded = loads.filter(l => l.claims.length < maxClaims * targetUtilization * 0.5);
831
- const suggestions = [];
832
- // Claim counts including moves suggested so far, so one target is not
833
- // handed more claims than maxClaims allows.
834
- const plannedCount = new Map(loads.map(l => [l.agentId, l.claims.length]));
835
- for (const over of overloaded) {
836
- // Find low-progress claims to redistribute
837
- const movable = over.claims
838
- .filter(c => c.progress < 25 && c.status === 'active')
839
- .slice(0, over.claims.length - Math.ceil(maxClaims * targetUtilization));
840
- for (const claim of movable) {
841
- const target = underloaded.find(u => u.agentType === over.agentType && plannedCount.get(u.agentId) < maxClaims);
842
- if (target) {
843
- plannedCount.set(target.agentId, plannedCount.get(target.agentId) + 1);
844
- suggestions.push({
845
- issueId: claim.issueId,
846
- from: `agent:${over.agentId}:${over.agentType}`,
847
- to: `agent:${target.agentId}:${target.agentType}`,
848
- reason: 'Load balancing',
849
- });
820
+ const loads = Array.from(agentLoads.values());
821
+ const maxClaims = DEFAULT_MAX_CLAIMS;
822
+ const avgLoad = loads.length > 0
823
+ ? loads.reduce((sum, l) => sum + l.claims.length, 0) / loads.length
824
+ : 0;
825
+ const overloaded = loads.filter(l => l.claims.length > maxClaims * targetUtilization * 1.5);
826
+ const underloaded = loads.filter(l => l.claims.length < maxClaims * targetUtilization * 0.5);
827
+ const suggestions = [];
828
+ // Claim counts including moves suggested so far, so one target is not
829
+ // handed more claims than maxClaims allows.
830
+ const plannedCount = new Map(loads.map(l => [l.agentId, l.claims.length]));
831
+ for (const over of overloaded) {
832
+ // Find low-progress claims to redistribute
833
+ const movable = over.claims
834
+ .filter(c => c.progress < 25 && c.status === 'active')
835
+ .slice(0, over.claims.length - Math.ceil(maxClaims * targetUtilization));
836
+ for (const claim of movable) {
837
+ const target = underloaded.find(u => u.agentType === over.agentType && plannedCount.get(u.agentId) < maxClaims);
838
+ if (target) {
839
+ plannedCount.set(target.agentId, plannedCount.get(target.agentId) + 1);
840
+ suggestions.push({
841
+ issueId: claim.issueId,
842
+ from: `agent:${over.agentId}:${over.agentType}`,
843
+ to: `agent:${target.agentId}:${target.agentType}`,
844
+ reason: 'Load balancing',
845
+ });
846
+ }
850
847
  }
851
848
  }
852
- }
853
- // When not a dry run, execute the suggested moves
854
- if (!dryRun) {
855
- for (const suggestion of suggestions) {
856
- const claim = store.claims[suggestion.issueId];
857
- if (claim) {
858
- const newOwner = parseClaimant(suggestion.to);
859
- if (newOwner) {
860
- claim.claimant = newOwner;
861
- claim.statusChangedAt = new Date().toISOString();
862
- store.claims[suggestion.issueId] = claim;
849
+ // When not a dry run, execute the suggested moves
850
+ if (!dryRun) {
851
+ for (const suggestion of suggestions) {
852
+ const claim = store.claims[suggestion.issueId];
853
+ if (claim) {
854
+ const newOwner = parseClaimant(suggestion.to);
855
+ if (newOwner) {
856
+ claim.claimant = newOwner;
857
+ claim.statusChangedAt = new Date().toISOString();
858
+ store.claims[suggestion.issueId] = claim;
859
+ }
863
860
  }
864
861
  }
865
862
  }
866
- saveClaims(store);
867
- }
868
- return {
869
- success: true,
870
- dryRun,
871
- suggestions,
872
- metrics: {
873
- totalAgents: loads.length,
874
- avgLoad,
875
- overloadedCount: overloaded.length,
876
- underloadedCount: underloaded.length,
877
- targetUtilization,
878
- },
879
- message: dryRun
880
- ? `Found ${suggestions.length} rebalancing opportunities (dry run)`
881
- : `Applied ${suggestions.length} rebalancing moves`,
882
- };
863
+ return {
864
+ save: !dryRun,
865
+ result: {
866
+ success: true,
867
+ dryRun,
868
+ suggestions,
869
+ metrics: {
870
+ totalAgents: loads.length,
871
+ avgLoad,
872
+ overloadedCount: overloaded.length,
873
+ underloadedCount: underloaded.length,
874
+ targetUtilization,
875
+ },
876
+ message: dryRun
877
+ ? `Found ${suggestions.length} rebalancing opportunities (dry run)`
878
+ : `Applied ${suggestions.length} rebalancing moves`,
879
+ },
880
+ };
881
+ });
883
882
  },
884
883
  },
885
884
  ];