Class: Aidp::Harness::ConditionDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/aidp/harness/condition_detector.rb

Overview

Detects run conditions (rate limits, user feedback, completion, errors)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConditionDetector

Returns a new instance of ConditionDetector.



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
# File 'lib/aidp/harness/condition_detector.rb', line 12

def initialize
  # Enhanced rate limit patterns for different providers
  @rate_limit_patterns = {
    # Common patterns
    common: [
      /rate limit/i,
      /too many requests/i,
      /quota exceeded/i,
      /429/i,
      /rate.{0,20}exceeded/i,
      /throttled/i,
      /limit.{0,20}exceeded/i,
      /session limit/i
    ],
    # Anthropic/Claude specific
    anthropic: [
      /rate limit exceeded/i,
      /too many requests/i,
      /quota.{0,20}exceeded/i,
      /anthropic.{0,20}rate.{0,20}limit/i,
      /session limit reached/i
    ],
    # OpenAI specific
    openai: [
      /rate limit exceeded/i,
      /requests per minute/i,
      /tokens per minute/i,
      /openai.{0,20}rate.{0,20}limit/i
    ],
    # Google/Gemini specific
    google: [
      /quota exceeded/i,
      /rate limit exceeded/i,
      /google.{0,20}api.{0,20}limit/i,
      /gemini.{0,20}rate.{0,20}limit/i
    ],
    # Cursor specific
    cursor: [
      /cursor.{0,20}rate.{0,20}limit/i,
      /package.{0,20}limit/i,
      /usage.{0,20}limit/i
    ]
  }

  # Enhanced user feedback patterns
  @user_feedback_patterns = {
    # Direct requests for input
    direct_requests: [
      /please provide/i,
      /can you provide/i,
      /could you provide/i,
      /i need.{0,20}input/i,
      /i require.{0,20}input/i,
      /please give me/i,
      /can you give me/i
    ],
    # Clarification requests
    clarification: [
      /can you clarify/i,
      /could you clarify/i,
      /please clarify/i,
      /i need clarification/i,
      /can you explain/i,
      /could you explain/i
    ],
    # Choice/decision requests
    choices: [
      /what would you like/i,
      /what do you prefer/i,
      /which.{0,20}would you prefer/i,
      /which.{0,20}do you want/i,
      /do you want/i,
      /should i/i,
      /would you like/i,
      /which option/i,
      /choose between/i,
      /select.{0,20}from/i
    ],
    # Confirmation requests
    confirmation: [
      /is this correct/i,
      /does this look right/i,
      /should i proceed/i,
      /can i continue/i,
      /is this what you want/i,
      /confirm.{0,20}this/i,
      /approve.{0,20}this/i
    ],
    # File/input requests
    file_requests: [
      /please upload/i,
      /can you upload/i,
      /i need.{0,20}file/i,
      /please provide.{0,20}file/i,
      /attach.{0,20}file/i,
      /send.{0,20}file/i
    ],
    # Specific information requests
    information: [
      /what is.{0,20}name/i,
      /what is.{0,20}email/i,
      /what is.{0,20}url/i,
      /what is.{0,20}path/i,
      /enter.{0,20}name/i,
      /enter.{0,20}email/i,
      /enter.{0,20}url/i,
      /enter.{0,20}path/i
    ]
  }

  # Enhanced question patterns
  @question_patterns = [
    # Numbered questions
    /^\d+\.\s+(.+)\?/,
    /^(\d+)\)\s+(.+)\?/,
    /^(\d+\.\s+.+)\?$/m,
    # Bullet point questions
    /^[-*]\s+(.+)\?/,
    # Lettered questions
    /^[a-z]\)\s+(.+)\?/i,
    /^[A-Z]\)\s+(.+)\?/,
    # Questions with colons
    /^(\d+):\s+(.+)\?/,
    # Questions in quotes
    /"([^"]+\?)"/,
    /'([^']+\?)'/
  ]

  # Context patterns that indicate user interaction is needed
  @context_patterns = [
    /waiting for.{0,20}input/i,
    /awaiting.{0,20}response/i,
    /need.{0,20}feedback/i,
    /require.{0,20}confirmation/i,
    /pending.{0,20}approval/i,
    /user.{0,20}interaction.{0,20}required/i,
    /manual.{0,20}intervention/i
  ]

  # Rate limit reset time patterns
  @reset_time_patterns = [
    /reset(?:s)?\s+in\s+(\d+)\s+seconds/i,
    /retry\s+after\s+(\d+)\s+seconds/i,
    /wait[^\d]*(\d+)[^\d]*seconds/i,
    /(\d+)\s+seconds\s+until\s+reset/i,
    /reset.{0,20}at.{0,20}(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})/i,
    /retry.{0,20}after.{0,20}(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})/i
  ]
end

Instance Attribute Details

#question_patternsObject (readonly)

Expose patterns for testability



10
11
12
# File 'lib/aidp/harness/condition_detector.rb', line 10

def question_patterns
  @question_patterns
end

#rate_limit_patternsObject (readonly)

Expose patterns for testability



10
11
12
# File 'lib/aidp/harness/condition_detector.rb', line 10

def rate_limit_patterns
  @rate_limit_patterns
end

#reset_time_patternsObject (readonly)

Expose patterns for testability



10
11
12
# File 'lib/aidp/harness/condition_detector.rb', line 10

def reset_time_patterns
  @reset_time_patterns
end

#user_feedback_patternsObject (readonly)

Expose patterns for testability



10
11
12
# File 'lib/aidp/harness/condition_detector.rb', line 10

def user_feedback_patterns
  @user_feedback_patterns
end

Instance Method Details

#classify_error(error) ⇒ Object

Classify error type with comprehensive analysis



851
852
853
854
855
856
# File 'lib/aidp/harness/condition_detector.rb', line 851

def classify_error(error)
  return :unknown unless error.is_a?(StandardError)

  error_info = extract_error_info(error)
  error_info[:type]
end

#classify_error_type(error_message, error_class) ⇒ Object

Classify error type based on message and class



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
# File 'lib/aidp/harness/condition_detector.rb', line 883

def classify_error_type(error_message, error_class)
  # Network and connectivity errors
  if error_message.match?(/timeout/i) || error_class.include?("timeout")
    :timeout
  elsif error_message.match?(/connection/i) || error_message.match?(/network/i) ||
      error_class.include?("connection") || error_class.include?("network")
    :network
  elsif error_message.match?(/dns/i) || error_message.match?(/resolve/i)
    :dns_resolution
  elsif error_message.match?(/ssl/i) || error_message.match?(/tls/i) || error_message.match?(/certificate/i)
    :ssl_tls

  # Authentication and authorization errors
  elsif error_message.match?(/authentication/i) || error_message.match?(/unauthorized/i) ||
      error_message.match?(/401/i) || error_class.include?("authentication")
    :authentication
  elsif error_message.match?(/permission/i) || error_message.match?(/forbidden/i) ||
      error_message.match?(/403/i) || error_class.include?("permission")
    :permission
  elsif error_message.match?(/access.{0,20}denied/i) || error_message.match?(/insufficient.{0,20}privileges/i)
    :access_denied

  # File and I/O errors (check these first as they're more specific)
  elsif error_message.match?(/file.{0,20}not.{0,20}found/i) || error_message.match?(/no.{0,20}such.{0,20}file/i)
    :file_not_found

  # HTTP and API errors
  elsif error_message.match?(/not found/i) || error_message.match?(/404/i)
    :not_found
  elsif error_message.match?(/server error/i) || error_message.match?(/500/i) ||
      error_message.match?(/internal.{0,20}error/i)
    :server_error
  elsif error_message.match?(/bad request/i) || error_message.match?(/400/i) ||
      error_message.match?(/invalid.{0,20}request/i)
    :bad_request
  elsif error_message.match?(/rate limit/i) || error_message.match?(/429/i) ||
      error_message.match?(/too many requests/i)
    :rate_limit
  elsif error_message.match?(/quota.{0,20}exceeded/i) || error_message.match?(/usage.{0,20}limit/i)
    :quota_exceeded
  elsif error_message.match?(/permission.{0,20}denied/i) || error_message.match?(/eacces/i)
    :file_permission
  elsif error_message.match?(/disk.{0,20}full/i) || error_message.match?(/no.{0,20}space/i)
    :disk_full
  elsif error_message.match?(/read.{0,20}only/i) || error_message.match?(/eacces/i)
    :read_only_filesystem

  # Memory and resource errors
  elsif error_message.match?(/memory/i) || error_message.match?(/out of memory/i) ||
      error_class.include?("memory")
    :memory_error
  elsif error_message.match?(/resource.{0,20}unavailable/i) || error_message.match?(/resource.{0,20}exhausted/i)
    :resource_exhausted

  # Configuration and setup errors
  elsif error_message.match?(/configuration/i) || error_message.match?(/config/i) ||
      error_class.include?("configuration")
    :configuration
  elsif error_message.match?(/missing.{0,20}dependency/i) || error_message.match?(/gem.{0,20}not found/i)
    :missing_dependency
  elsif error_message.match?(/environment/i) || error_message.match?(/env/i)
    :environment

  # Provider-specific errors
  elsif error_message.match?(/anthropic/i) || error_message.match?(/claude/i)
    :anthropic_error
  elsif error_message.match?(/openai/i) || error_message.match?(/gpt/i)
    :openai_error
  elsif error_message.match?(/google/i) || error_message.match?(/gemini/i)
    :google_error
  elsif error_message.match?(/cursor/i)
    :cursor_error

  # Parsing and format errors
  elsif error_message.match?(/parse/i) || error_message.match?(/json/i) ||
      error_message.match?(/syntax/i) || error_class.include?("parse")
    :parsing_error
  elsif error_message.match?(/format/i) || error_message.match?(/invalid.{0,20}format/i)
    :format_error

  # Validation errors
  elsif error_message.match?(/validation/i) || error_message.match?(/invalid.{0,20}input/i) ||
      error_class.include?("validation")
    :validation_error
  elsif error_message.match?(/argument/i) || error_message.match?(/parameter/i)
    :argument_error

  # System errors
  elsif error_message.match?(/system/i) || error_class.include?("system")
    :system_error
  elsif error_message.match?(/interrupt/i) || error_message.match?(/sigint/i) ||
      error_class.include?("interrupt")
    :interrupted

  else
    :unknown
  end
end

#completion_confidence(completion_info) ⇒ Object

Get completion confidence level



1465
1466
1467
1468
1469
# File 'lib/aidp/harness/condition_detector.rb', line 1465

def completion_confidence(completion_info)
  return 0.0 unless completion_info && completion_info[:confidence]

  completion_info[:confidence]
end

#detect_explicit_completion(text_content) ⇒ Object

Detect explicit completion indicators



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
# File 'lib/aidp/harness/condition_detector.rb', line 631

def detect_explicit_completion(text_content)
  completion_patterns = {
    # High confidence completion indicators
    high_confidence: [
      /all steps completed/i,
      /workflow complete/i,
      /analysis complete/i,
      /execution finished/i,
      /task completed/i,
      /all done/i,
      /finished successfully/i,
      /completed successfully/i,
      /workflow finished/i,
      /analysis finished/i,
      /execution completed/i
    ],
    # Medium confidence completion indicators
    medium_confidence: [
      /complete/i,
      /finished/i,
      /done/i,
      /success/i,
      /ready/i,
      /final/i
    ],
    # Low confidence completion indicators
    low_confidence: [
      /end/i,
      /stop/i,
      /close/i,
      /finalize/i
    ]
  }

  found_indicators = []
  max_confidence = 0.0
  completion_type = nil

  completion_patterns.each do |confidence_level, patterns|
    patterns.each do |pattern|
      if text_content.match?(pattern)
        found_indicators << pattern.source
        case confidence_level
        when :high_confidence
          if max_confidence < 0.9
            max_confidence = 0.9
            completion_type = "explicit_high_confidence"
          end
        when :medium_confidence
          if max_confidence < 0.7
            max_confidence = 0.7
            completion_type = "explicit_medium_confidence"
          end
        when :low_confidence
          if max_confidence < 0.5
            max_confidence = 0.5
            completion_type = "explicit_low_confidence"
          end
        end
      end
    end
  end

  {
    found: max_confidence > 0.0,
    type: completion_type,
    confidence: max_confidence,
    indicators: found_indicators
  }
end

#detect_feedback_type(text_content) ⇒ Object

Detect the type of feedback needed



366
367
368
369
370
371
372
373
374
# File 'lib/aidp/harness/condition_detector.rb', line 366

def detect_feedback_type(text_content)
  @user_feedback_patterns.each do |type, patterns|
    if patterns.any? { |pattern| text_content.match?(pattern) }
      return type.to_s
    end
  end

  "general"
end

#detect_implicit_completion(text_content, progress) ⇒ Object

Detect implicit completion indicators



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
# File 'lib/aidp/harness/condition_detector.rb', line 703

def detect_implicit_completion(text_content, progress)
  # Check for summary or conclusion patterns
  summary_patterns = [
    /summary/i,
    /conclusion/i,
    /overview/i,
    /results/i,
    /findings/i,
    /recommendations/i,
    /next steps/i
  ]

  # Check for deliverable patterns
  deliverable_patterns = [
    /report generated/i,
    /document created/i,
    /file created/i,
    /output generated/i,
    /result saved/i,
    /analysis saved/i
  ]

  # Check for status patterns
  status_patterns = [
    /status: complete/i,
    /status: finished/i,
    /status: done/i,
    /phase.{0,20}complete/i,
    /stage.{0,20}complete/i
  ]

  found_indicators = []
  max_confidence = 0.0
  completion_type = nil

  # Check summary patterns
  if summary_patterns.any? { |pattern| text_content.match?(pattern) }
    found_indicators << "summary_patterns"
    max_confidence = [max_confidence, 0.8].max
    completion_type = "implicit_summary"
  end

  # Check deliverable patterns
  if deliverable_patterns.any? { |pattern| text_content.match?(pattern) }
    found_indicators << "deliverable_patterns"
    max_confidence = [max_confidence, 0.8].max
    completion_type = "implicit_deliverable"
  end

  # Check status patterns
  if status_patterns.any? { |pattern| text_content.match?(pattern) }
    found_indicators << "status_patterns"
    max_confidence = [max_confidence, 0.7].max
    completion_type = "implicit_status"
  end

  # Check for progress completion
  if progress && progress.completed_steps.size > 0
    completion_ratio = progress.completed_steps.size.to_f / progress.total_steps
    if completion_ratio >= 0.8 # 80% or more complete
      found_indicators << "high_progress_ratio"
      max_confidence = [max_confidence, 0.6].max
      completion_type = "implicit_high_progress"
    end
  end

  {
    found: max_confidence > 0.0,
    type: completion_type,
    confidence: max_confidence,
    indicators: found_indicators
  }
end

#detect_input_type(text_content) ⇒ Object

Detect the type of input expected



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/aidp/harness/condition_detector.rb', line 418

def detect_input_type(text_content)
  if text_content.match?(/file/i) || text_content.match?(/upload/i) || text_content.match?(/attach/i)
    "file"
  elsif text_content.match?(/email/i)
    "email"
  elsif text_content.match?(/url/i) || text_content.match?(/link/i)
    "url"
  elsif text_content.match?(/path/i) || text_content.match?(/directory/i)
    "path"
  elsif text_content.match?(/number/i) || text_content.match?(/\d+/) ||
      text_content.match?(/how many/i) || text_content.match?(/how much/i) ||
      text_content.match?(/count/i) || text_content.match?(/quantity/i) ||
      text_content.match?(/amount/i)
    "number"
  elsif text_content.match?(/yes/i) || text_content.match?(/no/i) || text_content.match?(/confirm/i) ||
      text_content.match?(/should i/i) || text_content.match?(/can i/i) || text_content.match?(/may i/i) ||
      text_content.match?(/proceed/i) || text_content.match?(/continue/i) || text_content.match?(/approve/i)
    "boolean"
  else
    "text"
  end
end

#detect_limit_type(text_content, provider) ⇒ Object

Detect the type of rate limit



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
# File 'lib/aidp/harness/condition_detector.rb', line 283

def detect_limit_type(text_content, provider)
  return "session_limit" if text_content.match?(/session limit/i)

  case provider&.to_s&.downcase
  when "anthropic", "claude"
    if text_content.match?(/requests per minute/i)
      "requests_per_minute"
    elsif text_content.match?(/tokens per minute/i)
      "tokens_per_minute"
    else
      "general_rate_limit"
    end
  when "openai"
    if text_content.match?(/requests per minute/i)
      "requests_per_minute"
    elsif text_content.match?(/tokens per minute/i)
      "tokens_per_minute"
    else
      "general_rate_limit"
    end
  when "google", "gemini"
    if text_content.match?(/quota exceeded/i)
      "quota_exceeded"
    else
      "general_rate_limit"
    end
  when "cursor"
    if text_content.match?(/package\s+limit/i)
      "package_limit"
    elsif text_content.match?(/usage\s+limit/i)
      "usage_limit"
    else
      "general_rate_limit"
    end
  else
    "general_rate_limit"
  end
end

#detect_partial_completion(text_content, progress) ⇒ Object

Detect partial completion and next actions



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
# File 'lib/aidp/harness/condition_detector.rb', line 778

def detect_partial_completion(text_content, progress)
  next_actions = []
  status = "in_progress"

  # Check for next action indicators
  next_action_patterns = [
    /next step/i,
    /next action/i,
    /continue with/i,
    /proceed to/i,
    /move to/i,
    /now\s+will/i,
    /next\s+will/i
  ]

  if next_action_patterns.any? { |pattern| text_content.match?(pattern) }
    status = "has_next_actions"
    next_actions << "continue_execution"
  end

  # Check for waiting patterns
  waiting_patterns = [
    /waiting for/i,
    /pending/i,
    /awaiting/i,
    /need\s+input/i,
    /require\s+input/i
  ]

  if waiting_patterns.any? { |pattern| text_content.match?(pattern) }
    status = "waiting_for_input"
    next_actions << "collect_user_input"
  end

  # Check for error patterns
  error_patterns = [
    /error/i,
    /failed/i,
    /issue/i,
    /problem/i,
    /exception/i
  ]

  if error_patterns.any? { |pattern| text_content.match?(pattern) }
    status = "has_errors"
    next_actions << "handle_errors"
  end

  # Check progress status only if no specific status was detected from text
  if status == "in_progress" && progress
    completion_ratio = progress.completed_steps.size.to_f / progress.total_steps
    if completion_ratio >= 0.8
      status = "near_completion"
      next_actions << "continue_to_completion"
    elsif completion_ratio >= 0.5
      status = "half_complete"
      next_actions << "continue_execution"
    elsif completion_ratio >= 0.2
      status = "early_stage"
      next_actions << "continue_execution"
    else
      status = "just_started"
      next_actions << "continue_execution"
    end
  end

  {
    status: status,
    next_actions: next_actions
  }
end

#detect_question_type(question_text) ⇒ Object

Detect the type of question



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
# File 'lib/aidp/harness/condition_detector.rb', line 519

def detect_question_type(question_text)
  question_lower = question_text.downcase

  if question_lower.match?(/what.{0,20}name/i) || question_lower.match?(/what.{0,20}email/i)
    "information"
  elsif question_lower.match?(/which.{0,20}prefer/i) || question_lower.match?(/which.{0,20}want/i)
    "choice"
  elsif question_lower.match?(/should.{0,20}i/i) || question_lower.match?(/can.{0,20}i/i)
    "permission"
  elsif question_lower.match?(/is.{0,20}correct/i) || question_lower.match?(/does.{0,20}look/i)
    "confirmation"
  elsif question_lower.match?(/can.{0,20}you/i) || question_lower.match?(/could.{0,20}you/i)
    "request"
  elsif question_lower.match?(/how.{0,20}many/i) || question_lower.match?(/how.{0,20}much/i)
    "quantity"
  elsif question_lower.match?(/when/i)
    "time"
  elsif question_lower.match?(/where/i)
    "location"
  elsif question_lower.match?(/why/i)
    "explanation"
  else
    "general"
  end
end

#detect_urgency(text_content) ⇒ Object

Detect urgency level



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
# File 'lib/aidp/harness/condition_detector.rb', line 387

def detect_urgency(text_content)
  urgent_patterns = [
    /urgent/i,
    /asap/i,
    /immediately/i,
    /right now/i,
    /critical/i,
    /important/i
  ]

  low_urgency_patterns = [
    /when you have time/i,
    /when convenient/i,
    /at your convenience/i,
    /when possible/i,
    /no rush/i,
    /take your time/i
  ]

  if urgent_patterns.any? { |pattern| text_content.match?(pattern) }
    "high"
  elsif low_urgency_patterns.any? { |pattern| text_content.match?(pattern) }
    "low"
  elsif text_content.match?(/please/i) || text_content.match?(/can you/i)
    "medium"
  else
    "low"
  end
end

#determine_error_severity(error_type, _error_message) ⇒ Object

Determine error severity



983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File 'lib/aidp/harness/condition_detector.rb', line 983

def determine_error_severity(error_type, _error_message)
  case error_type
  when :authentication, :permission, :access_denied, :configuration, :missing_dependency
    :critical
  when :rate_limit, :quota_exceeded, :disk_full, :memory_error, :resource_exhausted
    :high
  when :timeout, :network, :dns_resolution, :ssl_tls, :server_error, :bad_request
    :medium
  when :not_found, :file_not_found, :file_permission, :read_only_filesystem
    :medium
  when :parsing_error, :format_error, :validation_error, :argument_error
    :low
  when :interrupted, :system_error
    :high
  else
    :medium
  end
end

#determine_recoverability(error_type, _error_message) ⇒ Object

Determine if error is recoverable



1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'lib/aidp/harness/condition_detector.rb', line 1003

def determine_recoverability(error_type, _error_message)
  case error_type
  when :authentication, :permission, :access_denied, :configuration, :missing_dependency
    false
  when :rate_limit, :quota_exceeded, :timeout, :network, :dns_resolution, :ssl_tls
    true
  when :server_error, :bad_request, :not_found, :file_not_found
    true
  when :disk_full, :memory_error, :resource_exhausted
    false
  when :file_permission, :read_only_filesystem
    false
  when :parsing_error, :format_error, :validation_error, :argument_error
    true
  when :interrupted, :system_error
    false
  else
    # Unknown errors are considered recoverable with caution
    true
  end
end

#determine_retry_strategy(error_type, _error_message) ⇒ Object

Determine retry strategy



1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
# File 'lib/aidp/harness/condition_detector.rb', line 1026

def determine_retry_strategy(error_type, _error_message)
  case error_type
  when :timeout, :network, :dns_resolution, :ssl_tls
    {strategy: :exponential_backoff, max_retries: 3, base_delay: 5}
  when :rate_limit, :quota_exceeded
    {strategy: :fixed_delay, max_retries: 2, delay: 60}
  when :server_error, :bad_request
    {strategy: :exponential_backoff, max_retries: 2, base_delay: 10}
  when :not_found, :file_not_found
    {strategy: :no_retry, max_retries: 0, delay: 0}
  when :parsing_error, :format_error, :validation_error, :argument_error
    {strategy: :no_retry, max_retries: 0, delay: 0}
  when :authentication, :permission, :access_denied, :configuration, :missing_dependency
    {strategy: :no_retry, max_retries: 0, delay: 0}
  when :disk_full, :memory_error, :resource_exhausted
    {strategy: :no_retry, max_retries: 0, delay: 0}
  when :interrupted, :system_error
    {strategy: :no_retry, max_retries: 0, delay: 0}
  else
    {strategy: :exponential_backoff, max_retries: 1, base_delay: 5}
  end
end

#extract_completion_info(result, progress) ⇒ Object

Extract comprehensive completion information



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
# File 'lib/aidp/harness/condition_detector.rb', line 571

def extract_completion_info(result, progress)
  # Get all text content to analyze
  text_content = [
    result[:output],
    result[:message],
    result[:response],
    result[:body]
  ].compact.join(" ")

  completion_info = {
    is_complete: false,
    completion_type: nil,
    confidence: 0.0,
    indicators: [],
    progress_status: nil,
    next_actions: []
  }

  # Check progress-based completion
  if progress&.completed_steps && progress.total_steps &&
      progress.completed_steps.size == progress.total_steps
    completion_info[:is_complete] = true
    completion_info[:completion_type] = "all_steps_completed"
    completion_info[:confidence] = 1.0
    completion_info[:progress_status] = "all_steps_completed"
    return completion_info
  end

  # Check for explicit completion indicators
  explicit_completion = detect_explicit_completion(text_content)
  if explicit_completion[:found]
    completion_info[:is_complete] = true
    completion_info[:completion_type] = explicit_completion[:type]
    completion_info[:confidence] = explicit_completion[:confidence]
    completion_info[:indicators] = explicit_completion[:indicators]
    return completion_info
  end

  # Check for implicit completion indicators
  implicit_completion = detect_implicit_completion(text_content, progress)
  if implicit_completion[:found]
    completion_info[:is_complete] = true
    completion_info[:completion_type] = implicit_completion[:type]
    completion_info[:confidence] = implicit_completion[:confidence]
    completion_info[:indicators] = implicit_completion[:indicators]
    return completion_info
  end

  # If no completion indicators found, check for partial completion
  partial_completion = detect_partial_completion(text_content, progress)
  completion_info[:progress_status] = partial_completion[:status]
  completion_info[:next_actions] = partial_completion[:next_actions]

  # Only consider work complete if we have explicit or implicit completion indicators
  completion_info[:is_complete] = false

  completion_info
end

#extract_context(text_content) ⇒ Object

Extract context information



377
378
379
380
381
382
383
384
# File 'lib/aidp/harness/condition_detector.rb', line 377

def extract_context(text_content)
  context_matches = []
  @context_patterns.each do |pattern|
    matches = text_content.scan(pattern)
    context_matches.concat(matches)
  end
  context_matches.uniq
end

#extract_error_info(error) ⇒ Object

Extract comprehensive error information



859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'lib/aidp/harness/condition_detector.rb', line 859

def extract_error_info(error)
  return {type: :unknown, severity: :low, recoverable: true} unless error.is_a?(StandardError)

  error_message = error.message.downcase
  error_class = error.class.name.downcase

  # Get error classification
  error_type = classify_error_type(error_message, error_class)
  severity = determine_error_severity(error_type, error_message)
  recoverable = determine_recoverability(error_type, error_message)
  retry_strategy = determine_retry_strategy(error_type, error_message)

  {
    type: error_type,
    severity: severity,
    recoverable: recoverable,
    retry_strategy: retry_strategy,
    message: error.message,
    class: error.class.name,
    backtrace: error.backtrace&.first(5)
  }
end

#extract_questions(result) ⇒ Object

Extract questions from result output



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
# File 'lib/aidp/harness/condition_detector.rb', line 442

def extract_questions(result)
  return [] unless result.is_a?(Hash)

  # Get all text content to analyze
  text_content = [
    result[:output],
    result[:message],
    result[:response],
    result[:body]
  ].compact.join(" ")

  return [] if text_content.empty?

  questions = []

  # Extract structured questions using patterns
  @question_patterns.each do |pattern|
    matches = text_content.scan(pattern)
    matches.each do |match|
      if match.is_a?(Array)
        if match.length == 2
          # Pattern with two capture groups (number and question)
          number = match[0]
          question = match[1]
          next if number.nil? || question.nil?

          questions << {
            number: number,
            question: question.strip,
            type: detect_question_type(question),
            input_type: detect_input_type(question)
          }
        elsif match.length == 1
          # Pattern with one capture group (just question)
          question = match[0]
          next if question.nil?

          questions << {
            question: question.strip,
            type: detect_question_type(question),
            input_type: detect_input_type(question)
          }
        end
      else
        # Single capture group
        next if match.nil?

        questions << {
          question: match.strip,
          type: detect_question_type(match),
          input_type: detect_input_type(match)
        }
      end
    end
  end

  # If no structured questions found, look for general questions
  if questions.empty?
    general_questions = text_content.scan(/([^.!?]{1,500}\?)/)
    general_questions.each_with_index do |match, index|
      question_text = match[0].strip
      next if question_text.length < 10 # Skip very short questions

      questions << {
        number: index + 1,
        question: question_text,
        type: detect_question_type(question_text),
        input_type: detect_input_type(question_text)
      }
    end
  end

  # Remove duplicates and clean up
  questions.uniq { |q| q[:question] }
end

#extract_rate_limit_info(result, provider = nil) ⇒ Object

Extract rate limit information from result



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/aidp/harness/condition_detector.rb', line 203

def extract_rate_limit_info(result, provider = nil)
  return nil unless is_rate_limited?(result, provider)

  text_content = [
    result[:error],
    result[:message],
    result[:output],
    result[:response],
    result[:body]
  ].compact.join(" ")

  {
    provider: provider,
    detected_at: Time.now,
    reset_time: extract_reset_time(text_content),
    retry_after: extract_retry_after(text_content),
    limit_type: detect_limit_type(text_content, provider),
    message: text_content
  }
end

#extract_reset_time(text_content) ⇒ Object

Extract reset time from rate limit message



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
# File 'lib/aidp/harness/condition_detector.rb', line 225

def extract_reset_time(text_content)
  # Handle expressions like "resets 4am" or "reset at 4:30pm"
  time_of_day_match = text_content.match(/reset(?:s)?(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)/i)
  if time_of_day_match
    hour = time_of_day_match[1].to_i
    minute = time_of_day_match[2] ? time_of_day_match[2].to_i : 0
    meridiem = time_of_day_match[3].downcase

    hour %= 12
    hour += 12 if meridiem == "pm"

    now = Time.now
    reset_time = Time.new(now.year, now.month, now.day, hour, minute, 0, now.utc_offset)
    reset_time += 86_400 if reset_time <= now
    return reset_time
  end

  @reset_time_patterns.each do |pattern|
    match = text_content.match(pattern)
    next unless match

    if match[1].match?(/^\d+$/)
      # Seconds from now
      return Time.now + match[1].to_i
    else
      # Specific timestamp
      begin
        parsed_time = Time.parse(match[1])
        return parsed_time if parsed_time
      rescue ArgumentError
        nil
      end
    end
  end

  # Default to 60 seconds if no specific time found
  Time.now + 60
end

#extract_retry_after(text_content) ⇒ Object

Extract retry-after value



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/aidp/harness/condition_detector.rb', line 265

def extract_retry_after(text_content)
  # Look for retry-after header or similar
  retry_patterns = [
    /retry\s+after\s+(\d{1,6})/i,
    /wait\s+(\d{1,6})\s+seconds/i,
    /(\d{1,6})\s+seconds\s+until/i
  ]

  retry_patterns.each do |pattern|
    match = text_content.match(pattern)
    return match[1].to_i if match
  end

  # Default retry time
  60
end

#extract_timeout_indicators(result) ⇒ Object

Extract timeout indicators from result



1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
# File 'lib/aidp/harness/condition_detector.rb', line 1313

def extract_timeout_indicators(result)
  text_content = [
    result[:output],
    result[:message],
    result[:response],
    result[:body],
    result[:error]
  ].compact.join(" ")

  timeout_patterns = [
    /timeout/i,
    /timed out/i,
    /time.{0,20}out/i,
    /request.{0,20}timeout/i,
    /connection.{0,20}timeout/i,
    /read.{0,20}timeout/i,
    /write.{0,20}timeout/i,
    /operation.{0,20}timeout/i,
    /execution.{0,20}timeout/i,
    /deadline.{0,20}exceeded/i,
    /time.{0,20}limit.{0,20}exceeded/i,
    /time.{0,20}expired/i
  ]

  found_indicators = []
  timeout_patterns.each do |pattern|
    if text_content.match?(pattern)
      found_indicators << pattern.source
    end
  end

  found_indicators
end

#extract_timeout_info(result, start_time, timeout_duration = nil) ⇒ Object

Extract timeout information from result



1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
# File 'lib/aidp/harness/condition_detector.rb', line 1278

def extract_timeout_info(result, start_time, timeout_duration = nil)
  timeout_info = {
    is_timeout: false,
    timeout_type: nil,
    duration: nil,
    timeout_duration: timeout_duration,
    exceeded_by: nil,
    indicators: []
  }

  return timeout_info unless result.is_a?(Hash) && start_time.is_a?(Time)

  # Check for explicit timeout indicators
  if has_timeout_indicators?(result)
    timeout_info[:is_timeout] = true
    timeout_info[:timeout_type] = "explicit"
    timeout_info[:indicators] = extract_timeout_indicators(result)
  end

  # Check for duration-based timeout
  if timeout_duration
    duration = Time.now - start_time
    timeout_info[:duration] = duration

    if duration > timeout_duration
      timeout_info[:is_timeout] = true
      timeout_info[:timeout_type] = "duration"
      timeout_info[:exceeded_by] = duration - timeout_duration
    end
  end

  timeout_info
end

#extract_user_feedback_info(result) ⇒ Object

Get detailed user feedback information



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/aidp/harness/condition_detector.rb', line 344

def extract_user_feedback_info(result)
  return nil unless needs_user_feedback?(result)

  # Get all text content to analyze
  text_content = [
    result[:output],
    result[:message],
    result[:response],
    result[:body]
  ].compact.join(" ")

  {
    detected_at: Time.now,
    feedback_type: detect_feedback_type(text_content),
    questions: extract_questions(result),
    context: extract_context(text_content),
    urgency: detect_urgency(text_content),
    input_type: detect_input_type(text_content)
  }
end

#get_error_description(error) ⇒ Object

Get error description



1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
# File 'lib/aidp/harness/condition_detector.rb', line 1090

def get_error_description(error)
  error_info = extract_error_info(error)
  error_type = error_info[:type]

  case error_type
  when :timeout
    "Request timed out"
  when :network
    "Network connection error"
  when :dns_resolution
    "DNS resolution failed"
  when :ssl_tls
    "SSL/TLS connection error"
  when :authentication
    "Authentication failed"
  when :permission
    "Permission denied"
  when :access_denied
    "Access denied"
  when :not_found
    "Resource not found"
  when :server_error
    "Server error"
  when :bad_request
    "Bad request"
  when :rate_limit
    "Rate limit exceeded"
  when :quota_exceeded
    "Quota exceeded"
  when :file_not_found
    "File not found"
  when :file_permission
    "File permission denied"
  when :disk_full
    "Disk full"
  when :read_only_filesystem
    "Read-only filesystem"
  when :memory_error
    "Memory error"
  when :resource_exhausted
    "Resource exhausted"
  when :configuration
    "Configuration error"
  when :missing_dependency
    "Missing dependency"
  when :environment
    "Environment error"
  when :anthropic_error
    "Anthropic API error"
  when :openai_error
    "OpenAI API error"
  when :google_error
    "Google API error"
  when :cursor_error
    "Cursor API error"
  when :parsing_error
    "Parsing error"
  when :format_error
    "Format error"
  when :validation_error
    "Validation error"
  when :argument_error
    "Argument error"
  when :system_error
    "System error"
  when :interrupted
    "Operation interrupted"
  else
    "Unknown error"
  end
end

#get_error_recovery_suggestions(error) ⇒ Object

Get error recovery suggestions



1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
# File 'lib/aidp/harness/condition_detector.rb', line 1163

def get_error_recovery_suggestions(error)
  error_info = extract_error_info(error)
  error_type = error_info[:type]

  case error_type
  when :timeout, :network, :dns_resolution, :ssl_tls
    ["Check network connection", "Retry the operation", "Check firewall settings"]
  when :authentication, :permission, :access_denied
    ["Check credentials", "Verify permissions", "Contact administrator"]
  when :rate_limit, :quota_exceeded
    ["Wait before retrying", "Check usage limits", "Consider upgrading plan"]
  when :file_not_found, :file_permission
    ["Check file path", "Verify file permissions", "Ensure file exists"]
  when :disk_full, :memory_error, :resource_exhausted
    ["Free up disk space", "Increase memory", "Check system resources"]
  when :configuration, :missing_dependency, :environment
    ["Check configuration", "Install missing dependencies", "Verify environment setup"]
  when :parsing_error, :format_error, :validation_error, :argument_error
    ["Check input format", "Validate parameters", "Review data structure"]
  when :server_error, :bad_request
    ["Retry the operation", "Check request format", "Contact service provider"]
  else
    ["Review error details", "Check logs", "Contact support"]
  end
end

#get_error_severity(error) ⇒ Object

Get error severity



1079
1080
1081
1082
# File 'lib/aidp/harness/condition_detector.rb', line 1079

def get_error_severity(error)
  error_info = extract_error_info(error)
  error_info[:severity]
end

#get_rate_limit_patterns(provider = nil) ⇒ Object

Get all available rate limit patterns for a provider



1218
1219
1220
1221
1222
1223
1224
# File 'lib/aidp/harness/condition_detector.rb', line 1218

def get_rate_limit_patterns(provider = nil)
  if provider && @rate_limit_patterns[provider.to_sym]
    @rate_limit_patterns[:common] + @rate_limit_patterns[provider.to_sym]
  else
    @rate_limit_patterns[:common]
  end
end

#get_timeout_duration(operation_type, configuration = nil) ⇒ Object

Get timeout duration for operation type



1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
# File 'lib/aidp/harness/condition_detector.rb', line 1348

def get_timeout_duration(operation_type, configuration = nil)
  default_timeouts = {
    analyze: 300, # 5 minutes
    execute: 600, # 10 minutes
    provider_call: 120, # 2 minutes
    file_operation: 30, # 30 seconds
    network_request: 60, # 1 minute
    user_input: 300, # 5 minutes
    default: 120 # 2 minutes
  }

  # Get timeout from configuration if available
  if configuration && configuration[:timeouts] && configuration[:timeouts][operation_type]
    return configuration[:timeouts][operation_type]
  end

  # Return default timeout for operation type
  default_timeouts[operation_type] || default_timeouts[:default]
end

#get_timeout_recovery_suggestions(timeout_info, operation_type = nil) ⇒ Object

Get timeout recovery suggestions



1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
# File 'lib/aidp/harness/condition_detector.rb', line 1396

def get_timeout_recovery_suggestions(timeout_info, operation_type = nil)
  suggestions = []

  case timeout_info[:timeout_type]
  when "explicit"
    suggestions << "Check network connection"
    suggestions << "Verify service availability"
    suggestions << "Retry with longer timeout"
  when "duration"
    suggestions << "Increase timeout duration"
    suggestions << "Optimize operation performance"
    suggestions << "Break operation into smaller chunks"
  end

  # Add operation-specific suggestions
  case operation_type
  when :analyze
    suggestions << "Reduce analysis scope"
    suggestions << "Use incremental analysis"
  when :execute
    suggestions << "Break execution into smaller steps"
    suggestions << "Optimize execution performance"
  when :provider_call
    suggestions << "Check provider status"
    suggestions << "Try different provider"
  when :file_operation
    suggestions << "Check file system performance"
    suggestions << "Verify file permissions"
  when :network_request
    suggestions << "Check network connectivity"
    suggestions << "Verify endpoint availability"
  end

  suggestions.uniq
end

#get_timeout_status_description(timeout_info) ⇒ Object

Get timeout status description



1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
# File 'lib/aidp/harness/condition_detector.rb', line 1378

def get_timeout_status_description(timeout_info)
  return "No timeout" unless timeout_info && timeout_info[:is_timeout]

  case timeout_info[:timeout_type]
  when "explicit"
    "Operation timed out (explicit timeout detected)"
  when "duration"
    if timeout_info[:exceeded_by]
      "Operation timed out (exceeded by #{timeout_info[:exceeded_by].round(2)}s)"
    else
      "Operation timed out (duration exceeded)"
    end
  else
    "Operation timed out"
  end
end

#get_user_feedback_patterns(feedback_type = nil) ⇒ Object

Get user feedback patterns for a specific type



1456
1457
1458
1459
1460
1461
1462
# File 'lib/aidp/harness/condition_detector.rb', line 1456

def get_user_feedback_patterns(feedback_type = nil)
  if feedback_type && @user_feedback_patterns[feedback_type.to_sym]
    @user_feedback_patterns[feedback_type.to_sym]
  else
    @user_feedback_patterns.values.flatten
  end
end

#has_errors?(completion_info) ⇒ Boolean

Check if work has errors

Returns:

  • (Boolean)


1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
# File 'lib/aidp/harness/condition_detector.rb', line 1520

def has_errors?(completion_info)
  return false unless completion_info

  if completion_info[:progress_status] == "has_errors"
    return true
  end

  if completion_info[:next_actions]&.include?("handle_errors")
    return true
  end

  false
end

#has_timeout_indicators?(result) ⇒ Boolean

Check for timeout indicators in result

Returns:

  • (Boolean)


1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
# File 'lib/aidp/harness/condition_detector.rb', line 1244

def has_timeout_indicators?(result)
  return false unless result.is_a?(Hash)

  # Get all text content to analyze
  text_content = [
    result[:output],
    result[:message],
    result[:response],
    result[:body],
    result[:error]
  ].compact.join(" ")

  return false if text_content.empty?

  # Check for timeout patterns
  timeout_patterns = [
    /timeout/i,
    /timed out/i,
    /time.{0,20}out/i,
    /request.{0,20}timeout/i,
    /connection.{0,20}timeout/i,
    /read.{0,20}timeout/i,
    /write.{0,20}timeout/i,
    /operation.{0,20}timeout/i,
    /execution.{0,20}timeout/i,
    /deadline.{0,20}exceeded/i,
    /time.{0,20}limit.{0,20}exceeded/i,
    /time.{0,20}expired/i
  ]

  timeout_patterns.any? { |pattern| text_content.match?(pattern) }
end

#high_confidence_completion?(completion_info) ⇒ Boolean

Check if completion is high confidence

Returns:

  • (Boolean)


1472
1473
1474
# File 'lib/aidp/harness/condition_detector.rb', line 1472

def high_confidence_completion?(completion_info)
  completion_confidence(completion_info) >= 0.8
end

#high_severity_error?(error) ⇒ Boolean

Check if error is high severity

Returns:

  • (Boolean)


1085
1086
1087
# File 'lib/aidp/harness/condition_detector.rb', line 1085

def high_severity_error?(error)
  [:critical, :high].include?(get_error_severity(error))
end

#is_provider_rate_limited?(provider, rate_limit_info) ⇒ Boolean

Check if a provider is currently rate limited

Returns:

  • (Boolean)


1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
# File 'lib/aidp/harness/condition_detector.rb', line 1190

def is_provider_rate_limited?(provider, rate_limit_info)
  return false unless rate_limit_info && rate_limit_info[:provider] == provider

  # Check if the rate limit has expired
  if rate_limit_info[:reset_time] && rate_limit_info[:reset_time] > Time.now
    return true
  end

  false
end

#is_rate_limited?(result, provider = nil) ⇒ Boolean

Check if result indicates rate limiting

Returns:

  • (Boolean)


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
# File 'lib/aidp/harness/condition_detector.rb', line 163

def is_rate_limited?(result, provider = nil)
  return false unless result.is_a?(Hash)

  # Check HTTP status codes
  if result[:status_code] == 429 || result[:http_status] == 429
    return true
  end

  # Get all text content to check
  text_content = [
    result[:error],
    result[:message],
    result[:output],
    result[:response],
    result[:body]
  ].compact.join(" ").strip

  return nil if text_content.empty?

  {
    provider: provider,
    detected_at: Time.now,
    reset_time: extract_reset_time(text_content),
    retry_after: extract_retry_after(text_content),
    limit_type: detect_limit_type(text_content, provider),
    message: text_content
  }

  return false if text_content.empty?

  # Check provider-specific patterns first
  if provider && @rate_limit_patterns[provider.to_sym]
    return true if @rate_limit_patterns[provider.to_sym].any? { |pattern| text_content.match?(pattern) }
  end

  # Check common patterns
  @rate_limit_patterns[:common].any? { |pattern| text_content.match?(pattern) }
end

#is_timeout?(result, start_time, timeout_duration = nil) ⇒ Boolean

Check if operation has timed out

Returns:

  • (Boolean)


1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
# File 'lib/aidp/harness/condition_detector.rb', line 1227

def is_timeout?(result, start_time, timeout_duration = nil)
  return false unless result.is_a?(Hash) && start_time.is_a?(Time)

  # Check for explicit timeout indicators in result
  if has_timeout_indicators?(result)
    return true
  end

  # Check if operation duration exceeds timeout
  if timeout_duration && (Time.now - start_time) > timeout_duration
    return true
  end

  false
end

#is_waiting_for_input?(completion_info) ⇒ Boolean

Check if work is waiting for input

Returns:

  • (Boolean)


1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
# File 'lib/aidp/harness/condition_detector.rb', line 1505

def is_waiting_for_input?(completion_info)
  return false unless completion_info

  if completion_info[:progress_status] == "waiting_for_input"
    return true
  end

  if completion_info[:next_actions]&.include?("collect_user_input")
    return true
  end

  false
end

#is_work_complete?(result, progress) ⇒ Boolean

Check if work is complete

Returns:

  • (Boolean)


546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'lib/aidp/harness/condition_detector.rb', line 546

def is_work_complete?(result, progress)
  return false unless result.is_a?(Hash)

  # Check if all steps are completed
  if progress&.completed_steps && progress.total_steps &&
      progress.completed_steps.size == progress.total_steps
    return true
  end

  # Get all text content to analyze
  text_content = [
    result[:output],
    result[:message],
    result[:response],
    result[:body]
  ].compact.join(" ")

  return false if text_content.empty?

  # Check for completion indicators
  completion_info = extract_completion_info(result, progress)
  completion_info[:is_complete]
end

#is_work_in_progress?(completion_info) ⇒ Boolean

Check if work is in progress

Returns:

  • (Boolean)


1496
1497
1498
1499
1500
1501
1502
# File 'lib/aidp/harness/condition_detector.rb', line 1496

def is_work_in_progress?(completion_info)
  return false unless completion_info

  !completion_info[:is_complete] &&
    completion_info[:progress_status] != "waiting_for_input" &&
    completion_info[:progress_status] != "has_errors"
end

#low_confidence_completion?(completion_info) ⇒ Boolean

Check if completion is low confidence

Returns:

  • (Boolean)


1483
1484
1485
1486
# File 'lib/aidp/harness/condition_detector.rb', line 1483

def low_confidence_completion?(completion_info)
  confidence = completion_confidence(completion_info)
  confidence > 0.0 && confidence < 0.5
end

#max_retries_for_error(error) ⇒ Object

Get maximum retries for error type



1073
1074
1075
1076
# File 'lib/aidp/harness/condition_detector.rb', line 1073

def max_retries_for_error(error)
  error_info = extract_error_info(error)
  error_info[:retry_strategy][:max_retries]
end

#medium_confidence_completion?(completion_info) ⇒ Boolean

Check if completion is medium confidence

Returns:

  • (Boolean)


1477
1478
1479
1480
# File 'lib/aidp/harness/condition_detector.rb', line 1477

def medium_confidence_completion?(completion_info)
  confidence = completion_confidence(completion_info)
  confidence >= 0.5 && confidence < 0.8
end

#needs_user_feedback?(result) ⇒ Boolean

Check if result needs user feedback

Returns:

  • (Boolean)


323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/aidp/harness/condition_detector.rb', line 323

def needs_user_feedback?(result)
  return false unless result.is_a?(Hash)

  # Get all text content to check
  text_content = [
    result[:output],
    result[:message],
    result[:response],
    result[:body]
  ].compact.join(" ")

  return false if text_content.empty?

  # Check for context patterns first
  return true if @context_patterns.any? { |pattern| text_content.match?(pattern) }

  # Check for any user feedback patterns
  @user_feedback_patterns.values.flatten.any? { |pattern| text_content.match?(pattern) }
end

#next_actions(completion_info) ⇒ Object

Get next actions from completion info



1489
1490
1491
1492
1493
# File 'lib/aidp/harness/condition_detector.rb', line 1489

def next_actions(completion_info)
  return [] unless completion_info && completion_info[:next_actions]

  completion_info[:next_actions]
end

#progress_status_description(completion_info) ⇒ Object

Get progress status description



1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
# File 'lib/aidp/harness/condition_detector.rb', line 1535

def progress_status_description(completion_info)
  return "unknown" unless completion_info

  case completion_info[:progress_status]
  when "all_steps_completed"
    "All steps completed successfully"
  when "near_completion"
    "Near completion (80%+ done)"
  when "half_complete"
    "Half complete (50%+ done)"
  when "early_stage"
    "Early stage (20%+ done)"
  when "just_started"
    "Just started (0-20% done)"
  when "has_next_actions"
    "Has next actions to perform"
  when "waiting_for_input"
    "Waiting for user input"
  when "has_errors"
    "Has errors that need attention"
  when "in_progress"
    "Work in progress"
  else
    "Status unknown"
  end
end

#rate_limit_expired?(rate_limit_info) ⇒ Boolean

Check if rate limit has expired

Returns:

  • (Boolean)


1211
1212
1213
1214
1215
# File 'lib/aidp/harness/condition_detector.rb', line 1211

def rate_limit_expired?(rate_limit_info)
  return true unless rate_limit_info && rate_limit_info[:reset_time]

  rate_limit_info[:reset_time] <= Time.now
end

#recoverable_error?(error) ⇒ Boolean

Check if error is recoverable

Returns:

  • (Boolean)


1050
1051
1052
1053
# File 'lib/aidp/harness/condition_detector.rb', line 1050

def recoverable_error?(error)
  error_info = extract_error_info(error)
  error_info[:recoverable]
end

#retry_delay_for_error(error, attempt_number) ⇒ Object

Get retry delay for error type



1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/aidp/harness/condition_detector.rb', line 1056

def retry_delay_for_error(error, attempt_number)
  error_info = extract_error_info(error)
  retry_strategy = error_info[:retry_strategy]

  case retry_strategy[:strategy]
  when :exponential_backoff
    retry_strategy[:base_delay] * (2**(attempt_number - 1))
  when :fixed_delay
    retry_strategy[:delay]
  when :no_retry
    0
  else
    5 # Default delay
  end
end

#time_until_reset(rate_limit_info) ⇒ Object

Get time until rate limit resets



1202
1203
1204
1205
1206
1207
1208
# File 'lib/aidp/harness/condition_detector.rb', line 1202

def time_until_reset(rate_limit_info)
  return 0 unless rate_limit_info && rate_limit_info[:reset_time]

  reset_time = rate_limit_info[:reset_time]
  remaining = reset_time - Time.now
  [remaining, 0].max
end

#time_until_timeout(start_time, timeout_duration) ⇒ Object

Get time remaining until timeout



1369
1370
1371
1372
1373
1374
1375
# File 'lib/aidp/harness/condition_detector.rb', line 1369

def time_until_timeout(start_time, timeout_duration)
  return 0 unless start_time.is_a?(Time) && timeout_duration

  elapsed = Time.now - start_time
  remaining = timeout_duration - elapsed
  [remaining, 0].max
end

#validate_user_response(response, expected_input_type) ⇒ Object

Validate user response based on expected input type



1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'lib/aidp/harness/condition_detector.rb', line 1433

def validate_user_response(response, expected_input_type)
  return false if response.nil? || response.strip.empty?

  case expected_input_type
  when "email"
    response.match?(/\A[\w+\-.]+@[a-z\d-]+(\.[a-z\d-]+)*\.[a-z]+\z/i)
  when "url"
    response.match?(/\Ahttps?:\/\/.+/i)
  when "number"
    response.match?(/^\d+$/)
  when "boolean"
    response.match?(/^(yes|no|true|false|y|n|1|0)$/i)
  when "file"
    response.match?(/^@/) || File.exist?(response)
  when "path"
    File.exist?(response) || Dir.exist?(response)
  else
    # For text input, just check it's not empty
    !response.strip.empty?
  end
end