File size: 12,798 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
"""Core types for question-preserving visual interventions (``docs/02`` §10).

An *intervention operator* transforms a structured ``World`` into a new
``World`` (plus bookkeeping) **without touching the human-authored question or
choices** and **without assigning a gold state**. The operator's only job is to
produce a well-formed transformed world and record what it did; the resulting
state (``FULL`` / ``A_SAME`` / ``A_CHANGED`` / ``U_MISSING`` / ``U_INVALID``) is
decided later by the P7 state-proof builder, which executes the program before
and after (``docs/02`` §11.1). This separation is a hard P5 gate
("operator가 state를 직접 assign하지 않음").

Design rules every operator obeys (``docs/07`` §7 P5 completion gate):

  * **Source world immutable** — :func:`apply` returns a brand-new world; the
    passed dict is never mutated.
  * **Deterministic** — the same ``(world, target_node, seed, operation)`` always
    reproduces the same ``transformed_world_sha256``; a different seed or
    operation changes it.
  * **Reject invalid mutations** — an operator that would break world
    well-formedness (a dangling geometry constraint, a label collision, an
    out-of-range substitute, a multiple-choice answer leaving the unchanged
    choice set) raises :class:`InterventionError` rather than emitting a broken
    world. Never a silent accept.
  * **No state assignment** — :class:`TransformedWorld` carries no ``state``
    field by construction.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Literal, Protocol

from ..dsl.ast import canonical_number_str, parse_number
from ..hashing import canonical_json_hash
from ..ingest.base import IngestError
from ..sources.base import World
from ..sources.world_ops import (
    NODE_VISIBILITY_KEY,
    clone_world,
    find_point,
    find_row,
    find_series,
    find_stating_constraint,
    hidden_nodes,
    looks_numeric,
    node_kind,
    world_sha256,
)

# The four deterministic intervention operators (``docs/02`` §10). REDACT_BLUR_V1
# is deliberately absent: it is a shortcut stress test only and never appears in
# a primary U certificate (§10.2).
OperatorName = Literal[
    "REDACT_SOLID_V1",
    "CLEAN_DELETE_V1",
    "SUBSTITUTE_V1",
    "CONTROL_MATCHED_V1",
]


class InterventionError(IngestError):
    """A requested intervention is infeasible / would break the world.

    Raised for an invalid geometry or plot mutation, a label collision, an
    out-of-range substitute, or a multiple-choice answer that leaves the
    unchanged choice set (``docs/02`` §10.4). An infeasible intervention is
    rejected — never silently coerced into a broken world or a faked state.
    """


@dataclass(frozen=True)
class TransformedWorld:
    """One operator's deterministic output over a source world.

    ``world`` is the transformed (or, for REDACT_SOLID_V1, visibility-marked)
    world. ``hidden_nodes`` lists semantic node ids a renderer must patch
    (REDACT_SOLID_V1 keeps the node in the world but hides its pixels, §10.1).
    ``substitute_value`` records the new value a SUBSTITUTE_V1 / completion
    placed on the target (canonical string, or ``None`` for non-substitute
    operators). ``transformed_world_sha256`` is the content-addressed identity of
    the *transformation* — deterministic over the full record, so the same
    ``(seed, operation, target, source)`` reproduces it byte-for-byte.

    There is deliberately **no** ``state`` field: the operator never assigns a
    gold state (P5 gate). P7's state-proof builder derives state by execution.
    """

    world: World
    operator: OperatorName
    target_node: str
    seed: int
    transformed_world_sha256: str
    hidden_nodes: frozenset[str] = field(default_factory=frozenset)
    substitute_value: str | None = None
    description: str = ""

    @property
    def is_hidden(self) -> bool:
        return bool(self.hidden_nodes)


class InterventionOperator(Protocol):
    """One deterministic intervention operator (``docs/02`` §10)."""

    name: OperatorName

    def apply(
        self,
        world: World,
        target_node: str,
        *,
        seed: int,
        **kwargs: Any,
    ) -> TransformedWorld:
        """Return a transformed world; never mutate ``world``, never assign state."""
        ...


# --- transformation hashing ------------------------------------------------


def transformed_hash(
    *,
    operator: OperatorName,
    target_node: str,
    seed: int,
    source_world_sha256: str,
    transformed_world_sha256: str,
    hidden_nodes: frozenset[str],
    substitute_value: str | None,
) -> str:
    """Content-addressed identity of one transformation (deterministic).

    Hashed over the full operator record — not just the world — so two
    operators that happen to leave the world identical (e.g. REDACT_SOLID over a
    node vs. a no-op) still differ, and the same transformation reproduces the
    same hash across runs (P5 gate: "seed/operation → same transformed world
    hash").
    """
    return canonical_json_hash(
        {
            "operator": operator,
            "target_node": target_node,
            "seed": seed,
            "source_world_sha256": source_world_sha256,
            "transformed_world_sha256": transformed_world_sha256,
            "hidden_nodes": sorted(hidden_nodes),
            "substitute_value": substitute_value,
        }
    )


# --- value setters (read-only in, new world out) ---------------------------


def with_value(world: World, node_id: str, value: Any) -> World:
    """Return a new world with ``node_id``'s value set to ``value``.

    The value is written to the same field the executor reads (a plot point's
    ``y``, a row cell, the stating constraint's numeric arg), so a completion
    built this way is executable. Raises :class:`InterventionError` when the
    node has no mutable value site. The source world is unchanged.
    """
    new = clone_world(world)
    if not _set_value(new, node_id, value):
        raise InterventionError(f"node {node_id!r} has no mutable value site")
    return new


def _set_value(world: World, node_id: str, value: Any) -> bool:
    """Write ``value`` onto ``node_id`` in place; return whether a site was found.

    The write site follows :func:`~explicit_learning.sources.world_ops.node_kind`:
    a plot point's ``y``, a series' ``label``, a row's first cell, a geometry
    entity's ``label``, or a stating constraint's numeric arg. Dispatching on the
    *node* kind (not the world kind) keeps a category substitute (a series/entity
    label) from being mis-written onto a numeric site.
    """
    kind = node_kind(world, node_id)
    if kind == "point":
        point = find_point(world, node_id)
        if point is None:
            return False
        sidx, pidx, p = point
        p["y"] = _canonical(value)
        world["series"][sidx]["points"][pidx] = p
        return True
    if kind == "series":
        series = find_series(world, node_id)
        if series is None:
            return False
        sidx, s = series
        s["label"] = _canonical(value)
        world["series"][sidx] = s
        return True
    if kind == "row":
        row = find_row(world, node_id)
        if row is None:
            return False
        ridx, r = row
        cells = r.get("cells", {}) or {}
        if not cells:
            return False
        key = next(iter(cells))
        cells[key] = _canonical(value)
        world["rows"][ridx]["cells"] = cells
        return True
    if kind == "entity":
        for i, e in enumerate(world.get("entities", []) or []):
            if e.get("id") == node_id:
                e["label"] = _canonical(value)
                world["entities"][i] = e
                return True
        return False
    if kind == "constraint":
        found = find_stating_constraint(world, node_id)
        if found is None:
            return False
        cidx, c = found
        args = list(c.get("args") or [])
        pred = c.get("predicate")
        if pred == "MeasureOf" and len(args) >= 2 and args[0] == node_id:
            args[1] = _canonical(value)
        elif pred == "Equals" and len(args) == 2:
            if args[0] == node_id and looks_numeric(args[1]):
                args[1] = _canonical(value)
            elif args[1] == node_id and looks_numeric(args[0]):
                args[0] = _canonical(value)
            else:
                return False
        else:
            return False
        c["args"] = args
        world["constraints"][cidx] = c
        return True
    return False


def _canonical(value: Any) -> str:
    """Canonical string form of a substitute value (numbers via §3.2/§3.3)."""
    if isinstance(value, str):
        return value
    try:
        return canonical_number_str(parse_number(value))
    except (ValueError, ZeroDivisionError):
        return str(value)


def set_hidden(world: World, node_ids: frozenset[str]) -> World:
    """Return a new world carrying a visibility marker hiding ``node_ids``.

    The nodes stay in the world (REDACT_SOLID_V1, §10.1: "semantic node는 world에
    남기고 node_visibility[node]=hidden"); only the reserved
    :data:`~explicit_learning.sources.world_ops.NODE_VISIBILITY_KEY` map is set,
    which the renderer (P6) reads and executors ignore.
    """
    new = clone_world(world)
    visibility = dict(new.get(NODE_VISIBILITY_KEY, {}))
    for nid in node_ids:
        visibility[nid] = "hidden"
    new[NODE_VISIBILITY_KEY] = visibility
    return new


def remove_observed_value(world: World, node_id: str) -> World:
    """Return a copy whose target node remains identifiable but has no value.

    REDACT is an epistemic operation: the renderer hides the value and the
    executor evaluating the *observed* transformed world must not retain a
    privileged copy of that value.  Identity/position fields remain so the
    question referent and a content-independent redaction anchor still exist.
    Completion witnesses can restore alternative values with :func:`with_value`
    while retaining the same visibility marker.
    """
    new = clone_world(world)
    kind = node_kind(new, node_id)
    if kind == "point":
        found_point = find_point(new, node_id)
        if found_point is None:
            raise InterventionError(f"point {node_id!r} not found")
        sidx, pidx, point = found_point
        point["y"] = None
        new["series"][sidx]["points"][pidx] = point
        return new
    if kind == "row":
        found_row = find_row(new, node_id)
        if found_row is None:
            raise InterventionError(f"row {node_id!r} not found")
        ridx, row = found_row
        cells = dict(row.get("cells", {}) or {})
        if not cells:
            raise InterventionError(f"row {node_id!r} has no observable cells")
        cells[next(iter(cells))] = None
        new["rows"][ridx]["cells"] = cells
        return new
    if kind == "constraint":
        found_constraint = find_stating_constraint(new, node_id)
        if found_constraint is None:
            raise InterventionError(f"no stating constraint for {node_id!r}")
        cidx, constraint = found_constraint
        args = list(constraint.get("args") or [])
        if constraint.get("predicate") == "MeasureOf" and len(args) >= 2:
            args[1] = None
        elif constraint.get("predicate") == "Equals" and len(args) == 2:
            if str(args[0]) == node_id:
                args[1] = None
            elif str(args[1]) == node_id:
                args[0] = None
            else:
                raise InterventionError(f"constraint for {node_id!r} has no value site")
        else:
            raise InterventionError(f"constraint for {node_id!r} has no value site")
        constraint["args"] = args
        new["constraints"][cidx] = constraint
        return new
    if kind == "series":
        found_series = find_series(new, node_id)
        if found_series is None:
            raise InterventionError(f"series {node_id!r} not found")
        sidx, series = found_series
        series["label"] = None
        new["series"][sidx] = series
        return new
    if kind == "entity":
        for idx, entity in enumerate(new.get("entities", []) or []):
            if entity.get("id") == node_id:
                entity["label"] = None
                new["entities"][idx] = entity
                return new
    raise InterventionError(f"node {node_id!r} has no redactable observed value")


__all__ = [
    "InterventionError",
    "InterventionOperator",
    "OperatorName",
    "TransformedWorld",
    "hidden_nodes",
    "set_hidden",
    "remove_observed_value",
    "transformed_hash",
    "with_value",
    "world_sha256",
]