-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtodo.ai
More file actions
executable file
·7193 lines (6284 loc) · 261 KB
/
todo.ai
File metadata and controls
executable file
·7193 lines (6284 loc) · 261 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
#!/bin/zsh
# todo - AI-Agent First TODO List Tracker
#
# Copyright 2025 Oliver Ratzesberger
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# AI-agent first TODO list management tool
# Keep AI agents on track and help humans supervise their work
#
# Version: 2.7.1
# Repository: https://github.com/fxstein/todo.ai
# Update: ./todo.ai update
set -e
set +x # Explicitly disable debug/trace output
# Cross-platform sed in-place editing function
sed_inplace() {
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' "$@"
else
sed -i "$@"
fi
}
# Version
VERSION="2.7.1"
REPO_URL="https://github.com/fxstein/todo.ai"
SCRIPT_URL="https://raw.githubusercontent.com/fxstein/todo.ai/main/todo.ai"
# Configuration
# Can be overridden with environment variables
TODO_FILE="${TODO_FILE:-$(pwd)/TODO.md}"
SERIAL_FILE="${TODO_SERIAL:-$(pwd)/.todo.ai/.todo.ai.serial}"
LOG_FILE="${TODO_LOG:-$(pwd)/.todo.ai/.todo.ai.log}"
CONFIG_FILE="${TODO_CONFIG:-$(pwd)/.todo.ai/config.yaml}"
# ============================================================================
# Hybrid Task Numbering System
# ============================================================================
# Configuration file path
get_config_file() {
echo "$CONFIG_FILE"
}
# Read YAML config value (supports nested keys like coordination.type)
#
# IMPORTANT YAML PARSING POLICY:
# ==============================
# This function and ALL YAML operations in this script ALWAYS use sed fallback when YAML parsers are missing.
# NEVER show errors for missing YAML parsers (yq, python3-yaml) - always provide sed fallback.
# This ensures the tool works on any system with basic shell utilities (sed, grep) without requiring
# external YAML parsing tools.
#
get_config_value() {
local key="$1" # e.g., "mode" or "coordination.type"
local config_file=$(get_config_file)
local default="${2:-}"
if [[ ! -f "$config_file" ]]; then
echo "$default"
return 0
fi
# Try yq first (best YAML parser)
if command -v yq >/dev/null 2>&1; then
local value=$(yq eval ".$key" "$config_file" 2>/dev/null || echo "")
if [[ -n "$value" ]] && [[ "$value" != "null" ]]; then
echo "$value"
return 0
fi
fi
# Fallback to Python if available (with yaml module)
if command -v python3 >/dev/null 2>&1 && python3 -c "import yaml" 2>/dev/null; then
local value=$(python3 <<EOF
import yaml
import sys
try:
with open('$config_file', 'r') as f:
config = yaml.safe_load(f)
if config is None:
print('')
sys.exit(0)
# Handle nested keys (e.g., "coordination.type")
keys = '$key'.split('.')
value = config
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
print('')
sys.exit(0)
print(str(value) if value is not None else '')
except Exception as e:
print('')
sys.exit(1)
EOF
)
if [[ -n "$value" ]]; then
echo "$value"
return 0
fi
fi
# Fallback to sed for nested keys (e.g., coordination.type, coordination.issue_number)
if [[ "$key" =~ ^([^.]+)\.(.+)$ ]]; then
local parent_key="${match[1]}" # BASH_CONVERT: BASH_REMATCH[1]
local child_key="${match[2]}" # BASH_CONVERT: BASH_REMATCH[2]
# Find the parent section (e.g., "coordination:")
local in_section=false
while IFS= read -r line; do
# Check if we're entering the parent section
if [[ "$line" =~ ^${parent_key}: ]]; then
in_section=true
continue
fi
# If we hit another top-level key, we've left the section
if [[ "$in_section" == true ]] && [[ "$line" =~ ^[a-z_]+: ]]; then
break
fi
# If we're in the section, look for the child key
if [[ "$in_section" == true ]] && [[ "$line" =~ ^[[:space:]]+${child_key}:[[:space:]]*(.+)$ ]]; then
local value="${match[1]}" # BASH_CONVERT: BASH_REMATCH[1]
# Remove quotes if present
value=$(echo "$value" | sed 's/^"\(.*\)"$/\1/' | sed "s/^'\(.*\)'$/\1/" | sed 's/[[:space:]]*$//')
if [[ -n "$value" ]] && [[ "$value" != "null" ]]; then
echo "$value"
return 0
fi
fi
done < "$config_file"
fi
# Handle simple keys (not nested) - check after nested key handling
# Use string contains check instead of regex for better compatibility
if [[ "$key" != *.* ]]; then
# Simple key (not nested) - use grep and sed
local value=$(grep "^${key}:" "$config_file" 2>/dev/null | sed "s/^${key}:[[:space:]]*//" | sed 's/[[:space:]]*$//' | head -1)
if [[ -n "$value" ]] && [[ "$value" != "null" ]]; then
echo "$value"
return 0
fi
fi
echo "$default"
}
# Get numbering mode (default: single-user)
get_numbering_mode() {
get_config_value "mode" "single-user"
}
# Validate configuration
validate_config() {
local config_file=$(get_config_file)
if [[ ! -f "$config_file" ]]; then
# No config file is valid (defaults to single-user)
return 0
fi
local mode=$(get_numbering_mode)
# Check mode is valid
case "$mode" in
"single-user"|"multi-user"|"branch"|"enhanced")
;;
*)
echo "ERROR: Invalid mode in config: $mode" >&2
echo "Valid modes: single-user, multi-user, branch, enhanced" >&2
return 1
;;
esac
# Validate coordination settings if enhanced mode or single-user mode with coordination
if [[ "$mode" == "enhanced" ]] || [[ "$mode" == "single-user" ]]; then
local coord_type=$(get_config_value "coordination.type" "")
if [[ "$coord_type" != "none" ]] && [[ -n "$coord_type" ]]; then
case "$coord_type" in
"github-issues")
local issue_num=$(get_config_value "coordination.issue_number" "")
if [[ -z "$issue_num" ]] || ! [[ "$issue_num" =~ ^[0-9]+$ ]]; then
echo "ERROR: Invalid or missing coordination.issue_number for github-issues mode" >&2
return 1
fi
;;
"counterapi")
local namespace=$(get_config_value "coordination.namespace" "")
if [[ -z "$namespace" ]]; then
echo "ERROR: Missing coordination.namespace for counterapi mode" >&2
return 1
fi
;;
*)
echo "ERROR: Invalid coordination.type: $coord_type" >&2
echo "Valid types: github-issues, counterapi, none" >&2
return 1
;;
esac
fi
fi
return 0
}
# Create backup before mode switching
create_mode_backup() {
local backup_dir="$(pwd)/.todo.ai/backups"
local timestamp=$(date +"%Y%m%d%H%M%S")
local backup_name="mode-switch-${timestamp}"
# Ensure backup directory exists
mkdir -p "$backup_dir" 2>/dev/null || return 1
# Create backup of TODO.md and config.yaml
local backup_todo="${backup_dir}/${backup_name}.TODO.md"
local backup_config="${backup_dir}/${backup_name}.config.yaml"
local backup_serial="${backup_dir}/${backup_name}.serial"
# Copy files
if [[ -f "$TODO_FILE" ]]; then
cp "$TODO_FILE" "$backup_todo" 2>/dev/null || return 1
fi
local config_file=$(get_config_file)
if [[ -f "$config_file" ]]; then
cp "$config_file" "$backup_config" 2>/dev/null || return 1
fi
if [[ -f "$SERIAL_FILE" ]]; then
cp "$SERIAL_FILE" "$backup_serial" 2>/dev/null || return 1
fi
echo "$backup_name"
return 0
}
# Rollback from backup
rollback_from_backup() {
local backup_name="$1"
if [[ -z "$backup_name" ]]; then
echo "Error: Please provide backup name"
echo "Usage: ./todo.ai rollback-mode <backup-name>"
echo "List backups: ./todo.ai list-mode-backups"
return 1
fi
local backup_dir="$(pwd)/.todo.ai/backups"
local backup_todo="${backup_dir}/${backup_name}.TODO.md"
local backup_config="${backup_dir}/${backup_name}.config.yaml"
local backup_serial="${backup_dir}/${backup_name}.serial"
# Check if backup exists
if [[ ! -f "$backup_todo" ]]; then
echo "Error: Backup '$backup_name' not found"
return 1
fi
# Restore files
if [[ -f "$backup_todo" ]]; then
cp "$backup_todo" "$TODO_FILE" 2>/dev/null || {
echo "Error: Could not restore TODO.md"
return 1
}
fi
local config_file=$(get_config_file)
if [[ -f "$backup_config" ]]; then
cp "$backup_config" "$config_file" 2>/dev/null || {
echo "Error: Could not restore config.yaml"
return 1
}
elif [[ -f "$config_file" ]]; then
# If backup has no config but current has one, remove it
rm -f "$config_file" 2>/dev/null || true
fi
if [[ -f "$backup_serial" ]]; then
cp "$backup_serial" "$SERIAL_FILE" 2>/dev/null || {
echo "Error: Could not restore serial file"
return 1
}
fi
echo "✅ Rollback complete: restored from backup '$backup_name'"
return 0
}
# List mode backups
list_mode_backups() {
local backup_dir="$(pwd)/.todo.ai/backups"
if [[ ! -d "$backup_dir" ]]; then
echo "No backups found"
return 0
fi
local backups=()
for backup_file in "$backup_dir"/mode-switch-*.TODO.md; do
if [[ -f "$backup_file" ]]; then
local backup_name=$(basename "$backup_file" | sed 's/\.TODO\.md$//')
backups+=("$backup_name")
fi
done
if [[ ${#backups[@]} -eq 0 ]]; then
echo "No mode switch backups found"
return 0
fi
echo "Mode switch backups:"
echo ""
for backup in "${backups[@]}"; do
local timestamp=$(echo "$backup" | sed 's/mode-switch-//')
local date_str=$(echo "$timestamp" | sed 's/\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)/\1-\2-\3 \4:\5:\6/')
echo " $backup ($date_str)"
done
}
# Get GitHub user ID (first 7 characters)
get_github_user_id() {
local user_id=""
# Try GitHub CLI first
if command -v gh >/dev/null 2>&1; then
user_id=$(gh api user --jq '.login' 2>/dev/null || echo "")
fi
# Fallback to Git config
if [[ -z "$user_id" ]]; then
# Try git config user.name
local git_user=$(git config --get user.name 2>/dev/null || echo "")
if [[ -n "$git_user" ]]; then
# Convert to lowercase, remove non-alphanumeric, take first 7 chars
user_id=$(echo "$git_user" | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]' | cut -c1-7)
fi
fi
# Final fallback
if [[ -z "$user_id" ]]; then
# Use system username as last resort
local sys_user=$(whoami 2>/dev/null || echo "user")
user_id=$(echo "$sys_user" | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]' | cut -c1-7)
fi
# Ensure we have something (at least 1 char)
if [[ -z "$user_id" ]]; then
user_id="user"
fi
# Take first 7 characters
echo "${user_id:0:7}"
}
# Get current Git branch name (first 7 characters)
get_branch_name() {
local branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
if [[ -z "$branch" ]] || [[ "$branch" == "HEAD" ]]; then
echo "main" # Default branch name
return 0
fi
# Take first 7 characters, remove non-alphanumeric
branch=$(echo "$branch" | tr -cd '[:alnum:]_' | cut -c1-7)
# Ensure we have something
if [[ -z "$branch" ]]; then
branch="main"
fi
echo "$branch"
}
# Assign task number based on current mode
assign_task_number() {
local mode=$(get_numbering_mode)
case "$mode" in
"single-user")
# Mode 1: Simple sequential numbering (with optional coordination)
assign_task_number_single_user
;;
"multi-user")
# Mode 2: Prefix with GitHub user ID
assign_task_number_multi_user
;;
"branch")
# Mode 3: Prefix with branch name
assign_task_number_branch
;;
"enhanced")
# Mode 4: Enhanced coordination (GitHub Issues or CounterAPI)
assign_task_number_enhanced
;;
*)
# Fallback to single-user
increment_serial
;;
esac
}
# Mode 1: Single-user numbering (with optional coordination)
assign_task_number_single_user() {
# Check if coordination is configured for single-user mode
local coord_type=$(get_config_value "coordination.type" "none")
case "$coord_type" in
"github-issues")
assign_task_number_single_user_github_issues || increment_serial
;;
"counterapi")
assign_task_number_single_user_counterapi || increment_serial
;;
*)
# No coordination - use simple serial increment
increment_serial
;;
esac
}
# Single-user mode: GitHub Issues coordination (returns plain number)
assign_task_number_single_user_github_issues() {
local issue_num=$(get_config_value "coordination.issue_number" "")
local repo_url=$(git config --get remote.origin.url 2>/dev/null | sed 's/\.git$//' | sed 's/.*github\.com[:/]//' || echo "")
if [[ -z "$issue_num" ]] || [[ -z "$repo_url" ]] || ! command -v gh >/dev/null 2>&1; then
return 1 # Trigger fallback
fi
# Check GitHub CLI authentication
if ! gh auth status >/dev/null 2>&1; then
return 1 # Trigger fallback
fi
# Get latest comment from issue
local latest_comment=$(gh api repos/${repo_url}/issues/${issue_num}/comments --jq 'sort_by(.created_at) | .[-1].body' 2>/dev/null || echo "")
# Get coordinator value from issue comment
local coordinator_value=0
if [[ -n "$latest_comment" ]]; then
# Extract number from comment (format: "Next task number: 123" or just "123")
local extracted_num=$(echo "$latest_comment" | grep -oE '[0-9]+' | tail -1)
if [[ -n "$extracted_num" ]] && [[ "$extracted_num" =~ ^[0-9]+$ ]]; then
coordinator_value=$extracted_num
fi
fi
# Get highest task number from TODO.md (checks both prefixed and non-prefixed tasks)
local highest_task_num=$(get_highest_task_number)
# Use max(coordinator_value, highest_task_num) + 1 to ensure no duplicates
local max_value=$coordinator_value
if [[ $highest_task_num -gt $max_value ]]; then
max_value=$highest_task_num
fi
local new_num=$((max_value + 1))
# If coordinator was behind, log a warning
if [[ $coordinator_value -lt $highest_task_num ]]; then
echo "⚠️ Warning: Coordinator value ($coordinator_value) was behind TODO.md highest ($highest_task_num)" >&2
echo " Using max value: $max_value, next task: $new_num" >&2
fi
# Append new number as comment (with retry on conflicts)
local max_retries=3
local retry=0
while [[ $retry -lt $max_retries ]]; do
# Create comment with new number
if gh api -X POST repos/${repo_url}/issues/${issue_num}/comments --field "body=Next task number: $new_num" >/dev/null 2>&1; then
# Return plain number (no prefix)
echo "$new_num"
return 0
fi
# Check if number changed (concurrent update) - get latest comment by sorting
local updated_comment=$(gh api repos/${repo_url}/issues/${issue_num}/comments --jq 'sort_by(.created_at) | .[-1].body' 2>/dev/null || echo "")
local updated_num=$(echo "$updated_comment" | grep -oE '[0-9]+' | tail -1)
if [[ -n "$updated_num" ]] && [[ "$updated_num" != "$coordinator_value" ]]; then
# Number changed, retry with new number
coordinator_value=$updated_num
max_value=$coordinator_value
if [[ $highest_task_num -gt $max_value ]]; then
max_value=$highest_task_num
fi
new_num=$((max_value + 1))
retry=$((retry + 1))
else
# Unknown error, fallback
return 1
fi
done
# Max retries reached, fallback
return 1
}
# Single-user mode: CounterAPI coordination (returns plain number)
assign_task_number_single_user_counterapi() {
local namespace=$(get_config_value "coordination.namespace" "")
local counter_name="task-counter"
if [[ -z "$namespace" ]] || ! command -v curl >/dev/null 2>&1; then
return 1 # Trigger fallback
fi
# Increment atomically via CounterAPI
local response=$(curl -s -X POST "https://api.counterapi.dev/v1/${namespace}/${counter_name}/up" 2>/dev/null || echo "")
if [[ -z "$response" ]]; then
return 1 # Trigger fallback
fi
# Parse response (expect JSON with "value" field)
local new_num=""
if command -v jq >/dev/null 2>&1; then
new_num=$(echo "$response" | jq -r '.value' 2>/dev/null || echo "")
elif command -v python3 >/dev/null 2>&1; then
new_num=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin).get('value', ''))" 2>/dev/null || echo "")
fi
if [[ -z "$new_num" ]] || ! [[ "$new_num" =~ ^[0-9]+$ ]]; then
return 1 # Trigger fallback
fi
# Check against TODO.md highest number and use max if needed
local highest_task_num=$(get_highest_task_number)
if [[ $highest_task_num -gt $new_num ]]; then
# CounterAPI value is behind - we need to increment beyond the highest
# Note: CounterAPI already incremented, so we use its value
# But we should sync it by using max
echo "⚠️ Warning: CounterAPI value ($new_num) was behind TODO.md highest ($highest_task_num)" >&2
# Use the higher value to ensure no duplicates
if [[ $highest_task_num -ge $new_num ]]; then
new_num=$((highest_task_num + 1))
# Note: CounterAPI has already incremented, so we're using a value ahead
# In practice, this is fine since CounterAPI ensures atomicity for concurrent requests
fi
fi
# Return plain number (no prefix)
echo "$new_num"
return 0
}
# Mode 2: Multi-user numbering (user-prefix)
assign_task_number_multi_user() {
local user_prefix=$(get_github_user_id)
local todo_file="$TODO_FILE"
# Find highest task number for this user prefix
local highest=0
# Construct pattern variable for zsh regex compatibility
local pattern="\\*\\*#${user_prefix}-([0-9]+)\\*\\*"
while IFS= read -r line; do
# Match task IDs like fxstein-50 in TODO.md
# Use pattern variable for zsh compatibility
if [[ "$line" =~ $pattern ]]; then
local num="${match[1]}"
if [[ $num -gt $highest ]]; then
highest=$num
fi
fi
done < "$todo_file"
local next_num=$((highest + 1))
echo "${user_prefix}-${next_num}"
}
# Mode 3: Branch numbering (branch-prefix)
assign_task_number_branch() {
local branch_prefix=$(get_branch_name)
local todo_file="$TODO_FILE"
# Find highest task number for this branch prefix
local highest=0
# Construct pattern variable for zsh regex compatibility
local pattern="\\*\\*#${branch_prefix}-([0-9]+)\\*\\*"
while IFS= read -r line; do
# Match task IDs like feature-50 in TODO.md
# Use pattern variable for zsh compatibility
if [[ "$line" =~ $pattern ]]; then
local num="${match[1]}"
if [[ $num -gt $highest ]]; then
highest=$num
fi
fi
done < "$todo_file"
local next_num=$((highest + 1))
echo "${branch_prefix}-${next_num}"
}
# Mode 4: Enhanced multi-user numbering (with coordination)
assign_task_number_enhanced() {
local coord_type=$(get_config_value "coordination.type" "none")
local fallback_mode=$(get_config_value "coordination.fallback" "multi-user")
case "$coord_type" in
"github-issues")
assign_task_number_enhanced_github_issues || assign_task_number_enhanced_fallback "$fallback_mode"
;;
"counterapi")
assign_task_number_enhanced_counterapi || assign_task_number_enhanced_fallback "$fallback_mode"
;;
*)
# No coordination configured, use fallback
assign_task_number_enhanced_fallback "$fallback_mode"
;;
esac
}
# Enhanced mode: GitHub Issues coordination
assign_task_number_enhanced_github_issues() {
local issue_num=$(get_config_value "coordination.issue_number" "")
local repo_url=$(git config --get remote.origin.url 2>/dev/null | sed 's/\.git$//' | sed 's/.*github\.com[:/]//' || echo "")
if [[ -z "$issue_num" ]] || [[ -z "$repo_url" ]] || ! command -v gh >/dev/null 2>&1; then
return 1 # Trigger fallback
fi
# Check GitHub CLI authentication
if ! gh auth status >/dev/null 2>&1; then
return 1 # Trigger fallback
fi
# Get latest comment from issue (comments are returned in chronological order, so get last one)
# Sort by created_at to ensure we get the newest comment, or use last element if already sorted
local latest_comment=$(gh api repos/${repo_url}/issues/${issue_num}/comments --jq 'sort_by(.created_at) | .[-1].body' 2>/dev/null || echo "")
# Get coordinator value from issue comment
local coordinator_value=0
if [[ -n "$latest_comment" ]]; then
# Extract number from comment (format: "Next task number: 123" or just "123")
local extracted_num=$(echo "$latest_comment" | grep -oE '[0-9]+' | tail -1)
if [[ -n "$extracted_num" ]] && [[ "$extracted_num" =~ ^[0-9]+$ ]]; then
coordinator_value=$extracted_num
fi
fi
# Get highest task number from TODO.md (checks both prefixed and non-prefixed tasks)
local highest_task_num=$(get_highest_task_number)
# Use max(coordinator_value, highest_task_num) + 1 to ensure no duplicates
local max_value=$coordinator_value
if [[ $highest_task_num -gt $max_value ]]; then
max_value=$highest_task_num
fi
local new_num=$((max_value + 1))
# If coordinator was behind, log a warning
if [[ $coordinator_value -lt $highest_task_num ]]; then
echo "⚠️ Warning: Coordinator value ($coordinator_value) was behind TODO.md highest ($highest_task_num)" >&2
echo " Using max value: $max_value, next task: $new_num" >&2
fi
# Append new number as comment (with retry on conflicts)
local max_retries=3
local retry=0
while [[ $retry -lt $max_retries ]]; do
# Create comment with new number
if gh api -X POST repos/${repo_url}/issues/${issue_num}/comments --field "body=Next task number: $new_num" >/dev/null 2>&1; then
# Get user prefix for formatting
local user_prefix=$(get_github_user_id)
echo "${user_prefix}-${new_num}"
return 0
fi
# Check if number changed (concurrent update) - get latest comment by sorting
local updated_comment=$(gh api repos/${repo_url}/issues/${issue_num}/comments --jq 'sort_by(.created_at) | .[-1].body' 2>/dev/null || echo "")
local updated_num=$(echo "$updated_comment" | grep -oE '[0-9]+' | tail -1)
if [[ -n "$updated_num" ]] && [[ "$updated_num" != "$current_num" ]]; then
# Number changed, retry with new number
current_num=$updated_num
new_num=$((current_num + 1))
retry=$((retry + 1))
else
# Unknown error, fallback
return 1
fi
done
# Max retries reached, fallback
return 1
}
# Enhanced mode: CounterAPI coordination
assign_task_number_enhanced_counterapi() {
local namespace=$(get_config_value "coordination.namespace" "")
local counter_name="task-counter"
if [[ -z "$namespace" ]] || ! command -v curl >/dev/null 2>&1; then
return 1 # Trigger fallback
fi
# Increment atomically via CounterAPI
local response=$(curl -s -X POST "https://api.counterapi.dev/v1/${namespace}/${counter_name}/up" 2>/dev/null || echo "")
if [[ -z "$response" ]]; then
return 1 # Trigger fallback
fi
# Parse response (expect JSON with "value" field)
local new_num=""
if command -v jq >/dev/null 2>&1; then
new_num=$(echo "$response" | jq -r '.value' 2>/dev/null || echo "")
elif command -v python3 >/dev/null 2>&1; then
new_num=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin).get('value', ''))" 2>/dev/null || echo "")
fi
if [[ -z "$new_num" ]] || ! [[ "$new_num" =~ ^[0-9]+$ ]]; then
return 1 # Trigger fallback
fi
# Get user prefix for formatting
local user_prefix=$(get_github_user_id)
echo "${user_prefix}-${new_num}"
return 0
}
# Enhanced mode: Fallback to simpler mode
assign_task_number_enhanced_fallback() {
local fallback_mode="$1"
case "$fallback_mode" in
"multi-user")
assign_task_number_multi_user
;;
"branch")
assign_task_number_branch
;;
*)
# Default to single-user
increment_serial
;;
esac
}
# Resolve task reference (auto-add prefix for number-only references)
resolve_task_reference() {
local input="$1"
local mode=$(get_numbering_mode)
# If already has prefix (format: prefix-number), use as-is
if [[ "$input" =~ ^[a-z0-9]{1,7}-[0-9]+$ ]]; then
echo "$input"
return 0
fi
# If just a number, add prefix based on mode
if [[ "$input" =~ ^[0-9]+$ ]]; then
case "$mode" in
"multi-user"|"enhanced")
local user_prefix=$(get_github_user_id)
echo "${user_prefix}-${input}"
return 0
;;
"branch")
local branch_prefix=$(get_branch_name)
echo "${branch_prefix}-${input}"
return 0
;;
"single-user")
# No prefix needed for single-user
echo "$input"
return 0
;;
esac
fi
# Invalid format
echo "ERROR: Invalid task ID format: $input" >&2
return 1
}
# Extract numeric part from task ID (removes prefix if present)
extract_task_number() {
local task_id="$1"
# If has prefix (format: prefix-number), extract number
if [[ "$task_id" =~ ^[a-z0-9]{1,7}-([0-9]+)$ ]]; then
echo "${match[1]}"
return 0
fi
# If has subtask format (prefix-number.subtask), extract both parts
if [[ "$task_id" =~ ^[a-z0-9]{1,7}-([0-9]+)\.([0-9]+)$ ]]; then
echo "${match[1]}.${match[2]}"
return 0
fi
# If just number or number.subtask, return as-is
if [[ "$task_id" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
echo "$task_id"
return 0
fi
# Invalid format
return 1
}
# Generate new task ID based on mode and numeric part
generate_new_task_id() {
local numeric_part="$1"
local mode="$2"
# Extract parent and subtask numbers if present
local parent_num=""
local subtask_num=""
if [[ "$numeric_part" =~ ^([0-9]+)\.([0-9]+)$ ]]; then
parent_num="${match[1]}"
subtask_num="${match[2]}"
elif [[ "$numeric_part" =~ ^([0-9]+)$ ]]; then
parent_num="${match[1]}"
else
return 1
fi
# Generate prefix based on mode
local prefix=""
case "$mode" in
"multi-user"|"enhanced")
prefix=$(get_github_user_id)
;;
"branch")
prefix=$(get_branch_name)
;;
"single-user")
prefix="" # No prefix
;;
*)
return 1
;;
esac
# Build new ID
if [[ -z "$prefix" ]]; then
# Single-user: no prefix
if [[ -n "$subtask_num" ]]; then
echo "${parent_num}.${subtask_num}"
else
echo "${parent_num}"
fi
else
# Multi-user/branch: with prefix
if [[ -n "$subtask_num" ]]; then
echo "${prefix}-${parent_num}.${subtask_num}"
else
echo "${prefix}-${parent_num}"
fi
fi
}
# Renumber tasks when switching modes
renumber_tasks_for_mode() {
local old_mode="$1"
local new_mode="$2"
if [[ ! -f "$TODO_FILE" ]]; then
return 1
fi
# Build ID mapping: old_id -> new_id
declare -A id_mapping
# Collect all task IDs from TODO.md
local temp_file=$(mktemp)
local tasks_found=0
# Find all task IDs in TODO.md (handle both prefixed and non-prefixed formats)
while IFS= read -r line; do
# Match task IDs in format: **#task_id** or **#prefix-task_id**
# Handle both main tasks and subtasks
if [[ "$line" =~ \*\*#([0-9a-z.\-]+)\*\* ]]; then
local full_task_id="${match[1]}" # BASH_CONVERT: BASH_REMATCH[1]
# Extract numeric part (removes prefix if present)
local numeric_part=$(extract_task_number "$full_task_id" 2>/dev/null)
if [[ -z "$numeric_part" ]]; then
continue
fi
# Generate new ID based on new mode
local new_id=$(generate_new_task_id "$numeric_part" "$new_mode" 2>/dev/null)
if [[ -z "$new_id" ]]; then
continue
fi
# Add to mapping if IDs differ
if [[ "$full_task_id" != "$new_id" ]]; then
id_mapping["$full_task_id"]="$new_id"
tasks_found=$((tasks_found + 1))
fi
fi
done < "$TODO_FILE"
if [[ $tasks_found -eq 0 ]]; then
rm -f "$temp_file"
return 0 # No tasks to renumber
fi
# Create new TODO.md with renumbered tasks
local new_file=$(mktemp)
local renumbered_count=0
while IFS= read -r line || [[ -n "$line" ]]; do
local new_line="$line"
local line_changed=false
# Skip empty lines
if [[ -z "$new_line" ]]; then
echo "" >> "$new_file"
continue
fi
# Replace task IDs in task lines (**#task_id**)
for old_id in "${!id_mapping[@]}"; do
local new_id="${id_mapping[$old_id]}"
# Escape old_id for sed (escape special regex characters)
local escaped_old_id=$(echo "$old_id" | sed 's/[[\.*^$()+?{|]/\\&/g')
# Replace in task definition: **#old_id**
if echo "$new_line" | grep -q "\*\*#${escaped_old_id}\*\*"; then
new_line=$(echo "$new_line" | sed "s/\*\*#${escaped_old_id}\*\*/\*\*#${new_id}\*\*/g")
line_changed=true
fi
# Replace in relationships and notes (plain text references)
# Match: #old_id (standalone or in lists)
if echo "$new_line" | grep -q "#${escaped_old_id}\([^0-9a-z-]\|$\)"; then
new_line=$(echo "$new_line" | sed "s/#${escaped_old_id}\([^0-9a-z-]\|$\)/#${new_id}\1/g")
line_changed=true
fi
# Replace in relationship comments (HTML comments)
if echo "$new_line" | grep -q "${escaped_old_id}:"; then
new_line=$(echo "$new_line" | sed "s/${escaped_old_id}:/${new_id}:/g")
line_changed=true
fi
done
if [[ "$line_changed" == true ]]; then
renumbered_count=$((renumbered_count + 1))
fi
echo "$new_line" >> "$new_file"
done < "$TODO_FILE"
# Replace original file
mv "$new_file" "$TODO_FILE"
rm -f "$temp_file"
if [[ $renumbered_count -gt 0 ]]; then
update_footer
return 0
else
return 1
fi
}
# Switch numbering mode
switch_mode() {
local new_mode="$1"
local force=false
local renumber=false
local original_args=("$@")
# Parse options
while [[ $# -gt 0 ]]; do
case "$1" in
--force|-f)
force=true
shift
;;
--renumber)
renumber=true