"""Receive a described program through the existing work ledger and compiler. Project nouns are kept verbatim. The existing parts decide which described stages connect; missing destination/evidence/meaning is filled on later turns. """ import ast import copy import hashlib import json from pathlib import Path import re import sys import tempfile _OBJECT = r'(?:program|tool|script|app|application|workflow)' _START = re.compile(r'(?is)^\s*(?:(?:can|could|would)\s+you\s+)?(?:please\s+)?(?:(?:build|create|make|write)\s+|I\s+(?:want|need|would like)\s+(?:you\s+to\s+(?:build|create|make|write)\s+)?)' + r'(?:(?![.;\n]).){0,100}?(?:\b' + _OBJECT + r'\b|[\w./-]+\.py\b)') _DEST = re.compile(r'(?is)^(?:(?:call|name)\s+(?:it|the\s+' + _OBJECT + r')\s+|(?:save|write)\s+it\s+as\s+)[`\"\']?([\w./-]+\.py)[`\"\']?[.!]?$') _CHECK = re.compile(r'(?is)^(?:(?:check|test|verify)(?:\s+it)?\s+(?:with|using)|run)\s+`([^`]+)`[.!]?$') _REVISION = re.compile(r'(?is)^\s*(?:instead\s*[,;:]?\s*|I meant\s+|actually\s*[,;:]?\s*)(.+)$') def _native_opening(reading): graph = (reading or {}).get('graph') or {} if graph.get('act') != 'request': return None parents = {link.get('to') for link in graph.get('links', []) if link.get('kind') == 'relative'} return next((node for node in graph.get('nodes', []) if node.get('id') in parents and node.get('speech_act') == 'request' and node.get('polarity') == 'positive' and node.get('predicate', {}).get('lemma') in {'build', 'create', 'make', 'write', 'want', 'need'}), None) def _delegated_reasons(text, reading): """Exact reason nodes remain owned here while executable parts read actions.""" result = copy.deepcopy(reading or {}) graph = result.get('graph') or {} nodes = {node.get('id'): node for node in graph.get('nodes', [])} delegated, reasons = [], [] for link in graph.get('links', []): if link.get('kind') != 'reason': continue node, connector = nodes.get(link.get('from'), {}), link.get('connector') or {} pieces = [] for atom in (connector, node): span = atom.get('span') if not isinstance(span, list) or len(span) != 2 or atom.get('source', graph.get('original')) != text: pieces = []; break lo, hi = span if not isinstance(lo, int) or not isinstance(hi, int) or not 0 <= lo <= hi <= len(text) or text[lo:hi] != atom.get('text'): pieces = []; break pieces.append({'span': list(span), 'owner': 'reason', 'text': text[lo:hi], 'node': node.get('id')}) if pieces: for piece in pieces: if not any(existing['span'] == piece['span'] for existing in delegated): delegated.append(piece) reason = ' '.join(piece['text'] for piece in pieces) if reason not in reasons: reasons.append(reason) result['project_delegated'] = delegated return result, reasons def _masked(text): literals = {} def keep(match): key = 'O7LITERAL%dTOKEN' % len(literals) literals[key] = match.group() return key masked = re.sub(r'`[^`]*`|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', keep, text) return masked, literals def _restore(text, literals): for key, value in literals.items(): text = text.replace(key, value) return text def clauses(text): masked, literals = _masked(text) return [_restore(piece.strip(' \t\r\n.;'), literals) for piece in re.split(r'[;\n]+|(?<=[.!?])\s+(?=[A-Z])', masked) if piece.strip(' \t\r\n.;')] def _literal(text): text = text.strip().rstrip('.').strip() try: value = json.loads(text) except (ValueError, TypeError): value = ast.literal_eval(text) json.dumps(value, allow_nan=False) return value def example(text): """Examples supply answers independently of the compiler's emitted moves.""" masked, literals = _masked(text) head = re.match(r'(?is)^(?:for|with)\s+(?:the\s+)?input\s+(.+)$', masked) filehead = re.match(r'(?is)^when\s+([\w./-]+)\s+(?:contains|has)\s+(.+)$', masked) bare = not head and not filehead # any clause " (should|must)? give|return|produce|expect|=> " ("100 should give 212") is an example # when both sides read as exact values; nothing else in the clause is guessed (11-17) body = masked if bare else (head.group(1) if head else filehead.group(2)) for divider in re.finditer(r'(?i),?\s+(?:(?:it|the\s+' + _OBJECT + r')\s+)?(?:should\s+|must\s+)?(?:return|produce|give|expect)s?\s+|\s*=>\s*', body): try: value = _literal(_restore(body[:divider.start()], literals)) expected = _literal(_restore(body[divider.end():], literals)) if filehead: if not isinstance(value, str): continue return {'files': {filehead.group(1): value}, 'expected': expected} return {'input': value, 'expected': expected} except (ValueError, SyntaxError, TypeError): continue if bare: # several examples in one clause ("2 gives 7 and 10 gives 23"): every part must read as an example on its own parts = [p for p in re.split(r'(?i)\s*(?:;|,|\band\b)\s*', _restore(masked, literals)) if p.strip()] if len(parts) > 1: read = [example(p) for p in parts] if all(r and 'input' in r for r in read): return dict(read[0], more=read[1:]) return None return {'hole': 'Give the input and expected result as literal values, for example: For input [1, 2], return 3.'} def _directive(text, reading=None): # Only grammatical wrappers and verb inflection are changed. The compiler # must still connect every remaining stage; no requested behavior is guessed. t = re.sub(r'(?is)^(?:it|the\s+' + _OBJECT + r')\s+(?:should|must|will|can)\s+', '', text.strip()) first = re.match(r'([A-Za-z]+)\b', t) if first: word = first.group(1) native = next((node.get('predicate', {}).get('lemma') for node in (reading or {}).get('graph', {}).get('nodes', []) if node.get('predicate', {}).get('text', '').lower() == word.lower() and node.get('predicate', {}).get('lemma')), None) if native: word = native elif word.endswith('ies'): word = word[:-3] + 'y' elif word.endswith('s') and not word.endswith(('ss', 'us')): word = word[:-1] t = word + t[first.end():] return t def _stages(text, reading=None): import make masked, literals = _masked(text) # A coordinated requested action stays a separate obligation, even when the # old compiler would otherwise accept only its first verb. masked = re.sub(r'\s+and\s+', '; ', masked, flags=re.I) return [_directive(_restore(stage, literals), reading) for stage in make.steps_of(masked)] def _is_continuation(text, intent): if not intent: return False t = text.strip() if _DEST.match(t) or _CHECK.match(t) or example(t) is not None or _REVISION.match(t): return True if re.fullmatch(r'[\w./-]+\.py[.!]?', t) and not intent.get('file'): return True return bool(re.match(r'(?i)^(?:also\s+|add\s+(?:a\s+)?step\s*:?|drop\s+(?:the\s+)?requirement\s+|replace\s+|change\s+|because\s+|' r'(?:it|the\s+\w+)\s+(?:should|must|needs? to|remembers?|retains?|starts?)\b)', t)) def owns_turn(text, work=None, reading=None): """Conversation can defer an actual build/fill while retaining ordinary questions.""" if re.match(r'(?i)^\s*(?:why|how|what|explain|discuss|compare|tell me)\b', text) or text.rstrip().endswith('?') and not (_START.match(text) or _native_opening(reading)): return False return accepts(text, kept=work, reading=reading) def accepts(text, root=None, kept=None, reading=None): intent = (kept or {}).get('build_intent') if _is_continuation(text, intent): return True try: import program_prose if program_prose.receive(text, kept=(intent or {}).get('interactive'), reading=reading) is not None: return True except ImportError: pass if not _START.match(text) and not _native_opening(reading): return False if re.match(r'(?i)^\s*(?:what if|explain|discuss|compare)\b', text): return False # Explicit existing table-project command syntax retains its owner. import project if project.ENTRY.search(text): return False # A build over a named table with an outcome someone can see is the table # project's request (its store, sha reuse and judges): the same ownership # work_tasks.accepts states, applied before this receiver takes the turn. if project.DATA.search(text) and project.is_project(text, None, root): return False mask, unused = _masked(text) if re.match(r'(?is)^\s*(?:build|create|make|write)\s+[\w./-]+\.py\s+from\s+[\w./-]+\.(?:steps|txt|md)\b', mask): return False # the earlier description-file connection keeps its owner return bool(re.search(r'(?i)\b(?:that|which|to)\b|:\s*\S|\b(?:browser|interactive)\b', mask)) def receive(text, kept=None, reading=None): prior = copy.deepcopy(kept) if kept else None if prior and (prior.get('original') == text or prior.get('turns') and prior['turns'][-1]['text'] == text): return prior part_reading, native_reasons_received = _delegated_reasons(text, reading) try: import program_prose interactive = program_prose.receive(text, kept=(prior or {}).get('interactive'), reading=part_reading) except ImportError: interactive = None fresh = bool(_START.match(text) or _native_opening(reading)) and not _REVISION.match(text) fresh = fresh or bool(interactive and interactive.get('original') == text and (prior or {}).get('original') != text) intent = {'version': 1, 'original': text, 'turns': [], 'mode': 'pipeline', 'file': None, 'stages': [], 'examples': [], 'reasons': [], 'constraints': [], 'requirements': [], 'unbound': []} if fresh or not prior else prior intent['turns'].append({'text': text, 'reading': copy.deepcopy(reading)}) if reading and reading.get('graph'): intent.setdefault('graphs', []).append(copy.deepcopy(reading['graph'])) if interactive is not None: intent['mode'], intent['interactive'] = 'interactive', interactive for reason in native_reasons_received: if reason not in intent['reasons']: intent['reasons'].append(reason) correction = _REVISION.match(text) pieces = clauses(correction.group(1) if correction else text) if fresh and pieces: destinations = re.findall(r'(?