File size: 7,772 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
#!/usr/bin/env python3
"""The SQUIRCLE REPLY ROUTER (Ben 2026-11-06: "it is squircle"). Repertoire decoupled from selector (Horn, "Convergence
onto a Non-Fixed-Point by Tracking", June 2026): seven ports on one circle - three INTERIOR (internal transfer, never
speak) and four BOUNDARY (the only way a reply leaves). The selector is a continuous fit of the turn's demand to each
port, w_i = softmax(beta * phi(u, s_i)), re-solved every turn: always converged, never settled.

INTERIOR (triangle)
  receive   the turn's claims enter the conversation's common ground (what was said, by whom, in which turn)
  ground    "it / that / this / the rest / them" bind to the last named subject or the last proposed operation
  check     the law: only the head's checked answers (proved or cited), the person's own words, or a named hole may reach a
            boundary port; anything else is dropped before emission
BOUNDARY (square) - DailyDialog's four acts (Austin/Searle)
  inform      the head's checked answer about the turn (its receipt kept); for a statement, what the record holds about
              its subject, cited
  question    the hole: what is missing for Oracle7 to act on or relate the turn, asked plainly
  commissive  for an instruction: the operation in Oracle7's own catalogue (oracle7-operation-v1) that would do it -
              a commitment to that operation, or a decline naming the missing one
  directive   propose the next operation that follows from common ground
phi(u, s): the human second-speaker act distribution P(reply act | opener act) counted on DailyDialog's DEVELOPMENT
dialogues (the relational instrument's own data) - learned from people, not written - times whether the port has
content that passes `check` for this turn (a port with nothing checked to say has fit 0).
usage: module (SquircleRouter(head_chat, operations_search))"""
from __future__ import annotations

import collections
import json
import math
import re

WORD = re.compile(r"[A-Za-z][A-Za-z'-]{2,}")
STOP = set("""a an the and or but if then so to of in on at by for with about from as is are was were be been being am do does
did have has had i you he she it we they me my your our their this that these those what which who whom whose when where
why how can could would should will shall may might must not no yes please thanks thank tell give let make just really
very much many some any there here get got like want know think lets let's also all one now still need into out up down
over more done going gonna okay ok yeah yep sure""".split())
REF = re.compile(r"\b(it|that|this|these|those|them|the rest|everything|all of it)\b", re.I)
REFUSAL = re.compile(r"didn't fully parse|won't guess|no provenance-admitted|contains no statement|will not infer|"
                     r"have received \"|no attested answer|nothing earlier in this conversation|what does \"[^\"]+\" refer to|"
                     r"i can summarize a topic|no verified primitive|i will not invent", re.I)


def content_words(t):
    return [w.lower() for w in WORD.findall(t or "") if w.lower() not in STOP]


def human_phi(dd_rows):
    """P(reply act | opener act) from human second speakers"""
    c = collections.defaultdict(collections.Counter)
    for r in dd_rows:
        if r.get("a0") and r.get("a1"):
            c[r["a0"]][r["a1"]] += 1
    return {a: {b: n / sum(cnt.values()) for b, n in cnt.items()} for a, cnt in c.items()}


class Common:
    """the conversation's common ground: claims received, subjects named, operations proposed (interior port state)"""

    def __init__(self):
        self.claims, self.subjects, self.ops = [], [], []


class SquircleRouter:
    def __init__(self, head_chat, operations_search, phi, act_of, beta=4.0):
        self.head_chat, self.ops_search, self.phi, self.act_of, self.beta = head_chat, operations_search, phi, act_of, beta
        self.common = collections.defaultdict(Common)

    # ---------------- interior ports
    def receive(self, cg, turn):
        words = content_words(turn)
        if words:
            cg.claims.append(turn)
            cg.subjects.append(" ".join(words[:4]))
        return words

    def ground(self, cg, turn):
        if REF.search(turn) and (cg.ops or cg.subjects):
            return {"op": cg.ops[-1] if cg.ops else None, "subject": cg.subjects[-2] if len(cg.subjects) > 1 else None}
        return {}

    @staticmethod
    def check(reply):
        body = str(reply.get("response", ""))
        return reply.get("status") == "answered" and not REFUSAL.search(body) and bool(body.strip())

    # ---------------- boundary ports (each returns text or None; None = nothing checked to say, fit 0)
    def p_inform(self, turn, head, words, bound):
        if self.check(head):
            return head["response"]
        subj = (bound.get("subject") or " ".join(words[:3])).strip()
        if not subj:
            return None
        rel = self.head_chat("What is %s?" % subj, None)
        if self.check(rel) and set(content_words(rel["response"])) & set(subj.split()):
            return "On %s, the record holds: %s" % (subj, rel["response"])
        return None

    def p_question(self, turn, words, bound):
        subj = (bound.get("subject") or " ".join(words[:3])).strip()
        if not subj:
            return None
        return ("I have that as received: %s. What should I do with it first - check it against the record, connect it "
                "to %s, or act on it?" % (turn.rstrip(".?! "), subj))

    def p_commissive(self, turn, words, bound, cg):
        cands = self.ops_search(" ".join(words[:6])) if words else []
        op = cands[0] if cands else (bound.get("op"))
        if op:
            cg.ops.append(op)
            return "I can do that with %s (%s). Say go and I will run it, with its receipt." % (op["id"], op.get("title", "")[:90])
        if words:
            return ("I can't do that from here: there is no operation in my catalogue for %s. That is a hole; it goes to "
                    "the builder as a named gap." % " ".join(words[:5]))
        return None

    def p_directive(self, cg):
        if cg.ops:
            return "Next I would run %s on what you just said. Shall I?" % cg.ops[-1]["id"]
        return None

    # ---------------- the selector
    def reply(self, turn, session="convo"):
        cg = self.common[session]
        bound = self.ground(cg, turn)
        words = self.receive(cg, turn)
        head = self.head_chat(turn, session)
        u = self.act_of(turn)
        cand = {"inform": lambda: self.p_inform(turn, head, words, bound),
                "question": lambda: self.p_question(turn, words, bound),
                "commissive": lambda: self.p_commissive(turn, words, bound, cg),
                "directive": lambda: self.p_directive(cg)}
        prior = self.phi.get(u) or {"inform": 1.0}
        scored = []
        for port, make in sorted(cand.items(), key=lambda kv: -prior.get(kv[0], 0.0)):
            p = prior.get(port, 0.0)
            if p <= 0:
                continue
            text = make()
            if text:
                scored.append((p, port, text))
        if not scored:
            return {"status": "declined", "response": "I can't reply to that with anything I can check.", "path": "squircle:none",
                    "act_in": u, "head": head}
        z = sum(math.exp(self.beta * p) for p, _, _ in scored)
        w = [(math.exp(self.beta * p) / z, port, text) for p, port, text in scored]
        w.sort(key=lambda x: -x[0])
        _, port, text = w[0]
        return {"status": "answered", "response": text, "path": "squircle:%s>%s" % (u, port), "act_in": u, "port": port,
                "weights": {pt: round(x, 3) for x, pt, _ in w}, "head_path": str(head.get("path"))}