-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathorchestrator.js
More file actions
4619 lines (4045 loc) · 157 KB
/
Copy pathorchestrator.js
File metadata and controls
4619 lines (4045 loc) · 157 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Orchestrator - Manages cluster lifecycle
*
* Provides:
* - Cluster initialization and configuration
* - Agent lifecycle management
* - GitHub issue integration
* - Cluster state tracking
* - Crash recovery
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const lockfile = require('proper-lockfile');
// Stale lock timeout in ms - if lock file is older than this, delete it
const LOCK_STALE_MS = 5000;
/**
* Remove lock file if it's stale (older than LOCK_STALE_MS)
* Handles crashes that leave orphaned lock files
*/
function cleanStaleLock(lockPath) {
try {
if (fs.existsSync(lockPath)) {
const age = Date.now() - fs.statSync(lockPath).mtimeMs;
if (age > LOCK_STALE_MS) {
fs.unlinkSync(lockPath);
}
}
} catch {
// Ignore - another process may have cleaned it
}
}
const { readClustersFileSync, writeClustersFileAtomic } = require('../lib/clusters-registry');
const AgentWrapper = require('./agent-wrapper');
const SubClusterWrapper = require('./sub-cluster-wrapper');
const MessageBus = require('./message-bus');
const Ledger = require('./ledger');
const InputHelpers = require('./input-helpers');
const { USER_GUIDANCE_AGENT, USER_GUIDANCE_CLUSTER } = require('./guidance-topics');
const { detectProvider } = require('./issue-providers');
const IsolationManager = require('./isolation-manager');
const { generateName } = require('./name-generator');
const configValidator = require('./config-validator');
const TemplateResolver = require('./template-resolver');
const { loadSettings } = require('../lib/settings');
const { normalizeProviderName } = require('../lib/provider-names');
const { resolveRunPlan } = require('../lib/run-plan');
const { isProcessRunning } = require('../lib/process-liveness');
const { getProvider } = require('./providers');
const StateSnapshotter = require('./state-snapshotter');
const { resolveClusterRequiredQualityGates } = require('./quality-gates');
const {
normalizeProviderSession,
restoreAgentProviderSession,
} = require('./agent/provider-session');
const {
commandProofsToQualityGates,
mergeCommandProofs,
resolveClusterCommandProofs,
} = require('./command-proofs');
const crypto = require('crypto');
/**
* Thrown when a run is rejected because the issue already has an active cluster.
* This is expected control flow (a benign guard), not a crash - callers should
* check `error.code === 'DUPLICATE_CLUSTER'` and present it without a stack trace.
*/
class DuplicateClusterError extends Error {
constructor(message, { issueNumber, existingClusterId, existingState, existingPid, ageMinutes }) {
super(message);
this.name = 'DuplicateClusterError';
this.code = 'DUPLICATE_CLUSTER';
this.issueNumber = issueNumber;
this.existingClusterId = existingClusterId;
this.existingState = existingState;
this.existingPid = existingPid;
this.ageMinutes = ageMinutes;
}
}
function applyModelOverride(agentConfig, modelOverride) {
if (!modelOverride) return;
agentConfig.model = modelOverride;
if (agentConfig.modelRules) {
delete agentConfig.modelRules;
}
if (agentConfig.modelConfig) {
delete agentConfig.modelConfig;
}
}
/**
* Operation Chain Schema
* Conductor (or any agent) can publish CLUSTER_OPERATIONS to dynamically modify cluster
*
* Supported operations:
* - add_agents: Spawn new agents with given configs
* - remove_agents: Stop and remove agents by ID
* - update_agent: Modify existing agent config
* - publish: Publish a message to the bus
* - load_config: Load agents from a named cluster config template
*/
const VALID_OPERATIONS = ['add_agents', 'remove_agents', 'update_agent', 'publish', 'load_config'];
/**
* Workflow-triggering topics that indicate cluster state progression
* These are the topics that MATTER for resume - not AGENT_OUTPUT noise
*/
const WORKFLOW_TRIGGERS = Object.freeze([
'ISSUE_OPENED',
'PLAN_READY',
'IMPLEMENTATION_READY',
'VALIDATION_RESULT',
'PUSH_BLOCKED',
'CONDUCTOR_ESCALATE',
]);
const PUSH_BLOCKED_REPAIR_TRIGGER = Object.freeze({
topic: 'PUSH_BLOCKED',
action: 'execute_task',
});
function applyRequiredQualityGatesToAgent(agentConfig, requiredQualityGates) {
if (!Array.isArray(requiredQualityGates) || requiredQualityGates.length === 0) {
return;
}
if (agentConfig.role !== 'validator') {
return;
}
if (!Array.isArray(agentConfig.requiredQualityGates)) {
agentConfig.requiredQualityGates = requiredQualityGates;
}
}
function applyRequiredQualityGatesToValidators(config, requiredQualityGates) {
if (!Array.isArray(requiredQualityGates) || requiredQualityGates.length === 0) {
return;
}
for (const agentConfig of config.agents || []) {
applyRequiredQualityGatesToAgent(agentConfig, requiredQualityGates);
}
}
function applyCommandProofsToAgent(agentConfig, commandProofs) {
if (!Array.isArray(commandProofs) || commandProofs.length === 0) {
return;
}
agentConfig.commandProofs = mergeCommandProofs(agentConfig.commandProofs, commandProofs);
}
function applyCommandProofsToAgents(config, commandProofs) {
if (!Array.isArray(commandProofs) || commandProofs.length === 0) {
return;
}
for (const agentConfig of config.agents || []) {
applyCommandProofsToAgent(agentConfig, commandProofs);
}
}
function mergeQualityGates(...sources) {
const byId = new Map();
const order = [];
for (const source of sources) {
if (!Array.isArray(source)) {
continue;
}
for (const gate of source) {
if (!gate?.id) {
continue;
}
if (!byId.has(gate.id)) {
order.push(gate.id);
}
byId.set(gate.id, gate);
}
}
return order.map((id) => byId.get(id));
}
function getTriggerTopic(trigger) {
return typeof trigger === 'string' ? trigger : trigger?.topic;
}
function shouldHandlePushBlockedRepair(agentConfig) {
return agentConfig?.role === 'implementation';
}
function applyPushBlockedRepairTrigger(agentConfig) {
if (!shouldHandlePushBlockedRepair(agentConfig)) {
return;
}
if (!Array.isArray(agentConfig.triggers)) {
agentConfig.triggers = [];
}
if (agentConfig.triggers.some((trigger) => getTriggerTopic(trigger) === 'PUSH_BLOCKED')) {
return;
}
agentConfig.triggers.push({ ...PUSH_BLOCKED_REPAIR_TRIGGER });
}
function applyPushBlockedRepairTriggers(config) {
for (const agentConfig of config?.agents || []) {
applyPushBlockedRepairTrigger(agentConfig);
}
}
function buildPrOptions(options, requiredQualityGates) {
// autoMerge must always be persisted (even when no other PR fields are set) so that
// `zeroshot run --pr` (autoMerge=false) vs `--ship` (autoMerge=true) survives resume.
// Derived from the canonical run plan — never recomputed from ship/pr here.
const autoMerge = resolveRunPlan(options).autoMerge;
return {
prBase: options.prBase || null,
mergeQueue: options.mergeQueue || false,
closeIssue: options.closeIssue || null,
gitRemote: options.gitRemote || null,
autoMerge,
...(requiredQualityGates.length > 0 ? { requiredQualityGates } : {}),
cwd: options.cwd || process.cwd(),
};
}
function serializeWorktree(worktree) {
if (!worktree) {
return null;
}
return {
enabled: true,
path: worktree.path,
branch: worktree.branch,
repoRoot: worktree.repoRoot,
workDir: worktree.workDir,
};
}
class Orchestrator {
constructor(options = {}) {
this.clusters = new Map(); // cluster_id -> cluster object
this.quiet = options.quiet || false; // Suppress verbose logging
// Read-only mode: opens ledgers without write access and skips schema DDL/
// side-effecting bootstrap (state snapshotter). Used by CLI read commands
// (list/status/logs) so they can never contend with a live daemon's writer
// connection or mutate shared state as a side effect of a plain read.
this.readonly = options.readonly === true;
// TaskRunner DI - allows injecting MockTaskRunner for testing
// When set, passed to all AgentWrappers to control task execution
this.taskRunner = options.taskRunner || null;
// Set up persistent storage directory (can be overridden for testing)
this.storageDir = options.storageDir || path.join(os.homedir(), '.zeroshot');
if (!fs.existsSync(this.storageDir)) {
fs.mkdirSync(this.storageDir, { recursive: true });
}
// Track if orchestrator is closed (prevents _saveClusters race conditions during cleanup)
this.closed = false;
// Track if clusters are loaded (for lazy loading pattern)
this._clustersLoaded = options.skipLoad === true;
}
/**
* Factory method for async initialization
* Use this instead of `new Orchestrator()` for proper async cluster loading
* @param {Object} options - Same options as constructor
* @returns {Promise<Orchestrator>}
*/
static async create(options = {}) {
const instance = new Orchestrator({ ...options, skipLoad: true });
if (options.skipLoad !== true) {
await instance._loadClusters();
instance._clustersLoaded = true;
}
return instance;
}
/**
* Log message (respects quiet mode)
* @private
*/
_log(...args) {
if (!this.quiet) {
console.log(...args);
}
}
/**
* Resolve provider for a cluster config using the standard precedence.
* @param {Object} clusterConfig
* @param {Object} settings
* @returns {string}
* @private
*/
_resolveClusterProvider(clusterConfig = {}, settings = loadSettings()) {
const resolved =
clusterConfig.forceProvider ||
clusterConfig.defaultProvider ||
settings.defaultProvider ||
'claude';
return normalizeProviderName(resolved) || 'claude';
}
/**
* Resolve the model level for internal completion agents.
* Uses provider minLevel when configured, otherwise provider default min level.
* @param {Object} clusterConfig
* @returns {string}
* @private
*/
_resolveCompletionDetectorLevel(clusterConfig = {}) {
const settings = loadSettings();
const providerName = this._resolveClusterProvider(clusterConfig, settings);
const provider = getProvider(providerName);
const providerSettings = settings.providerSettings?.[providerName] || {};
return providerSettings.minLevel || provider.getDefaultMinLevel();
}
/**
* Get input source type for metadata
* @param {Object} input - Input object
* @returns {string} Source type: 'github', 'file', or 'text'
* @private
*/
_getInputSource(input) {
if (input.issue) return 'github';
if (input.file) return 'file';
return 'text';
}
/**
* Load clusters from persistent storage
* Uses file locking for consistent reads
* @private
*/
async _loadClusters() {
const clustersFile = path.join(this.storageDir, 'clusters.json');
this._log(`[Orchestrator] Loading clusters from: ${clustersFile}`);
if (!fs.existsSync(clustersFile)) {
this._log(`[Orchestrator] No clusters file found at ${clustersFile}`);
return;
}
const lockfilePath = path.join(this.storageDir, 'clusters.json.lock');
let release;
try {
// Clean stale locks from crashed processes
cleanStaleLock(lockfilePath);
// Acquire lock with async API (proper retries without CPU spin-wait)
release = await lockfile.lock(clustersFile, {
lockfilePath,
stale: LOCK_STALE_MS,
retries: {
retries: 20,
minTimeout: 100,
maxTimeout: 200,
randomize: true,
},
});
const data = readClustersFileSync(this.storageDir);
const clusterIds = Object.keys(data);
this._log(`[Orchestrator] Found ${clusterIds.length} clusters in file:`, clusterIds);
// Track clusters to remove (missing .db files)
const clustersToRemove = [];
for (const [clusterId, clusterData] of Object.entries(data)) {
if (clusterData?.state === 'setup' || clusterData?.provisional === true) {
this.clusters.set(clusterId, this._loadSetupCluster(clusterId, clusterData));
continue;
}
// Skip clusters whose .db file doesn't exist (orphaned registry entries)
const dbPath = path.join(this.storageDir, `${clusterId}.db`);
if (!fs.existsSync(dbPath)) {
console.warn(
`[Orchestrator] Cluster ${clusterId} has no database file, removing from registry`
);
clustersToRemove.push(clusterId);
continue;
}
this._log(`[Orchestrator] Loading cluster: ${clusterId}`);
try {
this._loadSingleCluster(clusterId, clusterData);
} catch (error) {
console.warn(
`[Orchestrator] Skipping cluster ${clusterId}: ${error.message || String(error)}`
);
continue;
}
}
// Clean up orphaned entries from clusters.json. This is a write side effect,
// so it must never run for read-only (list/status/logs) instances - only the
// writable orchestrator that owns the registry performs cleanup.
if (!this.readonly && clustersToRemove.length > 0) {
for (const clusterId of clustersToRemove) {
delete data[clusterId];
}
writeClustersFileAtomic(this.storageDir, data);
this._log(
`[Orchestrator] Removed ${clustersToRemove.length} orphaned cluster(s) from registry`
);
}
this._log(`[Orchestrator] Total clusters loaded: ${this.clusters.size}`);
} catch (error) {
console.error('[Orchestrator] Failed to load clusters:', error.message);
console.error(error.stack);
} finally {
if (release) {
await release();
}
}
}
_loadSetupCluster(clusterId, clusterData) {
const ledger = this._createSetupLedgerStub();
const messageBus = this._createSetupMessageBusStub(ledger);
return {
...clusterData,
id: clusterId,
config: clusterData.config || { agents: [] },
state: clusterData.state || 'setup',
createdAt: clusterData.createdAt || Date.now(),
pid: clusterData.pid || null,
agents: [],
messageBus,
ledger,
setupLogPath: clusterData.setupLogPath || null,
setupStage: clusterData.setupStage || null,
failureInfo: clusterData.failureInfo || null,
provisional: true,
};
}
_createSetupLedgerStub() {
const emptyArray = () => [];
const noop = () => {};
return {
append: () => null,
batchAppend: () => [],
query: emptyArray,
queryGuidanceMailbox: emptyArray,
findLast: () => null,
count: () => 0,
since: emptyArray,
getAll: emptyArray,
getTokensByRole: () => ({
_total: { count: 0, inputTokens: 0, outputTokens: 0, totalCostUsd: 0 },
}),
readSnapshot: () => ({
messageCount: 0,
tokensByRole: { _total: { count: 0, inputTokens: 0, outputTokens: 0, totalCostUsd: 0 } },
}),
pollForMessages: () => noop,
on: noop,
off: noop,
close: noop,
clear: noop,
};
}
_createSetupMessageBusStub(ledger) {
const noop = () => {};
const unsubscribe = () => {};
return {
ledger,
publish: () => null,
batchPublish: () => [],
subscribe: () => unsubscribe,
subscribeTopic: () => unsubscribe,
subscribeTopics: () => unsubscribe,
query: (criteria) => ledger.query(criteria),
queryGuidanceMailbox: (criteria) => ledger.queryGuidanceMailbox(criteria),
findLast: (criteria) => ledger.findLast(criteria),
count: (criteria) => ledger.count(criteria),
since: (params) => ledger.since(params),
getAll: (clusterId) => ledger.getAll(clusterId),
getTokensByRole: (clusterId) => ledger.getTokensByRole(clusterId),
readSnapshot: (clusterId) => ledger.readSnapshot(clusterId),
addWebSocketClient: noop,
removeWebSocketClient: noop,
on: noop,
off: noop,
emit: () => false,
close: noop,
clear: noop,
};
}
_isSetupCluster(cluster) {
return Boolean(cluster?.provisional === true || cluster?.state === 'setup');
}
_resolveStartClusterId(requestedClusterId, dbPath) {
if (!requestedClusterId) {
return this._generateUniqueClusterId(null, dbPath || null);
}
const existingCluster = this.clusters.get(requestedClusterId);
const candidateDbPath = dbPath || path.join(this.storageDir, `${requestedClusterId}.db`);
if (this._isSetupCluster(existingCluster) && !fs.existsSync(candidateDbPath)) {
this.clusters.delete(requestedClusterId);
return requestedClusterId;
}
return this._generateUniqueClusterId(requestedClusterId, dbPath || null);
}
/**
* Load a single cluster from data
* @private
*/
_loadSingleCluster(clusterId, clusterData) {
// Skip if already loaded
if (this.clusters.has(clusterId)) {
return this.clusters.get(clusterId);
}
// Restore ledger and message bus. Read-only orchestrators (CLI list/status/logs)
// open the ledger without write access so they can never contend with the live
// daemon's writer connection or take a write lock on another process's database.
const dbPath = path.join(this.storageDir, `${clusterId}.db`);
const ledger = new Ledger(dbPath, { readonly: this.readonly });
const messageBus = new MessageBus(ledger);
// Restore isolation manager FIRST if cluster was running in isolation mode
const { isolation, isolationManager } = this._restoreClusterIsolation(clusterId, clusterData);
// Create mutable cluster context for reload path (used by AgentWrapper/SubClusterWrapper)
const clusterContext = {
...clusterData,
id: clusterId,
isolation,
};
let agents;
try {
// Reconstruct agent metadata from config (processes are ephemeral)
// CRITICAL: Pass isolation context to agents if cluster was running in isolation
agents = this._rebuildClusterAgents(clusterContext, messageBus, isolation, isolationManager);
} catch (error) {
try {
ledger.close();
} catch (closeError) {
console.warn(
`[Orchestrator] Failed to close ledger for ${clusterId}: ${closeError.message || String(closeError)}`
);
}
throw error;
}
const cluster = {
...clusterContext,
ledger,
messageBus,
agents,
isolation,
autoPr: clusterData.autoPr || false,
prOptions: clusterData.prOptions || null,
commandProofs: clusterData.commandProofs || [],
issue: clusterData.issue || null,
};
Object.assign(clusterContext, cluster);
this.clusters.set(clusterId, clusterContext);
// The snapshotter bootstraps by publishing a STATE_SNAPSHOT message if one is
// missing - a ledger write. Read-only orchestrators must never write, so they
// skip it; they only need to read existing snapshots, not produce new ones.
if (!this.readonly) {
this._registerClusterSubscriptions({
messageBus,
clusterId,
isolationManager,
containerId: isolation?.containerId || null,
});
if (clusterContext.state === 'running' && this._isProcessRunning(clusterContext.pid)) {
this._startSnapshotter(clusterContext);
}
}
this._log(`[Orchestrator] Loaded cluster: ${clusterId} with ${agents.length} agents`);
return clusterContext;
}
_restoreClusterIsolation(clusterId, clusterData) {
let isolation = clusterData.isolation || null;
let isolationManager = null;
if (isolation?.enabled && isolation.containerId) {
isolationManager = new IsolationManager({ image: isolation.image });
// Restore the container mapping so cleanup works
isolationManager.containers.set(clusterId, isolation.containerId);
// Restore isolated dir mapping for workspace preservation during cleanup
if (isolation.workDir) {
isolationManager.isolatedDirs.set(clusterId, {
path: path.join(os.tmpdir(), 'zeroshot-isolated', clusterId),
originalDir: isolation.workDir,
});
}
isolation = {
...isolation,
manager: isolationManager,
};
this._log(
`[Orchestrator] Restored isolation manager for ${clusterId} (container: ${isolation.containerId}, workDir: ${isolation.workDir || 'unknown'})`
);
}
return { isolation, isolationManager };
}
_resolveAgentCwd(clusterData) {
const worktreePath = clusterData.worktree?.path;
const isolationWorkDir = clusterData.isolation?.workDir;
return worktreePath || isolationWorkDir || null;
}
_buildAgentOptions(clusterId, clusterData, isolation, isolationManager) {
const agentOptions = {
id: clusterId,
quiet: this.quiet,
modelOverride: clusterData.modelOverride || null,
testMode: Boolean(this.taskRunner),
};
if (this.taskRunner) {
agentOptions.taskRunner = this.taskRunner;
}
if (isolation?.enabled && isolationManager) {
agentOptions.isolation = {
enabled: true,
manager: isolationManager,
clusterId,
};
}
if (clusterData.worktree?.enabled) {
agentOptions.worktree = {
enabled: true,
path: clusterData.worktree.path,
branch: clusterData.worktree.branch,
repoRoot: clusterData.worktree.repoRoot,
};
}
return agentOptions;
}
_instantiateAgent(agentConfig, messageBus, clusterContext, agentOptions) {
if (agentConfig.type === 'subcluster') {
return new SubClusterWrapper(agentConfig, messageBus, clusterContext, agentOptions);
}
return new AgentWrapper(agentConfig, messageBus, clusterContext, agentOptions);
}
_restoreAgentState(agent, agentConfig, clusterData, messageBus) {
if (!clusterData.agentStates) return;
const savedState = clusterData.agentStates.find((state) => state.id === agentConfig.id);
if (!savedState) return;
agent.state = savedState.state || 'idle';
agent.iteration = savedState.iteration || 0;
// currentTask is a live in-process handle, not durable state.
// Restoring a serialized boolean here revives a fake runtime handle and
// makes stopped/resumed agents look like they still own a running task.
agent.currentTask = null;
agent.currentTaskId = savedState.currentTaskId || null;
agent.processPid = savedState.processPid || null;
agent.providerSession = restoreAgentProviderSession({
agent,
savedState,
messageBus,
clusterId: clusterData.id,
});
agent.lastGuidanceAppliedId = agent.providerSession?.guidanceSequence ?? null;
}
_rebuildClusterAgents(clusterContext, messageBus, isolation, isolationManager) {
const agents = [];
const clusterId = clusterContext.id;
const clusterData = clusterContext;
const agentCwd = this._resolveAgentCwd(clusterData);
if (!clusterData.config?.agents) {
return agents;
}
for (const agentConfig of clusterData.config.agents) {
if (!agentConfig.cwd && agentCwd) {
agentConfig.cwd = agentCwd;
this._log(`[Orchestrator] Fixed missing cwd for agent ${agentConfig.id}: ${agentCwd}`);
}
if (clusterData.modelOverride) {
applyModelOverride(agentConfig, clusterData.modelOverride);
}
const agentOptions = this._buildAgentOptions(
clusterId,
clusterData,
isolation,
isolationManager
);
const agent = this._instantiateAgent(agentConfig, messageBus, clusterContext, agentOptions);
this._restoreAgentState(agent, agentConfig, clusterData, messageBus);
agents.push(agent);
}
return agents;
}
_startSnapshotter(cluster) {
if (cluster.snapshotter) {
cluster.snapshotter.start();
return;
}
const snapshotter = new StateSnapshotter({
messageBus: cluster.messageBus,
clusterId: cluster.id,
});
snapshotter.start();
cluster.snapshotter = snapshotter;
}
/**
* Ensure clusters file exists (required for file locking)
* @private
*/
_ensureClustersFile() {
if (!fs.existsSync(this.storageDir)) {
try {
fs.mkdirSync(this.storageDir, { recursive: true });
} catch (error) {
console.warn(
`[Orchestrator] Failed to create storage directory ${this.storageDir}: ${error.message}`
);
return null;
}
}
const clustersFile = path.join(this.storageDir, 'clusters.json');
if (!fs.existsSync(clustersFile)) {
writeClustersFileAtomic(this.storageDir, {});
}
return clustersFile;
}
/**
* Find active clusters for a given issue number
* Used to prevent duplicate runs on the same issue
* @param {number|string} issueNumber - Issue number to check
* @returns {Array<{id: string, state: string, createdAt: number}>} Active clusters for this issue
* @private
*/
_getActiveClustersForIssue(issueNumber, excludeClusterId = null) {
const activeClusters = [];
const issueNum = Number(issueNumber);
for (const [clusterId, cluster] of this.clusters) {
if (excludeClusterId && clusterId === excludeClusterId) continue;
// Skip clusters without issue numbers
if (!cluster.issue) continue;
// Check if same issue number
if (Number(cluster.issue) !== issueNum) continue;
// Check if cluster is still active (not completed/failed/stopped)
const inactiveStates = ['completed', 'failed', 'stopped', 'corrupted'];
if (inactiveStates.includes(cluster.state)) continue;
// Check if process is still running (zombie detection)
if (cluster.pid && this._isProcessRunning(cluster.pid)) {
activeClusters.push({
id: clusterId,
state: cluster.state,
createdAt: cluster.createdAt,
pid: cluster.pid,
});
}
}
return activeClusters;
}
/**
* Save clusters to persistent storage
* Uses file locking to prevent race conditions with other processes
* @private
*/
async _saveClusters() {
// Skip saving if orchestrator is closed (prevents race conditions during cleanup)
if (this.closed) {
return;
}
// Read-only orchestrators (CLI list/status/logs) must never write the registry.
if (this.readonly) {
return;
}
const clustersFile = this._ensureClustersFile();
if (!clustersFile) {
return;
}
const lockfilePath = path.join(this.storageDir, 'clusters.json.lock');
let release;
try {
// Clean stale locks from crashed processes
cleanStaleLock(lockfilePath);
// Acquire exclusive lock with async API (proper retries without CPU spin-wait)
release = await lockfile.lock(clustersFile, {
lockfilePath,
stale: LOCK_STALE_MS,
retries: {
retries: 50,
minTimeout: 100,
maxTimeout: 300,
randomize: true,
},
});
// Read existing clusters from file (other processes may have added clusters)
let existingClusters = {};
try {
existingClusters = readClustersFileSync(this.storageDir);
} catch (error) {
console.error('[Orchestrator] Failed to read existing clusters:', error.message);
}
// Merge: update/add clusters from this process
for (const [clusterId, cluster] of this.clusters.entries()) {
// CRITICAL: Only update clusters this process actually owns or has modified
// A process owns a cluster if: it started it (pid matches) OR it explicitly stopped/killed it
const isOwnedByThisProcess = cluster.pid === process.pid;
const wasModifiedByThisProcess = cluster.state === 'stopped' || cluster.state === 'killed';
// Skip clusters we don't own and haven't modified - prevents race condition
// where a running cluster overwrites another process's stop/kill operation
if (!isOwnedByThisProcess && !wasModifiedByThisProcess) {
// Preserve existing state from file for clusters we don't own
continue;
}
// CRITICAL: Killed clusters are DELETED from disk, not persisted
// This ensures they can't be accidentally resumed
if (cluster.state === 'killed') {
delete existingClusters[clusterId];
continue;
}
existingClusters[clusterId] = {
id: cluster.id,
config: cluster.config,
state: cluster.state,
createdAt: cluster.createdAt,
// Track PID for zombie detection (null if cluster is stopped/killed)
pid: cluster.state === 'running' ? cluster.pid : null,
// Persist failure info for resume capability
failureInfo: cluster.failureInfo || null,
// Persist PR mode for completion agent selection
autoPr: cluster.autoPr || false,
// Persist normalized run mode for status/list display
runMode: cluster.runMode || null,
// Persist PR options for resume
prOptions: cluster.prOptions || null,
// Persist cluster-scoped command proof configuration for resume and dynamic agents
commandProofs: cluster.commandProofs || [],
// Persist model override for consistent agent spawning on resume
modelOverride: cluster.modelOverride || null,
// Persist issue number for heroshot/external tools
issue: cluster.issue || null,
// Persist isolation info (excluding manager instance which can't be serialized)
// CRITICAL: workDir is required for resume() to recreate container with same workspace
isolation: cluster.isolation
? {
enabled: cluster.isolation.enabled,
containerId: cluster.isolation.containerId,
image: cluster.isolation.image,
workDir: cluster.isolation.workDir, // Required for resume
}
: null,
worktree: serializeWorktree(cluster.worktree),
// Persist agent runtime states for accurate status display from other processes
agentStates: cluster.agents
? cluster.agents.map((a) => ({
id: a.id,
state: a.state,
iteration: a.iteration,
currentTask: a.currentTask ? true : false,
currentTaskId: a.currentTaskId,
processPid: a.processPid,
providerSession: normalizeProviderSession(a.providerSession),
lastGuidanceAppliedId: a.lastGuidanceAppliedId ?? null,
}))
: null,
setupLogPath: cluster.setupLogPath || null,
setupStage: cluster.setupStage || null,
provisional: cluster.provisional || false,
};
}
// Write merged data atomically (temp file + rename) so no reader can ever
// observe a partially-written file.
writeClustersFileAtomic(this.storageDir, existingClusters);
this._log(
`[Orchestrator] Saved ${this.clusters.size} cluster(s), file now has ${Object.keys(existingClusters).length} total`
);
} catch (error) {
if (error.code === 'ENOENT') {
console.warn(
`[Orchestrator] Skipping cluster save; storage directory missing: ${this.storageDir}`
);
return;
}
throw error;
} finally {
// Always release lock
if (release) {
await release();
}
}
}
/**
* Watch for new clusters and call callback when found
* Polls the clusters file for changes with file locking
* @param {Function} onNewCluster - Callback(cluster) for each new cluster
* @param {Number} intervalMs - Poll interval in ms (default: 2000)
* @returns {Function} Stop function to cancel watching
*/
watchForNewClusters(onNewCluster, intervalMs = 2000) {
const clustersFile = path.join(this.storageDir, 'clusters.json');
const lockfilePath = path.join(this.storageDir, 'clusters.json.lock');
const knownClusterIds = new Set(this.clusters.keys());
const intervalId = setInterval(() => {
let release;
try {
if (!fs.existsSync(clustersFile)) return;
// Clean stale locks from crashed processes
cleanStaleLock(lockfilePath);
// Try to acquire lock once (polling is best-effort, will retry on next cycle)
try {
release = lockfile.lockSync(clustersFile, {
lockfilePath,
stale: LOCK_STALE_MS,
});
} catch (lockErr) {
// Lock busy - skip this poll cycle, try again next interval
if (lockErr.code === 'ELOCKED') return;
throw lockErr;
}
const data = readClustersFileSync(this.storageDir);
for (const [clusterId, clusterData] of Object.entries(data)) {
if (!knownClusterIds.has(clusterId)) {
// New cluster found
knownClusterIds.add(clusterId);
const cluster = this._loadSingleCluster(clusterId, clusterData);
if (cluster && onNewCluster) {
onNewCluster(cluster);
}
}
}