oracle7 / workbench /project_intent.py
psiloceyeben's picture
Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
d9b105f verified
Raw History Blame Contribute Delete
21.3 kB
"""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 "<value> (should|must)? give|return|produce|expect|=> <value>" ("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'(?<![\w])([\w./-]+\.py)\b', pieces[0])
if len(set(destinations)) == 1:
intent['file'] = destinations[0]
graph = (reading or {}).get('graph') or {}
reason_ids = {link.get('from') for link in graph.get('links', []) if link.get('kind') == 'reason'}
native_reasons = {node.get('text', '').strip(' .;') for node in graph.get('nodes', []) if node.get('id') in reason_ids}
for piece in pieces:
record = {'id': 'I%d' % (len(intent['requirements']) + 1), 'text': piece, 'kind': 'behavior'}
record['reading_nodes'] = [node['id'] for node in graph.get('nodes', []) if node.get('text') and node['text'] in piece]
dest = _DEST.match(piece)
drop = re.match(r'(?is)^drop\s+(?:the\s+)?requirement\s+(.+)$', piece)
if drop:
named = drop.group(1).strip('`"\' ')
matching = [item for item in intent['unbound'] if item['text'].strip(' .;') == named.strip(' .;')]
stage_matches = [stage for stage in intent['stages'] if stage == named]
if len(matching) + len(stage_matches) == 1:
intent['unbound'] = [item for item in intent['unbound'] if item not in matching]
intent['stages'] = [stage for stage in intent['stages'] if stage not in stage_matches]
intent.setdefault('revisions', []).append({'before': named, 'after': None, 'request': piece})
record['kind'] = 'revision'
else:
intent['unbound'].append({'text': piece, 'hole': 'Name one exact kept requirement to drop.'})
elif not dest and not intent.get('file') and re.fullmatch(r'[\w./-]+\.py', piece):
intent['file'] = piece; record.update(kind='destination', field='file')
elif dest:
intent['file'] = dest.group(1); record.update(kind='destination', field='file')
elif _CHECK.match(piece):
intent['check'] = _CHECK.match(piece).group(1); record.update(kind='evidence', field='check')
elif example(piece) is not None:
received = example(piece)
if 'hole' in received:
intent['unbound'].append({'text': piece, 'hole': received['hole'], 'field': 'examples'})
else:
intent['unbound'] = [item for item in intent['unbound'] if item.get('field') != 'examples']
# An explicitly revised example replaces its same input only.
for one in [dict((k, v) for k, v in received.items() if k != 'more')] + list(received.get('more') or []):
key = {k: v for k, v in one.items() if k != 'expected'}
intent['examples'] = [old for old in intent['examples'] if {k: v for k, v in old.items() if k != 'expected'} != key]
intent['examples'].append(one)
record.update(kind='evidence', field='examples')
elif re.match(r'(?i)^because\b', piece) or piece in native_reasons:
intent['reasons'].append(piece); record['kind'] = 'reason'
elif re.search(r"(?i)\b(?:do not|don't|must not|never|without)\b", piece):
intent['constraints'].append({'text': piece}); record['kind'] = 'constraint'
elif intent['mode'] == 'interactive':
record['owner'] = 'interactive'
if interactive is None:
intent['unbound'].append({'text': piece, 'hole': 'The browser program has no connected meaning for this requirement yet: ' + piece,
'field': 'behavior'})
else:
body = piece
header = _START.match(body)
native_header = _native_opening(reading)
if not header and native_header and body.startswith(native_header['text']):
body = re.sub(r'(?is)^\s*(?:that|which|to|:)\s*', '', body[len(native_header['text']):])
record.update(kind='goal', native_owner=native_header['id'])
if header:
prefix = header.group()
output = re.findall(r'[\w./-]+\.py\b', prefix)
if len(output) == 1:
intent['file'] = output[0]
body = re.sub(r'(?is)^\s*(?:that|which|to|:)\s*', '', body[header.end():])
# Named project purpose is retained in the original; every
# remaining requested stage must be connected below.
record['kind'] = 'goal'
masked, literals = _masked(body)
reason = re.search(r'(?i)\s+because\s+', masked)
if reason:
intent['reasons'].append(_restore(masked[reason.start():].strip(), literals))
body = _restore(masked[:reason.start()], literals)
change = re.match(r'(?is)^(?:replace|change)\s+(.+?)\s+(?:with|to)\s+(.+)$', body)
if change:
old, new = change.groups()
matches = [i for i, stage in enumerate(intent['stages']) if stage.lower() == old.strip('`"\' ').lower()]
if len(matches) == 1:
intent.setdefault('revisions', []).append({'before': intent['stages'][matches[0]], 'after': new, 'request': piece})
intent['stages'][matches[0]:matches[0]+1] = _stages(new.strip('`"\' '), reading)
else:
intent['unbound'].append({'text': piece, 'hole': 'Name the exact stage to replace; the earlier stages remain kept.'})
elif correction:
stages = _stages(body, reading)
if len(stages) == 1:
verb = stages[0].split()[0].lower() if stages[0].split() else ''
matches = [i for i, stage in enumerate(intent['stages']) if stage.split()[0].lower() == verb]
if len(matches) == 1:
intent.setdefault('revisions', []).append({'before': intent['stages'][matches[0]], 'after': stages[0], 'request': piece})
intent['stages'][matches[0]] = stages[0]
else:
intent['unbound'].append({'text': piece, 'hole': 'Name the stage this correction replaces; the full correction is kept.'})
else:
intent['unbound'].append({'text': piece, 'hole': 'Name the stage or complete description this correction replaces.'})
elif body.strip():
body = re.sub(r'(?i)^(?:also\s+|add\s+(?:a\s+)?step\s*:?\s*)', '', body)
for stage in _stages(body, reading):
# a stage that names the destination ("call it temps.py") or gives examples ("2 gives 7") is that
# destination or evidence, not a program step; a stage mixing them is read part by part
parts = [p.strip().rstrip('.') for p in re.split(r',\s*', stage) if p.strip()]
kinds = [('dest', _DEST.match(p)) if _DEST.match(p) else ('example', example(p)) for p in parts]
if all(found and (kind == 'dest' or 'input' in found) for kind, found in kinds):
for kind, found in kinds:
if kind == 'dest':
intent['file'] = found.group(1)
else:
intent['examples'] += [dict((k, v) for k, v in found.items() if k != 'more')] + list(found.get('more') or [])
else:
intent['stages'].append(stage)
intent['requirements'].append(record)
return intent
def semantic(intent):
result = {key: copy.deepcopy(intent.get(key)) for key in ('mode', 'file', 'stages', 'examples', 'check', 'constraints', 'unbound')}
if intent.get('interactive'):
result['interactive'] = {key: copy.deepcopy(intent['interactive'].get(key)) for key in ('contract', 'holes', 'ready')}
return result
def holes(intent):
found = [{'kind': 'meaning', 'text': item['hole'], 'received': item['text']} for item in intent.get('unbound', [])]
if not intent.get('file'):
found.append({'kind': 'destination', 'text': 'What should the program file be called? For example, call it report.py.'})
if intent['mode'] == 'interactive':
found.extend(dict(item, text=item.get('needed') or item['text'], received=item.get('text'))
for item in intent['interactive'].get('holes', []))
else:
if not intent.get('stages'):
found.append({'kind': 'description', 'text': 'Describe what the program should do to its input.'})
if not intent.get('examples') and not intent.get('check'):
found.append({'kind': 'behavior', 'text': 'Give an input and its expected result, or name the existing behavior check. The described stages are kept.'})
return found
def build(root, intent, runenv=None):
import work_tasks as work
missing = holes(intent)
if missing:
raise work.WorkHole('project-input', ' '.join(item['text'] for item in missing), fields=missing)
if intent['mode'] == 'interactive':
import work_bindings
result = work_bindings.execute('interactive_program', {'contract': intent['interactive']['contract'], 'file': intent['file']}, root, runenv)
else:
import program_steps
args = {'description': '; '.join(intent['stages']), 'file': intent['file'], 'examples': intent.get('examples') or []}
if intent.get('check') and not intent.get('examples'):
args['check'] = intent['check']
result = program_steps.build(root, args, runenv)
else:
with tempfile.TemporaryDirectory(prefix='oracle7-received-check-') as directory:
request = Path(directory) / 'examples.json'
request.write_text(json.dumps({'source': str(work._path(root, intent['file'])), 'examples': intent['examples']}, allow_nan=False), encoding='utf-8')
example_check = [sys.executable, '-I', str(Path(__file__).with_name('program_examples.py')), str(request)]
args['check'] = intent.get('check') or example_check
if intent.get('check'):
args['postcondition'] = example_check
result = program_steps.build(root, args, runenv)
result['received'] = {'original': intent['original'], 'requirements': intent['requirements'], 'reasons': intent['reasons'],
'examples': intent['examples'], 'revisions': intent.get('revisions', [])}
return result