File size: 10,088 Bytes
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""converse.builder - the build door inside the turn loop (directive Phase 1, the dew point).

A turn the head's own operation head resolves to `build` (or `compose`) opens an obligation whose places are example questions:
the swarm's builder (workbench/swarm/run.py) reads 3-6 of them, names the gap, builds the part from its sources and examines it.
Fewer than three bound -> the open places are asked back (the named hole, cited to the operation). Three or more -> the dew
point: run.build is called, and the reply is its receipt (outcome, gap named, exam verdict, where the part lives). Nothing here
decides by keyword: the operation is chosen by the head's catalogue resonance (op_head), the examples are the user's own questions.
"""
import re
import sys
import time

Q = re.compile(r"\?\s*$")


class Builder:
    def __init__(self, router):
        self.r = router
        self.state = {}                       # session -> {"op": cmd, "qs": [...], "turn": n, "built": [...]}

    def pending(self, session):
        return self.state.get(session)

    # ---- Amendment 14 (4): the builder PROPOSES during candidate generation and nothing changes until the reply is delivered.
    # step() records what it would do in self.proposal[session]; commit() applies it (and runs the swarm, once) only when the
    # delivered reply is the builder's own; a discarded candidate leaves no trace. Examples bind only when they fit the task.
    STOPFIT = set("build specialist specialists make that knows know about famous world world's worlds what how which who where "
                  "when the a an of in on is are long tell me please".split())

    def _stems(self, text):
        return {w[:5] for w in re.findall(r"[a-z]+", str(text).lower()) if len(w) > 3 and w not in self.STOPFIT}

    def fits(self, st, turn):
        """an example fits the open task when it shares a content stem with the request (its topic) or an earlier example"""
        want = set(st.get("topic") or set())
        for x in st["qs"]:
            want |= self._stems(x)
        return bool(want & self._stems(turn)) if want else True

    def step(self, turn, fr, session, q):
        """-> (act, text, substantive) or None; a PROPOSAL, applied by commit() only if this reply is delivered"""
        self.proposal = getattr(self, "proposal", {})
        self.proposal.pop(session, None)
        st = self.state.get(session)
        n = len(self.r.turns[session])
        # 1. a question while a build is pending binds one example place, if it fits the task
        if st and Q.search(turn.strip()) and not st.get("done") and self.fits(st, turn):
            k = len(st["qs"]) + 1
            if k < 3:
                text = "Kept as example %d [turn:%d]. %d more example question%s and I build it [op:%s]." % (
                    k, n, 3 - k, "s" if 3 - k != 1 else "", st["op"])
                self.proposal[session] = {"kind": "example", "q": turn.strip(), "text": text}
                return "hole", text, True
            text = "Building from your 3 examples [op:%s]." % st["op"]
            self.proposal[session] = {"kind": "build", "q": turn.strip(), "text": text}
            return "plan", text, True
        # 2. a new request the operation head resolves to build / compose
        mood = fr.get("mood")
        # the reader names moods directive / inform / commissive / question; the first end-to-end (2026-11-08) showed a build
        # request read as "directive" never reaching the operation head because only the older names were listed here.
        if mood not in ("request", "directive", "statement", "inform", "commitment", "commissive", "question"):
            return None
        op = self.operation(fr, q)
        if not op:
            return None
        fit, kind, cmd, usage, desc = op
        if cmd not in ("build", "compose"):
            return None
        if st and not st.get("done") and st["op"] == cmd:
            return "hole", "Still open [turn:%d]: %d example question%s so far; give me %d more and I build it [op:%s]." % (
                st["turn"], len(st["qs"]), "s" if len(st["qs"]) != 1 else "", 3 - len(st["qs"]), cmd), True
        text = ("I can build that [op:%s]: %s. The places I need are three to six example questions it should answer, "
                "one per turn; from them the swarm names what it needs and builds it from its sources." % (cmd, desc[:140].rstrip(".")))
        self.proposal[session] = {"kind": "open", "state": {"op": cmd, "qs": [], "turn": n, "done": False,
                                                              "topic": sorted(self._stems(turn))}, "text": text}
        return "hole", text, True

    def commit(self, session, delivered_text):
        """apply this turn's proposal iff the delivered reply is the builder's; returns the receipt text for a build, else None"""
        p = getattr(self, "proposal", {}).pop(session, None)
        if not p or p["text"] not in str(delivered_text):
            return None
        if p["kind"] == "open":
            self.state[session] = p["state"]
            self.r.stats["build_open"] += 1
            return None
        st = self.state.get(session)
        if st is None or st.get("done"):
            return None
        st["qs"].append(p["q"])
        if p["kind"] == "build":
            return self.build(session, st)[1]
        return None

    def operation(self, fr, q):
        """Amendment 13 (2026-11-08): the operation is read from what the turn asks, the frame's verb and object, not from the
        whole turn, whose topic words outweigh it (the probe: "Build me a specialist that knows how long the world's famous
        bridges are" put specialist.rel-bridges first and build at 0.27, under tau). The topic stays with the places. When the
        frame names no verb or object, the whole turn is used as before. No threshold changes."""
        def words_of(k):
            v = fr.get(k)
            return [str(x) for x in (v if isinstance(v, (list, tuple)) else [v]) if x]
        verb = " ".join(words_of("verb")).strip().lower()
        # 1. the turn NAMES the operation: its verb is a command of the catalogue (build, compose, ...). Exact, no threshold.
        if verb:
            for row in self.r.op_rows:
                if str(row[1]).lower() == verb:
                    return (1.0,) + tuple(row)
        # 2. the turn DESCRIBES the operation: resonance of the verb and object against the catalogue, under the same tau as
        #    any request (the second probe: build 0.26, compose 0.30 on these two words alone; under tau, so this rarely fires)
        try:
            from compose_reply_v8 import content_words, unit
            opw = [w for w in content_words(" ".join(words_of("verb") + words_of("object"))) if w]
        except Exception:  # noqa: BLE001
            opw = []
        if opw:
            q2 = unit(self.r.text_vec(opw, {w: 1.0 for w in opw}))
            op = self.r.op_head(q2, words=opw) or self.r.op_head(q2)
            if op:
                return op
        # 3. the whole turn, as before
        return self.r.op_head(q)

    def evidence(self, qs):
        """Amendment 14 (4): the store's evidence for the examples, read the way the answer path reads it: each example's entity
        and the relation the question asks for; the relation every example's entity holds is what the task asks about"""
        r = self.r
        from compose_reply_v8 import content_words, unit
        per = []
        for q in qs:
            ents = r.link(q)
            if not ents:
                continue
            span, e, _ = ents[0]
            names = set(content_words(span))
            rest = [w for w in content_words(q) if w not in names]
            if not rest:
                continue
            asked = "number" if re.match(r"\s*how (many|much|long|old|far|tall|high|big|deep|wide|heavy)", q.lower()) else None
            rels, _ = r.relations(e, unit(r.text_vec(rest, {w: 1.0 for w in rest})), asked)
            per.append((e, [(p, lab) for p, lab, _v, _f in rels[:3]]))
        if len(per) < 2:
            return None
        common = None
        for _e, rels in per:
            ps = {p for p, _l in rels}
            common = ps if common is None else common & ps
        if not common:
            return None
        p = next(pp for pp, _l in per[0][1] if pp in common)
        lab = next(l for pp, l in per[0][1] if pp == p)
        return {"pid": "P%d" % p, "label": lab, "entities": ["Q%d" % e for e, _ in per]}

    def build(self, session, st):
        try:
            import run as swarm_run
        except Exception as e:  # noqa: BLE001
            return "hole", "The builder is not on this install's path [none]: %s." % repr(e)[:80], False
        t0 = time.time()
        try:
            ev = self.evidence(st["qs"])
        except Exception:  # noqa: BLE001
            ev = None
        st["evidence"] = ev
        try:
            try:
                r = swarm_run.build(st["qs"], None, anyway=False, evidence=ev)
            except TypeError:
                r = swarm_run.build(st["qs"], None, anyway=False)
        except Exception as e:  # noqa: BLE001
            st["done"] = True
            return "hole", "The build raised %s [op:%s]; the %d examples are kept [turn:%d]." % (repr(e)[:100], st["op"], len(st["qs"]), st["turn"]), False
        st["done"] = True
        st["result"] = {k: v for k, v in r.items() if k != "build"}
        self.r.stats["build_run"] += 1
        b = r.get("brief") or {}
        parts = ["Built from your %d examples [op:%s] in %d s." % (len(st["qs"]), st["op"], time.time() - t0)]
        if b:
            parts.append("The swarm read them as %s%s%s." % (
                b.get("type") or "a task", (", near " + ", ".join(b.get("neighbors") or [])) if b.get("neighbors") else "",
                ("; the gap it named: " + str(b["gap"])) if b.get("gap") else ""))
        parts.append(str(r.get("message", "")).strip())
        return ("plan" if r.get("outcome") == "error" else "answer"), " ".join(p for p in parts if p), True