File size: 16,613 Bytes
2419253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""Receive questions about local code and answer from source and recorded runs.

This is a read part of the same workbench, not a repair attempt. Python's syntax
tree supplies definitions, control flow and calls; the existing runner supplies
failure evidence. Neither an identifier nor a comment establishes what a program
actually does at runtime. The original question and any missing evidence survive
opening a folder and follow-up turns.
"""
import ast
import hashlib
import re
from pathlib import Path


EXTENSIONS = {'.py', '.js', '.ts', '.jsx', '.tsx', '.c', '.cpp', '.h', '.java',
              '.rs', '.go', '.rb', '.php', '.cs', '.sh', '.ps1', '.html', '.css', '.sql'}
DIAGNOSTIC = re.compile(r"\b(?:fail(?:s|ed|ing|ure)?|crash(?:es|ed|ing)?|error|exception|broken|wrong|bug)\b", re.I)
REFERENCE = re.compile(r"\b(?:it|its|that|this|the code|the script|the function|the module)\b", re.I)


def _sha(data):
    return hashlib.sha256(data).hexdigest()


def receive(text, native=None, previous=None):
    """Identify an informational code question without accepting a work command."""
    import language_bridge as language
    from turn_meaning import literals, outside_literals
    reading = language.request_reading(text)['reading'].strip()
    instruction = outside_literals(reading)
    if not language.asks_about(text):
        return None
    # A requested action following the explanation is still work. Do not answer
    # one clause and silently consume the instruction to change/run something.
    if re.search(r"(?:\b(?:and|then|also)\b|[;!?\n]|\.(?=\s|$))\s*"
                 r"(?:(?:and|then|also|please)\s+)*"
                 r"(?:(?:could|can|would|will)\s+you\s+(?:please\s+)?)?"
                 r"(?:fix|repair|change|build|create|write|run|execute|delete|send)\b", instruction, re.I):
        return None
    files = list(dict.fromkeys(item['text'].strip('`\"\'') for item in literals(text)
                              if item['kind'] == 'file' and
                              Path(item['text'].strip('`\"\'')).suffix.lower() in EXTENSIONS))
    bound = False
    # A demonstrative with its own named object is a new subject, not a bare
    # reference to code ("this law" versus "this function").
    foreign_subject = re.search(r'\b(?:this|that|the)\s+([A-Za-z]+)', instruction, re.I)
    foreign_subject = bool(foreign_subject and foreign_subject[1].lower() not in
                           {'code', 'script', 'function', 'module', 'file', 'program', 'error', 'failure'})
    if not files and previous and not foreign_subject and (REFERENCE.search(instruction) or
                                  re.fullmatch(r"\s*(?:why|how|tell me more|explain further)[?.! ]*", reading, re.I)):
        files = list(previous.get('files') or [])
        bound = bool(files)
    if not files:
        return None
    failure = bool(DIAGNOSTIC.search(instruction)) or bool(bound and previous.get('failure') and
                      re.fullmatch(r"\s*(?:why|how|tell me more|explain further)[?.! ]*", reading, re.I))
    return {'question': text, 'files': files, 'failure': failure, 'bound_previous': bound,
            'basis': 'local source + existing run receipts',
            'request_graph': (native or {}).get('graph')}


def _inside(root, path):
    try:
        Path(path).resolve().relative_to(Path(root).resolve())
        return True
    except ValueError:
        return False


def _expr(node):
    return ast.unparse(node)


def inspect_source(name, source):
    """Facts mechanically recoverable from source, with line/column evidence."""
    receipt = {'file': name, 'sha256': _sha(source.encode('utf-8')), 'facts': [], 'syntax': None}
    if Path(name).suffix.lower() != '.py':
        receipt['limit'] = 'A structural explanation part for this source language is not connected.'
        return receipt
    try:
        tree = ast.parse(source, filename=name)
    except SyntaxError as error:
        receipt['syntax'] = {'message': error.msg, 'line': error.lineno, 'column': error.offset,
                             'source': (error.text or '').strip()}
        return receipt
    receipt['doc'] = ast.get_docstring(tree) or ''      # the module's own account of what it is for

    def fact(node, kind, **content):
        receipt['facts'].append(dict(kind=kind, line=node.lineno, end_line=node.end_lineno,
                                     source=ast.get_source_segment(source, node), **content))

    # Definition bodies have their own scope: a nested return is not a return
    # from its enclosing function. All the source remains in the receipt.
    def walk_scope(nodes, owner):
        for node in nodes:
            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                params = [a.arg for a in node.args.posonlyargs + node.args.args]
                if node.args.vararg:
                    params.append('*' + node.args.vararg.arg)
                params += [a.arg for a in node.args.kwonlyargs]
                if node.args.kwarg:
                    params.append('**' + node.args.kwarg.arg)
                path = owner + '.' + node.name if owner else node.name
                fact(node, 'function', name=path, parameters=params,
                     asynchronous=isinstance(node, ast.AsyncFunctionDef),
                     docstring=ast.get_docstring(node))
                walk_scope(node.body, path)
            elif isinstance(node, ast.ClassDef):
                path = owner + '.' + node.name if owner else node.name
                fact(node, 'class', name=path, bases=[_expr(b) for b in node.bases])
                walk_scope(node.body, path)
            else:
                if isinstance(node, ast.Return):
                    fact(node, 'return', owner=owner, value=_expr(node.value) if node.value else 'None')
                elif isinstance(node, (ast.Import, ast.ImportFrom)):
                    fact(node, 'import', owner=owner, statement=_expr(node))
                elif isinstance(node, ast.If):
                    fact(node, 'condition', owner=owner, condition=_expr(node.test), alternate=bool(node.orelse))
                elif isinstance(node, (ast.For, ast.AsyncFor)):
                    fact(node, 'iteration', owner=owner, target=_expr(node.target), iterable=_expr(node.iter))
                elif isinstance(node, ast.While):
                    fact(node, 'repetition', owner=owner, condition=_expr(node.test))
                elif isinstance(node, ast.Raise):
                    fact(node, 'raise', owner=owner, value=_expr(node.exc) if node.exc else 'the active exception')
                elif isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
                    fact(node, 'assignment', owner=owner, statement=_expr(node))
                elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
                    fact(node, 'call', owner=owner, expression=_expr(node.value))
                for field in ('body', 'orelse', 'finalbody'):
                    value = getattr(node, field, None)
                    if isinstance(value, list):
                        walk_scope(value, owner)
                for handler in getattr(node, 'handlers', []):
                    walk_scope(handler.body, owner)
                for case in getattr(node, 'cases', []):
                    walk_scope(case.body, owner)
    walk_scope(tree.body, '')
    return receipt


def describe(receipt):
    name = receipt['file']
    if receipt.get('syntax'):
        error = receipt['syntax']
        return ['`%s` cannot be parsed as Python: %s at line %s, column %s.' %
                (name, error['message'], error['line'], error['column']),
                'The source there is `%s`.' % error['source']]
    if receipt.get('limit'):
        return ['I can read `%s`, but %s' % (name, receipt['limit'][0].lower() + receipt['limit'][1:])]
    facts = receipt['facts']
    definitions = [f for f in facts if f['kind'] in ('function', 'class')]
    sentences = ['`%s` parses as Python. This describes the source; it does not establish a successful run.' % name]
    own = ' '.join(str(receipt.get('doc') or '').split())
    if own:                                             # what the file says it is for, in its own words, before its parts
        sentences.insert(0, 'In its own words (its module docstring): ' + ' '.join(
            __import__('re').split(r'(?<=[.!?])\s+', own)[:3]))
    if not facts:
        sentences.append('The structural reader found no definitions, assignments, calls, imports, or control-flow statements to explain.')
    for item in definitions:
        if item['kind'] == 'class':
            sentences.append('Line %d defines the class `%s`%s.' % (item['line'], item['name'],
                              ' with bases ' + ', '.join('`' + b + '`' for b in item['bases']) if item['bases'] else ''))
            continue
        sentence = 'Line %d defines `%s(%s)`' % (item['line'], item['name'], ', '.join(item['parameters']))
        returns = [f for f in facts if f['kind'] == 'return' and f['owner'] == item['name']]
        sentence += ('. Its return expressions are ' + '; '.join('`%s` (line %d)' % (f['value'], f['line']) for f in returns)
                     if returns else '. There is no explicit return in that function body')
        sentences.append(sentence + '.')
    wording = {
        'import': lambda f: '`%s`' % f['statement'],
        'condition': lambda f: 'tests `%s`%s' % (f['condition'], ' and has an alternative branch' if f['alternate'] else ''),
        'iteration': lambda f: 'iterates `%s` over `%s`' % (f['target'], f['iterable']),
        'repetition': lambda f: 'repeats while `%s`' % f['condition'],
        'raise': lambda f: 'raises `%s`' % f['value'],
        'assignment': lambda f: 'assigns `%s`' % f['statement'],
        'call': lambda f: 'calls `%s`' % f['expression'],
    }
    for item in facts:
        if item['kind'] in wording:
            sentences.append('At line %d, %s %s.' % (item['line'],
                '`%s`' % item['owner'] if item['owner'] else 'the module', wording[item['kind']](item)))
    return sentences


def failure_evidence(turn, sources, text):
    """Read a current conversation's existing failed run; never execute one."""
    import bench
    import repair
    if turn is None or turn.env is None:
        return None
    job = bench._job_for(turn, text)
    if not job or job.get('sid') != turn.sid or job.get('state') != 'finished' or job.get('passed'):
        return None
    path = Path(job['dir']) / 'log'
    if not path.is_file() or path.stat().st_size > 2_000_000:
        return None
    raw = path.read_bytes()
    log = raw.decode('utf-8', 'replace')
    if bench.SECRET_TEXT.search(log):
        return None
    errors = re.findall(r'^([\w.]+(?:Error|Exception)(?::[^\n]*)?|AssertionError(?::[^\n]*)?)$', log, re.M)
    frames = []
    for source, line in repair.frames_of(log, turn.env.root):
        record = sources.get(str(source))
        if record:
            lines = record['source'].splitlines()
            current = lines[line - 1].strip() if 0 < line <= len(lines) else None
            frames.append({'file': record['name'], 'line': line, 'current_source': current})
    if not frames:
        return None
    return {'job': job['id'], 'command': job.get('cmd'), 'exit': job.get('exit'),
            'log_sha256': _sha(raw), 'errors': errors, 'frames': frames,
            'freshness': 'historical run; current source inspected separately'}


def handle(text, native, env, turn=None):
    previous = None
    if turn is not None:
        kept = turn.s.get('code_discussion')
        if kept and kept.get('env') in (None, env.key if env else None):
            import reflect
            ledger = reflect.load(turn.sid).get('ledger') or []
            if not ledger or str(ledger[-1].get('path', '')).startswith('bench:code:'):
                previous = kept
    received = receive(text, native, previous)
    if received is None:
        return None
    received['env'] = env.key if env else None
    if turn is not None:
        turn.s['code_discussion'] = received
        if env is None:
            turn.s['pending_context_focus'] = 'code'
        turn.save()
    names = ', '.join('`' + file + '`' for file in received['files'])
    missing, records, sources = [], [], {}
    if env is None:
        missing.append({'kind': 'code_explanation', 'question': text, 'files': received['files'],
                        'environment': None, 'needed': 'project folder'})
        response = 'Which project folder contains %s? Open it with `open <folder path>` so I can inspect the local code.' % names
    elif env.kind != 'folder':
        missing.append({'kind': 'code_explanation', 'question': text, 'files': received['files'],
                        'environment': env.key, 'needed': 'local source inspection'})
        response = 'This code explanation part needs a local project folder. The question about %s is kept.' % names
    else:
        lines = []
        for name in received['files']:
            candidates = [p for p in env.resolve(name) if _inside(env.root, p)]
            if len(candidates) != 1:
                missing.append({'kind': 'code_explanation', 'question': text, 'files': [name],
                                'environment': env.key, 'needed': 'one readable source file',
                                'candidates': [env.rel(p) for p in candidates]})
                lines.append('I have not established an explanation for `%s`: %s.' %
                             (name, 'several matching files need a specific path' if candidates else 'that file is not available in this folder'))
                continue
            path = candidates[0]
            source = env.read(path)
            if source is None:
                missing.append({'kind': 'source', 'file': name, 'needed': 'readable source'})
                lines.append('`%s` is not available as readable source.' % name)
                continue
            record = inspect_source(env.rel(path), source)
            records.append(record)
            sources[str(Path(path).resolve())] = {'source': source, 'name': env.rel(path)}
            lines.extend(describe(record))
            if record.get('limit'):
                missing.append({'kind': 'source_language', 'file': name, 'needed': record['limit']})
        evidence = failure_evidence(turn, sources, text) if received['failure'] else None
        if evidence:
            lines.append('The recorded run of `%s` (job %s) exited with %s%s.' %
                (evidence['command'], evidence['job'], evidence['exit'],
                 ' and reported ' + '; '.join('`' + e + '`' for e in evidence['errors']) if evidence['errors'] else ''))
            frame = evidence['frames'][-1]
            lines.append('Its traceback reaches `%s`, line %s. The current source there is `%s`.' %
                         (frame['file'], frame['line'], frame['current_source']))
            lines.append('That log describes the earlier run; I have not rerun the current files or established their runtime values.')
        elif received['failure'] and not any(r.get('syntax') for r in records):
            missing.append({'kind': 'failure_evidence', 'question': text, 'files': received['files'],
                            'environment': env.key, 'needed': 'a failing run or traceback tied to these files'})
            lines.append('I do not yet have a failing run tied to these files. Run the failing command here, or provide its traceback and inputs, so I can distinguish a source observation from the cause of a failure.')
        response = '\n\n'.join(lines)
        received['source_receipts'] = records
        received['failure_evidence'] = evidence
    if turn is not None:
        turn.s['code_discussion'] = received
        turn.save()
    return {'status': 'hole' if missing else 'answered',
            'path': 'bench:code:context' if not records else 'bench:code:explain',
            'response': response, 'code_reading': received, 'missing_evidence': missing,
            'execution': {'state': 'missing' if missing else 'read', 'started': False, 'changed': False,
                          'files_read': [r['file'] for r in records], 'source_receipts': records}}


def resume_after_open(sid):
    import bench
    turn = bench.Turn(sid)
    kept = turn.s.get('code_discussion')
    if not kept or kept.get('env') is not None or turn.env is None or turn.s.get('pending_context_focus') not in (None, 'code'):
        return None
    return handle(kept['question'], None, turn.env, turn)