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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""Deterministic rule evaluation, state patching, and invariant checking."""

from __future__ import annotations

import copy
import re
from typing import Any
from uuid import uuid4
from trace2env.eligibility import rule_eligible

from trace2env.models import (
    normalize_state_path,
    Condition,
    EnvironmentState,
    Invariant,
    NormalizedAction,
    Operand,
    PendingEvent,
    StateMutation,
    TransitionPlan,
    TransitionRule,
    TrustPolicy,
    VerificationIssue,
    VerificationResult,
)


MISSING = object()
_RAISE_MISSING = object()


def _names_a_file(segment: str) -> bool:
    """A segment that is a filesystem path or a URL: the dots after it belong to the key, not to nested fields."""
    return segment.startswith("/") or segment.startswith("~/") or "://" in segment


def _step_key(container: dict[str, Any], parts: list[str], index: int, value: Any) -> tuple[str, int]:
    """The key of ``container`` that ``parts[index:]`` addresses, and the index of the first segment left over.

    An ordinary segment is a key by itself. A segment that names a file or URL (``/app/report.txt``,
    ``https://shop.example.com/cart``) absorbs the segments after it, since maps such as ``world.files`` are keyed by
    names that contain dots: an existing key is matched longest-first; writing an object creates or replaces the whole
    entry; reading or deleting addresses the longest existing key, else the whole remainder; writing a scalar or a
    list addresses the last segment as an attribute of the entry named by the rest
    (``world.files./app/report.txt.content``)."""
    segment = parts[index]
    if not _names_a_file(segment) or index == len(parts) - 1:
        return segment, index + 1
    joins = [(".".join(parts[index:stop]), stop) for stop in range(len(parts), index, -1)]  # longest first
    full = joins[0][0]
    if full in container:
        return full, len(parts)
    if isinstance(value, dict):
        prefix, stop = joins[1]
        entry = container.get(prefix)
        if isinstance(entry, dict) and parts[-1] in entry:  # an attribute the entry already has
            return prefix, stop
        return full, len(parts)
    for key, stop in joins[1:]:
        if key in container:
            return key, stop
    return (full, len(parts)) if value is _RAISE_MISSING else joins[1]


def get_path(value: Any, path: str, default: Any = _RAISE_MISSING) -> Any:
    current = value
    parts = normalize_state_path(path).split(".")
    index = 0
    while index < len(parts):
        part = parts[index]
        if isinstance(current, dict):
            key, index = _step_key(current, parts, index, _RAISE_MISSING)
            if key in current:
                current = current[key]
                continue
        elif isinstance(current, list) and part.isdigit() and int(part) < len(current):
            current = current[int(part)]
            index += 1
            continue
        if default is _RAISE_MISSING:
            raise KeyError(path)
        return default
    return current


def set_path(value: dict[str, Any], path: str, new_value: Any, create: bool = True) -> None:
    parts = normalize_state_path(path).split(".")
    current = value
    index = 0
    while True:
        key, index = _step_key(current, parts, index, new_value)
        if index >= len(parts):
            current[key] = new_value
            return
        child = current.get(key)
        if child is None and create:
            child = {}
            current[key] = child
        if not isinstance(child, dict):
            raise ValueError(f"Cannot traverse non-object at {key} in {path}")
        current = child


def delete_path(value: dict[str, Any], path: str) -> None:
    parts = normalize_state_path(path).split(".")
    current: Any = value
    index = 0
    while isinstance(current, dict):
        key, index = _step_key(current, parts, index, _RAISE_MISSING)
        if index >= len(parts):
            current.pop(key, None)
            return
        if key not in current:
            return
        current = current[key]


class UnresolvableOperand(KeyError):
    """A condition operand names an action argument the action does not carry (``{action.arguments.index}`` for a
    click without ``index``): the condition cannot hold, and the rule cannot apply."""


def resolve_operand(operand: Operand, state: EnvironmentState, action: NormalizedAction) -> Any:
    if operand.path is not None:
        try:
            path = re.sub(
                r"\{action\.arguments\.([^{}]+)\}",
                lambda match: str(get_path(action.arguments, match.group(1))),
                operand.path,
            )
        except KeyError as exc:
            raise UnresolvableOperand(str(exc)) from exc
        return get_path(state.model_dump(mode="python"), path, MISSING)
    if operand.action_arg is not None:
        return get_path(action.arguments, operand.action_arg, MISSING)
    return operand.literal


def evaluate_condition(condition: Condition, state: EnvironmentState, action: NormalizedAction) -> bool:
    try:
        return _evaluate_condition(condition, state, action)
    except UnresolvableOperand:
        return False  # a condition about an argument this action lacks never holds (found live: the android tracker crashed)


def _evaluate_condition(condition: Condition, state: EnvironmentState, action: NormalizedAction) -> bool:
    left = resolve_operand(condition.left, state, action)
    if condition.op == "exists":
        return left is not MISSING
    if condition.op == "not_exists":
        return left is MISSING
    if left is MISSING or condition.right is None:
        return False
    right = resolve_operand(condition.right, state, action)
    if right is MISSING:
        return False
    operations = {
        "eq": lambda: left == right,
        "ne": lambda: left != right,
        "gt": lambda: left > right,
        "gte": lambda: left >= right,
        "lt": lambda: left < right,
        "lte": lambda: left <= right,
        "contains": lambda: right in left,
        "in": lambda: left in right,
    }
    try:
        return bool(operations[condition.op]())
    except (TypeError, KeyError):
        return False


ACTION_TOKEN = re.compile(r"\{action\.arguments\.([^{}]+)\}")


def resolve_dynamic(value: Any, action: NormalizedAction) -> Any:
    if isinstance(value, dict) and set(value) == {"$action_arg"}:
        return get_path(action.arguments, str(value["$action_arg"]))
    if isinstance(value, dict) and set(value) == {"$state_path"}:
        return value
    if isinstance(value, dict):
        # Keys may carry tokens too: a file map entry keyed by the path the action names.
        return {_resolve_key(key, action): resolve_dynamic(item, action) for key, item in value.items()}
    if isinstance(value, list):
        return [resolve_dynamic(item, action) for item in value]
    if isinstance(value, str):
        full = ACTION_TOKEN.fullmatch(value)
        if full:
            return get_path(action.arguments, full.group(1))
        return ACTION_TOKEN.sub(lambda match: str(get_path(action.arguments, match.group(1))), value)
    return value


def _resolve_key(key: Any, action: NormalizedAction) -> Any:
    if isinstance(key, str) and ACTION_TOKEN.search(key):
        return ACTION_TOKEN.sub(lambda match: str(get_path(action.arguments, match.group(1))), key)
    return key


def resolve_mutation(mutation: StateMutation, action: NormalizedAction) -> StateMutation:
    path = ACTION_TOKEN.sub(lambda match: str(get_path(action.arguments, match.group(1))), mutation.path)
    return mutation.model_copy(update={"path": path, "value": resolve_dynamic(mutation.value, action)})


def apply_mutations(
    state: EnvironmentState,
    mutations: list[StateMutation],
    *,
    action: NormalizedAction | None = None,
) -> EnvironmentState:
    result = state.model_copy(deep=True)
    data = result.model_dump(mode="python")
    for original in mutations:
        mutation = resolve_mutation(original, action) if action else original
        if mutation.op == "schedule":
            if mutation.delay_steps is None:
                raise ValueError("schedule mutation requires delay_steps")
            if isinstance(mutation.value, dict) and "effects" in mutation.value:
                effects = [StateMutation.model_validate(item) for item in mutation.value["effects"]]
            else:
                effects = [StateMutation(op="set", path=mutation.path, value=mutation.value)]
            pending = PendingEvent(
                id=f"pending_{uuid4().hex}",
                due_step=result.step + mutation.delay_steps,
                effects=effects,
            )
            data.setdefault("pending_events", []).append(pending.model_dump(mode="python"))
            continue

        current = get_path(data, mutation.path, MISSING)
        if mutation.op in {"set", "create"}:
            set_path(data, mutation.path, copy.deepcopy(mutation.value))
        elif mutation.op == "delete":
            delete_path(data, mutation.path)
        elif mutation.op in {"increment", "decrement"}:
            if current is MISSING:
                raise ValueError(f"Cannot {mutation.op} missing path {mutation.path}")
            try:
                updated = current + mutation.value if mutation.op == "increment" else current - mutation.value
            except TypeError as exc:
                raise ValueError(f"Cannot {mutation.op} non-numeric path {mutation.path}: {exc}") from exc
            set_path(data, mutation.path, updated)
        elif mutation.op == "append":
            if current is MISSING:
                set_path(data, mutation.path, [copy.deepcopy(mutation.value)])
            elif isinstance(current, list):
                current.append(copy.deepcopy(mutation.value))
            else:
                raise ValueError(f"Cannot append to non-list path {mutation.path}")
        elif mutation.op == "merge":
            if not isinstance(mutation.value, dict):
                raise ValueError(f"merge requires an object value at {mutation.path}")
            if current is MISSING:
                set_path(data, mutation.path, copy.deepcopy(mutation.value))
            elif isinstance(current, dict):
                current.update(copy.deepcopy(mutation.value))
            else:
                raise ValueError(f"Cannot merge into non-object path {mutation.path}")
        elif mutation.op == "remove":
            if current is MISSING:
                continue
            if not isinstance(current, dict):
                raise ValueError(f"Cannot remove keys from non-object path {mutation.path}")
            keys = mutation.value if isinstance(mutation.value, list) else [mutation.value]
            for key in keys:
                current.pop(str(key), None)
    return EnvironmentState.model_validate(data)


def process_due_events(state: EnvironmentState, target_step: int) -> tuple[EnvironmentState, list[str]]:
    result = state.model_copy(deep=True)
    due = [event for event in result.pending_events if event.due_step <= target_step]
    remaining = [event for event in result.pending_events if event.due_step > target_step]
    result.pending_events = remaining
    for event in sorted(due, key=lambda item: (item.due_step, item.id)):
        result = apply_mutations(result, event.effects)
    return result, [event.id for event in due]


class AmbiguousRuleError(RuntimeError):
    pass


def select_rule(
    rules: list[TransitionRule], state: EnvironmentState, action: NormalizedAction,
    scope: dict[str, str] | None = None,
) -> TransitionRule | None:
    candidates: dict[str, tuple[TransitionRule, TransitionPlan]] = {}
    for rule in rules:
        if rule.action_type != action.type or not rule_eligible(rule, scope, state):
            continue
        if not all(evaluate_condition(condition, state, action) for condition in rule.conditions):
            continue
        try:
            plan = deterministic_plan(rule, action)
        except (KeyError, ValueError):
            # The rule's effects reference arguments this action does not carry; it cannot apply.
            continue
        candidates[rule.id] = (rule, plan)
    if not candidates:
        return None
    priority = max(rule.priority for rule, _ in candidates.values())
    finalists = [(rule, plan) for rule, plan in candidates.values() if rule.priority == priority]
    signatures = {plan.model_copy(update={"rule_ids": []}).model_dump_json() for _, plan in finalists}
    if len(signatures) > 1:
        raise AmbiguousRuleError(
            "Incompatible rules apply at the same priority: " + ", ".join(rule.id for rule, _ in finalists)
        )
    return max((rule for rule, _ in finalists), key=lambda rule: (rule.confidence, rule.id))


def deterministic_plan(rule: TransitionRule, action: NormalizedAction) -> TransitionPlan:
    return TransitionPlan(
        action=action,
        rule_ids=[rule.id],
        effects=[resolve_mutation(effect, action) for effect in rule.effects],
        outcome=rule.outcome,
        renderer_id=rule.renderer,
        observation_template=rule.observation_template,
    )


def check_invariants(
    invariants: list[Invariant], state: EnvironmentState, action: NormalizedAction
) -> VerificationResult:
    issues: list[VerificationIssue] = []
    for invariant in invariants:
        if not evaluate_condition(invariant.condition, state, action):
            issues.append(
                VerificationIssue(
                    code=f"invariant:{invariant.id}",
                    message=invariant.description,
                    severity=invariant.severity,
                )
            )
    return VerificationResult(
        accepted=not any(issue.severity == "error" for issue in issues),
        issues=issues,
        confidence=1.0 if not issues else 0.7,
    )


def verify_rule_support(
    plan: TransitionPlan, rules: list[TransitionRule], state_before: EnvironmentState,
    scope: dict[str, str] | None = None, *, trust_policy: TrustPolicy = "rules_only",
) -> list[VerificationIssue]:
    if not plan.rule_ids:
        if plan.effects and trust_policy == "schema_checked":
            # Graded trust: the effects already passed schema, mutability, type, and invariant
            # checks. They are accepted as a model proposal and flagged for the audit record.
            return [
                VerificationIssue(
                    code="model_proposed_effects",
                    message="The plan cites no reconstructed rule; its effects were accepted under the "
                            "schema_checked trust policy after schema, type, and invariant checks.",
                    severity="warning",
                )
            ]
        return [
            VerificationIssue(
                code="unsupported_plan",
                message="The plan cites no reconstructed rule; it requires agentic fallback judgment.",
                severity="error" if plan.effects else "warning",
            )
        ]
    by_id = {rule.id: rule for rule in rules}
    missing = [rule_id for rule_id in plan.rule_ids if rule_id not in by_id]
    if missing:
        return [
            VerificationIssue(
                code="unknown_rule",
                message=f"Plan cites rules that were not retrieved: {', '.join(missing)}",
                severity="error",
            )
        ]
    cited = [by_id[rule_id] for rule_id in plan.rule_ids]
    if len(plan.rule_ids) != len(set(plan.rule_ids)):
        return [VerificationIssue(code="duplicate_rule", message="A plan cannot apply the same rule twice")]
    if any(rule.action_type != plan.action.type or not rule_eligible(rule, scope, state_before) for rule in cited):
        return [VerificationIssue(code="ineligible_rule", message="A cited rule is not eligible for this action and scope.")]
    if any(
        not all(evaluate_condition(condition, state_before, plan.action) for condition in rule.conditions)
        for rule in cited
    ):
        return [
            VerificationIssue(
                code="inapplicable_rule",
                message="At least one cited rule does not apply to the pre-transition state.",
                severity="error",
            )
        ]
    if any(rule.outcome != plan.outcome for rule in cited):
        return [
            VerificationIssue(
                code="unsupported_outcome",
                message="The planned outcome differs from every cited rule outcome.",
                severity="error",
            )
        ]
    supported = {
        mutation.model_dump_json(exclude_none=True)
        for rule_id in plan.rule_ids
        for mutation in [resolve_mutation(item, plan.action) for item in by_id[rule_id].effects]
    }
    unsupported = [
        effect for effect in plan.effects if effect.model_dump_json(exclude_none=True) not in supported
    ]
    if unsupported:
        return [
            VerificationIssue(
                code="unsupported_effect",
                message="Plan contains effects absent from its cited rules.",
                severity="error",
            )
        ]
    actual = [effect.model_dump_json(exclude_none=True) for effect in plan.effects]
    expected = [resolve_mutation(effect, plan.action).model_dump_json(exclude_none=True)
                for rule in cited for effect in rule.effects]
    if actual != expected:
        return [VerificationIssue(code="effect_sequence_mismatch", message="Plan must preserve its rules' effect order and multiplicity.")]
    if any(rule.renderer != plan.renderer_id or rule.observation_template != plan.observation_template for rule in cited):
        return [VerificationIssue(code="unsupported_rendering", message="Plan changed the rendering specified by its rules.")]
    return []


TEMPLATE_TOKEN = re.compile(r"\{([a-zA-Z0-9_.]+)\}")


def render_template(template: str, context: dict[str, Any]) -> str:
    def replace(match: re.Match[str]) -> str:
        value = get_path(context, match.group(1), MISSING)
        if value is MISSING:
            raise KeyError(f"Template references missing value {match.group(1)}")
        return str(value)

    return TEMPLATE_TOKEN.sub(replace, template)