Repository navigation
Expand file tree
/
Copy pathkernel_lane.js
More file actions
4560 lines (4435 loc) · 303 KB
/
Copy pathkernel_lane.js
File metadata and controls
4560 lines (4435 loc) · 303 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
export const meta = {
name: 'kernel-lane',
description: 'SINGLE-LANGUAGE kernel optimization worker (Director/TechLead/specialist Engineers) with budget-controlled rounds, independent verification, and integration. Optimizes ONE kernel in ONE language (mode=optimize) or authors a fresh seed then optimizes it (mode=author). This is the worker invoked per lane by the kernel-workflow dispatcher (kernel_workflow.js) and by e2e_workflow; prefer calling kernel-workflow directly unless you specifically want one unchanged lane. Target: AMD Instinct MI-series (CDNA gfx942/gfx950), the validated RDNA4 product Radeon AI PRO R9700 (gfx1201) and the RDNA3 Radeon Pro W7900 (gfx1100) — auto-detected on-box; on R9700 use knowledge/amd_rdna4.md, on W7900 knowledge/amd_rdna3.md (wave32, WMMA). Generic gfx1201 without R9700 identity is not a calibrated target; gfx1100 without W7900 identity is refused.',
whenToUse: 'Internal single-language worker. Prefer the kernel-workflow dispatcher (kernel_workflow.js) as the entry point; invoke this directly only to run one unchanged lane. Pass args.kernel_path (required), args.mode, args.target_language, args.budget, args.gpu_ids, args.gpu_mode, args.gpus_per_job, args.job_gpu_ids, args.task.',
phases: [
{ title: 'Setup', detail: 'director builds the isolated eval dir + canonical workspace' },
{ title: 'Author', detail: 'author_engineer writes a fresh optimize-loop seed (only when mode=author); speedup denominator stays the frozen online kernel' },
{ title: 'Analyze', detail: 'tech_lead analyzes kernel + writes roadmap' },
{ title: 'Benchmark', detail: 'benchmark_engineer builds the COMMANDMENT + baseline' },
{ title: 'Profile', detail: 'profile_engineer classifies the bottleneck (only with args.profile=on; off by default)' },
{ title: 'Research', detail: 'OPT-IN (args.dra_enabled): researcher fans research questions out in parallel via native WebSearch/WebFetch, writes a ranked-directions brief the planner seeds from' },
{ title: 'WarmStart', detail: 'search the experience KB by canonical id (geak:kernel:*) — the shared service when credentialed, else the on-disk store, brought level with kb_artifacts/ first — for the best curated patch per optimization direction for this (kernel,language,gfx), validate each through the verify gate, adopt the first that passes [warm_start!=off]' },
{ title: 'Optimize', detail: 'budget loop: tech_lead plans, specialist OR deep_explore engineers optimize, reprofile' },
{ title: 'Verify', detail: 'each candidate patch independently re-benchmarked' },
{ title: 'Merge', detail: 'integrator combines the round winners' },
{ title: 'Report', detail: 'tech_lead writes the final report + patch' },
{ title: 'Validate', detail: 'director independently validates vs the true baseline, then the TechLead curates ONE distilled card into knowledge/learned/ on a measured win [update_experience!=off]' },
],
};
// ---------------------------------------------------------------------------
// Args + defaults. (The script cannot touch the filesystem or read its own
// path; agents do all FS work, and every path is supplied/derived from args —
// nothing about the install location is hard-coded.)
// ---------------------------------------------------------------------------
const A = args || {};
if (A.optimizer != null && typeof A.optimizer !== 'string') {
throw new Error('optimizer must be greedy or evo (a string)');
}
const OPTIMIZER = String(A.optimizer || '').trim().toLowerCase();
if (OPTIMIZER && !['greedy', 'evo'].includes(OPTIMIZER)) {
throw new Error('optimizer must be greedy or evo');
}
if (!A.kernel_path) throw new Error('args.kernel_path is required (absolute path to the kernel/model directory)');
// WORKFLOW_DIR = the directory that holds this script + roles/ + knowledge/ + scripts/.
// A JS workflow script can't read its own path, so the caller passes it (it is just the
// dirname of the scriptPath used to launch the workflow).
const WORKFLOW_DIR = String(A.workflow_dir || '').replace(/\/+$/, '');
if (!WORKFLOW_DIR) {
throw new Error('args.workflow_dir is required: absolute path to the directory containing ' +
'kernel_workflow.js, roles/, knowledge/, scripts/ (i.e. the dirname of this script).');
}
// EXP_ROOT = where timestamped run dirs are written. Default: a sibling "exp/" next to the
// kernel_workflow dir (…/<parent>/kernel_workflow -> …/<parent>/exp). Override with args.exp_root.
const EXP_ROOT = String(A.exp_root || (WORKFLOW_DIR.replace(/\/[^/]*$/, '') + '/exp')).replace(/\/+$/, '');
let EVO = OPTIMIZER === 'evo' ? createEvolution() : null;
let EVO_FALLBACK = null; // set when EVO could not start; the lane then runs as the ordinary lane
const KERNEL_PATH_ORIG = A.kernel_path;
const EXPECTED_GFX = String(A.expected_gfx || '').trim().toLowerCase();
const EXPECTED_TARGET = String(A.expected_target || '').trim().toLowerCase();
const EXPECTED_DEVICE_NAME = String(A.expected_device_name || '').trim();
const EXPECTED_PHYSICAL_CU_COUNT = Number(A.expected_physical_cu_count || 0);
if (['r9700', 'r9600d'].includes(EXPECTED_TARGET) && EXPECTED_GFX !== 'gfx1201') {
throw new Error(`expected_target=${EXPECTED_TARGET} requires expected_gfx=gfx1201`);
}
if (EXPECTED_GFX === 'gfx1200' || EXPECTED_TARGET === 'gfx1200') {
throw new Error('gfx1200 is not supported: this workflow is hardware-validated only on R9700 / gfx1201');
}
// ---- GPU families: keep this block identical in kernel_workflow.js, kernel_lane.js and e2e_workflow.js ----
// Per-GPU-family policy, looked up by ISA. The Workflow sandbox has no import, so each workflow carries
// a copy (kernel_workflow/scripts/test_gpu_family_table.js keeps them identical). An ISA no row
// matches gets GPU_FAMILY_DEFAULT, the Instinct (CDNA) policy. Each workflow reads the fields it needs.
// name how the bake-off Discover prompt names an isolated family (gfx1201 keeps
// upstream's 'R9700' label)
// isolate withhold the MI-series-calibrated inputs (perf_knowledge cards, expert skills, learned
// KB, warm start, tuning skillset); the in-tree guide is the hardware reference
// matrixCore the matrix ISA the prompts name
const GPU_FAMILIES = [
{ name: 'R9700', isa: /^gfx1201$/, isolate: true, matrixCore: 'WMMA' },
// RDNA 3.5 APUs (Strix Halo is gfx1151). Only a gfx1151 Radeon 8060S has been run.
{ name: 'RDNA 3.5', isa: /^gfx115\d$/, isolate: true, matrixCore: 'WMMA' },
// Discrete RDNA3. The workflows accept gfx1100 only as the exact Radeon Pro W7900 (target w7900).
{ name: 'W7900', isa: /^gfx1100$/, isolate: true, matrixCore: 'WMMA' },
];
const GPU_FAMILY_DEFAULT = { name: 'default', isa: null, isolate: false, matrixCore: 'MFMA' };
const gpuFamily = (gfx) => GPU_FAMILIES.find((f) => f.isa.test(String(gfx || ''))) || GPU_FAMILY_DEFAULT;
// ---- end GPU families ----
if (EXPECTED_TARGET === 'w7900' && EXPECTED_GFX !== 'gfx1100') {
throw new Error('expected_target=w7900 requires expected_gfx=gfx1100');
}
if (EXPECTED_GFX === 'gfx1100' && EXPECTED_TARGET !== 'w7900') {
throw new Error(
`expected_gfx=gfx1100 requires expected_target=w7900 (got ${EXPECTED_TARGET || 'none'}): ` +
'no other gfx1100 product is validated');
}
const BUDGET = parseInt(A.budget != null ? A.budget : 6, 10);
// Optional hard cap on optimization rounds (0 / absent = no cap, i.e. unchanged behaviour). Budget
// alone does not bound the round count: the TechLead may spend a budget of 2 as one round of two
// directions or as two rounds of one, which roughly doubles the wall time.
const MAX_ROUNDS = (() => {
const v = parseInt(A.max_rounds != null ? A.max_rounds : 0, 10);
return Number.isFinite(v) && v > 0 ? v : Infinity;
})();
// fast_mode (opt-in, for time-boxed runs such as workshops; absent/false = unchanged behaviour):
// - after the FINAL round, skip the re-profile and the cross-round memory update; their output
// only feeds a next round that will not happen;
// - give optimize engineers a wall-clock time box (engineer_minutes, default 6). Engineers stop on
// stalled STEPS (role + self_monitoring), not on time, and in practice reach most of their gain
// early: on an fp32 GEMM they had ~95% of their final speedup after ~5 min and spent the next
// ~20 min on <1%. A workflow script has no clock, so the box is enforced by the engineer reading
// `date +%s` -- a firm instruction, not a hard kill.
const FAST_MODE = String(A.fast_mode != null ? A.fast_mode : 'false').trim().toLowerCase() === 'true';
const ENGINEER_MINUTES = Math.max(1, parseFloat(A.engineer_minutes != null ? A.engineer_minutes : 6));
function fastModeEngineerBlock(outDir) {
if (!FAST_MODE) return '';
const secs = Math.round(ENGINEER_MINUTES * 60);
return `
## FAST MODE -- HARD TIME BOX (overrides the "Iterate" step and the self-monitoring stop rules)
1. Your FIRST command: \`date +%s > ${outDir}/.t0\`
2. Keep your current best kernel IN KERNEL_PATH (the workspace source file), never only in /tmp or a
scratch copy, and re-save best_patch.diff the moment your best improves.
3. Before starting EACH new experiment run \`echo $(( $(date +%s) - $(cat ${outDir}/.t0) ))\`.
If it prints >= ${secs} (${ENGINEER_MINUTES} min), STOP experimenting.
4. Also STOP when your last 3 benchmarked attempts together improved your best by < 3%, or after
3 consecutive attempts that failed correctness or were slower.
5. Iterate with the quick BENCHMARK command; run FULL_BENCHMARK once, on your final best only.
6. On STOP: workspace holds the best kernel, CORRECTNESS passes, best_patch.diff is saved AND non-empty
(check \`wc -c ${outDir}/best_patch.diff\`; an empty patch is DISCARDED by verify) -> return
the worker_result immediately. A correct result on time beats a marginally faster one delivered late.`;
}
// Minimum verified geomean improvement over the cumulative best for a round winner to be COMMITTED
// into the canonical workspace (default 2%). Kept as a knob rather than a hard-coded constant so the
// gate is tunable per run (e.g. raise it on a noisy box, lower it to bank small compounding wins).
const MIN_IMPROVE = (() => {
const v = parseFloat(A.min_improve != null ? A.min_improve : 0.02);
return Number.isFinite(v) && v >= 0 ? v : 0.02;
})();
// Minimum verified speedup for a candidate to enter the round's candidate list (default 1.0 = only a
// candidate that beats the baseline is worth looking at). A knob for the same reason MIN_IMPROVE is:
// a transcription (plain Triton -> Gluon/TileLang/HIP) lands BELOW the comparator by construction, and
// at 1.0 its recovery phase is invisible -- no patch saved, no verify, `winner` null every round. The
// COMMIT gate is separate and still requires beating `cumulative` by MIN_IMPROVE, so a sub-baseline
// candidate can be TRACKED but never BANKED.
const CANDIDATE_FLOOR = (() => {
const v = parseFloat(A.candidate_floor != null ? A.candidate_floor : 1.0);
return Number.isFinite(v) && v > 0 ? v : 1.0;
})();
// Rendered into the Optimize prompt, where `${1.0}` would stringify to "1" and silently reword a
// prompt that has always said "geomean>1.0". Keeps the default run byte-identical.
const CANDIDATE_FLOOR_TXT = Number.isInteger(CANDIDATE_FLOOR)
? CANDIDATE_FLOOR.toFixed(1) : String(CANDIDATE_FLOOR);
// How far BELOW the best candidate ever seen a round may land and still count as "the search is
// advancing" (default +MIN_IMPROVE = the historical test). A knob because a climb that starts under
// the comparator advances for many rounds without ever clearing `cumulative`, and scoring those as
// stalls ends it at MAX_NO_IMPROVE however much budget was given -- and no static counter substitutes,
// since it would have to pre-guess how many rounds the climb takes. Negative admits a round that gives
// ground (a layout experiment that does not pay is information, not a stall).
const PROGRESS_DELTA = (() => {
const v = parseFloat(A.progress_delta != null ? A.progress_delta : MIN_IMPROVE);
return Number.isFinite(v) && v > -1 ? v : MIN_IMPROVE;
})();
// Budget cost of ONE `deep_explore` direction. The deep-explore engineer does far more than a single
// specialist — broad rewrite authority, its own multi-iteration measure→profile→rewrite loop — so it
// is charged more than 1 against the direction budget (default 2). It also always runs in a DEDICATED
// round (no other directions that round), enforced below.
const DEEP_COST = (() => {
const v = parseInt(A.deep_cost != null ? A.deep_cost : 2, 10);
return Number.isFinite(v) && v >= 1 ? v : 2;
})();
// PD gpu_ids `decode:3`: every GPU_ID passed on names the engine again.
const GPU_IDS_ARG = String(A.gpu_ids != null ? A.gpu_ids : '0').trim();
const GPU_ENGINE = (/^([\w.-]+):(?=\d)/.exec(GPU_IDS_ARG) || [])[1] || '';
const onEngine = spec => (GPU_ENGINE && spec ? `${GPU_ENGINE}:${spec}` : spec);
const GPU_IDS = GPU_ENGINE ? GPU_IDS_ARG.slice(GPU_ENGINE.length + 1) : GPU_IDS_ARG;
const GPU_LIST = GPU_IDS.split(',').map(s => s.trim()).filter(Boolean);
// Every GPU consumer gets the WHOLE pool rather than a pinned lane. gpu_lock.sh
// resolves a comma spec by flocking whichever lane is free AND idle at acquire
// time, so placement follows what work actually costs instead of an index fixed
// before the cost is known. Measured task costs span 23x on campaign20, and a
// pinned round ends with the slowest LANE, not the slowest task -- at 4-way that
// idles ~43% of lane time. Pinning is also fragile on a shared box: GPU_LIST[0]
// has no fallback when lane 0 has a foreign tenant.
// gpu_mode='pin' restores the pre-scheduler behavior (direction i pinned to GPU_LIST[i % n]).
// It exists ONLY so the scheduler can be A/B'd as a single-variable change against the arm it
// replaced; leaving it out would make the "before" arm unreachable and force the comparison to be
// made across two different scripts, where any other drift would be indistinguishable from the
// scheduler's effect. Default 'pool'.
const GPU_MODE = String(A.gpu_mode || 'pool') === 'pin' ? 'pin' : 'pool';
// Multi-GPU jobs (multi-rank ops). gpus_per_job > 1 leases any N GPUs of gpu_ids per command
// (gpu_lock.sh pool:N:<ids>); job_gpu_ids pins one fixed group (group:<ids>). Either may also come
// from op_spec.resource. Without any of them the count is what Setup found in the task's own
// test/benchmark (`detected`, see scripts/detect_gpu_requirement.py). Every GPU consumer then gets
// that one spec, so each command holds the whole group. One GPU per job leaves everything unchanged.
// Setup's finding is a static hint: one that cannot run in gpu_ids (unknown, no usable count, more
// GPUs than the pool) keeps the lane single-GPU with a warning. Only an explicit request throws.
function resolveGpuRequest(A, gpuList, detected) {
const resource = (A.op_spec && A.op_spec.resource) || {};
const parseIds = (name, value) => {
const parts = String(value).split(',').map(s => s.trim()).filter(Boolean);
if (!parts.length) throw new Error(`${name} must contain at least one GPU id`);
if (parts.some(id => !/^\d+$/.test(id))) throw new Error(`${name} contains a non-numeric GPU id`);
const ids = parts.map(id => String(Number(id)));
if (new Set(ids).size !== ids.length) throw new Error(`${name} contains duplicate GPU ids`);
return ids;
};
const pool = parseIds('gpu_ids', gpuList.join(','));
const fixedValue = String(A.job_gpu_ids || '').trim() || resource.job_gpu_ids;
const fixedIds = String(fixedValue || '').trim() ? parseIds('job_gpu_ids', fixedValue) : [];
const explicit = A.gpus_per_job != null || resource.gpus_per_job != null || fixedIds.length > 0;
const found = (!explicit && detected) || {};
let foundCount = found.kind === 'scalable' ? pool.length : 1;
let problem = '';
if (found.kind === 'unknown') {
problem = 'Setup found multi-GPU code in this task but could not tell how many GPUs one run needs';
} else if (found.kind === 'fixed') {
const n = Number(found.gpus_per_job);
if (!Number.isSafeInteger(n) || n < 1) {
problem = `Setup reported no usable GPU count (${found.gpus_per_job})`;
} else if (n > pool.length) {
problem = `Setup found ${n} GPUs per run but gpu_ids holds ${pool.length}`;
} else {
foundCount = n;
}
}
const warning = problem ? `${problem} (${found.evidence || 'no evidence'}); running single-GPU. ` +
'Pass gpus_per_job=<N> (or job_gpu_ids) with enough gpu_ids to run it on N GPUs.' : '';
const countValue = A.gpus_per_job != null ? A.gpus_per_job
: (resource.gpus_per_job != null ? resource.gpus_per_job : (fixedIds.length || foundCount));
const countText = String(countValue).trim();
if (!/^[1-9]\d*$/.test(countText)) throw new Error('gpus_per_job must be a positive integer');
const gpusPerJob = Number(countText);
if (!Number.isSafeInteger(gpusPerJob)) throw new Error('gpus_per_job is too large');
if (fixedIds.length && fixedIds.length !== gpusPerJob) {
throw new Error(`gpus_per_job=${gpusPerJob} does not match job_gpu_ids size ${fixedIds.length}`);
}
if (!fixedIds.length && gpusPerJob > pool.length) {
throw new Error(`gpus_per_job=${gpusPerJob} exceeds gpu_ids pool size ${pool.length}; ` +
`pass gpu_ids with at least ${gpusPerJob} GPUs`);
}
if (fixedIds.some(id => !pool.includes(id))) throw new Error('job_gpu_ids must be a subset of gpu_ids');
const jobSpec = fixedIds.length ? `group:${fixedIds.join(',')}`
: (gpusPerJob > 1 ? `pool:${gpusPerJob}:${pool.join(',')}` : '');
return { gpusPerJob, fixedIds, jobSpec, explicit, warning };
}
// Validated now so a bad request fails before Setup; re-resolved from Setup's finding when implicit.
let GPU_RESOURCE = null;
let GPU_JOB = '';
let GPU_POOL = '';
let GPU_SINGLE = '';
function applyGpuResource(r) {
GPU_RESOURCE = r;
GPU_JOB = onEngine(r.jobSpec);
GPU_POOL = GPU_JOB || onEngine(GPU_MODE === 'pin' ? GPU_LIST[0] : GPU_LIST.join(','));
GPU_SINGLE = GPU_JOB || onEngine(GPU_LIST[0]);
}
applyGpuResource(resolveGpuRequest(A, GPU_LIST));
// A multi-GPU task delivered by the UT module (A22): set after Setup, once the GPU count is final,
// when that count is above 1 AND the task's own declaration (Setup's task_declaration) says more than
// one GPU. Only such a job gets the multi-rank prompts, receipts, lease and agent time limits; every
// other job, single- or multi-GPU, runs exactly as before. UT_TOTAL_S is its whole-UT time limit (s).
let UT_MR = false;
let UT_TOTAL_S = 0;
const TASK = A.task || '';
const EVAL_DIR_OVERRIDE = A.eval_dir || '';
const APPLY_TO_ORIGINAL = String(A.apply_to_original != null ? A.apply_to_original : 'false');
const KERNEL_NAME_HINT = KERNEL_PATH_ORIG.replace(/\/+$/, '').split('/').pop();
// --- author mode: when there is NO existing source, write a fresh from-scratch SEED first, then optimize it.
// mode=optimize (default) keeps the exact original behavior (backward compatible). mode=author seeds
// the workspace from an op task dir (immutable oracle + frozen online kernel in baseline_src/), the
// author_engineer writes a passing seed, then the SAME optimize loop runs — always timing against the
// frozen online kernel, never against the seed's own language. KERNEL_KNOWLEDGE_DIR is the AMD authoring
// knowledge base — REFERENCE ONLY (facts/how-to, never decisions; the author always measures regardless). Default:
// sibling perf_knowledge/ so standalone runs use it too; empty if WORKFLOW_DIR is unset (no behavior change).
const MODE = String(A.mode != null ? A.mode : 'optimize').trim() || 'optimize';
const TARGET_LANGUAGE = String(A.target_language != null ? A.target_language : 'triton').trim() || 'triton';
const OP_SPEC = A.op_spec || {};
// When the op will run on the CUDA/HIP-graph-captured decode path (e2e sets op_spec.cuda_graph_safe=true),
// the isolated oracle alone CANNOT catch a kernel that passes iso but host-syncs or lazily-compiles under
// graph capture — the "wins isolated, crashes serving" class (cuda_graph_capture_unsafe / NO_BINARY_FOR_GPU).
// This turns on an OPTIONAL capture+replay smoke in the verify step so that failure is caught at the cheap
// isolated stage. Unset (standalone single-kernel runs / non-graph ops) => byte-identical to before.
const REQUIRE_GRAPH_CAPTURE = !!(OP_SPEC && OP_SPEC.cuda_graph_safe === true);
// WORKLOAD ALIGNMENT (optional). When the caller supplies the real-workload shape/dtype case
// distribution, the benchmark harness benchmarks EXACTLY those (shape, dtype) cases, weights each
// by its total time contribution in the workload (weight = count * baseline_latency), and the
// optimization target becomes the time-weighted ratio-of-sums instead of an unweighted geomean.
// workload_spec_path : path to a workload-v1 json (produced by parse_profile.py --workload-out,
// or hand-written). The benchmark_engineer reads it (JS can't touch FS).
// op_spec.workload : inline cases, same shape as a workload-v1 "kernels[].cases" list (or the
// full object). Takes precedence; weight_source becomes "caller".
// Both unset => unweighted behavior, byte-identical to before. Correctness ALWAYS stays on the
// frozen immutable oracle (parity vs baseline_src/, + a recorded reference_io.pt where the task dir
// came from e2e's kernel_extractor); this only shapes the PERFORMANCE measurement.
const WORKLOAD_SPEC_PATH = String(A.workload_spec_path || (OP_SPEC && OP_SPEC.workload_path) || '').trim();
const WORKLOAD_SPEC = (OP_SPEC && OP_SPEC.workload) || A.workload || null;
const HAS_WORKLOAD = !!(WORKLOAD_SPEC_PATH ||
(Array.isArray(WORKLOAD_SPEC) && WORKLOAD_SPEC.length) ||
(WORKLOAD_SPEC && Array.isArray(WORKLOAD_SPEC.kernels) && WORKLOAD_SPEC.kernels.length));
// PRIMARY-metric selector: prefer the time-weighted number when a workload spec is in play and the
// agent reported one; otherwise fall back to the geomean (unweighted runs => unchanged behavior).
const primSpeedup = (o) => {
if (!o) return 0;
const w = o.verified_weighted != null ? o.verified_weighted
: (o.speedup_weighted != null ? o.speedup_weighted : null);
if (HAS_WORKLOAD && Number.isFinite(w)) return w;
const g = o.verified_geomean != null ? o.verified_geomean : o.speedup_geomean;
return Number.isFinite(g) ? g : 0;
};
// Gate fields like `correctness` / `status` are free strings in the schemas, so an agent legitimately
// answers "PASS - 15/15 draws" and a `=== 'pass'` test silently drops a genuinely verified candidate.
// Match the leading word instead: "PASS - ..." / "passed" gate open, "FAIL"/"did not pass" stay shut.
const says = (v, w) => String(v == null ? '' : v).trim().toLowerCase().startsWith(w);
let KERNEL_KNOWLEDGE_DIR = String(A.perf_knowledge_dir ||
(WORKFLOW_DIR ? WORKFLOW_DIR.replace(/\/[^/]*$/, '') + '/perf_knowledge' : '')).replace(/\/+$/, '');
// Expert skills = human-authored, validated kernel recipes (perf_knowledge/expert_skills/). ADVISORY
// priors only: a matched `validated` skill is a HIGH-PRIOR author/optimize candidate the planning/author
// roles reproduce, then gate by the isolated A/B vs the oracle — it NEVER overrides measurement. Default
// OFF (opt-in: pass use_expert_skills="true"). When OFF (the default) NOTHING is injected -> byte-identical
// to a build without this feature. When invoked by the e2e layer the flag + dir are passed down.
const USE_EXPERT_SKILLS_REQUESTED = String(A.use_expert_skills != null ? A.use_expert_skills : 'false') === 'true';
let USE_EXPERT_SKILLS = USE_EXPERT_SKILLS_REQUESTED;
const EXPERT_SKILLS_DIR = String(A.expert_skills_dir ||
(KERNEL_KNOWLEDGE_DIR ? KERNEL_KNOWLEDGE_DIR + '/expert_skills' : '')).replace(/\/+$/, '');
// Only planning + authoring roles consult skills; every other role gets no injection.
const EXPERT_SKILL_ROLES = new Set(['tech_lead', 'author_engineer', 'engineer', 'deep_engineer']);
// Expected-identity isolation must apply before Setup (no CDNA skills/KB on a declared isolated run).
// Detected identity is OR'd in after director setup — do not read GFX here (TDZ).
let SKILLS_ISOLATE = gpuFamily(EXPECTED_GFX).isolate;
// --- Deep Research Agent (DRA) -------------------------------------------------------------------
// OPT-IN: a v4-native research phase that runs AFTER Profile and BEFORE the optimize loop (so the
// COMMANDMENT + baseline profile + analysis exist). The `researcher` persona extracts facts and a
// ranked set of research QUESTIONS; the script fans those out in PARALLEL (each question = one
// hang-guarded agent using native WebSearch/WebFetch), then a synthesis pass writes a ranked
// directions portfolio (deep_search.md / deep_search_brief.md / deep_search.json) into EVAL_DIR that
// the TechLead's plan_round seeds from. DEFAULT OFF: when dra_enabled is not "true" NOTHING runs and
// behavior is byte-identical to a build without this feature (existing runs unchanged).
const DRA_ENABLED = String(A.dra_enabled != null ? A.dra_enabled : 'false') === 'true';
const DRA_MAX_QUESTIONS = (() => {
const v = parseInt(A.dra_max_questions != null ? A.dra_max_questions : 8, 10);
return Number.isFinite(v) && v >= 1 ? v : 8;
})();
// Optional Stage 5/6 blindspot-critique pass (one more parallel research wave). Default OFF (budget).
const DRA_BLINDSPOT = String(A.dra_blindspot != null ? A.dra_blindspot : 'false') === 'true';
const DRA_MAX_BLINDSPOTS = (() => {
const v = parseInt(A.dra_max_blindspots != null ? A.dra_max_blindspots : 4, 10);
return Number.isFinite(v) && v >= 1 ? v : 4;
})();
// ---------------------------------------------------------------------------
// LEARNED-KNOWLEDGE SINK. Derived from WORKFLOW_DIR and nothing else, so a lane spawned by
// e2e_workflow still curates into kernel_workflow/knowledge/learned/ — e2e's learned/ is a
// separate memory owned by its own system_architect step.
// update_experience = on (default) | off | false | none
// The bake-off dispatcher passes `off` and curates once centrally instead (N parallel lanes would
// file N near-duplicate cards for one op).
const LEARNED_DIR = `${WORKFLOW_DIR}/knowledge/learned`;
// How much of ONE round the learned KB may steer. Measured, not guessed: an arm whose planner was
// handed at most 3 matched cards and could KB-seed at most one direction reached 4.45x geomean on 16
// kernels; the same 16 under a planner that reads the whole 84-line index and picks freely reached
// 3.44x — a 22.7% regression, with the losses concentrated on kernels where the bounded arm had found
// an unusual win (one went 25.77x -> 2.15x). Both arms averaged ~3 rounds, so it was not lost rounds.
// The index-reading design is better at RECALL; what it lost was the profile-driven direction that
// nothing from the KB had touched — the per-round control. `knowledge/learned/README.md` says the KB
// must be "an accelerant, NOT a cage", and this is the line that keeps that true.
// KB_DIR_CAP directions per round that may draw on cards (default 1)
// KB_COLD_DIRECTION at least one direction per round must be profile-only (default on)
// Whether the planner is being pointed at the learned KB at all. Defined HERE because this lane is
// where it is USED: the constant of this name lives in the dispatcher, and referencing it from the
// lane threw `USE_LEARNED_READ is not defined` at the first plan step of every kernel — 13 of them
// before the run was stopped. A parse test cannot catch that: the file compiles, and the reference
// only resolves when the line runs. Default ON, matching this branch's design where the tech_lead
// role reads INDEX.md unconditionally; `use_learned_kb=false` turns the budget block off with it.
let USE_LEARNED_READ = String(A.use_learned_kb != null ? A.use_learned_kb : 'true') === 'true';
const KB_DIR_CAP = Math.max(0, parseInt(A.kb_dir_cap != null ? A.kb_dir_cap : 1, 10));
const KB_COLD_DIRECTION = String(A.kb_cold_direction != null ? A.kb_cold_direction : 'true') === 'true';
let kbCapBound = 0; // rounds where the cap actually had to strip something
const UPDATE_EXPERIENCE = String(A.update_experience != null ? A.update_experience : 'on').trim().toLowerCase() || 'on';
const UPDATE_EXPERIENCE_ON = UPDATE_EXPERIENCE !== 'off' && UPDATE_EXPERIENCE !== 'false' && UPDATE_EXPERIENCE !== 'none';
// Did the CALLER freeze this kernel through oracle_freezer? Only the bake-off dispatcher does, so this
// tells director whether a GEAK_TIMING_RECEIPT is producible at all before it gates on one. Must be an
// ARG: this file never runs Freeze itself, and a workflow script has no filesystem access to go looking.
const FROZEN_ORACLE = String(A.frozen_oracle != null ? A.frozen_oracle : 'false') === 'true';
// ---------------------------------------------------------------------------
// WARM-START (the experience KB). Before the optimize loop, search the machine-produced KB —
// addressed by canonical id on both planes — for the top-3 best patches for THIS (kernel, language,
// gfx), validate each through the SAME verify_engineer gate, and adopt the first that passes; after
// write this run's own win back.
// on (default) | read + validate top-3, ADOPT the first that passes.
// reference | read top-3 as prose only, never auto-apply.
// return_after_read | adopt then RETURN before the optimize loop.
// off/false/none, a STATE_DIR resume, or no arch => cold start (byte-identical to pre-feature).
const WARM_START = String(A.warm_start != null ? A.warm_start : 'on').trim().toLowerCase() || 'on';
let WARM_START_ON = WARM_START !== 'off' && WARM_START !== 'false' && WARM_START !== 'none';
if (SKILLS_ISOLATE) {
KERNEL_KNOWLEDGE_DIR = '';
USE_LEARNED_READ = false;
WARM_START_ON = false;
USE_EXPERT_SKILLS = false;
}
const WARM_START_REF_ONLY = WARM_START === 'reference';
const WARM_START_RETURN_AFTER = WARM_START === 'return_after_read';
const KB_ARTIFACTS_DIR = String(A.kb_artifacts_dir ||
(WORKFLOW_DIR ? WORKFLOW_DIR.replace(/\/[^/]*$/, '') + '/kb_artifacts' : '')).replace(/\/+$/, '');
const EXPERIENCE_STORE = `${WORKFLOW_DIR}/scripts/experience_store.py`;
// Every candidate costs a full on-box verify to reject, so a recorded near-tie is not worth reading.
const WARM_START_MIN_SPEEDUP = Number.isFinite(parseFloat(A.warm_start_min_speedup))
? parseFloat(A.warm_start_min_speedup) : 1.05;
// How hard the resolver may work to map this run's kernel name onto a stored page. The name is
// layout-derived (`fused_moe_kernel` standalone, `fused_moe_kernel_task` from an e2e head extraction),
// so `exact` alone would make the head path miss its own history; `fuzzy` also accepts an op_kind.
const WARM_START_MATCH = ['exact', 'normalized', 'fuzzy'].includes(String(A.warm_start_match || '').trim())
? String(A.warm_start_match).trim() : 'fuzzy';
// Which PLANE the experience is READ from. Same phases, same schemas, same verify gate either way
// — only the command string differs, because the store subcommands were built to print the same
// JSON as the directory ones.
// store (default) a KB Store on disk, in the shape the service uses, keyed by canonical id.
// local the kb_artifacts/ tree, keyed by slug. The original scheme, kept as an escape
// hatch for a box whose store is unusable.
//
// `store` is the default because it is the SAME addressing the service uses. Two schemes side by
// side drifted — `resolve` and `resolve-remote` assembled their filter chains separately, which is
// how the keyed read lost the `--include-retired` the slug read always had. Nothing moves: the tree
// is still written (`write-remote --plane both`) and `sync-local` carries the backlog across before
// each read; the tree stays the assembly buffer and the surface a curation pass edits.
const KB_MODE = String(A.kb_mode || 'store').trim().toLowerCase() === 'local' ? 'local' : 'store';
const KB_STORE_DIR = String(A.kb_store_dir ||
(KB_ARTIFACTS_DIR ? KB_ARTIFACTS_DIR.replace(/\/[^/]*$/, '') + '/kb_store_local' : '')).replace(/\/+$/, '');
// The key carries a rocm <major>.<minor>; on a box without /opt/rocm the measured stack is empty and
// every record would file under `unspecified`, which splits one kernel's history across two keys.
const KB_FRAMEWORK_VERSION = String(A.kb_framework_version || '').trim();
const KB_VERSION_FLAG = KB_FRAMEWORK_VERSION ? ` --framework-version ${JSON.stringify(KB_FRAMEWORK_VERSION)}` : '';
const KB_ROOT_OK = KB_MODE === 'store' ? !!KB_STORE_DIR : !!KB_ARTIFACTS_DIR;
// Whether this run may also talk to the KB Store SERVICE, on top of whichever local plane KB_MODE
// selected. `auto` (default) uses it when credentials are present and silently does not when they
// are not; `off` restores the directory-only behaviour byte for byte.
const KB_REMOTE = String(A.kb_remote || 'auto').trim().toLowerCase() === 'off' ? 'off' : 'auto';
// The credentials are NOT visible from this process. They live in the user's profile, and the
// shells these commands run in are non-interactive, so `process.env.KB_STORE_TOKEN` is empty here
// even on a box where the service is configured. Deciding the plane in JS would therefore mean
// deciding it wrong. Instead every emitted command exports its own credentials from the profile's
// two sources and then branches on what it actually got — the test happens where the answer is
// knowable. The token is read from a 0600 file into a variable, never passed in argv, because
// `ps` is world-readable on this box.
// The gateway's internal AMD CA is not in a stock container trust store, so a KB command run inside
// one fails TLS (the old workaround was `curl -k`). DETECT then heal: only when the caller has NOT
// already established trust (SSL_CERT_FILE unset) do we point urllib/requests/curl/node at the first
// readable AMD-root bundle we find. Most callers here run OUTSIDE the warm-start launcher (which sets
// these at `docker run`), so this self-heal is what keeps their KB reachable. Path-only, no CA
// content; overridable with KB_CA_BUNDLE; a no-op when SSL_CERT_FILE is already set or no bundle is
// readable (so CI and already-trusting images are byte-identical). DNS (the host has none
// in-container) is a launch concern, handled with `docker run --add-host`.
// GEAK_KB_STORE_* wins over the bare KB_STORE_* (so a host that also runs Hyperloom, which carries
// its own KB_STORE_*, can point GEAK at a distinct store); re-exported under the bare names every
// downstream reader here branches on.
const KB_ENV_PRELUDE =
'export KB_STORE_URL="${GEAK_KB_STORE_URL:-${KB_STORE_URL:-https://global.primus-safe.amd.com/knowledge-base}}"; ' +
'export KB_STORE_TOKEN="${GEAK_KB_STORE_TOKEN:-${KB_STORE_TOKEN:-$(cat ~/.geak_kb_token 2>/dev/null)}}"; ' +
'if [ -z "${SSL_CERT_FILE:-}" ]; then for _ca in "${KB_CA_BUNDLE:-}" ' +
'/shared_nfs/hyperloom/ca/amd-ca-combined.pem "$HOME/amd-extra-ca-bundle.pem"; do ' +
'[ -n "$_ca" ] && [ -r "$_ca" ] && { export SSL_CERT_FILE="$_ca" REQUESTS_CA_BUNDLE="$_ca" ' +
'CURL_CA_BUNDLE="$_ca" NODE_EXTRA_CA_CERTS="$_ca"; break; }; done; fi; ';
// Writing in store mode records BOTH planes in one call, so it needs both roots: the directory tree
// stays the source of truth a curation pass edits, and the store is derived from it.
const KB_WRITE_OK = KB_ROOT_OK && !!KB_ARTIFACTS_DIR;
const kebab = s => String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60);
// ---------------------------------------------------------------------------
// DEEP-MODE continuation + cross-backend / e2e-feedback hooks. ALL OPTIONAL.
// When none are passed (every normal/fast e2e run, and every standalone run) these are '' / the
// current defaults and are NEVER threaded into a prompt — so behavior is byte-identical to the
// pre-feature build. They are set ONLY by e2e_workflow's deep_mode head scheduler.
// STATE_DIR a STABLE dir for THIS (kernel,backend) ACROSS deep waves. When set the run
// RESUMES: director seeds the canonical from STATE_DIR/best (the cumulative-best
// code) and returns prior_state (cumulative + history) so re-invocation CONTINUES
// instead of restarting (no lost experience, no re-explored directions). The frozen
// oracle baseline (immutable unittest.py/meta.json) stays the reference, so speedups
// remain comparable to the TRUE baseline across waves. update_memory writes STATE.json
// + syncs best/ each round.
// SHARED_KB cross-backend blackboard file (read by plan+engineers, appended by update_memory).
// GLOBAL_KB run-global cross-KERNEL technique blackboard (deep): techniques that generalize
// across head ops/backends. Optional; unset (default/fast) => byte-identical prompts.
// E2E_FEEDBACK path to the latest end-to-end A/B result + problems from e2e_workflow (engaged?,
// cudagraph behavior, mem footprint, decode regression, e2e delta) — steers planning.
// HARNESS_ADDENDUM path to an e2e-refined harness addendum (timing-weight / cudagraph-capture / hard
// constraint gates). The IMMUTABLE oracle is NEVER touched; this only refines what the
// perf bench emphasizes so the isolated target aligns with e2e.
// MAX_NO_IMPROVE consecutive non-improving rounds before stopping (default 2 = current behavior).
const STATE_DIR = String(A.state_dir || '').replace(/\/+$/, '');
const SHARED_KB = String(A.shared_kb || '').trim();
const GLOBAL_KB = String(A.global_kb || '').trim(); // run-global cross-KERNEL technique blackboard (deep)
const E2E_FEEDBACK = String(A.e2e_feedback || '').trim();
const HARNESS_ADDENDUM = String(A.harness_addendum || '').trim();
// P2 (deep continuation): on a RESUMED wave (STATE_DIR holds prior work) the cold re-derivation of
// Analyze + baseline Profile is largely redundant. INCREMENTAL_RESUME tells those two ADVISORY agents to
// load the prior roadmap/profile and return it with only delta updates instead of re-deriving from
// scratch, so each burst spends its budget on optimization ROUNDS, not re-analysis. Benchmark is NEVER
// incremental (it re-pins a fresh in-window baseline every wave \u2014 the matched-A/B correctness rail).
// Unset (default/fast / first deep burst) => spreading {} adds nothing => byte-identical prompts.
const INCREMENTAL = !!STATE_DIR && String(A.incremental_analyze || '') === 'true';
const RESUME_INPUT = INCREMENTAL ? { INCREMENTAL_RESUME: '1' } : {};
const MAX_NO_IMPROVE = Math.max(1, parseInt(A.max_no_improve != null ? A.max_no_improve : 2, 10));
// Conditional inputs: spreading {} adds NOTHING to a prompt (byte-identical) when a hook is unset.
const KB_INPUTS = {
...(SHARED_KB ? { SHARED_KB } : {}),
...(GLOBAL_KB ? { GLOBAL_KB } : {}),
...(E2E_FEEDBACK ? { E2E_FEEDBACK } : {}),
...(HARNESS_ADDENDUM ? { HARNESS_ADDENDUM } : {}),
};
// ---------------------------------------------------------------------------
// Reusable JSON-schema fragments.
// ---------------------------------------------------------------------------
const perCase = {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string' },
baseline_ms: { type: 'number' },
optimized_ms: { type: 'number' },
speedup: { type: 'number' },
// Workload-alignment fields (present only when a WORKLOAD_SPEC drives the harness; absent
// on a normal unweighted run). weight = this case's baseline time SHARE in the real workload;
// it is the coefficient of the time-weighted metric Σweight / Σ(weight/speedup). count is
// optional/informational (regime-attributed cases have no per-call count).
weight: { type: 'number' },
count: { type: 'number' },
dims: { type: 'array', items: { type: 'array', items: { type: 'number' } } },
dtypes: { type: 'array', items: { type: 'string' } },
weight_source: { type: 'string' }, // trace | regime | regime_floor | prior | caller
},
required: ['name', 'speedup'],
},
};
const obj = (props, required) => ({ type: 'object', properties: props, required: required || [], additionalProperties: true });
const SETUP_SCHEMA = obj({
eval_dir: { type: 'string' }, workspace: { type: 'string' }, baseline_dir: { type: 'string' },
kernel_name: { type: 'string' },
device_gfx: { type: 'string' },
device_target: { type: 'string' },
device_name: { type: 'string' },
physical_cu_count: { type: 'number' },
source_files: { type: 'array', items: { type: 'string' } }, notes: { type: 'string' },
// Frozen-baseline verdict (BOTH modes). The unittest's timing + random-value parity baseline MUST be
// the real online kernel — the immutable baseline_src/ dir OR an importable meta.baseline_callable —
// never kernel_src/ (the candidate's own scaffold). The director sets baseline_frozen=true after it
// copies baseline_src/ + confirms meta.baseline_callable; the script aborts the run if neither holds.
baseline_frozen: { type: 'boolean' }, baseline_callable: { type: 'string' },
// GPUs one run of the task's test/benchmark needs (roles/director.md "GPU requirement").
gpu_requirement: obj({
kind: { type: 'string', enum: ['single', 'fixed', 'scalable', 'unknown'] },
gpus_per_job: { type: 'number' }, evidence: { type: 'string' },
}, ['kind']),
// What the task itself declares, verbatim from `detect_gpu_requirement.py --declaration <task dir>`
// (always run, also when the GPU count is explicit): its GPU count (null = none) and whole-UT limit.
task_declaration: obj({
required_gpu_count: { type: ['number', 'null'] }, ut_total_s: { type: 'number' },
evidence: { type: 'array', items: { type: 'string' } },
}, ['required_gpu_count', 'ut_total_s', 'evidence']),
// DEEP-MODE resume only: populated by the director ONLY when STATE_DIR was provided AND a prior best
// exists there. Lets a continued wave restore its cumulative speedup + insight/ledger history so it
// does not re-explore dead directions. Absent (undefined) on a fresh run -> no behavior change.
resumed: { type: 'boolean' },
prior_state: obj({
cumulative: { type: 'number' }, insights: { type: 'array', items: { type: 'string' } },
ledger: { type: 'array', items: { type: 'object', additionalProperties: true } },
bottleneck_now: { type: 'string' }, best_per_case: perCase,
}, []),
}, ['eval_dir', 'workspace', 'kernel_name', 'device_gfx', 'device_target', 'physical_cu_count', 'task_declaration']);
const AUTHOR_SCHEMA = obj({
authored: { type: 'boolean' }, target_language: { type: 'string' }, correctness: { type: 'string' },
baseline_ms: { type: 'number' }, kernel_src_path: { type: 'string' }, entry_point: { type: 'string' },
build: { type: 'boolean' }, notes: { type: 'string' },
}, ['authored', 'correctness']);
const ANALYZE_SCHEMA = obj({
kernel_type: { type: 'string' }, kernel_file: { type: 'string' }, entry_point: { type: 'string' },
modifiable_files: { type: 'array', items: { type: 'string' } },
bottleneck_guess: { type: 'string' }, roadmap_summary: { type: 'string' },
candidate_directions: { type: 'array', items: { type: 'object', additionalProperties: true } },
// perf_knowledge resolution (REFERENCE ONLY): the operator/language this kernel maps to in the
// AMD perf_knowledge base, plus the most relevant card paths, so engineers read focused context
// instead of re-navigating the whole base. Empty string / [] / null when no card applies.
kk_operator: { type: ['string', 'null'] }, kk_language: { type: ['string', 'null'] },
kk_refs: { type: 'array', items: { type: 'string' } },
}, ['kernel_type', 'roadmap_summary']);
const BENCH_SCHEMA = obj({
commandment_path: { type: 'string' }, correctness_cmd: { type: 'string' },
benchmark_cmd: { type: 'string' }, profile_cmd: { type: 'string' }, parse_hint: { type: 'string' },
baseline_per_case: { type: 'array', items: { type: 'object', additionalProperties: true } },
baseline_geomean_ms: { type: 'number' }, num_test_cases: { type: 'number' },
// Workload-aligned outputs: present when a WORKLOAD_SPEC drove case selection + weights.
// baseline_weighted_total_ms = the baseline time the weights represent (Σ weight_i in time units).
// The metric is Σ weight_i / Σ (weight_i/speedup_i). workload_aligned flags weights are real (not 1).
workload_aligned: { type: 'boolean' },
baseline_weighted_total_ms: { type: 'number' },
weights_provenance: { type: 'string' }, // e.g. "trace" | "regime" | "regime_floor" | "prior" | "caller" | "mixed"
reliable: { type: 'boolean' }, notes: { type: 'string' },
}, ['commandment_path', 'baseline_per_case', 'baseline_geomean_ms']);
const PROFILE_SCHEMA = obj({
bottleneck: { type: 'string' }, profiler_used: { type: 'string' }, dispatch_count: { type: 'number' },
// The accelerator detected on-box (e.g. "MI300X / gfx942 / CDNA3, 304 CU, ~5.3 TB/s"), so the
// roofline ceiling + grid-sizing advice downstream use the real card instead of an assumed MI300X.
device: { type: 'string' },
key_metrics: { type: 'object', additionalProperties: true },
top_kernels: { type: 'array', items: { type: 'object', additionalProperties: true } },
top_opportunities: { type: 'array', items: { type: 'string' } },
summary_path: { type: 'string' }, shift_note: { type: 'string' },
}, ['bottleneck', 'top_opportunities']);
// --- Deep Research Agent (DRA) schemas (opt-in via args.dra_enabled) -------
// Stage 0+1/2: the researcher extracts facts and returns a ranked set of research QUESTIONS the
// script then fans out in parallel. Stages 3/4: one answer per question (run concurrently). Stage 5:
// optional blindspot critique. Stage 7: the ranked-directions portfolio + brief the planner consumes.
const RESEARCH_PLAN_SCHEMA = obj({
facts: { type: 'object', additionalProperties: true },
questions: {
type: 'array',
items: obj({
id: { type: 'string' }, question: { type: 'string' },
search_queries: { type: 'array', items: { type: 'string' } },
rationale: { type: 'string' }, tests_hypothesis: { type: 'string' },
mode: { type: 'string', enum: ['bottleneck', 'design_space'] },
rank_score: { type: 'number' },
}, ['question']),
},
notes: { type: 'string' },
}, ['questions']);
const RESEARCH_QUESTION_SCHEMA = obj({
question_id: { type: 'string' }, question: { type: 'string' },
mode: { type: 'string' }, tests_hypothesis: { type: 'string' },
answer: { type: 'string' },
status: { type: 'string', enum: ['prefer', 'deprioritize', 'reject', 'open'] },
affected: { type: 'array', items: { type: 'string' } },
evidence: { type: 'array', items: { type: 'object', additionalProperties: true } },
taskgen_implications: { type: 'string' }, notes: { type: 'string' },
}, ['answer', 'status']);
const RESEARCH_BLINDSPOT_SCHEMA = obj({
blindspots: {
type: 'array',
items: obj({
description: { type: 'string' }, why_it_matters: { type: 'string' },
follow_up_question: { type: 'string' },
}, ['description']),
},
}, ['blindspots']);
// Stage 7 final portfolio. `directions` is kept COMPACT here (mirrors deep_search_brief.md): the
// planner reads the brief on disk, so this structured echo is just for logging/validation.
const RESEARCH_SCHEMA = obj({
num_questions: { type: 'number' }, num_directions: { type: 'number' },
brief_path: { type: 'string' }, full_path: { type: 'string' }, json_path: { type: 'string' },
directions: {
type: 'array',
items: obj({
id: { type: 'string' }, title: { type: 'string' },
specialty: { type: 'string', enum: ['algorithm', 'memory', 'compute', 'host_runtime', 'deep_explore'] },
mechanism: { type: 'string' }, expected_upside: { type: 'string' },
confidence: { type: 'string', enum: ['high', 'medium', 'low'] },
rank_score: { type: 'number' },
}, ['title']),
},
notes: { type: 'string' },
}, ['num_directions', 'brief_path']);
const PLAN_SCHEMA = obj({
stop: { type: 'boolean' }, reasoning: { type: 'string' },
directions: {
type: 'array',
items: obj({
id: { type: 'string' }, title: { type: 'string' },
specialty: { type: 'string', enum: ['algorithm', 'memory', 'compute', 'host_runtime', 'deep_explore'] },
focus_files: { type: 'array', items: { type: 'string' } },
expected_speedup: { type: 'number' }, prompt: { type: 'string' },
kk_refs: { type: 'array', items: { type: 'string' } }, // optional: perf_knowledge card paths for THIS direction (REFERENCE ONLY)
// Learned cards that SEEDED this direction, by filename. Structural attribution: the planner
// declares what it opened, the script joins that against what the VERIFIER independently
// measured. Declared here rather than inferred because the read path is semantic — the planner
// reads INDEX.md and judges by meaning, so nothing downstream can reconstruct which card it
// acted on. A citation is not a causal claim (the planner saw the profile too, and one run
// holds no counterfactual); it is the only way a card can ever LOSE standing.
learned_refs: { type: 'array', items: { type: 'string' } },
}, ['id', 'title', 'specialty', 'prompt']),
},
}, ['stop', 'directions']);
if (EVO) {
PLAN_SCHEMA.properties.directions.items.properties.parent_id = { type: 'string' };
PLAN_SCHEMA.properties.directions.items.properties.donor_ids = { type: 'array', items: { type: 'string' } };
}
const ENG_SCHEMA = obj({
engineer_id: { type: 'string' }, specialty: { type: 'string' }, task: { type: 'string' },
strategy: { type: 'string' }, speedup_geomean: { type: 'number' }, speedup_arithmetic: { type: 'number' },
// Time-weighted ratio-of-sums vs the TRUE baseline (PRIMARY metric when workload_aligned).
// = Σ weight_i / Σ (weight_i / speedup_i). Omitted on unweighted runs.
speedup_weighted: { type: 'number' },
per_case: perCase, status: { type: 'string' }, patch_file: { type: 'string' },
measurement_valid: { type: 'boolean' },
strategies_tried: { type: 'array', items: { type: 'string' } }, notes: { type: 'string' },
}, ['status', 'speedup_geomean', 'measurement_valid']);
const VERIFY_SCHEMA = obj({
status: { type: 'string' }, correctness: { type: 'string' },
verified_geomean: { type: 'number' }, verified_arithmetic: { type: 'number' },
verified_weighted: { type: 'number' }, // time-weighted ratio-of-sums (PRIMARY when workload_aligned)
per_case: perCase, variance_note: { type: 'string' }, notes: { type: 'string' },
graph_safe: { type: 'string' },
}, ['status', 'verified_geomean']);
const INTEGRATE_SCHEMA = obj({
attempted: { type: 'boolean' },
combos_tried: { type: 'array', items: { type: 'object', additionalProperties: true } },
best: { type: 'object', additionalProperties: true },
improved_over_best_individual: { type: 'boolean' },
conclusion: { type: 'string' }, notes: { type: 'string' },
}, ['attempted', 'conclusion']);
const MEMORY_SCHEMA = obj({
insights: { type: 'array', items: { type: 'string' } },
ledger: { type: 'array', items: { type: 'object', additionalProperties: true } },
bottleneck_now: { type: 'string' }, suggest_next: { type: 'string' },
}, ['insights']);
const COMMIT_SCHEMA = obj({
committed: { type: 'boolean' }, current_best_diff: { type: 'string' }, note: { type: 'string' },
}, ['committed']);
// eikos v2 E1 (R4 round-4 / Astra re-review #4): the round-3 PRECOMMIT_SCHEMA + RECOVERY_SCHEMA were
// removed with the restore-and-continue recovery they served. ABORT-AND-QUARANTINE neither snapshots a
// pre-attempt reference nor dispatches a restore, so no schema is needed for the failed-commit path.
// eikos v2 E1 (R9 / Astra re-review #10, Finding 2 — SHORTEST ROUTE): the round-7/8 host-side deterministic
// commit fallback (its fixed-script dispatch, its result schema, and its observed-postcondition acceptance
// predicate) have been REMOVED. Astra reproduced that a host-side install can only ever be accepted on
// AGENT-REPORTED evidence: a patch that merely APPLIES does not prove identity with the verified candidate;
// the committed-tree equivalence was computed from the CURRENT HEAD, not a pinned verified baseline; and the
// acceptance predicate consumed the returned flags/strings — she obtained acceptance with an empty reported
// post-HEAD. Rather than build a full install proof we take her explicit shortest route: there is NO host-side
// apply/commit path anymore. An unconfirmed commit is QUARANTINED + RETAINED (the verified winner stays
// recoverable) and is never installed from self-reported evidence, so no commit-fallback schema is needed.
const REPORT_SCHEMA = obj({
final_speedup_geomean: { type: 'number' }, final_speedup_arithmetic: { type: 'number' },
final_speedup_weighted: { type: 'number' }, // time-weighted ratio-of-sums (PRIMARY when workload_aligned)
rounds: { type: 'number' }, budget_used: { type: 'number' },
report_path: { type: 'string' }, final_patch: { type: 'string' }, per_case: perCase,
}, ['final_speedup_geomean', 'report_path', 'final_patch']);
const UPDATE_EXPERIENCE_SCHEMA = obj({
action: { type: 'string' }, // created | merged | skipped
card_path: { type: 'string' }, // path under knowledge/learned/, or "" if nothing distilled
key: { type: 'string' }, note: { type: 'string' },
}, []);
const VALIDATE_SCHEMA = obj({
kernel_name: { type: 'string' },
director_verified_speedup_geomean: { type: 'number' },
director_verified_speedup_arithmetic: { type: 'number' },
director_verified_speedup_weighted: { type: 'number' }, // PRIMARY when workload_aligned
tech_lead_reported_speedup_geomean: { type: 'number' },
validation_status: { type: 'string' }, correctness: { type: 'string' },
// clean | host_bound | unprimed | unknown | not_applicable. Declared so the relaying agent has no
// reason to drop it -- the gate calls it REQUIRED so a speedup never travels downstream unlabelled.
timing_basis: { type: 'string' },
per_case: perCase, applied_to_original: { type: 'string' },
arbitration_note: { type: 'string' }, final_patch: { type: 'string' },
}, ['director_verified_speedup_geomean', 'validation_status']);
// ---------------------------------------------------------------------------
// Multi-rank receipts (A01). In a UT-module multi-GPU task (UT_MR) every rank of the UT times the
// case, and one merged number hides how the ranks were aligned and which rank set the pace. These
// variants replace BENCH/REPORT/VALIDATE_SCHEMA only in such a job; any other call still passes
// the objects above, unchanged. The receipt has the shape of the UT's own GEAK_TIMING_RECEIPT
// (geak_timing_receipt/v2): {world_size, alignment, cases: {<sig>: {baseline: {ms, rank_ms},
// current: {ms, rank_ms}}}}; an older multi-rank UT's per_rank_us/step_us/alignment map onto it.
// ---------------------------------------------------------------------------
const rankArr = { type: 'array', items: { type: 'number' } };
// One leg of one case: the merged time (per sample the slowest rank, then the median) + each rank's
// when the UT reports them (null when it reports only the merged time).
const rankLeg = obj({ ms: { type: 'number' }, rank_ms: { type: ['array', 'null'], items: { type: 'number' } } }, ['ms']);
const timingReceipt = {
type: ['object', 'null'],
properties: {
version: { type: 'string' }, world_size: { type: 'number' }, source: { type: 'string' },
alignment: { type: ['object', 'null'], additionalProperties: true },
cases: { type: 'object', additionalProperties: obj({ baseline: rankLeg, current: rankLeg }, ['baseline']) },
},
required: ['world_size', 'cases'],
additionalProperties: true,
};
const perCaseMR = {
...perCase,
items: {
...perCase.items,
properties: {
...perCase.items.properties,
// Each rank's time for this case (ms, rank order) and how the ranks were aligned before every
// sample and merged into baseline_ms / optimized_ms.
baseline_rank_ms: rankArr, optimized_rank_ms: rankArr,
alignment: { type: 'object', additionalProperties: true },
},
},
};
const BENCH_SCHEMA_MR = obj({
...BENCH_SCHEMA.properties,
// rank_ms / alignment are REQUIRED but nullable: null says the UT gave no per-rank time or no
// alignment method for the case (then reliable=false), instead of one merged time copied per rank.
baseline_per_case: { type: 'array', items: obj({
name: { type: 'string' }, latency_ms: { type: 'number' },
rank_ms: { type: ['array', 'null'], items: { type: 'number' } },
alignment: { type: ['object', 'null'], additionalProperties: true },
}, ['name', 'latency_ms', 'rank_ms', 'alignment']) },
rank_timing_source: { type: 'string' },
}, [...BENCH_SCHEMA.required, 'reliable']);
const REPORT_SCHEMA_MR = obj({ ...REPORT_SCHEMA.properties, per_case: perCaseMR, timing_receipt: timingReceipt },
REPORT_SCHEMA.required);
const VALIDATE_SCHEMA_MR = obj({ ...VALIDATE_SCHEMA.properties, per_case: perCaseMR, timing_receipt: timingReceipt },
[...VALIDATE_SCHEMA.required, 'timing_receipt']);
// The consumer check for all three places (Benchmark record, director receipt, lane return). A merged
// time on every timed case is required; each rank's time and the alignment method are recorded when
// the UT reports them, and their absence is a note, not a failure (a hand-written UT may report only
// the merged, slowest-rank time). benchRankGap / receiptGap return the hard gap ('' when none);
// benchRankNote / receiptNote name what per-rank detail is missing ('' when complete).
const timeOk = (x) => typeof x === 'number' && Number.isFinite(x) && x > 0;
const rankTimesOk = (a, ranks) => Array.isArray(a) && a.length === ranks && a.every(timeOk);
const alignmentOk = (a) => !!a && typeof a === 'object' && !Array.isArray(a) && Object.keys(a).length > 0;
const legGap = (leg, ranks, what) => !leg || !rankTimesOk(leg.rank_ms, ranks) ? `no per-rank ${what} times`
: !timeOk(leg.ms) ? `no merged ${what} time (ms)` : '';
function benchRankGap(cases) {
if (!Array.isArray(cases) || !cases.length) return 'no baseline case was recorded';
for (const c of cases) {
const name = c && c.name != null ? c.name : '?';
if (!c || !timeOk(c.latency_ms)) return `baseline case ${name} has no merged time (latency_ms)`;
}
return '';
}
function benchRankNote(cases, ranks) {
const noRanks = [], noAlign = [];
for (const c of Array.isArray(cases) ? cases : []) {
const name = c && c.name != null ? c.name : '?';
if (!c || !rankTimesOk(c.rank_ms, ranks)) noRanks.push(name);
if (!c || !alignmentOk(c.alignment)) noAlign.push(name);
}
return [noRanks.length ? `no per-rank times (rank_ms of ${ranks}) for case(s) ${noRanks.join(', ')}` : '',
noAlign.length ? `no alignment method for case(s) ${noAlign.join(', ')}` : ''].filter(Boolean).join('; ');
}
function receiptGap(receipt, ranks, needCurrent) {
if (!receipt || typeof receipt !== 'object') return 'no timing_receipt';
if (Number(receipt.world_size) !== ranks) return `timing_receipt world_size is ${receipt.world_size}, not ${ranks}`;
const cases = receipt.cases && typeof receipt.cases === 'object' ? Object.entries(receipt.cases) : [];
if (!cases.length) return 'timing_receipt has no timed case';
for (const [sig, c] of cases) {
if (!c || !c.baseline || !timeOk(c.baseline.ms)) return `case ${sig} has no merged baseline time (ms)`;
const cur = c.current || c.candidate;
if (needCurrent && (!cur || !timeOk(cur.ms))) return `case ${sig} has no merged candidate time (ms)`;
}
return '';
}
function receiptNote(receipt, ranks, needCurrent) {
if (!receipt || typeof receipt !== 'object') return '';
const notes = alignmentOk(receipt.alignment) ? [] : ['no alignment method'];
const cases = receipt.cases && typeof receipt.cases === 'object' ? Object.entries(receipt.cases) : [];
for (const [sig, c] of cases) {
if (legGap(c && c.baseline, ranks, 'baseline')) notes.push(`case ${sig}: no per-rank baseline times`);
if (needCurrent && legGap(c && (c.current || c.candidate), ranks, 'candidate'))
notes.push(`case ${sig}: no per-rank candidate times`);
}
return notes.join('; ');
}
// The Benchmark's complete baseline record in receipt shape: what the lane returns when the director's
// own receipt is missing or incomplete, so the baseline receipt survives a failed validation.
function benchReceipt(cases, ranks, source) {
return {
world_size: ranks,
source: `Benchmark baseline_per_case${source ? ` (${source})` : ''}`,
alignment: cases[0].alignment ?? null,
cases: Object.fromEntries(cases.map((c) => [String(c.name),
{ baseline: { ms: c.latency_ms, rank_ms: c.rank_ms ?? null } }])),
};
}
// Warm-start resolver output = experience_store.py `resolve` JSON, verbatim.
const WARMSTART_RESOLVE_SCHEMA = obj({
read_reason: { type: 'string' }, slug: { type: 'string' },
// What this run's name derived to vs the page actually served, so a surprising match is visible.
requested_slug: { type: 'string' }, match_tier: { type: 'string' },
// store mode only: the key the candidates came from. Declared rather than left to
// additionalProperties so the agent relaying this JSON has no reason to drop it.
canonical_id: { type: 'string' },
// Which of the keyed read's planes answered ("remote" | "local"). Both are addressed by canonical
// id, so this is the ONLY field telling them apart — and the attest step picks its flags from it.
read_plane: { type: 'string' },
// Same kernel, another language: the wrong target_language was passed, not an empty store.
other_language_pages: { type: 'array', items: { type: 'string' } },
filtered: obj({
total: { type: 'number' }, retired: { type: 'number' }, below_min_speedup: { type: 'number' },
same_direction_collapsed: { type: 'number' }, demoted_by_hint: { type: 'number' },
// The caveat on every number above: the service pages `--scan` rows, so a saturated read
// describes a prefix of the page and reads identically to a thin page.
scanned: { type: 'number' }, scan_saturated: { type: 'boolean' },
}),
candidates: {
type: 'array',
items: obj({
rank: { type: 'number' }, slug: { type: 'string' }, speedup: { type: 'number' },
exp_dir: { type: 'string' }, arch: { type: 'string' },
// Declared for the same reason canonical_id is: without it the attest step below has no
// address to write this run's verdict back to.
session_id: { type: 'string' },
patch_path: { type: 'string' }, prose_path: { type: 'string' },
strategy: { type: 'string' }, status: { type: 'string' },
// direction = the IDEA (one rank each). comparable=false: recorded on a different bench key
// than rank 1's, so the order between them is a prior only.
direction: { type: 'string' }, bench_key: { type: 'string' }, comparable: { type: 'boolean' },
}, ['rank', 'patch_path']),
},
}, ['read_reason']);
// Warm-start writer output = experience_store.py `write` JSON, verbatim. written=false with reason
// "duplicate_impl" is a success: the store already held this code and counted a reproduction.
const WARMSTART_WRITE_SCHEMA = obj({
written: { type: 'boolean' }, reason: { type: 'string' }, slug: { type: 'string' },
dir: { type: 'string' }, speedup: { type: 'number' },
reproduced: { type: 'string' }, reproductions: { type: 'number' },
// store mode only: where the same result landed on the KB plane. `replaced` says which of the
// two outcomes it was — a new candidate under the key, or this patch's own one measured again.
remote: obj({
written: { type: 'boolean' }, reason: { type: 'string' }, canonical_id: { type: 'string' },
session_id: { type: 'string' }, champion: { type: 'boolean' }, replaced: { type: 'boolean' },
}),
}, ['written']);
// ---------------------------------------------------------------------------
// Prompt helpers. Every agent reads its role file from WORKFLOW_DIR and the
// relevant knowledge files itself; the script only passes paths + JSON inputs.
// ---------------------------------------------------------------------------
const cfg = (o) => Object.entries(o).map(([k, v]) =>
`- ${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`).join('\n');
// --- Hung-agent guard ------------------------------------------------------
// An agent LLM call that HANGS (no response, no terminal error) blocks a
// parallel()/pipeline() round-barrier forever (observed: engineer agents frozen
// mid-turn wedged the whole optimize round for >30min). The harness resolves
// terminal API errors to null but NOT an indefinite hang. So bound every agent()
// call: if it has not returned after AGENT_TIMEOUT_MS, resolve it to null (which
// every .filter(Boolean)/null-check downstream already tolerates) and let the
// round proceed. VERY generous default (3h): a true hang never returns, so this only fires on a
// hang, NEVER on a legitimately-long agent. Inner agents include benchmark/profile/verify that build
// (hipcc/ninja) and run benches, plus the LLM-heavy optimize engineers (the ones observed hanging).
// On a prepared extract UT one full run takes 20-40 min, so a MOE verify (one run + patch/build/
// correctness) plus a wait for another lane's GPU lock is ~95 min; a non-weighted UT still runs 3x
// in benchmark setup (~135 min). 60min killed every such lane (GEAK #606). Keep it under the
// standalone runtime's 4h spawn backstop (run_workflow.mjs), which must stay the longer of the two.
// Cache keys (prompt, opts) are unchanged so resume still works. Falls back to raw agent() if
// setTimeout is unavailable. args.agent_timeout_ms=0 disables.
// API-FAULT TOLERANCE: a transient API failure (gateway 4xx/5xx, rate-limit, dropped connection, the
// model API going down mid-run) must NOT crash the whole workflow. agentT retries the call up to
// AGENT_RETRIES times on a thrown API/agent error, then resolves to null (every .filter(Boolean)/
// null-check downstream — incl. the Director validate + final report — already degrades on null rather
// than exiting). A timeout (hang) resolves null immediately and is NOT retried (a real hang would just
// burn another full timeout window). args.agent_retries tunes the count. If the failure is PERSISTENT
// (e.g. an auth/header requirement the client doesn't send), retries are exhausted then the run
// degrades — re-run with Workflow({resumeFromRunId}) once the client/API is fixed; cached agent results
// make resume cheap.
const AGENT_TIMEOUT_MS = parseInt(A.agent_timeout_ms != null ? A.agent_timeout_ms : 10800000, 10);
// The wait limit agentT applies: AGENT_TIMEOUT_MS, widened after Setup only for a UT-module multi-GPU
// task (UT_MR) so that an agent's up to 3 full UT runs + 2 fit (Benchmark runs an unweighted UT 3
// times, a weighted oracle once); 0 (off) stays off. For such a task the limit can exceed the
// standalone runtime's 4h spawn backstop named above; the backstop then ends the agent first, so
// start that runtime with --agent-timeout-ms at or above the wait limit the lane logs.
let AGENT_WAIT_MS = AGENT_TIMEOUT_MS;
const AGENT_RETRIES = Math.max(1, parseInt(A.agent_retries != null ? A.agent_retries : 4, 10));
// Labels whose agent the guard gave up on. The agent is still running; stopAfterTimeout() reads this.
const TIMED_OUT_LABELS = new Set();
// GEAK-ABLATION-ARMS-v1 (B6): registered mechanical dispatches are folded into the NEXT
// agent instead of getting an agent of their own. In the historical Qwen3 run the
// storage-reclaim agent -- whose whole job is to run one fixed bash command -- cost
// 152 calls across 8 agents ($13.90), because every one of them paid the full
// bootstrap floor and then held a conversation. Folding removes the dispatch; the
// command still runs, verbatim, as the next agent's first action.
const ABLATION_ARM = String(A.ablation_arm || '').trim().toUpperCase();
const ABL_B6 = ABLATION_ARM === 'B6';
const ABL_PENDING = [];
const ABL_DRAINED = [];
function ablDrainPrelude() {
if (!ABL_PENDING.length) return '';
const cmds = ABL_PENDING.splice(0, ABL_PENDING.length);
for (const c of cmds) ABL_DRAINED.push(c);
return '## FIRST, run these registered maintenance commands EXACTLY as written, then continue with your task.\n' +
cmds.map((c) => '```bash\n' + c + '\n```').join('\n') + '\n\n';
}
// LLM token+time accounting (PURELY ADDITIVE; args.llm_stats="false" makes it a no-op).
// DELIBERATELY NO TIMESTAMPS: Date.now()/new Date() are unavailable in workflow scripts. Every
// duration in the report comes from the transcripts (scripts/llm_ledger.py); this records only the
// role/phase/attempt identity of each agent call so the ledger attributes tokens to the right agent.
const LLM_STATS = String(A.llm_stats != null ? A.llm_stats : 'true').trim().toLowerCase() !== 'false';
const LLM_TL = { schema: 'geak.agent_timeline/1', workflow: 'kernel_lane', events: [], nested: [] };