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