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
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
#!/usr/bin/env python3
"""network_glue_v2 - glue v1 plus the three classes its first run found (2026-11-05). Still 0 hand-written adapters.

1. CONDITIONS, learned by ablation from the specialist itself. Every content word of a face's template is removed in turn
   and the specialist re-asked with the face's own dev givens; a word whose removal changes the answer or makes the
   specialist decline is a CONDITION of the face. A face is eligible only when all its conditions are in the question.
   COVERAGE (second reading of the question): every question word that is a condition of SOME face, and every name
   (capitalised word after the first), must be covered by a face on the path, else the network declines. And a
   dimensionless quantity carrying a role (e.g. "twice Earth's mass") is a condition, never a free factor: core math may
   not absorb it. (v1's 2 wrong + 2 false yes: an Earth-gravity fall face applied to the Moon / another planet.)
2. OUTPUT KINDS. Yes/no faces (dev expect "Yes"/"No") answer bool goals; counting goals use v2's per-unit rule; faces whose
   dev questions carry bare numbers (geometry: "radius 2") get their dimensional law from a SCALING PROBE: the input is
   doubled and the exponent read from the answer's ratio (area 4x -> output = input^2), so a bare-number slot reads any
   quantity of one dimension and writes that dimension to the learned power.
3. SELECTOR: types gate (a face can only read quantities of its slot types), conditions gate, words rank (v1 gated on word
   fit at 0.5 and missed "a motor lifts a load" against "a box lifted").
usage: network_glue_v2.py <standing.txt> <spec_root> <combo_code> [question ...]"""
from __future__ import annotations

import collections
import itertools
import json
import math
import re
import sys

from network_glue_v1 import (GlueNetwork, Face, _slot, parse_out, reply_value, words)  # noqa: F401
from network_v2 import DIMLESS, TEMP, Q, core_math, dmul, g, normalise, read_givens, read_goal, unit_lookup, valid_given

FREE = "free"
BARE = re.compile(r"(?<![\w.])(-?\d+(?:\.\d+)?)(?![\w.]*\s*(?:%|°))")
YESNO = re.compile(r"^\W*(yes|no)\b", re.I)


def _stem(w):
    for suf in ("ing", "ed", "es", "s"):
        if len(w) > len(suf) + 3 and w.endswith(suf):
            return w[:-len(suf)]
    return w


def stems(ws):
    return {_stem(w) for w in ws}


class Face2(Face):
    def __init__(self, *a, out_kind="dim", power=None, **k):
        super().__init__(*a, **k)
        self.out_kind, self.power, self.conditions = out_kind, power, set()

    def render(self, qs):
        if self.power is None:
            return super().render(qs)
        text = self.template
        for i, q in enumerate(qs):
            text = text.replace("{%d}" % i, g(q.v), 1)
        return text

    def public(self):
        d = super().public()
        d.update(out_kind=self.out_kind, power=self.power, conditions=sorted(self.conditions))
        return d


class GlueNetwork2(GlueNetwork):
    # ------------------------------------------------------------ learning
    def _learn(self):
        faces, rep = [], {"specialists": 0, "with_panel": 0, "candidates": 0, "examined_ok": 0, "unexamined": 0, "failed": 0,
                          "bool_faces": 0, "scaling_faces": 0, "conditions_total": 0, "by_specialist": {}}
        for sid in self.reg.ids:
            rep["specialists"] += 1
            items = self._panel_any(sid)
            if not items:
                continue
            rep["with_panel"] += 1
            self._vocab = getattr(self, "_vocab", {})
            self._vocab[sid] = set().union(*(words(re.sub(r"-?\d[\d,.]*", " ", it["q"])) for it in items[:60]))
            self._kind_vocab = getattr(self, "_kind_vocab", {})
            for it in items[:60]:
                self._kind_vocab.setdefault((sid, it.get("kind", "")), set()).update(words(re.sub(r"-?\d[\d,.]*", " ", it["q"])))
            cands = [c for it in items[:60] for c in [self._candidate(sid, it)] if c]
            rep["candidates"] += len(cands)
            kept = 0
            groups = collections.defaultdict(list)
            for c in cands:
                groups[(c[0].kind, c[0].out_kind, c[0].signature(), c[0].power is not None)].append(c)
            for _key, group in groups.items():
                done = set()
                for f, gv, it in group:
                    if f.template in done:
                        continue
                    others = [(g2, i2) for f2, g2, i2 in group if f2.src_q != f.src_q]
                    if not others:
                        rep["unexamined"] += 1
                        continue
                    if not any(self._check(f, g2, i2) for g2, i2 in others[:3]):
                        rep["failed"] += 1
                        continue
                    f.conditions = self._conditions(f, gv, it)
                    f.out_name = stems(self._wh_words(f.template)) & stems(f.conditions)
                    f.ctx = stems(f.conditions) - f.out_name
                    rep["conditions_total"] += len(f.conditions)
                    faces.append(f)
                    done.add(f.template)
                    kept += 1
                    rep["examined_ok"] += 1
                    rep["bool_faces"] += f.out_kind == "bool"
                    rep["scaling_faces"] += f.power is not None
            rep["by_specialist"][sid] = kept
            if kept:
                self.log("faces %-22s %d" % (sid, kept))
        return faces, rep

    def _panel_any(self, sid):
        try:
            man = json.load(open("%s/%s/manifest.json" % (self.root, sid)))
            p = man.get("panel", {}).get("path", "")
            import os
            local = os.path.join(self.root, sid, os.path.basename(p))
            items = json.load(open(local if os.path.exists(local) else p))
        except Exception:  # noqa: BLE001
            return []
        out = []
        for it in items:
            if not isinstance(it, dict) or it.get("split") != "dev" or not it.get("valid", True):
                continue
            e = it.get("expect")
            if isinstance(e, bool):
                continue
            if isinstance(e, (int, float)) or (isinstance(e, str) and e.strip().lower() in ("yes", "no")):
                out.append(it)
        return out

    def _candidate(self, sid, it):
        q = normalise(it["q"])
        expect = it["expect"]
        boolish = isinstance(expect, str)
        givens, flags = read_givens(q)
        if givens and not flags.get("unread_numbers") and len(givens) <= 4 and all(q.find(x.text) >= 0 for x in givens):
            resp = self._ask(sid, it["q"])
            if not resp:
                return None
            if boolish:
                m = YESNO.match(resp)
                if not m or m.group(1).lower() != expect.strip().lower():
                    return None
                out_dim, factor, unit, kind = None, 1, "", "bool"
            else:
                hit = reply_value(resp, float(expect))
                if not hit or not hit[1]:
                    return None
                _v, (factor, out_dim), unit = hit
                kind = "dim"
            template, slots = q, []
            for i, x in enumerate(givens):
                s = _slot(x)
                if s is None:
                    return None
                template = template.replace(x.text, "{%d}" % i, 1)
                slots.append(s)
            if not all("{%d}" % i in template for i in range(len(slots))):
                return None
            return (Face2(sid, it.get("kind", ""), template, slots, out_dim, factor, unit, it["q"], out_kind=kind), givens, it)
        if boolish or givens:
            return None
        # bare numbers: a scaling probe gives the dimensional law
        nums = list(BARE.finditer(q))
        if not nums or len(nums) > 2:
            return None
        resp = self._ask(sid, it["q"])
        if not resp or not reply_value(resp, float(expect)):
            return None
        vals = [float(m.group(1)) for m in nums]
        template = q
        for i, m in enumerate(reversed(nums)):
            j = len(nums) - 1 - i
            template = template[:m.start()] + "{%d}" % j + template[m.end():]
        f = Face2(sid, it.get("kind", ""), template, [{"dim": FREE, "role": ""} for _ in nums], None, 1, "", it["q"], power=0)
        base = float(expect)
        r2 = self._ask(sid, f.render([Q(v * 2, DIMLESS, "") for v in vals]))
        out = self._first_number(r2)
        if out is None or base == 0 or out / base <= 0:
            return None
        p = math.log(out / base, 2)
        if abs(p - round(p)) > 0.02 or round(p) == 0:
            return None
        f.power = int(round(p))
        return (f, [Q(v, DIMLESS, "") for v in vals], it)

    @staticmethod
    def _wh_words(template):
        """the words naming what a dev question asks for: its wh-phrase, up to the first preposition or verb join"""
        last = [s for s in re.split(r"(?<=[.?!])\s+", template) if s][-1:] or [template]
        m = re.search(r"\b(?:what|how|which)\b(.*?)(?:\bof\b|\bdoes\b|\bdo\b|\bat\b|\bwill\b|\bfor\b|\bwith\b|\?|$)",
                      last[0], re.I)
        return words(m.group(1)) if m else set()

    @staticmethod
    def _first_number(resp):
        m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?", resp or "")
        return float(m.group(0).replace(",", "")) if m else None

    def _value(self, f, resp):
        if not resp:
            return None
        if f.out_kind == "bool":
            m = YESNO.match(resp)
            return m.group(1).lower() if m else None
        if f.power is not None:
            return self._first_number(resp)
        return parse_out(resp, f)

    def _check(self, f, givens, it):
        v = self._value(f, self._ask(f.sid, f.render(givens)))
        e = it["expect"]
        if f.out_kind == "bool":
            return v is not None and v == str(e).strip().lower()
        return v is not None and abs(v - float(e)) <= 0.01 * max(abs(float(e)), 1e-12)

    def _conditions(self, f, givens, it):
        """words of the template that change what the specialist computes. Each word is swapped for words the SAME
        specialist uses in its other dev questions (its own vocabulary, so the sentence stays one it reads); if any
        swap gives a different answer, the word is a condition ("lead" -> "water" changes the heat; "okay" ->
        "compliant" changes nothing). A swap the specialist declines says nothing either way."""
        base = self._value(f, self._ask(f.sid, f.render(givens)))
        # first the words that vary across the same KIND of dev question (where materials, bodies, objects change),
        # then the rest of the specialist's vocabulary
        same_kind = sorted(self._kind_vocab.get((f.sid, f.kind), set()) - f.words)
        vocab = same_kind + sorted(self._vocab.get(f.sid, set()) - f.words - set(same_kind))
        conds = set()
        for w in sorted(f.words):
            for alt in vocab[:12]:
                t = re.sub(r"\b%s\b" % re.escape(w), alt, f.template, count=1, flags=re.I)
                probe = Face2(f.sid, f.kind, t, f.slots, f.out_dim, f.out_factor, f.out_unit, f.src_q, out_kind=f.out_kind,
                              power=f.power)
                v = self._value(probe, self._ask(f.sid, probe.render(givens)))
                if v is None:
                    continue
                same = (v == base) if f.out_kind == "bool" else (base is not None and abs(v - base) <= 1e-6 * max(abs(base), 1e-12))
                if not same:
                    conds.add(w)
                    break
        return conds

    # ------------------------------------------------------------ solving
    def _fillers(self, pool, used, slot):
        if slot["dim"] == FREE:
            # a bare-number slot reads a quantity with no role, or one whose role word the face's own template uses
            fw = getattr(self, "_face_words", set())
            return [i for i, q in enumerate(pool) if i not in used and q.dim != DIMLESS and not q.temp_point
                    and (not q.role or q.role in fw)]
        named = {i for i, q in enumerate(pool) if q.dim == DIMLESS and q.role and re.search(r"\b[A-Z][a-z]+", q.text)}
        # a ratio to a named body never enters a derived input either (the side door v2's first run found)
        return [sp for sp in super()._fillers(pool, used, slot)
                if not (isinstance(sp, tuple) and set(sp[1]) & named)]

    def _apply(self, face, pool, used, trace):
        self._face_words = face.words
        fills = [self._fillers(pool, used, s) for s in face.slots]
        for combo in itertools.product(*fills):
            flat = []
            for sp in combo:
                flat += list(sp[1]) if isinstance(sp, tuple) else [sp]
            if len(flat) != len(set(flat)):
                continue
            if face.power is not None:
                dims = {pool[i].dim for i in combo}
                if len(dims) != 1:
                    continue
            args, tr = [], list(trace)
            for sp, s in zip(combo, face.slots):
                if isinstance(sp, tuple):
                    cm = core_math([pool[i] for i in sp[1]], s["dim"])
                    tr.append({"node": "core_math", "op": "derive", "formula": cm[1], "value": cm[0]})
                    args.append(Q(cm[0], s["dim"], "(%s)" % cm[1], ""))
                else:
                    args.append(pool[sp])
            text = face.render(args)
            val = self._value(face, self._ask(face.sid, text))
            tr.append({"node": face.sid, "kind": face.kind, "asked": text, "value": val, "face": face.template})
            if val is None:
                continue
            if face.out_kind == "bool":
                yield pool + [("bool", val)], used | set(flat), tr
                continue
            if not isinstance(val, float) or not math.isfinite(val):
                continue
            if face.power is not None:
                d = args[0].dim
                out_dim = DIMLESS
                for _ in range(abs(face.power)):
                    out_dim = dmul(out_dim, d, 1 if face.power > 0 else -1)
                out = Q(val, out_dim, "%s(%s)" % (face.kind, ", ".join(a.text for a in args)), "", src=face.sid)
            else:
                out = Q(val * face.out_factor, face.out_dim, "%s(%s)" % (face.kind or face.sid, ", ".join(a.text for a in args)),
                        "", src=face.sid)
            yield pool + [out], used | set(flat), tr

    def solve(self, text):
        text = normalise(text)
        givens, flags = read_givens(text)
        goal = read_goal(text)
        base = {"question": text, "givens": [repr(q) for q in givens], "goal": str(goal)}
        if goal is None:
            return dict(base, status="declined", reason="no goal I can reach")
        if not givens:
            return dict(base, status="declined", reason="no quantities to work from")
        for q in givens:
            bad = valid_given(q)
            if bad:
                return dict(base, status="declined", reason=bad, check="validity")
        if flags.get("unread_numbers"):
            return dict(base, status="declined", reason="numbers I could not read", check="all numbers read")
        qw = stems(words(text))
        in_givens = " ".join(q.text for q in givens).lower()
        names = {_stem(w.lower()) for w in re.findall(r"(?<=[^.?!:]\s)([A-Z][a-z]+)\b", text)
                 if not unit_lookup(w) and w.lower() not in in_givens}
        all_conds = set().union(*(stems(f.conditions) for f in self.faces)) if self.faces else set()
        goal_dim = goal[1] if goal[0] == "dim" else None

        def ok(f):
            final = f.out_kind == "bool" or (f.power is None and f.out_dim == goal_dim) or f.power is not None
            if final:   # its output is the answer: every condition named, and the words fit
                if not stems(f.conditions) <= qw:
                    return False
                return bool(f.conditions) or self.fit(f, qw) >= 0.5   # word fit only when no condition was learned
            # an intermediate step: the question names its situation, not the quantity it hands on
            return f.ctx <= qw and bool(stems(f.words - f.conditions) & qw or f.ctx & qw)
        eligible = [f for f in self.faces if ok(f)]
        # siblings (same specialist, same slot types, same output kind) compete on the words that tell them apart
        sib = collections.defaultdict(list)
        for f in self.faces:
            sib[(f.sid, f.signature(), f.out_kind)].append(f)
        keep = []
        for f in eligible:
            group = sib[(f.sid, f.signature(), f.out_kind)]
            if len(group) == 1:
                keep.append(f)
                continue
            def score(x):
                others = set().union(*(stems(y.words) for y in group if y is not x))
                return len((stems(x.words) - others) & qw)
            mine = score(f)
            rival = max(score(y) for y in group if y is not f)
            if mine >= 1 and mine > rival:
                keep.append(f)
        eligible = keep
        # coverage reads only conditions of faces that could have read these quantities (a competing reading)
        fillable = [f for f in self.faces if all(self._fillers(list(givens), set(), s) for s in f.slots)]
        all_conds = set().union(*(stems(f.conditions) for f in fillable)) if fillable else set()
        if goal[0] == "bool":
            eligible = [f for f in eligible if f.out_kind == "bool"]
        else:
            eligible = [f for f in eligible if f.out_kind != "bool"]
        eligible.sort(key=lambda f: -self.fit(f, qw))
        frontier = [(list(givens), set(), [], 0, [])]
        for _depth in range(3):
            nxt = []
            for pool, used, trace, hops, path in frontier:
                done = self._finish2(base, givens, pool, used, goal, trace, hops, path, qw, names, all_conds)
                if done:
                    return done
                if hops < 2:
                    for f in eligible:
                        for p2, u2, t2 in self._apply(f, pool, used, trace):
                            nxt.append((p2, u2, t2, hops + 1, path + [f]))
            frontier = nxt[:200]
        return dict(base, status="declined", reason="no checked path from the givens to what is asked",
                    eligible=[f.sid + ":" + f.kind for f in eligible[:6]])

    def _covered(self, path, qw, names, all_conds):
        cover = set()
        for f in path:
            cover |= stems(f.words) | stems(f.conditions)
        # a condition word of another face that only names an output quantity is not a situation the path ignored
        all_conds = all_conds - set().union(*(getattr(f, "out_name", set()) for f in self.faces))
        return sorted(((qw & all_conds) | names) - cover)

    def _finish2(self, base, givens, pool, used, goal, trace, hops, path, qw, names, all_conds):
        rest = [q for i, q in enumerate(pool) if i not in used]
        bools = [x for x in rest if isinstance(x, tuple)]
        rest = [x for x in rest if not isinstance(x, tuple)]
        if goal[0] == "bool":
            if len(bools) != 1 or rest:
                return None
            ans = bools[0][1]
            sentence = "%s." % ans.capitalize()
        else:
            if bools:
                return None
            if any(q.dim == DIMLESS and q.role and re.search(r"\b[A-Z][a-z]+", q.text) for q in rest):
                return None                     # a ratio to a named body is a condition, never a free factor
            if goal[0] == "count":
                per = [q for q in rest if q.role.startswith("per_unit_")]
                if len(per) != 1:
                    return None
                cm = core_math([q for q in rest if q is not per[0]], (0, 0, 1, 0, 0, 0))
                if not cm:
                    return None
                n = cm[0] / per[0].v
                ans = "%s" % g(n)
                sentence = "That is %s %s." % (g(round(n, 4)), goal[1])
            else:
                cm = core_math(rest, goal[1])
                if not cm:
                    return None
                val = cm[0] / goal[3]
                if not math.isfinite(val) or val < 0:
                    return None
                if hops == 0 and len(givens) == 1:
                    return dict(base, status="declined", reason="single conversion (the core's own operator)", check="multi-step only")
                if hops == 0 and any(abs(cm[0] - q.v) <= 1e-9 * max(1.0, abs(q.v)) and q.dim == goal[1] for q in givens):
                    return None
                unit = goal[2]
                ans = ("$%.2f" % val) if unit == "$" else "%s %s" % (g(round(val, 6)), unit)
                sentence = "The answer is %s." % ans
                trace = trace + [{"node": "core_math", "op": "dimensional", "formula": cm[1], "value": val, "unit": unit}]
        missing = self._covered(path, qw, names, all_conds)
        if missing:
            return dict(base, status="declined", reason="part of the question no path read: %s" % ", ".join(missing[:5]),
                        check="coverage")
        nodes = [t["node"] for t in trace]
        return dict(base, status="answered", answer=ans, response="%s (path: %s)" % (sentence, " → ".join(nodes) or "core_math"),
                    trace=trace, hops=hops)


if __name__ == "__main__":
    net = GlueNetwork2(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3])
    print(json.dumps({k: v for k, v in net.report.items() if k != "by_specialist"}))
    for q in sys.argv[4:]:
        print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1200])