Release 12.0 (slim): 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)
6e2225f verified Download workbench/program_prose.py from psiloceyeben/oracle7-slim: direct link, hf CLI and curl.
- Browser
- Download file 23.7 kB
-
https://huggingface.co/psiloceyeben/oracle7-slim/resolve/main/workbench/program_prose.py
- Command line
-
hf download hf://psiloceyeben/oracle7-slim/workbench/program_prose.py
-
curl -L -o program_prose.py https://huggingface.co/psiloceyeben/oracle7-slim/resolve/main/workbench/program_prose.py
23.7 kB
| """Connect described state/event relationships to the existing browser program part. | |
| Every accepted clause has an exact source receipt. Unknown behavior remains an | |
| owned hole; this part never treats a retained description as a finished build. | |
| The named grammar is about executable relationships, not application templates. | |
| """ | |
| import copy | |
| import hashlib | |
| import json | |
| import re | |
| NAME = r'[A-Za-z][A-Za-z0-9_]{0,63}' | |
| NUM = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)' | |
| PREFIX = r'(?:(?:please|(?:can|could|would) you(?: please)?)\s+)?' | |
| INTRO = (PREFIX + r'(?:build|create|make|i (?:need|want)(?: to build)?)\s+(?:a |an |the )?' | |
| r'(?:(?:local|small|simple|interactive)\s+)*(?:(?:browser|web)\s+)?(?:app|application|program|counter|checklist|panel)\b') | |
| def _literal(text): | |
| text = text.strip().strip('`') | |
| if len(text) >= 2 and text[0] == text[-1] and text[0] in '\"\'': | |
| return text[1:-1] | |
| if re.fullmatch(NUM, text): | |
| return float(text) if '.' in text else int(text) | |
| if text.lower() in ('true', 'false'): | |
| return text.lower() == 'true' | |
| if re.fullmatch(NAME, text): | |
| return text | |
| raise ValueError('name a quoted text value, number, or boolean') | |
| def _type(value): | |
| return 'boolean' if isinstance(value, bool) else 'integer' if isinstance(value, int) else 'number' if isinstance(value, float) else 'string' | |
| def _split(text, pattern): | |
| """Split outside quoted strings; preserve offsets in the received turn.""" | |
| masked = list(text) | |
| for quoted in re.finditer(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|`[^`]*`', text): | |
| masked[quoted.start():quoted.end()] = ' ' * (quoted.end() - quoted.start()) | |
| start = 0 | |
| for match in re.finditer(pattern, ''.join(masked), re.I): | |
| if text[start:match.start()].strip(): | |
| yield start, text[start:match.start()] | |
| start = match.end() | |
| if text[start:].strip(): | |
| yield start, text[start:] | |
| def _event_id(label): | |
| return label.lower() | |
| def _hole(kind, text, needed, event=None): | |
| result = {'id': 'P' + hashlib.sha256((kind + ':' + text + ':' + str(event)).encode()).hexdigest()[:10], | |
| 'kind': kind, 'text': text, 'needed': needed} | |
| if event: | |
| result['event'] = event | |
| return result | |
| def _guard(text, state): | |
| """Resolve explicit conditions; shorthand needs one possible owning field.""" | |
| match = re.fullmatch(r'(?:only\s+)?(?:when|if)\s+(' + NAME + r')\s+(?:is\s+)?(?:(not|below|above|less than|greater than|at least|at most)\s+)?(.+)', text, re.I) | |
| if match: | |
| field, compare, val = match.groups() | |
| if field not in state: | |
| raise ValueError('condition needs declared field ' + field) | |
| value = _literal(val) | |
| op = {None: 'eq', 'not': 'ne', 'below': 'lt', 'less than': 'lt', 'above': 'gt', | |
| 'greater than': 'gt', 'at least': 'ge', 'at most': 'le'}[compare.lower() if compare else None] | |
| return {'field': field, 'compare': op, 'value': value} | |
| match = re.fullmatch(r'(?:only\s+)?in\s+(.+)', text, re.I) | |
| if match: | |
| value = _literal(match[1]) | |
| fields = [name for name, schema in state.items() if schema['type'] == _type(value)] | |
| if len(fields) != 1: | |
| raise ValueError('name the field for condition ' + text) | |
| return {'field': fields[0], 'compare': 'eq', 'value': value} | |
| raise ValueError('name one explicit state condition for this event') | |
| def _action(text, fields): | |
| text = re.sub(r'^(?:it\s+)?(?:should\s+)?', '', text.strip(), flags=re.I) | |
| match = re.fullmatch(r'(?:increases?|decreases?)\s+(' + NAME + r')(?:\s+by\s+(' + NUM + r'))?', text, re.I) | |
| if match: | |
| return {'kind': 'delta', 'field': match[1], 'value': _literal(match[2]) if match[2] else None, | |
| 'sign': -1 if text.lower().startswith('decrease') else 1} | |
| match = re.fullmatch(r'(?:adds?|subtracts?)\s+(' + NUM + r')\s+(?:to|from)\s+(' + NAME + r')', text, re.I) | |
| if match: | |
| if text.lower().startswith('add') and fields.get(match[2], {}).get('type') == 'array': | |
| return {'kind': 'append', 'field': match[2], 'value': _literal(match[1])} | |
| return {'kind': 'delta', 'field': match[2], 'value': _literal(match[1]), 'sign': -1 if text.lower().startswith('subtract') else 1} | |
| match = re.fullmatch(r'(?:sets?|changes?)\s+(' + NAME + r')\s+to\s+(.+)', text, re.I) | |
| if match: | |
| return {'kind': 'set', 'field': match[1], 'value': _literal(match[2])} | |
| match = re.fullmatch(r'(?:adds?|appends?|removes?)\s+(.+?)\s+(?:to|from)\s+(' + NAME + r')', text, re.I) | |
| if match: | |
| return {'kind': 'remove' if text.lower().startswith('remove') else 'append', 'field': match[2], 'value': _literal(match[1])} | |
| raise ValueError('name a set, numeric change, list addition, or list removal') | |
| def _test_guard(guard, values): | |
| if not guard: | |
| return True | |
| a, b = values[guard['field']], guard['value'] | |
| return {'eq': lambda: type(a) == type(b) and a == b, 'ne': lambda: type(a) != type(b) or a != b, | |
| 'lt': lambda: a < b, 'le': lambda: a <= b, 'gt': lambda: a > b, 'ge': lambda: a >= b}[guard['compare']]() | |
| def _expected(event, values): | |
| """Interpret received changes, independently of the compiled action graph.""" | |
| result = copy.deepcopy(values) | |
| for action in event['changes']: | |
| field, value = action['field'], action['value'] | |
| if action['kind'] == 'delta': | |
| result[field] += value * action['sign'] | |
| elif action['kind'] == 'set': | |
| result[field] = copy.deepcopy(value) | |
| elif action['kind'] == 'append': | |
| result[field].append(copy.deepcopy(value)) | |
| elif action['kind'] == 'remove': | |
| result[field] = [item for item in result[field] if item != value] | |
| return result | |
| def _checks(fields, events): | |
| """Find explicit event paths, bounded at 256 states and 32 events per path.""" | |
| initial = {k: copy.deepcopy(v['initial']) for k, v in fields.items()} | |
| todo = [(initial, [])]; seen = set(); covered = set(); checks = [] | |
| while todo and len(seen) < 256 and len(covered) < len(events): | |
| values, path = todo.pop(0) | |
| key = json.dumps(values, sort_keys=True) | |
| if key in seen or len(path) >= 32: | |
| continue | |
| seen.add(key) | |
| for name, event in events.items(): | |
| if not _test_guard(event.get('condition'), values): | |
| continue | |
| after = _expected(event, values); steps = path + [{'event': name}] | |
| if name not in covered: | |
| checks.append({'events': steps, 'state': after}); covered.add(name) | |
| if _test_guard(event.get('condition'), after): | |
| checks.append({'events': steps + [{'event': name}], 'state': _expected(event, after)}) | |
| todo.append((after, steps)) | |
| return checks, set(events) - covered | |
| def _compile(record): | |
| fields, events = copy.deepcopy(record['fields']), copy.deepcopy(record['events']) | |
| holes = copy.deepcopy(record['unbound']) | |
| if not fields: | |
| holes.append(_hole('state', record['original'], 'name state and its initial value')) | |
| if not events: | |
| holes.append(_hole('event', record['original'], 'name a browser event and its changes')) | |
| for event_id, event in events.items(): | |
| if not event['changes']: | |
| holes.append(_hole('event_action', event['source'], 'name the changes made by ' + event['label'], event_id)) | |
| if event.get('condition_text'): | |
| try: | |
| event['condition'] = _guard(event['condition_text'], fields) | |
| except ValueError as error: | |
| holes.append(_hole('condition', event['source'], str(error), event_id)) | |
| for action in event['changes']: | |
| target = fields.get(action['field']) | |
| if not target: | |
| holes.append(_hole('target', event['source'], 'declare state ' + action['field'], event_id)); continue | |
| if action['kind'] == 'delta' and (action['value'] is None or target['type'] not in ('integer', 'number')): | |
| holes.append(_hole('amount', event['source'], 'name the numeric amount and numeric field for ' + event['label'], event_id)) | |
| elif action['kind'] in ('append', 'remove'): | |
| if target['type'] != 'array': | |
| holes.append(_hole('target_type', event['source'], 'list changes need an array field', event_id)) | |
| else: | |
| typ = _type(action['value']) | |
| if target.get('items') and target['items']['type'] != typ: | |
| holes.append(_hole('item_type', event['source'], 'all list values need the declared item type', event_id)) | |
| else: | |
| target['items'] = {'type': typ} | |
| for name, field in fields.items(): | |
| if field['type'] == 'array' and 'items' not in field: | |
| holes.append(_hole('item_type', name, 'name the type of items in ' + name)) | |
| for field in record['views']: | |
| if field not in fields: | |
| holes.append(_hole('view', field, 'declare displayed state ' + field)) | |
| if not record['views']: | |
| holes.append(_hole('view', record['original'], 'name the state to display')) | |
| contract = {'version': 1, 'title': record['title'], 'state': fields, 'events': {}, 'parts': {}, | |
| 'views': [{'kind': 'list' if fields.get(f, {}).get('type') == 'array' else 'text', 'label': f, 'value': {'state': f}} for f in record['views']], | |
| 'controls': [], 'checks': []} | |
| for name, event in events.items(): | |
| actions = [] | |
| for change in event['changes']: | |
| value = change['value'] | |
| if change['kind'] == 'delta': | |
| value = {'op': 'add' if change['sign'] == 1 else 'subtract', 'args': [{'state': change['field']}, value]} | |
| actions.append({'op': 'set' if change['kind'] in ('delta', 'set') else change['kind'], 'field': change['field'], 'value': value}) | |
| contract['events'][name] = {'actions': actions} | |
| if event.get('condition'): | |
| guard = event['condition'] | |
| contract['events'][name]['guard'] = {'op': guard['compare'], 'args': [{'state': guard['field']}, guard['value']]} | |
| contract['controls'].append({'kind': 'button', 'label': event['label'], 'event': name}) | |
| if not holes: | |
| try: | |
| checks, missing = _checks(fields, events); contract['checks'] = checks | |
| for name in sorted(missing): | |
| holes.append(_hole('event_path', name, 'provide a reachable event sequence for ' + events[name]['label'])) | |
| import interactive_program as IP | |
| contract = IP.validate(contract) | |
| except (ValueError, TypeError, KeyError) as error: | |
| holes.append(_hole('program_shape', record['original'], str(error))) | |
| record['contract'], record['holes'], record['ready'] = contract, holes, not holes | |
| return record | |
| def receive(text, kept=None, reading=None): | |
| """Receive reusable program clauses or return None for unrelated turns. | |
| A kept record is copied. The caller owns file destination, authority, durable | |
| work history and deciding whether to build, discuss, or ask for a hole fill. | |
| """ | |
| text = str(text).strip() | |
| if re.fullmatch(r'(?:call|name|save)\s+it\s+.+\.py[.!]?', text, re.I): | |
| return copy.deepcopy(kept) if kept else None | |
| if re.match(r'\s*(?:what|why|how|does|do not|don\'t|explain|describe|before building)\b', text, re.I): | |
| return None | |
| opening = re.match(INTRO, text, re.I) | |
| if opening and not re.search(r'\b(?:browser|web)\b', opening[0], re.I) and not re.search(r'\b(?:button|clicking|when I click)\b', text, re.I): | |
| opening = None | |
| if not kept and not opening: | |
| return None | |
| if kept and not opening: | |
| labels = '|'.join(re.escape(e['label']) for e in kept.get('events', {}).values()) | |
| continued = (r'^(?:actually|instead|no[, ]|change|revise|add|also|start|set|display|show|save|persist|remember|' | |
| r'keep|clicking|when I click|it should have|a button|an? (?:integer|number|string|boolean|empty list))\b') | |
| if not re.match(continued, text, re.I) and not (labels and re.match(r'^(?:' + labels + r')\s+should\b', text, re.I)): | |
| return None | |
| if kept and opening: | |
| kept = None # a complete new named project does not inherit old handlers | |
| record = copy.deepcopy(kept) if kept else {'kind': 'interactive_program_intent', 'original': text, 'turns': [], | |
| 'fields': {}, 'events': {}, 'views': [], 'storage': 'local', 'title': 'Browser program', 'unbound': [], 'consumed': []} | |
| record['turns'].append({'text': text, 'reading': copy.deepcopy(reading)}) | |
| turn = len(record['turns']) - 1 | |
| revision = bool(re.match(r'(?:actually|instead|no[, ]|change|revise)\b', text, re.I)) | |
| current_event = None | |
| def consume(raw, offset, kind): | |
| nodes = ((reading or {}).get('graph') or {}).get('nodes', []) | |
| joined = [n.get('id') for n in nodes if isinstance(n.get('span'), list) and len(n['span']) == 2 | |
| and n['span'][0] < offset + len(raw) and n['span'][1] > offset] | |
| exact = text[offset:offset + len(raw)] | |
| receipt = {'turn': turn, 'span': [offset, offset + len(raw)], 'text': exact, 'kind': kind, 'native_nodes': joined} | |
| if exact != raw: | |
| receipt['binding_text'] = raw | |
| record['consumed'].append(receipt) | |
| def fail(raw, offset, needed, kind='clause'): | |
| h = _hole(kind, raw.strip(), needed); h.update(turn=turn, span=[offset, offset + len(raw)]) | |
| if h['id'] not in {x['id'] for x in record['unbound']}: | |
| record['unbound'].append(h) | |
| def event_changes(label, body, raw, offset, append=False): | |
| nonlocal current_event | |
| event_id = _event_id(label); current_event = event_id | |
| old = record['events'].get(event_id) | |
| event = copy.deepcopy(old) if old else {'label': label, 'changes': [], 'source': raw.strip()} | |
| if re.match(r'(?:is\s+)?allowed\s+', body, re.I): | |
| condition = re.sub(r'^(?:is\s+)?allowed\s+', '', body, flags=re.I) | |
| event['condition_text'] = condition; event['condition_source'] = raw.strip(); record['events'][event_id] = event | |
| consume(raw, offset, 'condition'); return | |
| parts = list(_split(body, r'\s+and\s+')) | |
| parsed = [] | |
| for _, part in parts: | |
| condition = re.search(r'\s+(only\s+(?:when|if|in)\s+.+)$', part, re.I) | |
| if condition: | |
| event['condition_text'] = condition[1]; event['condition_source'] = raw.strip(); part = part[:condition.start()] | |
| try: | |
| change = _action(part, record['fields']); change['source'] = part.strip(); change['turn'] = turn; parsed.append(change) | |
| except ValueError as error: | |
| fail(part, offset + raw.find(part), str(error), 'event_action') | |
| for change in parsed: | |
| matches = [i for i, old_change in enumerate(event['changes']) | |
| if old_change['field'] == change['field'] and old_change['kind'] == change['kind']] | |
| if not old or append: | |
| event['changes'].append(change) # ordered repetition is behavior, not duplicate metadata | |
| elif matches and (revision or any(event['changes'][i].get('value') is None for i in matches)): | |
| if len(matches) != 1: | |
| fail(raw, offset, 'name which ordered change to replace in ' + label, 'event_revision') | |
| else: | |
| event['changes'][matches[0]] = change | |
| elif not any(all(previous.get(k) == change.get(k) for k in ('kind', 'field', 'value', 'sign')) for previous in event['changes']): | |
| if matches: | |
| fail(raw, offset, 'say whether to replace or add this change to ' + label, 'event_revision') | |
| else: | |
| event['changes'].append(change) | |
| record['events'][event_id] = event | |
| if parsed: | |
| consume(raw, offset, 'event') | |
| def clause(raw, offset, initial_context=False): | |
| nonlocal current_event | |
| leading = len(raw) - len(raw.lstrip()); offset += leading; raw = raw.strip() | |
| if not raw: | |
| return | |
| value = raw | |
| initial_context = initial_context or bool(re.match(r'^start\s+with\s+', raw, re.I)) | |
| start = re.match(INTRO + r'(?:\s+(?:in|as|called)\s+[^\s]+\.py)?', value, re.I) | |
| if start: | |
| consume(raw[:start.end()], offset, 'program') | |
| tail = value[start.end():].strip() | |
| if tail: | |
| tail = re.sub(r'^with\s+', '', tail, flags=re.I) | |
| clause(tail, offset + value.index(tail)) | |
| return | |
| if re.fullmatch(r'(?:call|name|save)\s+it\s+.+\.py', value, re.I): | |
| consume(raw, offset, 'destination'); return | |
| value = re.sub(r'^(?:actually|instead|no)[,\s]+', '', value, flags=re.I) | |
| value = re.sub(r'^(?:it\s+)?should\s+have\s+|^start\s+with\s+', '', value, flags=re.I) | |
| # An event named in a previous clause owns only an immediate explicit it. | |
| if current_event and re.match(r'^it\s+(?:adds?|sets?|changes?|increases?|decreases?|removes?)\b', value, re.I): | |
| event_changes(record['events'][current_event]['label'], re.sub(r'^it\s+', '', value, flags=re.I), raw, offset, append=True); return | |
| event = re.fullmatch(r'(?:a\s+button\s+(?:named|called)\s+|clicking\s+|when I click\s+)(' + NAME + r')\s*,?\s+(.+)', value, re.I) | |
| if not event: | |
| event = re.fullmatch(r'(?:an?\s+)?(' + NAME + r')\s+button\s+that\s+(.+)', value, re.I) | |
| if not event: | |
| event = re.fullmatch(r'(' + NAME + r')\s+should\s+(.+)', value, re.I) | |
| if event and _event_id(event[1]) not in record['events']: | |
| event = None | |
| if event: | |
| event_changes(event[1], event[2], raw, offset); return | |
| # A correction names the target event and field; all other actions stay. | |
| correction = re.fullmatch(r'(increase|decrease)\s+(' + NAME + r')\s+by\s+(' + NUM + r')\s+on\s+(' + NAME + r')', value, re.I) | |
| if correction and _event_id(correction[4]) in record['events']: | |
| event_changes(correction[4], '%s %s by %s' % (correction[1], correction[2], correction[3]), raw, offset); return | |
| correction = re.fullmatch(r'make\s+(' + NAME + r')\s+add\s+(' + NUM + r')\s+instead\s+of\s+(' + NUM + r')(.*)', value, re.I) | |
| if correction and _event_id(correction[1]) in record['events']: | |
| e = record['events'][_event_id(correction[1])] | |
| changes = [a for a in e['changes'] if a['kind'] == 'delta' and a['sign'] == 1 and a['value'] == _literal(correction[3])] | |
| if len(changes) != 1: | |
| fail(raw, offset, 'name the field and old amount to replace', 'event_revision'); return | |
| changes[0]['value'] = _literal(correction[2]); changes[0]['source'] = raw[:correction.start(4)]; changes[0]['turn'] = turn | |
| consume(raw[:correction.start(4)], offset, 'event_revision') | |
| if correction[4].strip(): | |
| tail = re.sub(r'^\s*,?\s*and\s+', '', correction[4], flags=re.I); clause(tail, offset + raw.find(tail)) | |
| return | |
| keep = re.fullmatch(r'keep\s+the\s+starting\s+value\s+at\s+(' + NUM + r')', value, re.I) | |
| if keep and len(record['fields']) == 1 and next(iter(record['fields'].values()))['initial'] == _literal(keep[1]): | |
| consume(raw, offset, 'preserve_initial'); return | |
| # Display fields are references. No undeclared extra words disappear. | |
| display = re.match(r'^(?:display|show)\s+', value, re.I) | |
| if display: | |
| sections = list(_split(value[display.end():], r',?\s+and\s+(?=(?:save|persist|remember)\b)|,\s*(?=(?:save|persist|remember)\b)')) | |
| names = re.split(r'\s*(?:,|\band\b)\s*', sections[0][1]) | |
| if all(re.fullmatch(NAME, name) for name in names): | |
| record['views'] = list(dict.fromkeys(record['views'] + names)); consume(raw[:display.end()+len(sections[0][1])], offset, 'view') | |
| for part_offset, part in sections[1:]: | |
| clause(part, offset + display.end() + part_offset) | |
| return | |
| if re.fullmatch(r'(?:save|persist|remember)\s+(?:changes|(?:the\s+)?state|it|them)(?:\s+locally)?\s+(?:across\s+reloads|after\s+(?:reopening|reloads)|across\s+restarts)', value, re.I): | |
| record['storage'] = 'local'; consume(raw, offset, 'storage'); return | |
| if re.fullmatch(r'(?:save|persist|remember)\s+(?:the\s+)?(' + NAME + r')\s+(?:across\s+reloads|after\s+reopening)', value, re.I): | |
| name = re.fullmatch(r'(?:save|persist|remember)\s+(?:the\s+)?(' + NAME + r')\s+.+', value, re.I)[1] | |
| if name in record['fields']: | |
| record['storage'] = 'local'; consume(raw, offset, 'storage'); return | |
| # State declarations can be joined, each with its own complete meaning. | |
| pieces = list(_split(value, r'\s+and\s+')) | |
| if len(pieces) > 1: | |
| for shift, piece in pieces: | |
| clause(piece, offset + raw.find(value) + shift, initial_context) | |
| return | |
| empty = re.fullmatch(r'(?:an?\s+)?empty\s+list\s+(?:named|called)\s+(' + NAME + r')', value, re.I) | |
| match = re.fullmatch(r'(?:an?\s+)?(?:(integer|number|string|boolean)\s+)?(' + NAME + r')\s+(?:starting\s+at|initially|starts\s+at|starting\s+with)\s+(.+)', value, re.I) | |
| if not match and initial_context: | |
| match = re.fullmatch(r'()(' + NAME + r')\s+(.+)', value, re.I) | |
| if empty or match: | |
| try: | |
| name = empty[1] if empty else match[2] | |
| initial = [] if empty else _literal(match[3]) | |
| schema = {'type': 'array' if empty else (match[1] or _type(initial)).lower(), 'initial': initial} | |
| old = record['fields'].get(name) | |
| if old and old != schema and not revision: | |
| raise ValueError('say whether to revise the existing initial state ' + name) | |
| record['fields'][name] = schema; consume(raw, offset, 'state'); return | |
| except ValueError as error: | |
| fail(raw, offset, str(error), 'state'); return | |
| fail(raw, offset, 'connect this exact clause to a state, event, condition, view, or storage part') | |
| binding_text = list(text) | |
| owned = set() | |
| for delegated in (reading or {}).get('project_delegated', []): | |
| if not isinstance(delegated, dict): | |
| fail(text, 0, 'delegated reason needs a named native source receipt', 'reason_ownership') | |
| continue | |
| span = delegated.get('span') | |
| if (delegated.get('owner') != 'reason' or not isinstance(span, list) or len(span) != 2 | |
| or any(type(n) is not int for n in span) or not 0 <= span[0] < span[1] <= len(text) | |
| or text[span[0]:span[1]] != delegated.get('text') or any(i in owned for i in range(*span))): | |
| fail(text, 0, 'delegated reason needs an exact, nonoverlapping native source receipt', 'reason_ownership') | |
| continue | |
| consume(text[span[0]:span[1]], span[0], 'delegated_reason') | |
| for i in range(*span): | |
| # Preserve sentence boundaries so a reason cannot merge separate actions. | |
| if text[i] not in '.;\n': | |
| binding_text[i] = ' ' | |
| owned.add(i) | |
| for offset, segment in _split(''.join(binding_text), r';\s*|\.(?=\s|$)\s*|\n+'): | |
| clause(segment, offset) | |
| return _compile(record) | |