Repository navigation
Expand file tree
/
Copy pathserver.mjs
More file actions
3352 lines (3165 loc) · 130 KB
/
Copy pathserver.mjs
File metadata and controls
3352 lines (3165 loc) · 130 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
// Transport and wiring only. Every rule lives in core/; every I/O detail lives
// in adapters/. This file moves messages between them.
import { createServer } from 'node:http';
import { randomUUID } from 'node:crypto';
import { readFile, stat } from 'node:fs/promises';
import { extname, join, normalize, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
appendEvent,
BLOCKED_REASONS,
createBlockedEvent,
createEvent,
EVENT_KINDS,
eventsFor,
} from './core/events.mjs';
import {
createRoster,
assignEngine,
configureRuntime as configureAgentRuntime,
defaultRuntime,
DEFAULT_ROSTER,
ENGINES,
ROLES,
isActive,
} from './core/roster.mjs';
import {
WORKER_STATE,
ensureWorkers,
freeWorkers,
hasLiveWorker,
hydrateWorker,
liveWorkers,
patchWorker,
primarySessionId,
projectWorkers,
workerForCheckpoint,
workerForSession,
} from './core/workers.mjs';
import { canResumeSession, isCurrentSessionEvent } from './core/session-lifecycle.mjs';
import { setGoal, getGoal, clearGoal, deriveGoals } from './core/goals.mjs';
import { claimFiles, releaseClaim } from './core/claims.mjs';
import {
composeDispatch,
buildOutputSchema,
workerDispatches,
REPORT_FENCE,
WORK_PLAN_FENCE,
planningTask,
EDITABLE_STEPS,
defaultStepText,
dispatchPipeline,
} from './core/dispatch.mjs';
import { createDriverRegistry } from './ports/driver.mjs';
import { createCodexDriver } from './adapters/codex.mjs';
import { createClaudeDriver } from './adapters/claude.mjs';
import { createSimDriver } from './adapters/sim.mjs';
import { ensureCodexServer } from './adapters/codexd.mjs';
import { REMOTE, remoteMode, remoteName, wantsRemote } from './core/remote.mjs';
import { createStore } from './adapters/store.mjs';
import { createWorktrees } from './adapters/git.mjs';
import { createRepoIndex } from './adapters/fs.mjs';
import { createUploads } from './adapters/uploads.mjs';
import { createGithubChecksPort } from './adapters/github-checks.mjs';
import { createCiMonitor } from './application/ci-monitor.mjs';
import { createWorkBoard } from './application/work-board.mjs';
import { createWorkPlanningService } from './application/work-planning.mjs';
import { createScheduler } from './application/scheduler.mjs';
import { createFleetCoordination } from './application/fleet-coordination.mjs';
import { createConversationService } from './application/conversations.mjs';
import { createWorkspaceQuery } from './application/workspace-query.mjs';
import { createWorkerLeaseService } from './application/worker-leases.mjs';
import { createRuntimeSupervisor } from './application/runtime-supervisor.mjs';
import { ORDER_ACTION } from './core/coordination.mjs';
import { LEASE_LIMIT_MS, finishLease } from './core/leases.mjs';
import { readyCheckpoints } from './core/scheduler.mjs';
import {
CONTEXT_KIND,
messagesForContext,
} from './core/conversation.mjs';
import { projectMissionFlows } from './core/mission-flows.mjs';
import {
createAcceptancePolicy,
missionIsComplete,
validateAcceptancePolicy,
reconcileAcceptanceChange,
} from './core/acceptance.mjs';
import {
projectMissionProgress,
repositoryQualitySummary,
missionContradictions,
} from './core/mission-quality.mjs';
import { parseMentions, routeOf } from './core/mentions.mjs';
import {
deriveCards,
diffCards,
indexByAgent,
cardKey,
prayerOf,
stampCards,
} from './core/monitor.mjs';
import {
createBoard,
closeItem,
revise as reviseItem,
setPaused as setCheckpointPaused,
moveItem as moveCheckpointItem,
itemsOf,
itemsFor,
canWork,
isClosed,
isDone,
unmetDeps,
stateOf as checkpointState,
findItem,
beginCheckpoint,
failCheckpointStart,
} from './core/board.mjs';
import {
routeCard,
guardVerdict,
governanceTask,
parseVerdicts,
VERDICT,
VERDICT_FENCE,
} from './core/governance.mjs';
import { splitFenced, isMachineNoise } from './core/readable.mjs';
import { AGENT_TOOL, roleCanUseTool } from './core/agent-tools.mjs';
import { applyFleetEvent } from './core/fleet-reducer.mjs';
import { activationPlan } from './core/crew.mjs';
import { estimateDispatchTokens } from './core/token-estimate.mjs';
import {
isVerificationCheckpoint,
reconcileReleaseCheckpoints,
STAGE_GATES,
} from './core/work-units.mjs';
const ROOT = resolve(fileURLToPath(new URL('.', import.meta.url)));
const MIME = {
'.html': 'text/html; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.heic': 'image/heic',
'.pdf': 'application/pdf',
'.glb': 'model/gltf-binary',
'.gltf': 'model/gltf+json',
'.json': 'application/json; charset=utf-8',
};
const options = parseArgs(process.argv.slice(2));
// A personal roster is a local file, never a repo default: names and meshes
// are taste, and one machine's taste should not ship with the tool.
if (options.rosterPath) {
const file = JSON.parse(await readFile(options.rosterPath, 'utf8').catch(() => '{}'));
// "$team" names the crew; every other key is an agent override.
const { $team, ...agents } = file;
options.team = $team ?? options.team;
options.rosterOverrides = agents;
}
const state = {
agents: forceEngine(createRoster(DEFAULT_ROSTER, options.rosterOverrides), options.engine),
goals: {},
claims: {},
events: [],
assembly: null,
mission: options.mission,
// What the room has noticed and nobody has reported. Derived here rather
// than in the browser, so the same answer reaches the screen AND anything
// that can act on it.
cards: [],
// Suppressed only while the same condition remains true. When it clears,
// the key is released and a later recurrence becomes a new decision.
dismissedCards: new Set(),
// What Thor has said about each card, keyed by cardKey so it dies with it.
verdicts: {},
governing: false,
// The shared board. One list of work every agent reads and writes, so
// coordination stops being prose.
board: createBoard(),
acceptance: createAcceptancePolicy(),
completedAt: null,
};
const MAX_REFERENCE_BYTES = 2 * 1024 * 1024;
state.goals = deriveGoals(state.goals, state.agents, state.mission);
const store = createStore({ file: join(ROOT, 'data', 'minimac.db') });
function runtimeKey(agentId, engine) {
return `agent-runtime:${agentId}:${engine}`;
}
function applySavedRuntime(agentId) {
const agent = state.agents[agentId];
if (!agent) return;
const runtime = store.setting(runtimeKey(agent.id, agent.engine), defaultRuntime(agent.engine));
try {
state.agents = configureAgentRuntime(state.agents, agent.id, runtime);
} catch {
state.agents = configureAgentRuntime(state.agents, agent.id, defaultRuntime(agent.engine));
}
}
for (const agent of Object.values(state.agents)) applySavedRuntime(agent.id);
// A restart is not new work. If this repo left a run open, rejoin it and take
// back its mission and its goals - otherwise every restart puts the whole
// fleet back to "no goal - this agent would start blind" while the run it
// belongs to is still sitting in the list marked running.
const adopted = store.adoptRun(options.repo);
let adoptedSessions = [];
if (adopted) {
// Engine selection is run state. Restore it before session reconciliation,
// because a handle can only be opened by the engine that created it.
for (const row of store.enginesFor(adopted.id)) {
state.agents = assignEngine(state.agents, row.agent_id, row.engine);
}
for (const agent of Object.values(state.agents)) applySavedRuntime(agent.id);
adoptedSessions = store.workerSessionsFor(adopted.id);
if (!state.mission && adopted.mission) state.mission = adopted.mission;
// The mission only arrives here, so the derive at boot ran against an empty
// one and gave every worker nothing. Derive again now that we know what the
// run is for - a worker with no goal is the drift this tool exists to stop.
state.goals = deriveGoals(state.goals, state.agents, state.mission);
// Saved goals are the truth and outrank anything derived, so they land last.
for (const row of store.goalsFor(adopted.id)) {
if (!row.objective) continue;
state.goals = setGoal(
state.goals,
row.agent_id,
row.objective,
row.token_budget,
row.status ?? 'active',
row.source ?? 'manual',
);
}
// Whatever the run was missing is now written down, so this cannot silently
// come back as blank goals on the next restart.
for (const [agentId, goal] of Object.entries(state.goals)) store.saveGoal(agentId, goal);
// And the run's HISTORY, not just its goals. Without this the monitor was
// blind to everything before the restart while the browser replayed the lot
// from the database - so the room could show a loop the server could not
// see, and no card was ever raised for it.
state.events = store.replayRun(adopted.id);
for (const event of state.events) state.agents = applyFleetEvent(state.agents, event);
// Start from a safe projection, then reconcile saved handles with each
// engine after its transport is ready. Idle conversations remain resumable.
for (const agent of Object.values(state.agents)) {
const saved = adoptedSessions
.filter((row) => row.agent_id === agent.id)
.map(hydrateWorker);
const restored = projectWorkers({ ...agent, workers: saved, blockedReason: null });
state.agents = patchAgent(state.agents, agent.id, projectWorkers(restored, ensureWorkers(restored)));
}
// The checkpoints belong to the run, so rejoining a run rejoins its work.
const adoptedItems = store.itemsFor(adopted.id);
state.board = { workUnits: store.workUnitsFor(adopted.id), items: adoptedItems };
state.acceptance = store.acceptanceFor(adopted.id) ?? createAcceptancePolicy();
const savedMissionState = store.missionStateFor(adopted.id);
state.completedAt = savedMissionState?.completedAt
?? (missionIsComplete(state.acceptance, state.board) ? Date.now() : null);
const adoptedAt = Date.now();
state.cards = stampCards(
state.cards,
deriveCards(Object.values(state.agents), indexByAgent(state.events), state.board, adoptedAt),
adoptedAt,
);
}
const worktrees = createWorktrees({ repo: options.repo, root: join(ROOT, 'worktrees') });
const repoIndex = createRepoIndex();
const uploads = createUploads({ dir: join(ROOT, 'data', 'attachments') });
const agentTokens = new Map();
const agentsByToken = new Map();
function mcpServerFor(agent) {
const principalId = agent.workerId ?? agent.id;
let token = agentTokens.get(principalId);
// One worker is one local tool principal for this server process. Engine
// turns and resumable sessions can keep the MCP child that received this
// environment, so activity changes must never rotate its identity.
if (!token || !agentsByToken.has(token)) {
token = randomUUID();
agentTokens.set(principalId, token);
agentsByToken.set(token, { agentId: agent.id, workerId: agent.workerId ?? null });
}
return {
command: process.execPath,
args: [join(ROOT, 'adapters', 'fleet-mcp.mjs')],
env: {
MINIMAC_SERVER_URL: `http://127.0.0.1:${options.port}`,
MINIMAC_AGENT_TOKEN: token,
MINIMAC_AGENT_ROLE: agent.role,
},
};
}
// How this fleet is told to work. Survives runs and restarts.
const middleware = store.middleware();
// Who is reachable from your phone. core/remote decides; the drivers carry it
// to the two CLIs, which differ in what they can honour - see core/remote.
function remoteFor(agent) {
return wantsRemote(agent, options.remote)
? remoteName(agent, { team: options.team })
: null;
}
const getDriver = createDriverRegistry({
[ENGINES.CODEX]: createCodexDriver({ url: options.codexUrl, mcpServer: mcpServerFor }),
[ENGINES.CLAUDE]: createClaudeDriver({ remoteName: remoteFor, mcpServer: mcpServerFor }),
[ENGINES.SIM]: createSimDriver(),
});
for (const engine of Object.values(ENGINES)) {
getDriver(engine).onEvent(ingest);
}
const subscribers = new Set();
const HANDOFF_LIMIT = 16_000;
let workerLeases = null;
function boundedHandoff(text) {
const transcript = String(text ?? '').trim();
return transcript.length > HANDOFF_LIMIT
? `[earlier history omitted]\n${transcript.slice(-HANDOFF_LIMIT)}`
: transcript;
}
function eventTranscript(agentId) {
const lines = [];
for (const event of eventsFor(state.events, agentId)) {
const payload = event.payload ?? {};
if (event.kind === EVENT_KINDS.CONVERSATION_MESSAGE && payload.message?.body) {
lines.push(`${payload.message.from === 'you' ? 'USER' : 'ASSISTANT'}\n${payload.message.body}`);
} else if (event.kind === EVENT_KINDS.TOOL) {
lines.push(`TOOL\n${payload.action ?? 'tool'} ${payload.target ?? ''} ${payload.phase ?? ''}`.trim());
} else if (event.kind === EVENT_KINDS.CLAIM && payload.text) {
lines.push(`CLAIM\n${payload.text}${payload.receipt ? `\nreceipt: ${payload.receipt}` : ''}`);
} else if (event.kind === EVENT_KINDS.RESULT && payload.report) {
lines.push(`RESULT\n${JSON.stringify(payload.report)}`);
} else if (event.kind === EVENT_KINDS.BLOCKED && payload.reason) {
lines.push(`BLOCKED\n${payload.reason}`);
} else if (event.kind === EVENT_KINDS.STATUS && payload.text) {
lines.push(`STATUS\n${payload.text}`);
}
}
return boundedHandoff(lines.join('\n\n'));
}
async function captureEngineHandoff(agentId, fromEngine, toEngine, sessionId) {
if (fromEngine === toEngine) return null;
const sessionIds = (Array.isArray(sessionId) ? sessionId : [sessionId]).filter(Boolean);
const transcripts = [];
const driver = getDriver(fromEngine);
if (typeof driver.history === 'function') {
for (const id of sessionIds) {
try {
const history = await driver.history(id, options.repo);
if (history) transcripts.push(`SESSION ${id}\n${history}`);
} catch {
// The durable MINIMAC event transcript remains the fallback.
}
}
}
const transcript = boundedHandoff(transcripts.join('\n\n') || eventTranscript(agentId));
if (!transcript) return null;
const handoff = {
fromEngine,
toEngine,
sourceSessionId: sessionIds.join(','),
transcript,
};
store.saveHandoff(agentId, handoff);
return handoff;
}
// A restart does not guess. Ask each engine about the saved handle without
// starting work. A live thread stays on; a resumable idle thread stays off
// until the user or Thor starts it.
async function reconcileAdoptedSessions() {
for (const row of adoptedSessions) {
const agent = state.agents[row.agent_id];
if (!agent) continue;
const workerId = row.worker_id ?? `${agent.id}:1`;
if (row.engine !== agent.engine) {
await captureEngineHandoff(agent.id, row.engine, agent.engine, row.session_id);
state.agents = patchAgent(state.agents, agent.id, patchWorker(agent, workerId, {
sessionId: null,
resumeSessionId: null,
state: WORKER_STATE.IDLE,
}));
continue;
}
const driver = getDriver(agent.engine);
if (typeof driver.reconcile !== 'function') continue;
try {
const result = await driver.reconcile({ ...agent, workerId }, options.repo, row.session_id);
const live = result?.live === true;
const next = patchWorker(state.agents[agent.id], workerId, {
sessionId: live ? result.sessionId ?? row.session_id : null,
resumeSessionId: result?.resumable === false ? null : row.session_id,
state: live ? WORKER_STATE.RUNNING : (result?.state ?? WORKER_STATE.IDLE),
});
state.agents = patchAgent(state.agents, agent.id, {
...next,
enabled: live ? true : agent.enabled,
});
store.saveWorkerSession(workerForSession(state.agents[agent.id], row.session_id));
if (live && row.checkpoint_id) {
const item = findItem(state.board, row.checkpoint_id);
if (item?.lease?.workerId === workerId && item.lease.state === 'running') {
workerLeases.restore(item.lease);
}
} else if (row.checkpoint_id) {
const item = findItem(state.board, row.checkpoint_id);
if (item?.lease?.workerId === workerId && item.lease.state === 'running') {
const failedGate = Object.entries(item.gates ?? {})
.find(([, gateState]) => gateState === 'fail')?.[0] ?? null;
const evidence = [...(item.evidence ?? [])].reverse()
.find((entry) => entry.state === 'fail');
const settled = failedGate && !isVerificationCheckpoint(item)
? reviseItem(state.board, item.id, {
lease: finishLease(item.lease, 'failed'),
paused: true,
pauseReason: evidence?.receipt || `${failedGate} failed before restart`,
})
: failCheckpointStart(
state.board,
item.id,
'worker session ended before the checkpoint reported completion',
Date.now() + 15_000,
);
if (!settled.error) {
state.board = settled.board;
store.saveItem(settled.item);
}
}
}
} catch {
state.agents = patchAgent(state.agents, agent.id, patchWorker(agent, workerId, {
sessionId: null,
state: WORKER_STATE.IDLE,
}));
}
}
}
// ---------------------------------------------------------------- ingestion
// An agent's report arrives inside its prose. Pulling it out here means both
// engines produce the same flows and claims without either CLI having to
// support a schema flag.
const REPORT_BLOCK = new RegExp('```' + REPORT_FENCE + '\\s*([\\s\\S]*?)```');
const WORK_PLAN_BLOCK = new RegExp('```' + WORK_PLAN_FENCE + '\\s*([\\s\\S]*?)```');
// The orchestrator's answer to "what should each of them be doing".
async function harvestWorkPlan(event) {
if (state.completedAt) return { applied: false, error: 'mission is complete' };
const assemblyId = state.assembly?.id ?? null;
const match = WORK_PLAN_BLOCK.exec(String(event.payload?.text ?? ''));
if (!match) {
if (assemblyId) failAssembly(assemblyId, 'Thor finished without a valid work plan');
return { applied: false, error: 'no assemble payload' };
}
if (!assemblyId) return { applied: false, error: 'no active assemble attempt' };
let parsed;
try {
parsed = JSON.parse(match[1]);
} catch {
if (assemblyId) failAssembly(assemblyId, 'Thor returned a work plan that is not valid JSON');
return { applied: false, error: 'assemble payload is not valid JSON' };
}
if (!['local', 'publish'].includes(parsed.delivery)) {
if (assemblyId) failAssembly(assemblyId, 'Thor returned a work plan without a valid delivery mode');
return { applied: false, error: 'assemble needs delivery: local or publish' };
}
// Who the mission needs. An agent taken off sits it out entirely: startCrew
// skips anything disabled, so this is the orchestrator sizing its own crew.
// No crew call is a failed assemble, not a partial one. Silently leaving
// everyone on is how a two-hero mission ends up with seven idle seats.
const crewSpec = parsed.crew ?? null;
const named = Object.keys(crewSpec ?? {}).length;
const expected = Object.values(state.agents)
.filter((agent) => agent.role !== ROLES.ORCHESTRATOR)
.map((agent) => agent.id);
const missing = crewSpec
? expected.filter((agentId) => !Object.hasOwn(crewSpec, agentId))
: expected;
const unknown = crewSpec
? Object.keys(crewSpec).filter((agentId) => !expected.includes(agentId))
: [];
if ((assemblyId || crewSpec) && (missing.length > 0 || unknown.length > 0)) {
const problem = [
missing.length > 0 && `missing ${missing.join(', ')}`,
unknown.length > 0 && `unknown ${unknown.join(', ')}`,
].filter(Boolean).join('; ');
ingest(createEvent(event.agentId, EVENT_KINDS.STATUS, {
text: `assemble incomplete: ${problem}; the roster was not changed`,
from: 'you',
}));
if (assemblyId) settleAssembly(assemblyId);
return { applied: false, error: problem };
}
const crew = [];
for (const [agentId, wanted] of Object.entries(crewSpec ?? {})) {
const agent = state.agents[agentId];
if (!agent || agent.role === ROLES.ORCHESTRATOR) continue;
// A number is how many of that hero the work needs; a boolean is one or none.
const copies = typeof wanted === 'number'
? Math.min(4, Math.max(0, Math.round(wanted)))
: (wanted === true ? 1 : wanted === false ? 0 : null);
if (copies === null) continue;
const enabled = copies > 0;
const instances = Math.max(1, copies);
const changed = agent.enabled !== enabled || agent.instances !== instances;
if (changed) state.agents = patchAgent(state.agents, agentId, { enabled, instances });
if (changed) {
crew.push(enabled
? `+${agent.label ?? agentId}${instances > 1 ? ` x${instances}` : ''}`
: `-${agent.label ?? agentId}`);
}
}
if (crew.length) {
ingest(createEvent(event.agentId, EVENT_KINDS.STATUS, {
text: `crew for this mission: ${crew.join(' ')}`,
from: 'you',
}));
}
const activeBeforeRegroup = itemsOf(state.board)
.filter((item) => item.lease?.state === 'running')
.map((item) => ({ id: item.id, agentId: item.lease.agentId, workerId: item.lease.workerId }));
const required = [...new Set((parsed.workUnits ?? []).flatMap((unit) =>
(unit.stages ?? [])
.filter((stage) => stage.required !== false)
.flatMap((stage) => STAGE_GATES[stage.stage] ?? [])))];
if (parsed.delivery === 'publish') required.push('prepush', 'push');
const nextAcceptance = createAcceptancePolicy({ required });
const planned = workPlanning.publishWorkPlan(parsed.workUnits, nextAcceptance);
if (planned.error) {
ingest(createEvent(event.agentId, EVENT_KINDS.STATUS, {
text: `assemble refused: ${planned.error}; nobody was started`,
from: 'you',
}));
if (assemblyId) settleAssembly(assemblyId);
return { applied: false, error: planned.error };
}
state.acceptance = nextAcceptance;
store.saveMissionState({ acceptance: state.acceptance, completedAt: null });
for (const previous of activeBeforeRegroup) {
const current = findItem(state.board, previous.id);
if (current?.lease?.workerId === previous.workerId && current.lease.state === 'running') continue;
await interruptWorker(previous.agentId, previous.workerId, { clearCheckpoint: true }).catch(() => {});
}
let applied = 0;
for (const agentId of expected) {
const outcomes = parsed.workUnits
.filter((unit) => unit.stages.some((stage) => stage.required !== false && stage.owner === agentId))
.map((unit) => unit.outcome);
if (outcomes.length === 0) continue;
const objective = `Done when your required stages pass for: ${outcomes.join('; ')}`;
state.goals = setGoal(state.goals, agentId, objective, null, 'active', 'derived');
store.saveGoal(agentId, getGoal(state.goals, agentId));
orders(agentId, objective, ORDER_ACTION.GOAL);
applied += 1;
}
if (named > 0) {
await startCrew(`${event.agentId} assembled ${named} Avengers`, true, crewSpec);
} else if (applied > 0) {
await startCrew(`${event.agentId} set goals for ${applied} agents`);
} else if (assemblyId) {
failAssembly(assemblyId, 'Thor returned a plan with no runnable crew or goals');
return { applied: false, error: 'assemble plan has no runnable crew or goals' };
}
return { applied: true, avengers: named, goals: applied };
}
function harvestReport(event) {
const match = REPORT_BLOCK.exec(String(event.payload?.text ?? ''));
if (!match) return;
let report;
try {
report = JSON.parse(match[1]);
} catch {
return; // a malformed block is not a report; the prose still stands
}
// The fallback has the same destination as the MCP tool: Thor. It is not a
// human decision and must not enter Mac's queue.
const plea = typeof report.escalate === 'string'
? { why: report.escalate, needs: 'unblock' }
: report.escalate;
if (plea?.why && String(plea.why).trim()) {
const need = ['decision', 'unblock', 'conflict'].includes(plea.needs)
? plea.needs
: 'decision';
const worker = event.payload?.workerId
? ensureWorkers(state.agents[event.agentId]).find(
(candidate) => candidate.id === event.payload.workerId,
)
: null;
void coordination.escalate({
fromAgentId: event.agentId,
fromWorkerId: event.payload?.workerId ?? null,
checkpointId: plea.checkpointId ?? worker?.checkpointId ?? null,
needs: need,
why: String(plea.why).trim(),
involvedAgentId: plea.agent ?? null,
receipt: plea.receipt ?? '',
}).catch(() => {});
}
// A worker can ask to stand down, but one worker must not stop every session
// behind a shared seat. Apply that request after checkpoint moves, when the
// server can see whether the whole assigned batch is complete.
const done = report.standDown;
const completedWork = [];
const failedWork = [];
// Gate moves. This is the only way the board changes from a worker, and
// board.mjs refuses anything out of order or without a receipt - so an agent
// cannot report a push over untested code however confidently it tries.
for (const move of report.gates ?? []) {
const reportingWorker = event.payload?.workerId
? ensureWorkers(state.agents[event.agentId])
.find((candidate) => candidate.id === event.payload.workerId)
: null;
const ownedMove = reportingWorker?.checkpointId
? { ...move, item: reportingWorker.checkpointId }
: move;
const result = workBoard.updateCheckpoint(
event.agentId,
ownedMove,
event.payload?.workerId ?? null,
);
if (result.error) continue;
if (result.item.closedAt) completedWork.push(result.item);
if (ownedMove.state === 'fail') failedWork.push({ item: result.item, move: ownedMove });
}
for (const failure of failedWork) {
// Verification can discover new correction work. An implementation
// checkpoint is already that correction work, so a failure stays on it
// and waits for an explicit retry instead of creating repairs forever.
if (!isVerificationCheckpoint(failure.item)) {
const paused = reviseItem(state.board, failure.item.id, {
paused: true,
pauseReason: failure.move.receipt || `${failure.move.gate} failed`,
});
if (!paused.error) {
state.board = paused.board;
store.saveItem(paused.item);
}
if (event.payload?.workerId) workerLeases?.clear(event.payload.workerId);
continue;
}
const discoveries = (report.discoveries ?? [])
.filter((finding) => !finding.checkpointId || finding.checkpointId === failure.item.id);
const findings = discoveries.length ? discoveries : [{
id: `${failure.move.gate}-failure`,
checkpointId: failure.item.id,
title: `Fix ${failure.item.title}`,
outcome: `${failure.item.outcome} passes ${failure.move.gate} verification.`,
scope: failure.item.scope,
files: failure.item.files ?? [],
receipt: failure.move.receipt,
}];
const remediation = workBoard.addRemediation(failure.item.id, findings);
if (remediation.error) {
ingest(createBlockedEvent('minimac', {
category: BLOCKED_REASONS.ERROR,
reason: `could not own failure from ${failure.item.id}: ${remediation.error}`,
}));
}
if (event.payload?.workerId) workerLeases?.clear(event.payload.workerId);
}
for (const claim of report.claims ?? []) {
const text = String(claim?.text ?? claim?.claim ?? '').trim();
if (!text) continue;
ingest(createEvent(event.agentId, EVENT_KINDS.CLAIM, {
...claim, text, workerId: event.payload?.workerId ?? null,
}));
}
const reportingWorker = event.payload?.workerId
? ensureWorkers(state.agents[event.agentId]).find((worker) => worker.id === event.payload.workerId)
: null;
const assignedIds = reportingWorker?.checkpointId
? [reportingWorker.checkpointId]
: activeCheckpointIds(event.agentId);
const assignedDone = assignedIds.length === 0 || assignedIds.every((id) => {
const item = findItem(state.board, id);
return item && isDone(item);
});
const isWorker = state.agents[event.agentId]?.role !== ROLES.ORCHESTRATOR;
const askedToStop = Boolean(done?.why && String(done.why).trim());
const shouldStop = isWorker && (
failedWork.length > 0
|| (assignedDone && (completedWork.length > 0 || askedToStop))
);
if (askedToStop && !assignedDone) {
ingest(createEvent(event.agentId, EVENT_KINDS.STATUS, {
text: `one worker finished its slice: ${String(done.why).trim()}`,
from: 'you',
}));
}
if (shouldStop) {
const why = askedToStop
? String(done.why).trim()
: failedWork.length
? `verification failed on ${failedWork.map(({ item }) => item.id).join(', ')}; correction work is assigned`
: `completed ${completedWork.map((item) => item.id).join(', ')}`;
ingest(createEvent(event.agentId, EVENT_KINDS.STATUS, {
text: `stood down: ${why}`,
from: 'you',
}));
const stop = reportingWorker
? interruptWorker(event.agentId, reportingWorker.id)
: COMMANDS.setActive({ agentId: event.agentId, active: false });
stop
.then(() => {
publish({ type: 'state', state: snapshot() });
scheduleReadyWork();
})
.catch(() => {});
}
}
// Every fenced block an agent may emit. These are payload for the tool, never
// speech: they are parsed here and stripped before anything is shown.
const FENCES = [REPORT_FENCE, WORK_PLAN_FENCE, VERDICT_FENCE];
function partitionAgentOutput(event) {
if (event.kind !== EVENT_KINDS.ENGINE_OUTPUT) return { event, raw: null };
// Draft output is temporary adapter state. Only the complete answer becomes
// a message or is inspected for machine report blocks.
if (event.payload?.final !== true) return { event, raw: null };
const buffer = String(event.payload?.text ?? '');
const { prose, open } = splitFenced(buffer, FENCES, false, true);
// A block that has closed is complete and can be parsed. Nothing is parsed
// while one is still open, which is why a split report used to be dropped.
const raw = open ? null : buffer;
if (!prose || isMachineNoise(prose)) return { event: null, raw };
return { event: { ...event, payload: { ...event.payload, text: prose } }, raw };
}
function identifyWorker(event) {
if (!event?.agentId) return event;
const sessionId = event.payload?.sessionId;
const worker = event.payload?.workerId
? ensureWorkers(state.agents[event.agentId])
.find((candidate) => candidate.id === event.payload.workerId)
: sessionId && workerForSession(state.agents[event.agentId], sessionId);
return worker
? { ...event, payload: { ...event.payload, workerId: worker.id, checkpointId: worker.checkpointId } }
: event;
}
function persistEventWorker(event) {
const workerId = event.payload?.workerId;
if (!workerId) return;
const worker = ensureWorkers(state.agents[event.agentId]).find((candidate) => candidate.id === workerId);
if (worker) store.saveWorkerSession(worker);
}
function acceptsWorkerEvent(event) {
const workerId = event.payload?.workerId;
const sessionId = event.payload?.sessionId;
if (!workerId && !sessionId) return true;
const agent = state.agents[event.agentId];
const worker = workerId
? ensureWorkers(agent).find((candidate) => candidate.id === workerId)
: workerForSession(agent, sessionId);
if (!worker || !isCurrentSessionEvent(worker, event.payload)) return false;
const checkpointId = event.payload?.checkpointId ?? worker.checkpointId;
if (!checkpointId) return true;
if (worker.checkpointId && worker.checkpointId !== checkpointId) return false;
const item = findItem(state.board, checkpointId);
if (!item) return false;
if (item.lease?.workerId && item.lease.workerId !== worker.id) return false;
const terminalWorkerStatus = event.kind === EVENT_KINDS.STATUS
&& [WORKER_STATE.IDLE, WORKER_STATE.STOPPED, WORKER_STATE.FAILED]
.includes(event.payload?.state);
return !isClosed(item) || terminalWorkerStatus;
}
function settleEventLease(event) {
const workerId = event.payload?.workerId;
if (!workerId) return;
const worker = ensureWorkers(state.agents[event.agentId])
.find((candidate) => candidate.id === workerId);
if (!isCurrentSessionEvent(worker, event.payload)) return;
const checkpointId = event.payload?.checkpointId ?? worker.checkpointId;
const item = checkpointId && findItem(state.board, checkpointId);
if (!item?.lease || item.lease.state !== 'running' || item.lease.workerId !== workerId) return;
if (item.lease.sessionId && event.payload?.sessionId
&& item.lease.sessionId !== event.payload.sessionId) return;
const retryAt = event.ts + 15_000;
const settled = isClosed(item)
? reviseItem(state.board, checkpointId, {
lease: finishLease(item.lease, event.payload.state, event.ts),
})
: failCheckpointStart(
state.board,
checkpointId,
`worker ${event.payload.state}; MINIMAC will retry`,
retryAt,
);
if (settled.error) return;
state.board = settled.board;
store.saveItem(settled.item);
if (!isClosed(item)) {
const timer = setTimeout(scheduleReadyWork, Math.max(0, retryAt - Date.now()));
timer.unref?.();
}
}
function hasValidCheckpointReport(event) {
const match = REPORT_BLOCK.exec(blockText(event));
if (!match) return false;
try {
JSON.parse(match[1]);
return true;
} catch {
return false;
}
}
function settleUnreportedResult(event) {
if (hasValidCheckpointReport(event)) return false;
const workerId = event.payload?.workerId;
if (!workerId) return false;
const worker = ensureWorkers(state.agents[event.agentId])
.find((candidate) => candidate.id === workerId);
if (!worker || !isCurrentSessionEvent(worker, event.payload)) return false;
const checkpointId = event.payload?.checkpointId ?? worker.checkpointId;
const item = checkpointId && findItem(state.board, checkpointId);
if (!item?.lease || item.lease.state !== 'running' || item.lease.workerId !== workerId) return false;
const text = blockText(event).trim().replace(/\s+/g, ' ').slice(0, 300);
const settled = reviseItem(state.board, checkpointId, {
lease: finishLease(item.lease, 'unreported', event.ts),
paused: true,
pauseReason: text
? `worker ended without a checkpoint report: ${text}`
: 'worker ended without a checkpoint report',
});
if (settled.error) return false;
workerLeases?.clear(workerId);
state.board = settled.board;
store.saveItem(settled.item);
ingest(createEvent(event.agentId, EVENT_KINDS.STATUS, {
text: `${checkpointId} paused: worker ended without a checkpoint report`,
checkpointId,
workerId,
sessionId: event.payload?.sessionId ?? null,
launchId: event.payload?.launchId ?? null,
from: 'you',
}));
return true;
}
function repeatsUnchangedFact(event, withinMs = 300_000) {
if (![EVENT_KINDS.STATUS, EVENT_KINDS.BLOCKED].includes(event.kind)) return false;
const facts = event.payload ?? {};
const signature = JSON.stringify([
event.agentId, event.kind, facts.state ?? null, facts.text ?? null,
facts.reason ?? null, facts.checkpointId ?? null,
]);
const previous = [...state.events].reverse().find((candidate) =>
candidate.agentId === event.agentId && candidate.kind === event.kind);
if (!previous || event.ts - previous.ts > withinMs) return false;
const prior = previous.payload ?? {};
return signature === JSON.stringify([
previous.agentId, previous.kind, prior.state ?? null, prior.text ?? null,
prior.reason ?? null, prior.checkpointId ?? null,
]);
}
function ingest(rawIncoming) {
const incoming = identifyWorker(rawIncoming);
if (!acceptsWorkerEvent(incoming)) return;
// Engine adapters can announce IDLE before they deliver the turn result.
// IDLE means the session can accept another turn; it does not mean the
// checkpoint lease is over. Closing the lease here made the final report
// arrive one event too late and fail its stable worker-identity check.
if (incoming.kind === EVENT_KINDS.STATUS
&& [WORKER_STATE.STOPPED, WORKER_STATE.FAILED, WORKER_STATE.STALE]
.includes(incoming.payload?.state)) {
const worker = incoming.payload?.workerId
? ensureWorkers(state.agents[incoming.agentId])
.find((candidate) => candidate.id === incoming.payload.workerId)
: workerForSession(state.agents[incoming.agentId], incoming.payload?.sessionId);
if (isCurrentSessionEvent(worker, incoming.payload)) {
workerLeases?.clear(worker.id);
settleEventLease(incoming);
}
}
// A result carries its text in its own envelope and is never split, so it
// goes straight to the parsers.
if (incoming.kind === EVENT_KINDS.RESULT) {
state.events = appendEvent(state.events, incoming);
state.agents = applyFleetEvent(state.agents, incoming);
persistEventWorker(incoming);
store.record(incoming);
publish({
type: 'event',
runId: store.runId,
event: incoming,
agent: publicAgent(state.agents[incoming.agentId]),
});
harvestBlocks(incoming);
settleUnreportedResult(incoming);
scheduleCards();
return;
}
const { event, raw } = partitionAgentOutput(incoming);
// Payload with no prose still has to be parsed - it just is not said aloud.
if (!event) {
if (raw) harvestBlocks({ ...incoming, payload: { ...incoming.payload, text: raw } });
return;
}
if (event.kind === EVENT_KINDS.ENGINE_OUTPUT) {
if (raw) harvestBlocks({ ...event, payload: { ...event.payload, text: raw } });
conversations?.acceptAgentOutput(event, event.payload?.checkpointId
? { kind: CONTEXT_KIND.CHECKPOINT, id: event.payload.checkpointId }
: { kind: CONTEXT_KIND.MISSION, id: String(store.runId) });
return;
}
if (raw !== null) event.payload = { ...event.payload, raw };
if (repeatsUnchangedFact(event)) {
state.agents = applyFleetEvent(state.agents, event);
persistEventWorker(event);
return;
}
state.events = appendEvent(state.events, event);
state.agents = applyFleetEvent(state.agents, event);
persistEventWorker(event);
store.record(event);
publish({
type: 'event',
runId: store.runId,
event,
agent: publicAgent(state.agents[event.agentId]),
});
if (raw !== null) harvestBlocks({ ...event, payload: { ...event.payload, text: raw } });
scheduleCards();
}
// Thor telling a hero something is an event in the ROOM, not just a row in a
// table: the floor walks him over and has him say it. Every outbound act of
// his goes through here, so a goal, an assignment and a ruling all look the
// same on the floor.
let coordination = null;
let conversations = null;
let workspaceQuery = null;
let scheduler = null;
let runtimeSupervisor = null;
let schedulerQueued = false;
function scheduleReadyWork() {
if (!scheduler || schedulerQueued || state.completedAt) return;
schedulerQueued = true;
queueMicrotask(() => {
schedulerQueued = false;
void scheduler.reconcile()
.then((started) => {
if (started.length > 0) publish({ type: 'state', state: snapshot() });
})
.catch((error) => ingest(createBlockedEvent('minimac', {
category: BLOCKED_REASONS.ERROR,
reason: `ready work could not start: ${error.message}`,
})));
});
}
function orders(toAgentId, text, action = ORDER_ACTION.STEER, checkpointId = null) {
const boss = Object.values(state.agents).find((a) => a.role === ROLES.ORCHESTRATOR);
if (!boss || !state.agents[toAgentId] || toAgentId === boss.id) return;
if (!String(text ?? '').trim()) return;
coordination?.order({
fromAgentId: boss.id,