"""Discuss a received program from its saved meaning, without building or running it. State, events, conditions, examples and reasons are the vocabulary of the current project. Questions bind to that record; a hypothetical state is never reported as the live application's state. No application-specific templates or topic facts. """ import json import re def _value(value): return json.dumps(value, ensure_ascii=False) def _mentions(text, name): return bool(name and re.search(r'(? 1 and all(re.fullmatch(r"(?i)(?:do not|don't)\s+(?:build|create|modify|change|run)\s+.+", p) for p in pieces[:-1] if p): return pieces[-1] if language.asks_about(pieces[-1]) else None return None def _expression(expr): if not isinstance(expr, dict): return _value(expr) if 'state' in expr: return '`%s`' % expr['state'] if 'param' in expr: return 'the `%s` input' % expr['param'] args = [_expression(a) for a in expr.get('args', [])] operators = {'eq': 'equals', 'ne': 'does not equal', 'lt': 'is below', 'le': 'is at most', 'gt': 'is above', 'ge': 'is at least', 'add': 'plus', 'subtract': 'minus', 'multiply': 'times', 'divide': 'divided by', 'contains': 'contains'} op = expr.get('op') if op in operators and len(args) == 2: return '%s %s %s' % (args[0], operators[op], args[1]) if op in ('and', 'or'): return (' %s ' % op).join('(' + a + ')' for a in args) if op == 'not' and len(args) == 1: return 'not (' + args[0] + ')' return '`' + json.dumps(expr, ensure_ascii=False) + '`' def _actions(actions): result = [] for action in actions: op, field = action.get('op'), action.get('field') val = _expression(action.get('value')) if op == 'set': result.append('set `%s` to %s' % (field, val)) elif op == 'append': result.append('append %s to `%s`' % (val, field)) elif op == 'remove': result.append('remove %s from `%s`' % (val, field)) else: result.append('apply the saved `%s` action: `%s`' % (op, _value(action))) return '; then '.join(result) or 'no change is bound yet' def _hypothesis(text, fields): """Bind a hypothetical clause to named fields or one unique typed state.""" markers = list(re.finditer(r'\b(?:while|when|if)\b', text, re.I)) if not markers: return None, [] tail = text[markers[-1].end():].strip().rstrip('?.!') supplied, holes = {}, [] for name, schema in fields.items(): for explicit in re.finditer(r'\b' + re.escape(name) + r'\s+(?:is|equals|=)\s+("[^"]*"|\S+)', tail, re.I): raw = explicit[1].rstrip(',') try: value = json.loads(raw) except ValueError: value = raw.strip('"\'') if name in supplied and (type(supplied[name]) is not type(value) or supplied[name] != value): holes.append('The hypothetical gives conflicting values for `%s`; clarify which value applies.' % name) else: supplied[name] = value short = re.fullmatch(r'(?i)(?:still\s+)?in\s+("[^"]*"|[\w-]+)', tail) if short: value = short[1].strip('"') candidates = [name for name, schema in fields.items() if schema.get('type') == 'string'] if len(candidates) == 1: supplied[candidates[0]] = value else: holes.append('Name the state field whose hypothetical value is %s.' % _value(value)) for name, value in supplied.items(): schema = fields[name] try: import interactive_program interactive_program._value(value, schema, name) except (ValueError, TypeError, KeyError) as error: holes.append('The hypothetical value for `%s` is outside its declared state: %s.' % (name, error)) return supplied, holes def _guard_verdict(expr, supplied): """Three-valued evaluation of a saved guard over explicitly supplied facts.""" if not isinstance(expr, dict): return expr, True if 'state' in expr: name = expr['state'] return supplied.get(name), name in supplied if 'param' in expr: return None, False results = [_guard_verdict(a, supplied) for a in expr.get('args', [])] if not all(known for value, known in results): return None, False vals = [v for v, k in results] op = expr.get('op') try: if op in ('eq', 'ne'): same = type(vals[0]) == type(vals[1]) and vals[0] == vals[1] return (same if op == 'eq' else not same), True if op in ('lt', 'le', 'gt', 'ge'): if any(isinstance(v, bool) or not isinstance(v, (int, float)) for v in vals): return None, False return {'lt': lambda: vals[0] < vals[1], 'le': lambda: vals[0] <= vals[1], 'gt': lambda: vals[0] > vals[1], 'ge': lambda: vals[0] >= vals[1]}[op](), True if op in ('and', 'or', 'not') and all(isinstance(v, bool) for v in vals): return (all(vals) if op == 'and' else any(vals) if op == 'or' else not vals[0]), True except (TypeError, ValueError, IndexError): pass return None, False def answer(text, work, reading=None): intent = (work or {}).get('build_intent') question = _question(text) if not intent or question is None: return None low = question.lower() interactive = intent.get('interactive') or {} contract = interactive.get('contract') or {} fields = contract.get('state') or interactive.get('fields') or {} events = contract.get('events') or {} event_records = interactive.get('events') or {} interactions = bool(re.search(r'\b(?:click|press|button|event|handler|rule)\b', low)) named = [] for name in events: label = event_records.get(name, {}).get('label') or name direct = re.fullmatch(r'(?i)\s*(?:what\s+(?:should|does|will|can)\s+|how\s+does\s+)' + re.escape(label) + r'\s+(?:do|work|behave|change)(?:\s+(?:the\s+)?(?:state|project|app))?[?.! ]*', question) if (interactions or direct) and (_mentions(question, name) or _mentions(question, label)): named.append(name) mentioned_fields = [name for name in fields if _mentions(question, name)] named_file = _mentions(question, intent.get('file')) project_reference = bool(re.search(r'\b(?:project|program|app|work|task|goal|it|its|this|that)\b', low)) reason_question = bool(re.search(r'\b(?:reason|reasons|why|purpose)\b', low)) asked_reason = reason_question and (project_reference or re.search(r'\b(?:i|my|give|gave|asked)\b', low)) if not (named or mentioned_fields or named_file or project_reference or asked_reason): # A guard value can identify a rule even if the question uses a nominal # form of its label ("approval" for Approve); never invent that alias. for name, event in events.items() if re.search(r'\b(?:allowed|wait|condition|only|before|after|guard)\b', low) else (): guard = event.get('guard') or {} if isinstance(guard, dict) and any(isinstance(a, str) and _mentions(question, a) for a in guard.get('args', [])): named.append(name) if not named: return None lines, holes, basis = [], [], [] if asked_reason and not named: reasons = intent.get('reasons') or [] if reasons: lines.append('You gave this reason for the project: ' + '; '.join(reasons)) basis.append('build_intent.reasons') else: holes.append('No separate reason is recorded for this project. Its requested behavior is kept, but I cannot supply your reason from that alone.') elif named: hypothesis, ambiguity = _hypothesis(question, fields) holes.extend(ambiguity) for name in named: event, record = events[name], event_records.get(name, {}) label = record.get('label') or name guard = event.get('guard') required = _expression(guard) if guard is not None else None lines.append('The saved rule for `%s` is to %s%s.' % (label, _actions(event.get('actions', [])), ', only when ' + required if required else '')) basis.append('build_intent.interactive.contract.events.' + name) if hypothesis is not None and not ambiguity: if guard is None: lines.append('This rule has no state condition. The described event would attempt its actions, subject to state and action checks; this is a hypothetical explanation, not a live button click.') else: verdict, known = _guard_verdict(guard, hypothesis) if known: lines.append('With %s, the condition %s. %s No live state has been read or changed.' % (', '.join('`%s` = %s' % (k, _value(v)) for k, v in hypothesis.items()), 'holds' if verdict else 'does not hold', 'The described event would attempt its actions, subject to remaining state and action checks.' if verdict else 'The described event would be rejected and leave the state unchanged.')) else: holes.append('The hypothetical needs enough state values to evaluate ' + required + '.') elif reason_question: source_key = 'condition_source' if record.get('condition_source') else 'source' if record.get(source_key): lines.append('That condition comes from your received rule: ' + record[source_key]) basis.append('build_intent.interactive.events.' + name + '.' + source_key) if intent.get('reasons'): lines.append('The project reason you gave was: ' + '; '.join(intent['reasons'])) else: lines.append('No separate explanation of why you chose this rule is recorded.') elif mentioned_fields: for name in mentioned_fields: schema = fields[name] lines.append('`%s` is %s state, initially %s.' % (name, schema.get('type'), _value(schema.get('initial')))) events_using = [n for n, event in events.items() if any(action.get('field') == name for action in event.get('actions', []))] if events_using: lines.append('The saved events that change it are ' + ', '.join('`%s`' % (event_records.get(n, {}).get('label') or n) for n in events_using) + '.') basis.append('build_intent.interactive.contract.state.' + name) lines.append('These are the requested initial values, not a reading of the running app.') elif re.search(r'\b(?:does|do|should|supposed|understand|asked|description|describe|steps)\b', low): if intent.get('stages'): lines.append('The requested program applies these stages in order: ' + ' → '.join(intent['stages']) + '.') basis.append('build_intent.stages') elif events: for name, event in events.items(): guard = event.get('guard') lines.append('`%s`: %s%s.' % (event_records.get(name, {}).get('label') or name, _actions(event.get('actions', [])), ', only when ' + _expression(guard) if guard else '')) basis.append('build_intent.interactive.contract.events') else: lines.append('Your kept request is: ' + intent['original']) basis.append('build_intent.original') if intent.get('constraints'): lines.append('The constraints remain: ' + '; '.join(c['text'] for c in intent['constraints'])) basis.append('build_intent.constraints') else: return None lines.extend(holes) lines.append('This answers from the saved request. It does not run or rebuild the project.') return {'status': 'hole' if holes else 'answered', 'path': 'bench:work:record:meaning', 'response': '\n\n'.join(lines), 'missing_evidence': [{'kind': 'project_discussion', 'text': h} for h in holes], 'execution': {'state': 'missing' if holes else 'read', 'started': False, 'changed': False, 'work_id': work.get('id'), 'basis': basis}}