-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.js
More file actions
1945 lines (1849 loc) · 67.6 KB
/
Copy pathmodel.js
File metadata and controls
1945 lines (1849 loc) · 67.6 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
import fs from "node:fs/promises";
import path from "node:path";
import { renderHumanDraftTemplate } from "./draft-template.js";
import { makeId, slugify } from "./ids.js";
import {
appendJsonl,
boardDir,
ensureStore,
goalDir,
ledgerDir,
planDir,
readJson,
readJsonl,
readRegistry,
upsertRegistryEntry,
writeJson
} from "./store.js";
const PLAN_ID_PATTERN = /\b([A-Z]{1,5}-\d+)\b/g;
const NODE_KINDS = ["phase", "loop", "checkpoint", "milestone", "task", "lane", "gate", "lesson"];
const NODE_STATUSES = [
"planned",
"active",
"waiting-human",
"waiting-external",
"blocked",
"gate-ready",
"passed",
"failed",
"done",
"idle",
"closed"
];
const NODE_TERMINAL_STATUSES = ["passed", "failed", "closed"];
const NODE_DONE_STATUSES = ["done", "passed", "closed"];
const NODE_CONTAINMENT = {
root: ["phase"],
phase: ["loop", "checkpoint", "milestone", "task", "lane", "gate", "lesson"],
loop: ["checkpoint", "gate", "task", "lane"],
checkpoint: ["task", "lane", "gate"],
milestone: ["task", "lane", "gate"],
task: [],
lane: [],
gate: [],
lesson: []
};
export async function initGoal(home, { seed, idOptions = {} }) {
if (!seed) throw new Error("goal init requires --seed");
await ensureStore(home);
const now = new Date().toISOString();
const id = makeId("goal", seed, idOptions);
const goal = {
id,
originalSeed: seed,
refined: {
statement: "",
purpose: "",
successProof: "",
constraints: [],
nonGoals: [],
openQuestions: [],
contextGathered: [],
confidence: "low",
phase: "goal-seed"
},
status: "seeded",
createdAt: now,
updatedAt: now
};
await writeJson(path.join(goalDir(home, id), "goal.json"), goal);
await appendJsonl(path.join(goalDir(home, id), "decisions.jsonl"), {
type: "goal-created",
goalId: id,
seed,
at: now
});
await upsertRegistryEntry(home, "goals", {
id,
path: path.join(goalDir(home, id), "goal.json"),
status: goal.status,
updatedAt: now
});
return goal;
}
export async function readGoal(home, goalId) {
return readJson(path.join(goalDir(home, goalId), "goal.json"));
}
export async function addContext(home, goalId, { note, source = "operator" }) {
if (!note) throw new Error("context add requires --note");
const goal = await readGoal(home, goalId);
const event = {
type: "context",
goalId,
source,
note,
at: new Date().toISOString()
};
await appendJsonl(path.join(goalDir(home, goalId), "context.jsonl"), event);
goal.refined.contextGathered.push(note);
goal.updatedAt = event.at;
await writeJson(path.join(goalDir(home, goalId), "goal.json"), goal);
await upsertRegistryEntry(home, "goals", {
id: goal.id,
path: path.join(goalDir(home, goal.id), "goal.json"),
status: goal.status,
updatedAt: goal.updatedAt
});
return event;
}
export async function refineGoal(home, goalId, fields) {
const goal = await readGoal(home, goalId);
const before = structuredClone(goal.refined);
const refined = goal.refined;
assignIfPresent(refined, "statement", fields.statement);
assignIfPresent(refined, "purpose", fields.purpose);
assignIfPresent(refined, "successProof", fields.successProof);
assignIfPresent(refined, "confidence", fields.confidence);
assignIfPresent(refined, "phase", fields.phase);
appendList(refined.constraints, fields.constraint);
appendList(refined.nonGoals, fields.nonGoal);
appendList(refined.openQuestions, fields.openQuestion);
goal.status = "refined";
goal.updatedAt = new Date().toISOString();
await writeJson(path.join(goalDir(home, goalId), "goal.json"), goal);
const decision = {
type: "goal-refined",
goalId,
before,
after: goal.refined,
why: fields.why || "Goal refined after context discovery.",
at: goal.updatedAt
};
await appendJsonl(path.join(goalDir(home, goalId), "decisions.jsonl"), decision);
await upsertRegistryEntry(home, "goals", {
id: goal.id,
path: path.join(goalDir(home, goal.id), "goal.json"),
status: goal.status,
updatedAt: goal.updatedAt
});
return { goal, decision };
}
export async function draftPlan(home, goalId, { from, title, idOptions = {} } = {}) {
const goal = await readGoal(home, goalId);
const sourceText = from
? await fs.readFile(from, "utf8")
: defaultPlanDraft(goal);
const parsed = parseMarkdownPlan(sourceText);
const planTitle = title || parsed.title || `${goal.originalSeed} plan`;
const id = makeId("plan", planTitle, idOptions);
const now = new Date().toISOString();
const dir = planDir(home, id);
const draftPath = path.join(dir, "draft.md");
const plan = {
id,
goalId,
title: planTitle,
status: "draft",
source: {
type: from ? "markdown-file" : "generated-skeleton",
path: from ? path.resolve(from) : draftPath
},
sourceIds: parsed.sourceIds,
sections: parsed.sections,
phases: parsed.phases,
workstreams: parsed.workstreams,
refinedGoalSnapshot: goal.refined,
createdAt: now,
updatedAt: now
};
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(draftPath, sourceText);
await writeJson(path.join(dir, "plan.json"), plan);
await upsertRegistryEntry(home, "plans", {
id,
goalId,
path: path.join(dir, "plan.json"),
status: plan.status,
updatedAt: now
});
return plan;
}
export async function reviewPlan(home, planId, { decision = "approved", note = "" } = {}) {
const plan = await readPlan(home, planId);
const event = {
type: "plan-reviewed",
planId,
goalId: plan.goalId,
decision,
note,
at: new Date().toISOString()
};
plan.status = decision;
plan.updatedAt = event.at;
await writeJson(path.join(planDir(home, planId), "plan.json"), plan);
await appendJsonl(path.join(planDir(home, planId), "decisions.jsonl"), event);
await upsertRegistryEntry(home, "plans", {
id: plan.id,
goalId: plan.goalId,
path: path.join(planDir(home, plan.id), "plan.json"),
status: plan.status,
updatedAt: plan.updatedAt
});
return { plan, event };
}
export async function readPlan(home, planId) {
return readJson(path.join(planDir(home, planId), "plan.json"));
}
export async function enrichPlan(home, planId, { note = "" } = {}) {
const plan = await readPlan(home, planId);
const draftPath = path.join(planDir(home, planId), "draft.md");
const sourcePath = plan.source?.type === "markdown-file" ? plan.source.path : draftPath;
const sourceText = await fs.readFile(sourcePath, "utf8");
const parsed = parseMarkdownPlan(sourceText);
const decisions = await readJsonl(path.join(planDir(home, planId), "decisions.jsonl"));
const now = new Date().toISOString();
plan.title = parsed.title || plan.title;
plan.status = getOpenPlanDecisions(decisions).length > 0 ? "reviewing" : "draft-loop";
plan.sourceIds = parsed.sourceIds;
plan.sections = parsed.sections;
plan.phases = parsed.phases;
plan.workstreams = parsed.workstreams;
plan.enrichmentCount = (plan.enrichmentCount || 0) + 1;
plan.updatedAt = now;
await fs.writeFile(draftPath, sourceText);
await writeJson(path.join(planDir(home, planId), "plan.json"), plan);
await appendJsonl(path.join(planDir(home, planId), "decisions.jsonl"), {
type: "plan-enriched",
planId,
goalId: plan.goalId,
sourceIds: plan.sourceIds,
sections: plan.sections.length,
phases: plan.phases.length,
note,
at: now
});
await upsertRegistryEntry(home, "plans", {
id: plan.id,
goalId: plan.goalId,
path: path.join(planDir(home, plan.id), "plan.json"),
status: plan.status,
updatedAt: plan.updatedAt
});
return plan;
}
export async function addPlanDecision(home, planId, fields) {
if (!fields.note) throw new Error("plan decision requires --note");
const plan = await readPlan(home, planId);
const decisions = await readJsonl(path.join(planDir(home, planId), "decisions.jsonl"));
const existingDecisionCount = decisions.filter((decision) => decision.type === "plan-decision").length;
const event = {
type: "plan-decision",
decisionId: fields.decisionId || `D${String(existingDecisionCount + 1).padStart(3, "0")}`,
planId,
goalId: plan.goalId,
kind: fields.kind || "review-note",
status: fields.status || "open",
sectionId: fields.sectionId || "",
sectionHeading: findSectionHeading(plan, fields.sectionId),
sourceIds: normalizeList(fields.sourceId),
note: fields.note,
resolution: fields.resolution || "",
at: new Date().toISOString()
};
plan.status = "reviewing";
plan.reviewDecisionCount = (plan.reviewDecisionCount || 0) + 1;
plan.updatedAt = event.at;
await writeJson(path.join(planDir(home, planId), "plan.json"), plan);
await appendJsonl(path.join(planDir(home, planId), "decisions.jsonl"), event);
await upsertRegistryEntry(home, "plans", {
id: plan.id,
goalId: plan.goalId,
path: path.join(planDir(home, plan.id), "plan.json"),
status: plan.status,
updatedAt: plan.updatedAt
});
return { plan, event };
}
export async function resolvePlanDecision(home, planId, fields) {
if (!fields.decisionId) throw new Error("plan resolve requires --decision-id");
if (!fields.resolution) throw new Error("plan resolve requires --resolution");
const plan = await readPlan(home, planId);
const decisions = await readJsonl(path.join(planDir(home, planId), "decisions.jsonl"));
const target = decisions.find((decision) =>
decision.type === "plan-decision" && decision.decisionId === fields.decisionId
);
if (!target) throw new Error(`Cannot resolve unknown plan decision ${fields.decisionId}`);
const event = {
type: "plan-decision-resolved",
decisionId: fields.decisionId,
planId,
goalId: plan.goalId,
resolution: fields.resolution,
note: fields.note || "",
at: new Date().toISOString()
};
const nextDecisions = [...decisions, event];
plan.status = getOpenPlanDecisions(nextDecisions).length > 0 ? "reviewing" : "draft-loop";
plan.updatedAt = event.at;
await writeJson(path.join(planDir(home, planId), "plan.json"), plan);
await appendJsonl(path.join(planDir(home, planId), "decisions.jsonl"), event);
await upsertRegistryEntry(home, "plans", {
id: plan.id,
goalId: plan.goalId,
path: path.join(planDir(home, plan.id), "plan.json"),
status: plan.status,
updatedAt: plan.updatedAt
});
return { plan, event };
}
export async function markPlanReady(home, planId, { note = "" } = {}) {
const plan = await readPlan(home, planId);
const decisions = await readJsonl(path.join(planDir(home, planId), "decisions.jsonl"));
const openDecisions = getOpenPlanDecisions(decisions);
if (openDecisions.length > 0) {
throw new Error(`Cannot mark plan ${planId} ready: ${openDecisions.length} open draft review decision(s) remain`);
}
const now = new Date().toISOString();
plan.status = "ready-for-board";
plan.readyAt = now;
plan.readyNote = note;
plan.updatedAt = now;
await writeJson(path.join(planDir(home, planId), "plan.json"), plan);
await appendJsonl(path.join(planDir(home, planId), "decisions.jsonl"), {
type: "plan-ready",
planId,
goalId: plan.goalId,
note,
at: now
});
await upsertRegistryEntry(home, "plans", {
id: plan.id,
goalId: plan.goalId,
path: path.join(planDir(home, plan.id), "plan.json"),
status: plan.status,
updatedAt: plan.updatedAt
});
return plan;
}
export async function compilePlan(home, planId, { idOptions = {} } = {}) {
const plan = await readPlan(home, planId);
if (!plan.goalId) {
throw new Error(`Cannot compile plan ${planId}: missing goalId`);
}
if (plan.status !== "ready-for-board") {
throw new Error(`Cannot compile plan ${planId}: plan status is ${plan.status}, expected ready-for-board`);
}
const goal = await readGoal(home, plan.goalId);
const now = new Date().toISOString();
const boardId = makeId("board", plan.title, idOptions);
const tasks = buildTasks(goal, plan);
const board = {
id: boardId,
goalId: goal.id,
planId: plan.id,
status: "planning",
activeTask: tasks[0]?.id ?? null,
tasks,
createdAt: now,
updatedAt: now
};
await writeJson(path.join(boardDir(home, boardId), "board.json"), board);
await appendJsonl(path.join(boardDir(home, boardId), "events.jsonl"), {
type: "plan-board-created",
goalId: goal.id,
planId: plan.id,
boardId,
at: now
});
await writeCompileReport(home, goal, plan, board);
await upsertRegistryEntry(home, "boards", {
id: boardId,
goalId: goal.id,
planId: plan.id,
path: path.join(boardDir(home, boardId), "board.json"),
status: board.status,
updatedAt: now
});
return { board };
}
export async function startRuntime(home, boardId, { idOptions = {} } = {}) {
const board = await readBoard(home, boardId);
if (board.status !== "approved") {
throw new Error(`Cannot start runtime for board ${boardId}: board status is ${board.status}, expected approved`);
}
const goal = await readGoal(home, board.goalId);
const plan = await readPlan(home, board.planId);
const now = new Date().toISOString();
const ledgerId = makeId("ledger", plan.title, idOptions);
const ledger = {
id: ledgerId,
goalId: goal.id,
planId: plan.id,
boardId,
status: "active",
scheduler: {
callStack: board.activeTask || "idle",
readyQueue: board.tasks.filter((task) => task.id !== board.activeTask).map((task) => task.id),
waitingSet: [],
statusInbox: [],
doneSet: [],
externalWaits: [],
polling: {
status: "active",
reason: "",
blockers: [],
updatedAt: now
}
},
nodes: [],
dispatchPlans: [],
workers: [],
createdAt: now,
updatedAt: now
};
board.status = "runtime-ready";
board.runtimeLedgerId = ledgerId;
board.updatedAt = now;
await writeJson(path.join(boardDir(home, boardId), "board.json"), board);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), {
type: "runtime-started",
goalId: goal.id,
planId: plan.id,
boardId,
ledgerId,
at: now
});
await upsertRegistryEntry(home, "boards", {
id: board.id,
goalId: goal.id,
planId: plan.id,
ledgerId,
path: path.join(boardDir(home, board.id), "board.json"),
status: board.status,
updatedAt: now
});
await upsertRegistryEntry(home, "ledgers", {
id: ledgerId,
goalId: goal.id,
planId: plan.id,
boardId,
path: path.join(ledgerDir(home, ledgerId), "ledger.json"),
status: ledger.status,
updatedAt: now
});
return { board, ledger };
}
export async function readLedger(home, ledgerId) {
return readJson(path.join(ledgerDir(home, ledgerId), "ledger.json"));
}
export async function assignWorker(home, ledgerId, fields) {
const ledger = await readLedger(home, ledgerId);
const now = new Date().toISOString();
const ownsDomain = toBoolean(fields.ownsDomain);
const workerId = fields.workerId || `W${String((ledger.workers || []).length + 1).padStart(3, "0")}`;
const domainTasks = normalizeList(fields.task).map((objective, index) => ({
id: `DT${String(index + 1).padStart(3, "0")}`,
objective,
status: "queued",
createdAt: now,
updatedAt: now
}));
const worker = {
id: workerId,
workerType: fields.workerType || (ownsDomain ? "nested-root" : "child-chat"),
domain: fields.domain || "",
repoRoot: fields.repoRoot || "",
nodeId: fields.nodeId || "",
ownsDomain,
parentLedger: ledgerId,
childLedger: fields.childLedger || "",
thread: fields.thread || "",
status: ownsDomain ? "domain-active" : "waiting",
domainStatus: ownsDomain ? "active" : "none",
domainTasks,
rootActionNeeded: fields.rootActionNeeded || "",
blockedBy: "",
blockedReason: "",
humanResponseNeeded: false,
lastStatus: "",
createdAt: now,
updatedAt: now
};
ledger.workers = [...(ledger.workers || []), worker];
ledger.scheduler = normalizeScheduler(ledger.scheduler);
ledger.scheduler.waitingSet = unique([...ledger.scheduler.waitingSet, worker.id]);
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
const event = {
type: "worker-assigned",
ledgerId,
workerId: worker.id,
workerType: worker.workerType,
domain: worker.domain,
ownsDomain: worker.ownsDomain,
rootActionNeeded: worker.rootActionNeeded,
at: now
};
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, worker, event };
}
export async function addWorkerDomainTask(home, ledgerId, fields) {
if (!fields.workerId) throw new Error("worker task requires --worker-id");
if (!fields.objective) throw new Error("worker task requires --objective");
const ledger = await readLedger(home, ledgerId);
const worker = findWorker(ledger, fields.workerId);
if (!worker.ownsDomain) throw new Error(`Worker ${worker.id} does not own a domain`);
const now = new Date().toISOString();
const task = {
id: fields.taskId || `DT${String((worker.domainTasks || []).length + 1).padStart(3, "0")}`,
objective: fields.objective,
status: "queued",
nodeId: fields.nodeId || "",
sourceIds: normalizeList(fields.sourceId),
createdAt: now,
updatedAt: now
};
worker.domainTasks = [...(worker.domainTasks || []), task];
worker.status = "domain-active";
worker.domainStatus = "active";
worker.blockedBy = "";
worker.blockedReason = "";
worker.humanResponseNeeded = false;
worker.updatedAt = now;
ledger.scheduler = normalizeScheduler(ledger.scheduler);
ledger.scheduler.waitingSet = unique([...ledger.scheduler.waitingSet, worker.id]);
ledger.scheduler.doneSet = ledger.scheduler.doneSet.filter((id) => id !== worker.id);
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
const event = {
type: "domain-task-added",
ledgerId,
workerId: worker.id,
taskId: task.id,
domain: worker.domain,
objective: task.objective,
at: now
};
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, worker, task, event };
}
export async function updateWorkerStatus(home, ledgerId, fields) {
if (!fields.workerId) throw new Error("worker status requires --worker-id");
if (!fields.state && !fields.status) throw new Error("worker status requires --state");
const ledger = await readLedger(home, ledgerId);
const worker = findWorker(ledger, fields.workerId);
const now = new Date().toISOString();
const state = fields.state || fields.status;
const openTasks = openDomainTasks(worker);
worker.lastStatus = state;
worker.lastMessage = fields.message || "";
worker.rootActionNeeded = state === "idle" ? "" : fields.rootActionNeeded || worker.rootActionNeeded || "";
if (state === "blocked") {
worker.blockedBy = fields.blockedBy || worker.blockedBy || "";
worker.blockedReason = fields.blockedReason || fields.message || worker.blockedReason || "";
worker.humanResponseNeeded = isHumanBlock(fields, worker);
} else if (state !== "needs-root") {
worker.blockedBy = "";
worker.blockedReason = "";
worker.humanResponseNeeded = false;
}
worker.updatedAt = now;
ledger.scheduler = normalizeScheduler(ledger.scheduler);
if (worker.ownsDomain) {
if (state === "idle") {
if (openTasks.length > 0) {
throw new Error(`Cannot mark domain ${worker.domain || worker.id} idle: ${openTasks.length} open domain task(s) remain`);
}
worker.status = "domain-idle";
worker.domainStatus = "idle";
} else if (state === "done" && openTasks.length === 0 && !worker.rootActionNeeded && !worker.blockedBy) {
worker.status = "domain-idle";
worker.domainStatus = "idle";
} else if (state === "ready-for-review" && openTasks.length === 0) {
worker.status = "domain-ready-for-close";
worker.domainStatus = "ready-for-close";
worker.rootActionNeeded = worker.rootActionNeeded || "Review domain receipt and decide whether to close or keep the domain idle.";
} else if (state === "blocked" || state === "needs-root" || state === "ready-for-review") {
worker.status = state;
} else {
worker.status = "domain-active";
}
ledger.scheduler.waitingSet = unique([...ledger.scheduler.waitingSet, worker.id]);
ledger.scheduler.doneSet = ledger.scheduler.doneSet.filter((id) => id !== worker.id);
} else {
worker.status = state;
if (state === "done") {
ledger.scheduler.waitingSet = ledger.scheduler.waitingSet.filter((id) => id !== worker.id);
ledger.scheduler.doneSet = unique([...ledger.scheduler.doneSet, worker.id]);
} else {
ledger.scheduler.waitingSet = unique([...ledger.scheduler.waitingSet, worker.id]);
}
}
const event = {
type: "worker-status",
ledgerId,
workerId: worker.id,
state,
status: worker.status,
domain: worker.domain,
ownsDomain: worker.ownsDomain,
openDomainTasks: openTasks.length,
blockedBy: worker.blockedBy,
humanResponseNeeded: worker.humanResponseNeeded,
message: fields.message || "",
rootActionNeeded: worker.rootActionNeeded,
at: now
};
if (["needs-root", "blocked", "ready-for-review"].includes(state) || worker.rootActionNeeded) {
ledger.scheduler.statusInbox = [...ledger.scheduler.statusInbox, event];
}
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, worker, event };
}
export async function completeWorkerDomainTask(home, ledgerId, fields) {
if (!fields.workerId) throw new Error("worker complete-task requires --worker-id");
if (!fields.taskId) throw new Error("worker complete-task requires --task-id");
const ledger = await readLedger(home, ledgerId);
const worker = findWorker(ledger, fields.workerId);
if (!worker.ownsDomain) throw new Error(`Worker ${worker.id} does not own a domain`);
const task = (worker.domainTasks || []).find((candidate) => candidate.id === fields.taskId);
if (!task) throw new Error(`Unknown domain task ${fields.taskId}`);
const now = new Date().toISOString();
task.status = "done";
task.summary = fields.summary || "";
task.verification = fields.verification || "";
task.completedAt = now;
task.updatedAt = now;
const openTasks = openDomainTasks(worker);
if (openTasks.length === 0) {
worker.status = "domain-idle";
worker.domainStatus = "idle";
worker.rootActionNeeded = "";
} else {
worker.status = "domain-active";
worker.domainStatus = "active";
}
worker.blockedBy = "";
worker.blockedReason = "";
worker.humanResponseNeeded = false;
worker.updatedAt = now;
ledger.scheduler = normalizeScheduler(ledger.scheduler);
ledger.scheduler.waitingSet = unique([...ledger.scheduler.waitingSet, worker.id]);
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
const event = {
type: "domain-task-completed",
ledgerId,
workerId: worker.id,
taskId: task.id,
domain: worker.domain,
openDomainTasks: openTasks.length,
rootActionNeeded: worker.rootActionNeeded,
at: now
};
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
const receiptId = await nextReceiptId(home, ledgerId);
await appendJsonl(path.join(ledgerDir(home, ledgerId), "receipts.jsonl"), {
type: "domain-task-receipt",
receiptId,
ledgerId,
workerId: worker.id,
taskId: task.id,
nodeId: task.nodeId || worker.nodeId || "",
summary: task.summary,
verification: task.verification,
at: now
});
await touchLedgerRegistry(home, ledger);
return { ledger, worker, task, event };
}
export async function closeWorkerDomain(home, ledgerId, fields) {
if (!fields.workerId) throw new Error("worker close-domain requires --worker-id");
const ledger = await readLedger(home, ledgerId);
const worker = findWorker(ledger, fields.workerId);
if (!worker.ownsDomain) throw new Error(`Worker ${worker.id} does not own a domain`);
const openTasks = openDomainTasks(worker);
if (openTasks.length > 0) {
throw new Error(`Cannot close domain ${worker.domain || worker.id}: ${openTasks.length} open domain task(s) remain`);
}
const now = new Date().toISOString();
worker.status = "domain-closed";
worker.domainStatus = "closed";
worker.rootActionNeeded = "";
worker.blockedBy = "";
worker.blockedReason = "";
worker.humanResponseNeeded = false;
worker.closedAt = now;
worker.closeNote = fields.note || "";
worker.updatedAt = now;
ledger.scheduler = normalizeScheduler(ledger.scheduler);
ledger.scheduler.waitingSet = ledger.scheduler.waitingSet.filter((id) => id !== worker.id);
ledger.scheduler.doneSet = unique([...ledger.scheduler.doneSet, worker.id]);
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
const event = {
type: "domain-closed",
ledgerId,
workerId: worker.id,
domain: worker.domain,
note: fields.note || "",
at: now
};
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, worker, event };
}
export async function recordHumanResponse(home, ledgerId, fields = {}) {
const ledger = await readLedger(home, ledgerId);
const now = new Date().toISOString();
ledger.scheduler = normalizeScheduler(ledger.scheduler);
const targetIds = normalizeList(fields.workerId);
const affectedWorkers = (ledger.workers || []).filter((worker) =>
isHumanBlockedWorker(worker) && (targetIds.length === 0 || targetIds.includes(worker.id))
);
for (const worker of affectedWorkers) {
worker.status = "needs-root";
worker.humanResponseNeeded = false;
worker.blockedBy = "";
worker.blockedReason = "";
worker.rootActionNeeded = fields.note
? `Process human response: ${fields.note}`
: "Process human response and decide the next action.";
worker.updatedAt = now;
}
const event = {
type: "human-response",
ledgerId,
workerIds: affectedWorkers.map((worker) => worker.id),
note: fields.note || "",
at: now
};
ledger.scheduler.statusInbox = [...ledger.scheduler.statusInbox, event];
ledger.scheduler.polling = {
status: "active",
reason: "Human response recorded; root should drain status inbox before polling again.",
blockers: [],
updatedAt: now,
resumedAt: now
};
ledger.updatedAt = now;
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, event };
}
export async function recordRuntimeWake(home, ledgerId, fields = {}) {
if (!fields.note) throw new Error("runtime wake requires --note");
const ledger = await readLedger(home, ledgerId);
const now = new Date().toISOString();
ledger.scheduler = normalizeScheduler(ledger.scheduler);
const event = {
type: "human-wake",
ledgerId,
note: fields.note,
at: now
};
ledger.scheduler.statusInbox = [...ledger.scheduler.statusInbox, event];
ledger.scheduler.polling = {
status: "active",
reason: "Human input woke an idle runtime; root should decide the next dispatch.",
blockers: [],
updatedAt: now,
resumedAt: now
};
ledger.updatedAt = now;
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, event };
}
export async function recordCodeDispatchPlan(home, ledgerId, fields = {}) {
if (!fields.objective) throw new Error("runtime plan-code requires --objective");
const ledger = await readLedger(home, ledgerId);
const now = new Date().toISOString();
ledger.scheduler = normalizeScheduler(ledger.scheduler);
ledger.dispatchPlans = Array.isArray(ledger.dispatchPlans) ? ledger.dispatchPlans : [];
const route = normalizeDispatchRoute(fields.route || fields.surface || "root");
const plan = {
id: fields.planId || `DP${String(ledger.dispatchPlans.length + 1).padStart(3, "0")}`,
type: "code-dispatch-plan",
objective: fields.objective,
route,
domain: fields.domain || "",
workerId: fields.workerId || "",
repoRoot: fields.repoRoot || "",
worktree: fields.worktree || "",
nodeId: fields.nodeId || "",
ownership: fields.ownership || "",
allowedFiles: normalizeList(fields.allowedFile || fields.allowedFiles),
verification: normalizeList(fields.verify || fields.verification),
reasoning: fields.reasoning || defaultReasoningForRoute(route),
why: fields.why || fields.reason || "",
stopIf: normalizeList(fields.stopIf),
status: "",
missing: [],
createdAt: now,
updatedAt: now
};
plan.missing = dispatchPlanMissingFields(plan);
plan.status = plan.missing.length > 0 ? "needs-boundary" : dispatchPlanReadyStatus(plan.route);
ledger.dispatchPlans = [...ledger.dispatchPlans, plan];
const event = {
type: "code-dispatch-planned",
ledgerId,
planId: plan.id,
objective: plan.objective,
route: plan.route,
status: plan.status,
domain: plan.domain,
workerId: plan.workerId,
nodeId: plan.nodeId,
missing: plan.missing,
rootActionNeeded: plan.status === "needs-boundary"
? `Finish dispatch boundaries before handing off ${plan.id}.`
: `Review and execute code dispatch plan ${plan.id}.`,
at: now
};
ledger.scheduler.statusInbox = [...ledger.scheduler.statusInbox, event];
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, plan, event };
}
export async function recordExternalWait(home, ledgerId, fields = {}) {
if (!fields.nextCheckAt) throw new Error("runtime wait requires --next-check-at");
const ledger = await readLedger(home, ledgerId);
const now = new Date().toISOString();
ledger.scheduler = normalizeScheduler(ledger.scheduler);
const wait = {
id: fields.waitId || `EW${String(ledger.scheduler.externalWaits.length + 1).padStart(3, "0")}`,
status: "waiting",
reason: fields.reason || fields.message || "Waiting for an external timer or event.",
nextCheckAt: fields.nextCheckAt,
resumeOn: fields.resumeOn || "next-check-at",
workerId: fields.workerId || "",
nodeId: fields.nodeId || "",
repo: fields.repo || "",
createdAt: now,
updatedAt: now
};
ledger.scheduler.externalWaits = [...ledger.scheduler.externalWaits, wait];
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
const event = {
type: "external-wait-recorded",
ledgerId,
waitId: wait.id,
reason: wait.reason,
nextCheckAt: wait.nextCheckAt,
at: now
};
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, wait, event };
}
export async function clearExternalWait(home, ledgerId, fields = {}) {
const ledger = await readLedger(home, ledgerId);
const now = new Date().toISOString();
ledger.scheduler = normalizeScheduler(ledger.scheduler);
const waitIds = normalizeList(fields.waitId);
let cleared = 0;
ledger.scheduler.externalWaits = ledger.scheduler.externalWaits.map((wait) => {
if (wait.status !== "waiting") return wait;
if (waitIds.length > 0 && !waitIds.includes(wait.id)) return wait;
cleared += 1;
return {
...wait,
status: "cleared",
clearedAt: now,
clearNote: fields.note || "",
updatedAt: now
};
});
if (cleared === 0) {
throw new Error(waitIds.length > 0 ? `Unknown active external wait ${waitIds.join(", ")}` : "No active external waits to clear");
}
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
const event = {
type: "external-wait-cleared",
ledgerId,
waitIds: waitIds.length > 0 ? waitIds : ["all"],
note: fields.note || "",
at: now
};
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, event };
}
export async function addNode(home, ledgerId, fields = {}) {
const ledger = await readLedger(home, ledgerId);
const now = new Date().toISOString();
ledger.nodes = normalizeNodes(ledger.nodes);
const kind = normalizeNodeKind(fields.kind || "phase");
const parentId = fields.parentId || "";
validateNodeContainment(ledger, parentId, kind);
const node = {
id: fields.nodeId || `N${String(ledger.nodes.length + 1).padStart(3, "0")}`,
parentId,
kind,
title: fields.title || titleForNodeKind(kind),
status: normalizeNodeStatus(fields.state || fields.status || "planned"),
objective: fields.objective || "",
owner: fields.owner || "root",
route: fields.route || "",
children: [],
requiredReceipts: normalizeList(fields.requiredReceipt || fields.requiredReceipts),
receiptRefs: [],
executionRefs: {
workerIds: normalizeList(fields.workerId),
dispatchPlanIds: normalizeList(fields.dispatchPlanId),
waitIds: normalizeList(fields.waitId)
},
decisionGate: null,
humanBlocker: null,
createdAt: now,
updatedAt: now
};
if (ledger.nodes.some((candidate) => candidate.id === node.id)) {
throw new Error(`Node ${node.id} already exists`);
}
ledger.nodes = [...ledger.nodes, node];
refreshNodeStatuses(ledger, now);
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);
const event = {
type: "node-added",
ledgerId,
nodeId: node.id,
parentId: node.parentId,
kind: node.kind,
status: node.status,
at: now
};
await appendJsonl(path.join(ledgerDir(home, ledgerId), "events.jsonl"), event);
await touchLedgerRegistry(home, ledger);
return { ledger, node, event };
}
export async function updateNodeStatus(home, ledgerId, fields = {}) {
if (!fields.nodeId) throw new Error("node status requires --node-id");
const ledger = await readLedger(home, ledgerId);
const node = findNode(ledger, fields.nodeId);
const now = new Date().toISOString();
node.status = normalizeNodeStatus(fields.state || fields.status);
node.statusContext = fields.context || fields.message || "";
node.updatedAt = now;
if (node.status !== "waiting-human") {
node.humanBlocker = null;
}
refreshNodeStatuses(ledger, now);
ledger.updatedAt = now;
refreshPollingState(ledger, now);
await writeJson(path.join(ledgerDir(home, ledgerId), "ledger.json"), ledger);