-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwavemill-common.sh
More file actions
2208 lines (1920 loc) · 74.6 KB
/
wavemill-common.sh
File metadata and controls
2208 lines (1920 loc) · 74.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
#!/usr/bin/env bash
# Wavemill Common Library
# Shared functions used across wavemill-mill.sh and wavemill-expand.sh
# Default tmux window names for mill mode surfaces.
WAVEMILL_WINDOW_MILL="${WAVEMILL_WINDOW_MILL:-mill}"
WAVEMILL_WINDOW_BACKSTAGE="${WAVEMILL_WINDOW_BACKSTAGE:-backstage}"
# Dashboard footer tips should stay short enough to fit on one line with the
# stable refresh prefix.
declare -a WAVEMILL_USAGE_TIPS=(
"wavemill expand HOK-1234: build a task packet from Linear"
"wavemill plan: split large work into scoped issues"
"wavemill eval: inspect workflow results and export data"
"wavemill ready 42: check if a PR can merge"
"wavemill tend --once: run one integration queue pass"
"wavemill context init --force: refresh subsystem specs"
"WAVEMILL_DASHBOARD_REFRESH_SECONDS=1..10: tune refresh"
"Ctrl+B N: jump to the next done task"
"challenge.autoMergeWinner=true: auto-merge challenge winners"
"constraints.cleanupAfterMerge=true: clean merged constraints"
)
wavemill_pick_usage_tip() {
local tip_count="${#WAVEMILL_USAGE_TIPS[@]}"
local tip_index="${WAVEMILL_TIP_INDEX:-}"
if (( tip_count == 0 )); then
printf 'Ctrl+B N: next done\n'
return 0
fi
if [[ "$tip_index" =~ ^[0-9]+$ ]]; then
printf '%s\n' "${WAVEMILL_USAGE_TIPS[tip_index % tip_count]}"
return 0
fi
printf '%s\n' "${WAVEMILL_USAGE_TIPS[RANDOM % tip_count]}"
}
# ============================================================================
# LAYERED CONFIGURATION LOADING
# ============================================================================
# Format a task-scoped status/info/debug message so the task id appears first
# in the log pane. WARN/ERROR formatting is handled by separate helpers.
wavemill_task_log_message() {
local task_id="${1:-}"
shift || true
local msg="$*"
msg="${msg#"${msg%%[![:space:]]*}"}"
if [[ -z "$task_id" ]]; then
printf '%s\n' "$msg"
return 0
fi
case "$msg" in
"$task_id"*|"[$task_id]"*) printf '%s\n' "$msg" ;;
*) printf '[%s] %s\n' "$task_id" "$msg" ;;
esac
}
# Hardcoded defaults (ultimate fallbacks)
_WAVEMILL_DEFAULTS='{
"linear": { "project": "" },
"git": {
"fetchTtlSeconds": 60
},
"mill": {
"session": "",
"maxParallel": 7,
"pollSeconds": 10,
"baseBranch": "main",
"worktreeRoot": "worktrees",
"agentCmd": "claude",
"requireConfirm": true,
"planningMode": "interactive",
"maxRetries": 3,
"retryDelay": 2,
"setupCommand": "",
"defaultMaxCostUsd": 25.00
},
"expand": {
"maxSelect": 3,
"maxDisplay": 9
},
"plan": {
"maxDisplay": 9
},
"projectContext": {
"compactionThresholdKb": 100,
"recentWorkKeep": 25
},
"dashboard": {
"verbosity": "info",
"logToFile": true
},
"challenge": {
"enabled": false,
"rate": 0.10,
"models": null,
"comparisonModel": "claude-opus-4-7",
"autoMergeWinner": false
},
"mergeQueue": {
"enabled": true,
"maxConcurrentCandidates": 2,
"stuckTimeoutSeconds": 900,
"conflictGroupingEnabled": true,
"skipCooldownSeconds": 60
}
}'
# Load layered config: defaults < ~/.wavemill/config.json < .wavemill-config.json
# < .wavemill-config.local.json < env vars
#
# Resolution order (later wins):
# 1. Hardcoded defaults (_WAVEMILL_DEFAULTS)
# 2. User-level config (~/.wavemill/config.json)
# 3. Per-repo config (.wavemill-config.json)
# 4. Per-developer overlay (.wavemill-config.local.json) — gitignored,
# mirrors the loadWavemillConfig() overlay on the TypeScript side.
# 5. Environment variables (always win)
#
# Sets: SESSION, MAX_PARALLEL, POLL_SECONDS, BASE_BRANCH, WORKTREE_ROOT,
# AGENT_CMD, REQUIRE_CONFIRM, PLANNING_MODE, MAX_RETRIES, RETRY_DELAY,
# PROJECT_NAME, MAX_SELECT, MAX_DISPLAY, SETUP_CMD,
# GIT_FETCH_TTL_SECONDS
#
# Args: $1 = repo directory (default: $PWD)
load_config() {
local repo_dir="${1:-$PWD}"
local user_config="$HOME/.wavemill/config.json"
local repo_config="$repo_dir/.wavemill-config.json"
local local_config="$repo_dir/.wavemill-config.local.json"
# Read config files (empty object if missing)
local user_json='{}'
local repo_json='{}'
local local_json='{}'
if [[ -f "$user_config" ]]; then
user_json=$(cat "$user_config") || user_json='{}'
fi
if [[ -f "$repo_config" ]]; then
repo_json=$(cat "$repo_config") || repo_json='{}'
fi
if [[ -f "$local_config" ]]; then
local_json=$(cat "$local_config") || local_json='{}'
fi
# Single jq call: deep-merge all layers, emit shell-safe variable assignments
local shell_vars
shell_vars=$(jq -n -r \
--argjson defaults "$_WAVEMILL_DEFAULTS" \
--argjson user "$user_json" \
--argjson repo "$repo_json" \
--argjson local "$local_json" \
'
($defaults * $user * $repo * $local) as $c |
[
"_CFG_PROJECT=\($c.linear.project // "" | @sh)",
"_CFG_GIT_FETCH_TTL_SECONDS=\($c.git.fetchTtlSeconds // 60)",
"_CFG_SESSION=\($c.mill.session | @sh)",
"_CFG_MAX_PARALLEL=\($c.mill.maxParallel)",
"_CFG_POLL_SECONDS=\($c.mill.pollSeconds)",
"_CFG_BASE_BRANCH=\($c.mill.baseBranch | @sh)",
"_CFG_WORKTREE_ROOT=\($c.mill.worktreeRoot | @sh)",
"_CFG_AGENT_CMD=\($c.mill.agentCmd | @sh)",
"_CFG_REQUIRE_CONFIRM=\($c.mill.requireConfirm)",
"_CFG_PLANNING_MODE=\($c.mill.planningMode | @sh)",
"_CFG_MAX_RETRIES=\($c.mill.maxRetries)",
"_CFG_RETRY_DELAY=\($c.mill.retryDelay)",
"_CFG_MAX_SELECT=\($c.expand.maxSelect)",
"_CFG_MAX_DISPLAY=\($c.expand.maxDisplay)",
"_CFG_PLAN_MAX_DISPLAY=\($c.plan.maxDisplay)",
"_CFG_PROJECT_CONTEXT_COMPACTION_THRESHOLD_KB=\($c.projectContext.compactionThresholdKb // 100)",
"_CFG_PROJECT_CONTEXT_RECENT_WORK_KEEP=\($c.projectContext.recentWorkKeep // 25)",
"_CFG_PLAN_RESEARCH=\($c.plan.research // false)",
"_CFG_PLAN_MODEL=\($c.plan.model // "claude-opus-4-7" | @sh)",
"_CFG_DASHBOARD_VERBOSITY=\($c.dashboard.verbosity // "info" | @sh)",
"_CFG_DASHBOARD_LOG_TO_FILE=\(if ($c.dashboard | has("logToFile")) then $c.dashboard.logToFile else true end)",
"_CFG_ENTER_LAUNCHES_WAVE=\(if ($c.taskSelection | has("enterLaunchesWave")) then $c.taskSelection.enterLaunchesWave else true end)",
"_CFG_CHALLENGE_ENABLED=\($c.challenge.enabled // false)",
"_CFG_CHALLENGE_RATE=\($c.challenge.rate // 0.10)",
"_CFG_CHALLENGE_MODELS=\(($c.challenge.models // null) | @json | @sh)",
"_CFG_CHALLENGE_COMPARISON_MODEL=\($c.challenge.comparisonModel // "claude-opus-4-7" | @sh)",
"_CFG_CHALLENGE_AUTO_MERGE=\($c.challenge.autoMergeWinner // false)",
"_CFG_MERGE_QUEUE_ENABLED=\($c.mergeQueue.enabled // true)",
"_CFG_MERGE_QUEUE_MAX_CONCURRENT=\($c.mergeQueue.maxConcurrentCandidates // 2)",
"_CFG_MERGE_QUEUE_STUCK_TIMEOUT_SECONDS=\($c.mergeQueue.stuckTimeoutSeconds // 900)",
"_CFG_MERGE_QUEUE_CONFLICT_GROUPING_ENABLED=\($c.mergeQueue.conflictGroupingEnabled // true)",
"_CFG_MERGE_QUEUE_SKIP_COOLDOWN_SECONDS=\($c.mergeQueue.skipCooldownSeconds // 60)",
"_CFG_ROUTER_ENABLED=\($c.router.enabled // true)",
"_CFG_ROUTER_DEFAULT_MODEL=\($c.router.defaultModel // "claude-sonnet-4-6" | @sh)",
"_CFG_AUTO_EVAL=\($c.autoEval // true)",
"_CFG_SETUP_CMD=\($c.mill.setupCommand // "" | @sh)",
"_CFG_DEFAULT_MAX_COST_USD=\(($c.mill.defaultMaxCostUsd // null) | if . == null then "" else tostring end | @sh)"
] | .[]
'
) || {
echo "Error: Failed to parse config files. Check JSON syntax in:" >&2
[[ -f "$user_config" ]] && echo " $user_config" >&2
[[ -f "$repo_config" ]] && echo " $repo_config" >&2
[[ -f "$local_config" ]] && echo " $local_config" >&2
exit 1
}
eval "$shell_vars"
# Apply env var overrides (env > repo config > user config > defaults)
#
# Project selection is special:
# - LINEAR_PROJECT is the explicit override
# - repo config should beat an ambient/exported PROJECT_NAME to avoid
# cross-repo leakage from prior shells or sessions
# - legacy PROJECT_NAME is only used when no repo/user project is configured
if [[ -n "${LINEAR_PROJECT:-}" ]]; then
PROJECT_NAME="$LINEAR_PROJECT"
elif [[ -n "$_CFG_PROJECT" ]]; then
PROJECT_NAME="$_CFG_PROJECT"
else
PROJECT_NAME="${PROJECT_NAME:-}"
fi
# Session name: env var > config > repo-specific default
# Repo-specific default prevents cross-repo session collisions
local _repo_basename
_repo_basename="$(basename "$repo_dir" | tr '.:-' '___')"
local _default_session="wavemill-${_repo_basename}"
if [[ -n "${SESSION:-}" ]]; then
: # Explicit env var — keep it
elif [[ -n "$_CFG_SESSION" ]]; then
SESSION="$_CFG_SESSION"
else
SESSION="$_default_session"
fi
MAX_PARALLEL="${MAX_PARALLEL:-$_CFG_MAX_PARALLEL}"
POLL_SECONDS="${POLL_SECONDS:-$_CFG_POLL_SECONDS}"
GIT_FETCH_TTL_SECONDS="${GIT_FETCH_TTL_SECONDS:-$_CFG_GIT_FETCH_TTL_SECONDS}"
BASE_BRANCH="${BASE_BRANCH:-$_CFG_BASE_BRANCH}"
AGENT_CMD="${AGENT_CMD:-$_CFG_AGENT_CMD}"
REQUIRE_CONFIRM="${REQUIRE_CONFIRM:-$_CFG_REQUIRE_CONFIRM}"
PLANNING_MODE="${PLANNING_MODE:-$_CFG_PLANNING_MODE}"
MAX_RETRIES="${MAX_RETRIES:-$_CFG_MAX_RETRIES}"
RETRY_DELAY="${RETRY_DELAY:-$_CFG_RETRY_DELAY}"
MAX_SELECT="${MAX_SELECT:-$_CFG_MAX_SELECT}"
MAX_DISPLAY="${MAX_DISPLAY:-$_CFG_MAX_DISPLAY}"
PLAN_MAX_DISPLAY="${PLAN_MAX_DISPLAY:-$_CFG_PLAN_MAX_DISPLAY}"
PROJECT_CONTEXT_COMPACTION_THRESHOLD_KB="${PROJECT_CONTEXT_COMPACTION_THRESHOLD_KB:-$_CFG_PROJECT_CONTEXT_COMPACTION_THRESHOLD_KB}"
PROJECT_CONTEXT_RECENT_WORK_KEEP="${PROJECT_CONTEXT_RECENT_WORK_KEEP:-$_CFG_PROJECT_CONTEXT_RECENT_WORK_KEEP}"
PLAN_RESEARCH="${PLAN_RESEARCH:-$_CFG_PLAN_RESEARCH}"
PLAN_MODEL="${PLAN_MODEL:-$_CFG_PLAN_MODEL}"
DASHBOARD_VERBOSITY="${DASHBOARD_VERBOSITY:-$_CFG_DASHBOARD_VERBOSITY}"
DASHBOARD_LOG_TO_FILE="${DASHBOARD_LOG_TO_FILE:-$_CFG_DASHBOARD_LOG_TO_FILE}"
ENTER_LAUNCHES_WAVE="${ENTER_LAUNCHES_WAVE:-$_CFG_ENTER_LAUNCHES_WAVE}"
CHALLENGE_ENABLED="${CHALLENGE_ENABLED:-$_CFG_CHALLENGE_ENABLED}"
CHALLENGE_RATE="${CHALLENGE_RATE:-$_CFG_CHALLENGE_RATE}"
CHALLENGE_MODELS_JSON="${CHALLENGE_MODELS_JSON:-$_CFG_CHALLENGE_MODELS}"
CHALLENGE_COMPARISON_MODEL="${CHALLENGE_COMPARISON_MODEL:-$_CFG_CHALLENGE_COMPARISON_MODEL}"
CHALLENGE_AUTO_MERGE="${CHALLENGE_AUTO_MERGE:-$_CFG_CHALLENGE_AUTO_MERGE}"
MERGE_QUEUE_ENABLED="${MERGE_QUEUE_ENABLED:-$_CFG_MERGE_QUEUE_ENABLED}"
MERGE_QUEUE_MAX_CONCURRENT="${MERGE_QUEUE_MAX_CONCURRENT:-$_CFG_MERGE_QUEUE_MAX_CONCURRENT}"
MERGE_QUEUE_STUCK_TIMEOUT_SECONDS="${MERGE_QUEUE_STUCK_TIMEOUT_SECONDS:-$_CFG_MERGE_QUEUE_STUCK_TIMEOUT_SECONDS}"
MERGE_QUEUE_CONFLICT_GROUPING_ENABLED="${MERGE_QUEUE_CONFLICT_GROUPING_ENABLED:-$_CFG_MERGE_QUEUE_CONFLICT_GROUPING_ENABLED}"
MERGE_QUEUE_SKIP_COOLDOWN_SECONDS="${MERGE_QUEUE_SKIP_COOLDOWN_SECONDS:-$_CFG_MERGE_QUEUE_SKIP_COOLDOWN_SECONDS}"
ROUTER_ENABLED="${ROUTER_ENABLED:-$_CFG_ROUTER_ENABLED}"
ROUTER_DEFAULT_MODEL="${ROUTER_DEFAULT_MODEL:-$_CFG_ROUTER_DEFAULT_MODEL}"
AUTO_EVAL="${AUTO_EVAL:-$_CFG_AUTO_EVAL}"
SETUP_CMD="${SETUP_CMD:-$_CFG_SETUP_CMD}"
DEFAULT_MAX_COST_USD="${DEFAULT_MAX_COST_USD:-$_CFG_DEFAULT_MAX_COST_USD}"
if [[ "$PLANNING_MODE" != "interactive" ]]; then
echo "Warning: planningMode='$PLANNING_MODE' is no longer supported; forcing interactive planning." >&2
PLANNING_MODE="interactive"
fi
# WORKTREE_ROOT: resolve relative paths against repo_dir
local wt_raw="${WORKTREE_ROOT:-$_CFG_WORKTREE_ROOT}"
if [[ "$wt_raw" != /* ]]; then
WORKTREE_ROOT="$repo_dir/$wt_raw"
else
WORKTREE_ROOT="$wt_raw"
fi
# Export for child processes (orchestrator, monitor, agents)
export SESSION MAX_PARALLEL POLL_SECONDS BASE_BRANCH WORKTREE_ROOT
export GIT_FETCH_TTL_SECONDS
export AGENT_CMD REQUIRE_CONFIRM PLANNING_MODE MAX_RETRIES RETRY_DELAY
export PROJECT_NAME MAX_SELECT MAX_DISPLAY PLAN_MAX_DISPLAY PLAN_RESEARCH PLAN_MODEL
export PROJECT_CONTEXT_COMPACTION_THRESHOLD_KB PROJECT_CONTEXT_RECENT_WORK_KEEP
export DASHBOARD_VERBOSITY DASHBOARD_LOG_TO_FILE
export ENTER_LAUNCHES_WAVE
export CHALLENGE_ENABLED CHALLENGE_RATE CHALLENGE_MODELS_JSON
export CHALLENGE_COMPARISON_MODEL CHALLENGE_AUTO_MERGE
export MERGE_QUEUE_ENABLED MERGE_QUEUE_MAX_CONCURRENT
export MERGE_QUEUE_STUCK_TIMEOUT_SECONDS MERGE_QUEUE_CONFLICT_GROUPING_ENABLED
export MERGE_QUEUE_SKIP_COOLDOWN_SECONDS
export ROUTER_ENABLED ROUTER_DEFAULT_MODEL AUTO_EVAL SETUP_CMD DEFAULT_MAX_COST_USD
# Clean up temp variables
unset _CFG_PROJECT _CFG_GIT_FETCH_TTL_SECONDS _CFG_SESSION _CFG_MAX_PARALLEL _CFG_POLL_SECONDS
unset _CFG_BASE_BRANCH _CFG_WORKTREE_ROOT _CFG_AGENT_CMD _CFG_REQUIRE_CONFIRM
unset _CFG_PLANNING_MODE _CFG_MAX_RETRIES _CFG_RETRY_DELAY _CFG_MAX_SELECT _CFG_MAX_DISPLAY
unset _CFG_PLAN_MAX_DISPLAY _CFG_PLAN_RESEARCH _CFG_PLAN_MODEL
unset _CFG_PROJECT_CONTEXT_COMPACTION_THRESHOLD_KB _CFG_PROJECT_CONTEXT_RECENT_WORK_KEEP
unset _CFG_DASHBOARD_VERBOSITY _CFG_DASHBOARD_LOG_TO_FILE _CFG_ENTER_LAUNCHES_WAVE
unset _CFG_CHALLENGE_ENABLED _CFG_CHALLENGE_RATE _CFG_CHALLENGE_MODELS
unset _CFG_CHALLENGE_COMPARISON_MODEL _CFG_CHALLENGE_AUTO_MERGE
unset _CFG_MERGE_QUEUE_ENABLED _CFG_MERGE_QUEUE_MAX_CONCURRENT
unset _CFG_MERGE_QUEUE_STUCK_TIMEOUT_SECONDS _CFG_MERGE_QUEUE_CONFLICT_GROUPING_ENABLED
unset _CFG_MERGE_QUEUE_SKIP_COOLDOWN_SECONDS
unset _CFG_ROUTER_ENABLED _CFG_ROUTER_DEFAULT_MODEL _CFG_AUTO_EVAL _CFG_SETUP_CMD _CFG_DEFAULT_MAX_COST_USD
# Sentinel so downstream scripts can skip re-loading
_WAVEMILL_CONFIG_LOADED=1
}
wavemill_config_annotation() {
local path="${1:-}"
local value="${2:-}"
printf ' (%s=%s)' "$path" "$value"
}
BACKLOG_BUDGET_WARNED=false
wavemill_backlog_compute_budget() {
local session="${1:-}"
local window_pane="${2:-}"
local config_file="${3:-}"
local budget=""
if [[ -n "$config_file" && -f "$config_file" ]]; then
budget="$(jq -r '.backlog.maxLines // empty' "$config_file" 2>/dev/null || true)"
elif [[ -n "${REPO_DIR:-}" ]]; then
budget="$(wavemill_load_config "$REPO_DIR" | jq -r '.backlog.maxLines // empty' 2>/dev/null || true)"
fi
if [[ "$budget" =~ ^[0-9]+$ ]] && (( budget >= 10 && budget <= 200 )); then
printf '%s\n' "$budget"
return 0
fi
local pane_height=""
if [[ -n "$session" && -n "$window_pane" ]]; then
pane_height="$(tmux display-message -t "$session:$window_pane" -p "#{pane_height}" 2>/dev/null || true)"
fi
if [[ "$pane_height" =~ ^[0-9]+$ ]]; then
# The grouped renderer receives only the task-list body budget. The mill
# pane frame adds "Next tasks:", a blank separator, and a long prompt that
# commonly wraps, so reserve enough rows for that fixed chrome.
budget=$((pane_height - 8))
(( budget < 10 )) && budget=10
printf '%s\n' "$budget"
return 0
fi
if [[ "${BACKLOG_BUDGET_WARNED:-false}" != "true" ]]; then
log_warn "Backlog pane height unavailable; using fallback budget 20"
BACKLOG_BUDGET_WARNED=true
fi
printf '20\n'
return 0
}
ready_debug_log_file() {
local session="${SESSION:-${WAVEMILL_SESSION:-wavemill}}"
local sanitized="${session//[^[:alnum:]._-]/-}"
if [[ -z "$sanitized" ]]; then
sanitized="wavemill"
fi
if (( ${#sanitized} > 40 )); then
local session_hash
session_hash="$(printf '%s' "$sanitized" | cksum | awk '{print $1}')"
sanitized="${sanitized:0:28}-${session_hash}"
fi
printf '/tmp/wavemill-%s-ready-debug.jsonl\n' "$sanitized"
}
summarize_ready_result() {
local payload="${1-}"
local summary max_len=72 total_count failed_count other_count
local failed_json item name detail
local failed_parts=()
if [[ -z "$payload" ]] || ! command -v jq >/dev/null 2>&1; then
printf '%s\n' "(summary unavailable)"
return 0
fi
total_count="$(printf '%s' "$payload" | jq -r '.checks | if type == "array" then length else 0 end' 2>/dev/null || printf '0')"
failed_json="$(printf '%s' "$payload" | jq -c '[.checks[]? | select(.status == "fail")]' 2>/dev/null || printf '[]')"
failed_count="$(printf '%s' "$failed_json" | jq -r 'length' 2>/dev/null || printf '0')"
if [[ ! "$total_count" =~ ^[0-9]+$ ]] || [[ ! "$failed_count" =~ ^[0-9]+$ ]]; then
printf '%s\n' "(summary unavailable)"
return 0
fi
other_count=$(( total_count - failed_count ))
while IFS= read -r item; do
[[ -n "$item" ]] || continue
name="$(printf '%s' "$item" | jq -r '.name // "unknown-check"' 2>/dev/null || printf 'unknown-check')"
detail="$(printf '%s' "$item" | jq -r '
(.details // null) as $details
| if ($details | type) == "object" and (($details.failedChecks? | type) == "array") then
($details.failedChecks | length) as $count | ($count | tostring) + " check" + (if $count == 1 then "" else "s" end)
elif ($details | type) == "array" then
($details | length) as $count | ($count | tostring) + " file" + (if $count == 1 then "" else "s" end)
elif ($details | type) == "object" and (($details.files? | type) == "array") then
($details.files | length) as $count | ($count | tostring) + " file" + (if $count == 1 then "" else "s" end)
elif ($details | type) == "object" and (($details.paths? | type) == "array") then
($details.paths | length) as $count | ($count | tostring) + " file" + (if $count == 1 then "" else "s" end)
elif ($details | type) == "object" and ($details | length) > 0 then
($details | length) as $count | ($count | tostring) + " detail" + (if $count == 1 then "" else "s" end)
else
""
end
' 2>/dev/null || printf '')"
if [[ -n "$detail" ]]; then
failed_parts+=("$name: $detail")
else
failed_parts+=("$name")
fi
done < <(printf '%s' "$failed_json" | jq -c '.[]' 2>/dev/null)
if (( failed_count == 0 )); then
summary="0 failed, $other_count passed/skipped"
else
local failed_preview preview_limit
preview_limit=$failed_count
if (( preview_limit > 2 )); then
preview_limit=2
fi
failed_preview="$(printf '%s, ' "${failed_parts[@]:0:preview_limit}")"
failed_preview="${failed_preview%, }"
summary="$failed_count failed ($failed_preview"
if (( failed_count > 2 )); then
summary+=", +$(( failed_count - 2 )) more"
fi
summary+="), $other_count passed/skipped"
fi
if [[ -z "$summary" ]]; then
summary="(summary unavailable)"
elif (( ${#summary} > max_len )); then
summary="${summary:0:$(( max_len - 3 ))}..."
fi
printf '%s\n' "$summary"
}
log_debug_json() {
local category="${1:-debug}"
local payload="${2-}"
local target ts record
[[ -n "$payload" ]] || return 0
command -v jq >/dev/null 2>&1 || return 0
target="$(ready_debug_log_file)"
ts="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
mkdir -p "$(dirname "$target")" 2>/dev/null || true
if record="$(
printf '%s' "$payload" | jq -c --arg ts "$ts" --arg category "$category" \
'{ts: $ts, category: $category, payload: .}' 2>/dev/null
)"; then
printf '%s\n' "$record" >> "$target" 2>/dev/null || true
return 0
fi
if record="$(
jq -cn --arg ts "$ts" --arg category "$category" --arg raw "$payload" \
'{ts: $ts, category: $category, raw: $raw, error: "non_json"}' 2>/dev/null
)"; then
printf '%s\n' "$record" >> "$target" 2>/dev/null || true
fi
return 0
}
wavemill_fetch_base_branch() {
local base_branch="${1:-}"
shift || true
local force_fetch="false"
while (( $# > 0 )); do
case "$1" in
--force)
force_fetch="true"
;;
*)
return 1
;;
esac
shift
done
[[ -n "$base_branch" ]] || return 1
local ttl="${GIT_FETCH_TTL_SECONDS:-60}"
if [[ ! "$ttl" =~ ^[0-9]+$ ]]; then
ttl=60
fi
local now last_fetch_at
now="$(date +%s)"
if [[ "$force_fetch" != "true" ]] && (( ttl > 0 )) && [[ -r "${STATE_FILE:-}" ]] && [[ -s "${STATE_FILE:-}" ]]; then
if last_fetch_at=$(jq -r --arg branch "$base_branch" '.baseBranchFetchCache[$branch].last_fetch_at // empty' "$STATE_FILE" 2>/dev/null); then
if [[ "$last_fetch_at" =~ ^[0-9]+$ ]] && (( now - last_fetch_at < ttl )); then
return 0
fi
fi
fi
local fetch_rc=0
git -C "$REPO_DIR" fetch origin "$base_branch" || fetch_rc=$?
if (( fetch_rc != 0 )); then
return "$fetch_rc"
fi
if [[ -n "${STATE_FILE:-}" ]]; then
local state_dir tmp
state_dir="$(dirname "$STATE_FILE")"
mkdir -p "$state_dir" 2>/dev/null || true
tmp="$(mktemp "${state_dir%/}/fetch-cache.XXXXXX")" || return 0
if [[ ! -s "$STATE_FILE" ]]; then
printf '{"tasks":{}}\n' > "$STATE_FILE" 2>/dev/null || true
fi
if jq --arg branch "$base_branch" --argjson fetchedAt "$now" \
'.baseBranchFetchCache = (.baseBranchFetchCache // {})
| .baseBranchFetchCache[$branch] = ((.baseBranchFetchCache[$branch] // {}) + {last_fetch_at: $fetchedAt})' \
"$STATE_FILE" > "$tmp" 2>/dev/null; then
mv "$tmp" "$STATE_FILE"
else
rm -f "$tmp"
fi
fi
}
# Backwards-compatible wrapper for callers that haven't migrated to load_config()
detect_project_name() {
local repo_dir="${1:-$PWD}"
# If load_config() already ran, PROJECT_NAME is set
if [[ -n "${PROJECT_NAME:-}" ]]; then
echo "$PROJECT_NAME"
return
fi
# Legacy fallback
local project_name=""
project_name=$(wavemill_load_config "$repo_dir" | jq -r '.linear.project // empty' 2>/dev/null)
if [[ -z "$project_name" ]]; then
project_name="${PROJECT_NAME:-}"
fi
echo "$project_name"
}
# Returns the operating mode for a specific model: normal|constrained|survival
get_model_operating_mode() {
local model_id="$1"
local repo_dir="${2:-${REPO_DIR:-$PWD}}"
local tools_dir="${TOOLS_DIR:-${repo_dir%/}/tools}"
npx tsx "$tools_dir/get-operating-mode.ts" model "$model_id" --repo-dir "$repo_dir" 2>/dev/null || echo "normal"
}
# Returns exit code 0 if any model is healthy, 1 if all are degraded/exhausted.
# On unexpected errors (exit code > 1, e.g. npx not found), returns 0 to safely assume models are healthy.
has_any_healthy_model() {
local repo_dir="${1:-${REPO_DIR:-$PWD}}"
local tools_dir="${TOOLS_DIR:-${repo_dir%/}/tools}"
npx tsx "$tools_dir/get-operating-mode.ts" any-healthy --repo-dir "$repo_dir" 2>/dev/null
local exit_code=$?
if [[ $exit_code -gt 1 ]]; then
return 0 # Unexpected error, assume models are healthy
fi
return $exit_code # Pass through 0 or 1
}
# ============================================================================
# PR CACHE HELPERS
# ============================================================================
wavemill_pr_cache_refresh() {
local session="${SESSION:-wavemill}"
local cache_file="${MONITOR_PR_CACHE:-/tmp/${session}-pr-cache.json}"
local tmp_file
# Per-writer tmp file: monitor and dashboard both refresh this cache, and a
# shared "${cache_file}.tmp" leads to a race where one writer's mv consumes
# the file before the other's mv runs.
tmp_file="$(mktemp "${cache_file}.tmp.XXXXXX" 2>/dev/null)" || return 0
if gh pr list --json number,headRefName,state,statusCheckRollup --limit 50 \
< /dev/null 2>/dev/null > "$tmp_file"; then
if [[ -s "$tmp_file" ]]; then
mv "$tmp_file" "$cache_file" 2>/dev/null || rm -f "$tmp_file"
else
rm -f "$tmp_file"
fi
else
rm -f "$tmp_file"
fi
}
wavemill_pr_lookup_by_branch() {
local branch="${1:-}"
local session="${SESSION:-wavemill}"
local cache_file="${MONITOR_PR_CACHE:-/tmp/${session}-pr-cache.json}"
[[ -n "$branch" && -f "$cache_file" ]] || return 0
jq -r --arg b "$branch" \
'.[] | select(.headRefName == $b) | .number' \
"${cache_file}" 2>/dev/null | head -1
}
# ============================================================================
# GITHUB HELPERS
# ============================================================================
# Check whether a branch has any PR in GitHub, including closed or merged PRs.
# Returns 0 when a PR exists and 1 when no PR is found or GitHub cannot be
# queried. Callers use this as a guard before taking destructive cleanup paths.
check_pr_exists() {
local branch="$1"
local pr_number=""
if [[ -z "$branch" ]]; then
return 1
fi
pr_number=$(gh pr list --head "$branch" --state all --json number --jq '.[0].number // empty' 2>/dev/null || echo "")
[[ -n "$pr_number" ]]
}
# Read a field from the canonical startup routing artifact.
# Fallback chain: route.json -> model-suggestion.json shim -> default value.
#
# Canonical route.json contract (written by tools/route-task.ts):
# {
# planner,
# coder,
# reviewer,
# planDepth,
# codeDepth,
# reviewRecommended,
# routingMode,
# neighborCount,
# expectedSuccess,
# constraints,
# signals,
# reasoning
# }
#
# COMPAT: model-suggestion.json is a temporary coder-only shim for pre-HOK-1198
# consumers and pre-HOK-1197 startup sessions. New routing consumers should
# read route.json through this helper instead of reading the shim directly.
#
# Usage: read_route_json <session> <issue> <field> [default]
route_read_field() {
local route_file="$1" field="$2" default_value="${3:-}"
local value=""
if [[ ! -f "$route_file" ]]; then
return 1
fi
if ! jq -e '.' "$route_file" >/dev/null 2>&1; then
return 2
fi
value=$(jq -r --arg field "$field" '
if ($field | contains(".")) then
($field | split(".")) as $path | getpath($path) // empty
else
.[$field] // .provenance[$field] // empty
end
' "$route_file" 2>/dev/null || true)
if [[ -n "$value" ]]; then
echo "$value"
return 0
fi
echo "$default_value"
return 0
}
write_json_artifact() {
local target_path="$1"
local tmp_file
tmp_file="$(mktemp "${target_path}.tmp.XXXXXX")" || {
echo "write_json_artifact: failed to allocate temp file for $target_path" >&2
return 1
}
if ! cat > "$tmp_file"; then
rm -f "$tmp_file"
echo "write_json_artifact: failed to read JSON payload for $target_path" >&2
return 1
fi
if ! jq -e . "$tmp_file" >/dev/null 2>&1; then
rm -f "$tmp_file"
echo "write_json_artifact: invalid JSON for $target_path" >&2
return 1
fi
if ! mv "$tmp_file" "$target_path"; then
rm -f "$tmp_file"
echo "write_json_artifact: failed to move temp file into place for $target_path" >&2
return 1
fi
}
read_route_json() {
local session="$1" issue="$2" field="$3" default_value="${4:-}"
local route_file="/tmp/${session}-${issue}-route.json"
local suggestion_file="/tmp/${session}-${issue}-model-suggestion.json"
local value=""
if value=$(route_read_field "$route_file" "$field" ""); then
if [[ -n "$value" ]]; then
echo "$value"
return 0
fi
fi
if [[ -f "$suggestion_file" ]]; then
case "$field" in
coder)
value=$(jq -r '.recommendedModel // empty' "$suggestion_file" 2>/dev/null || true)
if [[ -n "$value" ]]; then
echo "$value"
return 0
fi
;;
esac
fi
echo "$default_value"
}
find_expanded_route_artifact() {
local feature_dir="$1"
local route_file=""
for route_file in \
"$feature_dir/.post-expansion-route.json" \
"$feature_dir/.expanded-route.json"; do
if [[ -f "$route_file" ]]; then
printf '%s\n' "$route_file"
return 0
fi
done
return 1
}
get_expansion_handshake_policy() {
local repo_dir="$1"
local cfg_policy=""
cfg_policy=$(wavemill_load_config "$repo_dir" | jq -r '.mill.expansionHandshake.policy // "recover"' 2>/dev/null || echo "recover")
case "$cfg_policy" in
recover|block|warn)
printf '%s\n' "$cfg_policy"
;;
*)
printf 'recover\n'
;;
esac
}
get_expansion_handshake_timeout_seconds() {
local repo_dir="$1"
local cfg_timeout=""
cfg_timeout=$(wavemill_load_config "$repo_dir" | jq -r '.mill.expansionHandshake.timeoutSeconds // 300' 2>/dev/null || echo "300")
if [[ "$cfg_timeout" =~ ^[0-9]+$ ]] && (( cfg_timeout >= 1 )); then
printf '%s\n' "$cfg_timeout"
else
printf '300\n'
fi
}
validate_expanded_route_artifact() {
local route_file="$1"
[[ -n "$route_file" && -f "$route_file" ]] || return 1
jq -e '
type == "object"
and (.coder | type == "string" and length > 0)
and (.codeDepth | type == "string" and length > 0)
and (.reviewer | type == "string" and length > 0)
and ((.reviewMode // .reviewRecommended // "") | type == "string" and length > 0)
' "$route_file" >/dev/null 2>&1
}
mill_expansion_handshake_reason() {
local feature_dir="$1"
local packet_file="$feature_dir/task-packet.md"
local route_file=""
local packet_content=""
if [[ -f "$packet_file" ]]; then
packet_content=$(cat "$packet_file" 2>/dev/null || echo "")
fi
if is_task_packet "$packet_content"; then
printf 'already-expanded\n'
return 0
fi
route_file="$(find_expanded_route_artifact "$feature_dir" 2>/dev/null || true)"
if [[ -n "$route_file" ]]; then
if ! jq -e '.' "$route_file" >/dev/null 2>&1; then
printf 'invalid-json\n'
return 0
fi
if validate_expanded_route_artifact "$route_file"; then
printf 'expanded-route-present\n'
return 0
fi
printf 'missing-required-field\n'
return 0
fi
printf 'missing\n'
return 0
}
route_lifecycle_route_id() {
local route_file="$1"
[[ -n "$route_file" && -f "$route_file" ]] || return 1
jq -r '
"coder=\(.coder // ""),codeDepth=\(.codeDepth // ""),reviewer=\(.reviewer // ""),reviewMode=\(.reviewMode // .reviewRecommended // "")"
' "$route_file" 2>/dev/null
}
router_log_verbose_enabled() {
local raw="${WAVEMILL_ROUTER_LOG_VERBOSE:-}"
raw="$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]')"
case "$raw" in
1|true|yes|on)
return 0
;;
*)
return 1
;;
esac
}
route_summary_signature() {
local route_file="$1"
[[ -n "$route_file" && -f "$route_file" ]] || return 1
jq -r '
[
(if ((.planner // "") | length) > 0 then "planner=\(.planner)" else empty end),
(if ((.planDepth // "") | length) > 0 then "planDepth=\(.planDepth)" else empty end),
(if ((.coder // "") | length) > 0 then "coder=\(.coder)" else empty end),
(if ((.codeDepth // "") | length) > 0 then "codeDepth=\(.codeDepth)" else empty end),
(if ((.reviewer // "") | length) > 0 then "reviewer=\(.reviewer)" else empty end),
(if ((.reviewMode // .reviewRecommended // "") | length) > 0 then "reviewMode=\(.reviewMode // .reviewRecommended)" else empty end)
] | join(", ")
' "$route_file" 2>/dev/null
}
route_summary_mode_tag() {
local route_file="$1"
[[ -n "$route_file" && -f "$route_file" ]] || return 1
local mode
mode="$(jq -r '.provenance.routerMode // .routerMode // .routingMode // empty' "$route_file" 2>/dev/null || true)"
case "$mode" in
constrained|survival)
printf '[mode=%s] ' "$mode"
;;
*)
printf ''
;;
esac
}
log_router_route_summary() {
local issue="$1" route_file="$2"
[[ -n "$issue" && -n "$route_file" && -f "$route_file" ]] || return 0
local signature mode_tag key
signature="$(route_summary_signature "$route_file" 2>/dev/null || true)"
[[ -n "$signature" ]] || return 0
mode_tag="$(route_summary_mode_tag "$route_file" 2>/dev/null || true)"
key="${issue}|${mode_tag}${signature}"
if [[ "${_WAVEMILL_LAST_ROUTE_SUMMARY_KEY:-}" == "$key" ]]; then
return 0
fi
_WAVEMILL_LAST_ROUTE_SUMMARY_KEY="$key"
log "info" "[$issue] [router] ${mode_tag}${signature}"
}
log_route_lifecycle() {
local event="$1"
shift || true
if ! router_log_verbose_enabled; then
case "$event" in
bootstrap_assigned|expanded_assigned|expansion_cache_hit|execution_active)
return 0
;;
esac
fi
local line="route.lifecycle: event=${event}"
local token
for token in "$@"; do
[[ -n "$token" ]] || continue
line+=" ${token}"
done
log "info" "$line"
}
emit_execution_active_route() {
local feature_dir="$1" issue="$2"
local routing_file="$feature_dir/.routing-complete"
local bootstrap_file="$feature_dir/.initial-route.json"
local expanded_file=""
local active_route="" bootstrap_route="" expanded_route="" route_changed="" source=""
[[ -f "$routing_file" ]] || return 0
active_route="$(route_lifecycle_route_id "$routing_file" 2>/dev/null || true)"
[[ -n "$active_route" ]] || return 0
if [[ -f "$bootstrap_file" ]]; then
bootstrap_route="$(route_lifecycle_route_id "$bootstrap_file" 2>/dev/null || true)"
fi
expanded_file="$(find_expanded_route_artifact "$feature_dir" 2>/dev/null || true)"
if [[ -n "$expanded_file" ]]; then
expanded_route="$(route_lifecycle_route_id "$expanded_file" 2>/dev/null || true)"
fi
route_changed="false"
if [[ -n "$bootstrap_route" && "$bootstrap_route" != "$active_route" ]]; then
route_changed="true"
fi
source="bootstrap"
if [[ -n "$expanded_route" ]]; then
if [[ "$expanded_route" == "$active_route" ]]; then
if [[ -n "$bootstrap_route" && "$bootstrap_route" == "$active_route" ]]; then
source="preserved"
else
source="expanded"
fi
else
source="preserved"
fi
fi
log_router_route_summary "$issue" "$routing_file"
log_route_lifecycle "execution_active" \
"issue=$issue" \
"route=\"$active_route\"" \
"route_changed=$route_changed" \
"source=$source"
}
ensure_phase_config_state_file() {
local feature_dir="$1"
local config_file="$feature_dir/.phase-config.json"
if [[ -f "$config_file" ]] && jq empty "$config_file" >/dev/null 2>&1; then
return 0
fi
mkdir -p "$feature_dir"
cat > "$config_file" <<'EOF'
{
"planning": {
"model": "",
"agent": "",
"depth": ""
},
"coding": {
"model": "",
"agent": "",
"depth": ""
},
"review": {