100XZX001 commited on
Commit
b89d049
·
verified ·
1 Parent(s): 6b4dcf0

Update author.py

Browse files
Files changed (1) hide show
  1. author.py +218 -212
author.py CHANGED
@@ -1,213 +1,219 @@
1
- # cell 7 author.py – Final production version: stateful, evidence-driven, belief tracking
2
-
3
- import re
4
- import ast
5
- from dataclasses import dataclass, field
6
- from typing import List, Dict, Any, Optional
7
-
8
- @dataclass
9
- class PersonaAuthor:
10
- """
11
- Simulates a human developer with:
12
- - Continuous belief (confidence)
13
- - Evidence-based reasoning
14
- - Conversation memory
15
- - Code inspection awareness
16
- """
17
-
18
- personality: str = "defensive" # defensive | junior | collaborative
19
- max_persuasion_rounds: int = 5
20
-
21
- # Evidence weights
22
- weight_test_pass: float = 0.5
23
- weight_lint_clean: float = 0.2
24
- weight_doc_found: float = 0.15
25
- weight_explanation_quality: float = 0.15
26
-
27
- # Personality thresholds
28
- thresholds: Dict[str, float] = field(default_factory=lambda: {
29
- "defensive": 0.7,
30
- "junior": 0.3,
31
- "collaborative": 0.5,
32
- })
33
-
34
- # Internal state
35
- _confidence: float = 0.0
36
- _conversation: List[Dict[str, Any]] = field(default_factory=list)
37
- _pushback_count: int = 0
38
- _last_evidence_score: float = 0.0
39
- _stagnation_counter: int = 0
40
-
41
- # ------------------------------------------------------------------
42
- # Lifecycle
43
- # ------------------------------------------------------------------
44
- def __post_init__(self):
45
- self.reset()
46
-
47
- def reset(self):
48
- self._confidence = 0.0
49
- self._conversation.clear()
50
- self._pushback_count = 0
51
- self._last_evidence_score = 0.0
52
- self._stagnation_counter = 0
53
-
54
- # ------------------------------------------------------------------
55
- # Main interaction
56
- # ------------------------------------------------------------------
57
- def respond(self,
58
- agent_comment: str = "",
59
- agent_question: str = "",
60
- test_results: Optional[str] = None,
61
- lint_results: Optional[str] = None,
62
- doc_results: Optional[str] = None,
63
- proposed_fix: Optional[str] = None,
64
- original_code: Optional[str] = None) -> str:
65
-
66
- # Store conversation
67
- self._conversation.append({
68
- "comment": agent_comment,
69
- "question": agent_question,
70
- "test": test_results,
71
- "lint": lint_results,
72
- "docs": doc_results
73
- })
74
-
75
- # Extract structured evidence
76
- evidence = self._extract_evidence(test_results, lint_results, doc_results)
77
-
78
- # Code inspection
79
- if proposed_fix and original_code:
80
- evidence["code_change"] = self._inspect_code(proposed_fix, original_code)
81
-
82
- # Explanation score
83
- text = (agent_comment + " " + agent_question).lower()
84
- explanation_score = self._score_explanation(text)
85
-
86
- # Compute evidence score
87
- evidence_score = (
88
- self.weight_test_pass * evidence.get("test_pass_ratio", 0.0) +
89
- self.weight_lint_clean * (1 - min(1.0, evidence.get("lint_errors", 0)/10)) +
90
- self.weight_doc_found * (1.0 if evidence.get("doc_found") else 0.0) +
91
- self.weight_explanation_quality * explanation_score
92
- )
93
-
94
- evidence_score = max(0.0, min(1.0, evidence_score))
95
-
96
- # Detect improvement
97
- delta = evidence_score - self._last_evidence_score
98
- self._last_evidence_score = evidence_score
99
-
100
- if delta > 0.05:
101
- self._stagnation_counter = 0
102
- else:
103
- self._stagnation_counter += 1
104
-
105
- # Update belief (momentum)
106
- lr = 0.3
107
- self._confidence = (1 - lr) * self._confidence + lr * evidence_score
108
-
109
- # Penalise stagnation
110
- if self._stagnation_counter >= 2:
111
- self._confidence *= 0.9
112
-
113
- # Decision
114
- threshold = self.thresholds.get(self.personality, 0.5)
115
-
116
- if self._confidence >= threshold or self._pushback_count >= self.max_persuasion_rounds:
117
- return "Alright, I'm convinced. Let's proceed with your fix."
118
-
119
- # Otherwise push back
120
- self._pushback_count += 1
121
- return self._generate_pushback(evidence, text)
122
-
123
- # ------------------------------------------------------------------
124
- # Evidence extraction
125
- # ------------------------------------------------------------------
126
- def _extract_evidence(self, test_results, lint_results, doc_results):
127
- evidence = {
128
- "test_pass_ratio": 0.0,
129
- "lint_errors": 0,
130
- "doc_found": False
131
- }
132
-
133
- # Parse test results
134
- if test_results:
135
- match = re.search(r'(\d+)\s*/\s*(\d+)', test_results)
136
- if match:
137
- p, t = int(match.group(1)), int(match.group(2))
138
- evidence["test_pass_ratio"] = p / t if t else 0.0
139
- elif "true" in test_results.lower():
140
- evidence["test_pass_ratio"] = 1.0
141
- elif "false" in test_results.lower():
142
- evidence["test_pass_ratio"] = 0.0
143
-
144
- # Lint errors
145
- if lint_results:
146
- evidence["lint_errors"] = len(re.findall(r'error', lint_results.lower()))
147
-
148
- # Docs
149
- if doc_results and "no relevant" not in doc_results.lower():
150
- evidence["doc_found"] = True
151
-
152
- return evidence
153
-
154
- # ------------------------------------------------------------------
155
- # Explanation scoring
156
- # ------------------------------------------------------------------
157
- def _score_explanation(self, text: str) -> float:
158
- score = 0.0
159
-
160
- if "because" in text or "therefore" in text:
161
- score += 0.3
162
- if "test" in text or "example" in text:
163
- score += 0.2
164
- if len(text.split()) > 30:
165
- score += 0.2
166
- if "error" in text or "fix" in text:
167
- score += 0.1
168
-
169
- return min(1.0, score)
170
-
171
- # ------------------------------------------------------------------
172
- # Code inspection
173
- # ------------------------------------------------------------------
174
- def _inspect_code(self, new_code: str, old_code: str) -> float:
175
- try:
176
- t1 = ast.parse(old_code)
177
- t2 = ast.parse(new_code)
178
-
179
- n1 = len(list(ast.walk(t1)))
180
- n2 = len(list(ast.walk(t2)))
181
-
182
- change = abs(n2 - n1) / max(n1, 1)
183
- return min(1.0, change)
184
- except:
185
- return 0.0
186
-
187
- # ------------------------------------------------------------------
188
- # Pushback generator
189
- # ------------------------------------------------------------------
190
- def _generate_pushback(self, evidence, text):
191
- if evidence["test_pass_ratio"] < 0.5:
192
- return "Tests are still failing. Show a passing case."
193
-
194
- if evidence["lint_errors"] > 0:
195
- return f"There are {evidence['lint_errors']} lint errors. Fix them."
196
-
197
- if not evidence["doc_found"]:
198
- return "Provide documentation or reference."
199
-
200
- if "because" not in text:
201
- return "Explain why this works."
202
-
203
- if len(text.split()) < 20:
204
- return "Too brief. Expand your reasoning."
205
-
206
- return "Not convinced yet. Give a concrete example."
207
-
208
- # ------------------------------------------------------------------
209
- # Score
210
- # ------------------------------------------------------------------
211
- def get_negotiation_score(self) -> float:
212
- penalty = 0.1 * min(3, self._pushback_count)
 
 
 
 
 
 
213
  return max(0.0, min(1.0, self._confidence - penalty))
 
1
+ # cell 7 author.py – Final production version: stateful, evidence-driven, belief tracking
2
+
3
+ import re
4
+ import ast
5
+ from dataclasses import dataclass, field
6
+ from typing import List, Dict, Any, Optional
7
+
8
+ @dataclass
9
+ class PersonaAuthor:
10
+ """
11
+ Simulates a human developer with:
12
+ - Continuous belief (confidence)
13
+ - Evidence-based reasoning
14
+ - Conversation memory
15
+ - Code inspection awareness
16
+ """
17
+
18
+ personality: str = "defensive" # defensive | junior | collaborative
19
+ max_persuasion_rounds: int = 5
20
+
21
+ # Evidence weights
22
+ weight_test_pass: float = 0.5
23
+ weight_lint_clean: float = 0.2
24
+ weight_doc_found: float = 0.15
25
+ weight_explanation_quality: float = 0.15
26
+
27
+ # Personality thresholds
28
+ thresholds: Dict[str, float] = field(default_factory=lambda: {
29
+ "defensive": 0.7,
30
+ "junior": 0.3,
31
+ "collaborative": 0.5,
32
+ })
33
+
34
+ # Internal state
35
+ _confidence: float = 0.0
36
+ _conversation: List[Dict[str, Any]] = field(default_factory=list)
37
+ _pushback_count: int = 0
38
+ _last_evidence_score: float = 0.0
39
+ _stagnation_counter: int = 0
40
+
41
+ # ------------------------------------------------------------------
42
+ # Lifecycle
43
+ # ------------------------------------------------------------------
44
+ def __post_init__(self):
45
+ self.reset()
46
+
47
+ def reset(self):
48
+ self._confidence = 0.0
49
+ self._conversation.clear()
50
+ self._pushback_count = 0
51
+ self._last_evidence_score = 0.0
52
+ self._stagnation_counter = 0
53
+
54
+ # ------------------------------------------------------------------
55
+ # Main interaction
56
+ # ------------------------------------------------------------------
57
+ # Added weight for code change magnitude
58
+ weight_code_change: float = 0.1 # small change is better
59
+
60
+ def respond(self,
61
+ agent_comment: str = "",
62
+ agent_question: str = "",
63
+ test_results: Optional[str] = None,
64
+ lint_results: Optional[str] = None,
65
+ doc_results: Optional[str] = None,
66
+ proposed_fix: Optional[str] = None,
67
+ original_code: Optional[str] = None) -> str:
68
+
69
+ # Store conversation
70
+ self._conversation.append({
71
+ "comment": agent_comment,
72
+ "question": agent_question,
73
+ "test": test_results,
74
+ "lint": lint_results,
75
+ "docs": doc_results
76
+ })
77
+
78
+ # Extract structured evidence
79
+ evidence = self._extract_evidence(test_results, lint_results, doc_results)
80
+
81
+ # Code inspection
82
+ code_change = 0.0
83
+ if proposed_fix and original_code:
84
+ code_change = self._inspect_code(proposed_fix, original_code)
85
+ evidence["code_change"] = code_change
86
+
87
+ # Explanation score
88
+ text = (agent_comment + " " + agent_question).lower()
89
+ explanation_score = self._score_explanation(text)
90
+
91
+ # Compute evidence score – now includes code change penalty (1 - change)
92
+ evidence_score = (
93
+ self.weight_test_pass * evidence.get("test_pass_ratio", 0.0) +
94
+ self.weight_lint_clean * (1 - min(1.0, evidence.get("lint_errors", 0)/10)) +
95
+ self.weight_doc_found * (1.0 if evidence.get("doc_found") else 0.0) +
96
+ self.weight_explanation_quality * explanation_score +
97
+ self.weight_code_change * (1.0 - code_change) # surgical fix rewarded
98
+ )
99
+
100
+ evidence_score = max(0.0, min(1.0, evidence_score))
101
+
102
+ # Detect improvement
103
+ delta = evidence_score - self._last_evidence_score
104
+ self._last_evidence_score = evidence_score
105
+
106
+ if delta > 0.05:
107
+ self._stagnation_counter = 0
108
+ else:
109
+ self._stagnation_counter += 1
110
+
111
+ # Update belief (momentum)
112
+ lr = 0.3
113
+ self._confidence = (1 - lr) * self._confidence + lr * evidence_score
114
+
115
+ # Penalise stagnation
116
+ if self._stagnation_counter >= 2:
117
+ self._confidence *= 0.9
118
+
119
+ # Decision
120
+ threshold = self.thresholds.get(self.personality, 0.5)
121
+
122
+ if self._confidence >= threshold or self._pushback_count >= self.max_persuasion_rounds:
123
+ return "Alright, I'm convinced. Let's proceed with your fix."
124
+
125
+ # Otherwise push back
126
+ self._pushback_count += 1
127
+ return self._generate_pushback(evidence, text)
128
+
129
+ # ------------------------------------------------------------------
130
+ # Evidence extraction
131
+ # ------------------------------------------------------------------
132
+ def _extract_evidence(self, test_results, lint_results, doc_results):
133
+ evidence = {
134
+ "test_pass_ratio": 0.0,
135
+ "lint_errors": 0,
136
+ "doc_found": False
137
+ }
138
+
139
+ # Parse test results
140
+ if test_results:
141
+ match = re.search(r'(\d+)\s*/\s*(\d+)', test_results)
142
+ if match:
143
+ p, t = int(match.group(1)), int(match.group(2))
144
+ evidence["test_pass_ratio"] = p / t if t else 0.0
145
+ elif "true" in test_results.lower():
146
+ evidence["test_pass_ratio"] = 1.0
147
+ elif "false" in test_results.lower():
148
+ evidence["test_pass_ratio"] = 0.0
149
+
150
+ # Lint errors
151
+ if lint_results:
152
+ evidence["lint_errors"] = len(re.findall(r'error', lint_results.lower()))
153
+
154
+ # Docs
155
+ if doc_results and "no relevant" not in doc_results.lower():
156
+ evidence["doc_found"] = True
157
+
158
+ return evidence
159
+
160
+ # ------------------------------------------------------------------
161
+ # Explanation scoring
162
+ # ------------------------------------------------------------------
163
+ def _score_explanation(self, text: str) -> float:
164
+ score = 0.0
165
+
166
+ if "because" in text or "therefore" in text:
167
+ score += 0.3
168
+ if "test" in text or "example" in text:
169
+ score += 0.2
170
+ if len(text.split()) > 30:
171
+ score += 0.2
172
+ if "error" in text or "fix" in text:
173
+ score += 0.1
174
+
175
+ return min(1.0, score)
176
+
177
+ # ------------------------------------------------------------------
178
+ # Code inspection
179
+ # ------------------------------------------------------------------
180
+ def _inspect_code(self, new_code: str, old_code: str) -> float:
181
+ try:
182
+ t1 = ast.parse(old_code)
183
+ t2 = ast.parse(new_code)
184
+
185
+ n1 = len(list(ast.walk(t1)))
186
+ n2 = len(list(ast.walk(t2)))
187
+
188
+ change = abs(n2 - n1) / max(n1, 1)
189
+ return min(1.0, change)
190
+ except:
191
+ return 0.0
192
+
193
+ # ------------------------------------------------------------------
194
+ # Pushback generator
195
+ # ------------------------------------------------------------------
196
+ def _generate_pushback(self, evidence, text):
197
+ if evidence["test_pass_ratio"] < 0.5:
198
+ return "Tests are still failing. Show a passing case."
199
+
200
+ if evidence["lint_errors"] > 0:
201
+ return f"There are {evidence['lint_errors']} lint errors. Fix them."
202
+
203
+ if not evidence["doc_found"]:
204
+ return "Provide documentation or reference."
205
+
206
+ if "because" not in text:
207
+ return "Explain why this works."
208
+
209
+ if len(text.split()) < 20:
210
+ return "Too brief. Expand your reasoning."
211
+
212
+ return "Not convinced yet. Give a concrete example."
213
+
214
+ # ------------------------------------------------------------------
215
+ # Score
216
+ # ------------------------------------------------------------------
217
+ def get_negotiation_score(self) -> float:
218
+ penalty = 0.1 * min(3, self._pushback_count)
219
  return max(0.0, min(1.0, self._confidence - penalty))