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 Method Summary collapse

Constructor Details

#initializeConditionDetector

Returns a new instance of ConditionDetector.



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

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
    ],
    # 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
    ],
    # 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.{0,20}in.{0,20}(\d+).{0,20}seconds/i,
    /retry.{0,20}after.{0,20}(\d+).{0,20}seconds/i,
    /wait[^\d]*(\d+)[^\d]*seconds/i,
    /(\d+).{0,20}seconds.{0,20}until.{0,20}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 Method Details

#classify_error(error) ⇒ Object

Classify error type with comprehensive analysis



814
815
816
817
818
819
# File 'lib/aidp/harness/condition_detector.rb', line 814

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



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

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

#detect_explicit_completion(text_content) ⇒ Object

Detect explicit completion indicators



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

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



329
330
331
332
333
334
335
336
337
# File 'lib/aidp/harness/condition_detector.rb', line 329

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



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

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



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/aidp/harness/condition_detector.rb', line 381

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



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

def detect_limit_type(text_content, provider)
  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



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

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



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

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



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

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



946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
# File 'lib/aidp/harness/condition_detector.rb', line 946

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



966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
# File 'lib/aidp/harness/condition_detector.rb', line 966

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



989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
# File 'lib/aidp/harness/condition_detector.rb', line 989

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



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

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



340
341
342
343
344
345
346
347
# File 'lib/aidp/harness/condition_detector.rb', line 340

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



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# File 'lib/aidp/harness/condition_detector.rb', line 822

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



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

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



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/aidp/harness/condition_detector.rb', line 185

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



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/aidp/harness/condition_detector.rb', line 207

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

    if match[1].match?(/^\d+$/)
      # Seconds from now
      Time.now + match[1].to_i
    else
      # Specific timestamp
      begin
        Time.parse(match[1])
      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



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/aidp/harness/condition_detector.rb', line 230

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



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

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



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

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



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/aidp/harness/condition_detector.rb', line 307

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_completion_confidence(completion_info) ⇒ Object

Get completion confidence level



1428
1429
1430
1431
1432
# File 'lib/aidp/harness/condition_detector.rb', line 1428

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

  completion_info[:confidence]
end

#get_error_description(error) ⇒ Object

Get error description



1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
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
# File 'lib/aidp/harness/condition_detector.rb', line 1053

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



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

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



1042
1043
1044
1045
# File 'lib/aidp/harness/condition_detector.rb', line 1042

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

#get_next_actions(completion_info) ⇒ Object

Get next actions from completion info



1452
1453
1454
1455
1456
# File 'lib/aidp/harness/condition_detector.rb', line 1452

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

  completion_info[:next_actions]
end

#get_progress_status_description(completion_info) ⇒ Object

Get progress status description



1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
# File 'lib/aidp/harness/condition_detector.rb', line 1498

def get_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

#get_rate_limit_patterns(provider = nil) ⇒ Object

Get all available rate limit patterns for a provider



1181
1182
1183
1184
1185
1186
1187
# File 'lib/aidp/harness/condition_detector.rb', line 1181

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



1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
# File 'lib/aidp/harness/condition_detector.rb', line 1311

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



1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
# File 'lib/aidp/harness/condition_detector.rb', line 1359

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



1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
# File 'lib/aidp/harness/condition_detector.rb', line 1341

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



1419
1420
1421
1422
1423
1424
1425
# File 'lib/aidp/harness/condition_detector.rb', line 1419

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)


1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# File 'lib/aidp/harness/condition_detector.rb', line 1483

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)


1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'lib/aidp/harness/condition_detector.rb', line 1207

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)


1435
1436
1437
# File 'lib/aidp/harness/condition_detector.rb', line 1435

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

#high_severity_error?(error) ⇒ Boolean

Check if error is high severity

Returns:

  • (Boolean)


1048
1049
1050
# File 'lib/aidp/harness/condition_detector.rb', line 1048

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)


1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
# File 'lib/aidp/harness/condition_detector.rb', line 1153

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)


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

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(" ")

  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)


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

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)


1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
# File 'lib/aidp/harness/condition_detector.rb', line 1468

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)


509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/aidp/harness/condition_detector.rb', line 509

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)


1459
1460
1461
1462
1463
1464
1465
# File 'lib/aidp/harness/condition_detector.rb', line 1459

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)


1446
1447
1448
1449
# File 'lib/aidp/harness/condition_detector.rb', line 1446

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

#max_retries_for_error(error) ⇒ Object

Get maximum retries for error type



1036
1037
1038
1039
# File 'lib/aidp/harness/condition_detector.rb', line 1036

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)


1440
1441
1442
1443
# File 'lib/aidp/harness/condition_detector.rb', line 1440

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

#needs_user_feedback?(result) ⇒ Boolean

Check if result needs user feedback

Returns:

  • (Boolean)


286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/aidp/harness/condition_detector.rb', line 286

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

#rate_limit_expired?(rate_limit_info) ⇒ Boolean

Check if rate limit has expired

Returns:

  • (Boolean)


1174
1175
1176
1177
1178
# File 'lib/aidp/harness/condition_detector.rb', line 1174

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)


1013
1014
1015
1016
# File 'lib/aidp/harness/condition_detector.rb', line 1013

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



1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# File 'lib/aidp/harness/condition_detector.rb', line 1019

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



1165
1166
1167
1168
1169
1170
1171
# File 'lib/aidp/harness/condition_detector.rb', line 1165

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



1332
1333
1334
1335
1336
1337
1338
# File 'lib/aidp/harness/condition_detector.rb', line 1332

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



1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
# File 'lib/aidp/harness/condition_detector.rb', line 1396

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