File size: 19,609 Bytes
d61eb28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
// ============================================================================
//  SyFox β€” roles.hpp  (v3.7.0, Move 3 of the AI-agent limit analysis)
//  ---------------------------------------------------------------------------
//  TYPED ORDERED LANES β€” the STRONG version of order, not the bigram patch.
//  The v3.6 ordered bigram lanes escape the multiset-invariance theorem for
//  ADJACENT transpositions ("a beats b" vs "b beats a") β€” that was measured
//  7/7. What bigrams still miss is ROLE asymmetry carried across inserted
//  material: in "alice gave the book to bob" vs "bob gave the book to alice"
//  only 2 of 5 bigram lanes differ, so the reversal margin is diluted by the
//  shared middle; with longer VPs the dilution wins. The strong version is
//  scene-grammar / symbolic parsing, pre-deep-NLP: nodes carry a ROLE and
//  lanes carry a RELATION TYPE.
//
//  This file is that grammar β€” compact, deterministic, inspectable, honest
//  about being a heuristic:
//
//    roles   S (subject/agent)  V (verb/action)  O (object/patient)
//            M (modifier/other content)          F (function word)
//    cues    a closed function-word list + a seed verb-cue lexicon (stemmed,
//            since normalize() runs Porter before this) + a negation list.
//            All tables are inline, printable, and overridable by
//            data/roles_lexicon.txt when present (verb cues one per line,
//            '#' comments).
//    rules   single-clause scope (lesson states are short):
//              S = nearest content token BEFORE the first verb cue,
//                  else the first content token;
//              O = nearest content token AFTER the last verb cue,
//                  else the last content token (never S itself);
//              V = the verb-cue tokens; M = every other content token;
//              F = function words (excluded from typed pairs).
//            A negation cue within 2 tokens before the first verb marks the
//            verb negated.
//
//  Typed pair NODES (mangled names, interned like the v3.6 bigrams β€” '~'
//  proved the pattern: a non-alphanumeric separator can never collide with
//  a normalized token):
//      S->V   "w#s>v#v"        V->O   "w#v>o#o"        S->O   "w#s>o#o"
//      negated verb: "!w#v"
//  The '#' and '>' and '!' characters are stripped by normalize(), so these
//  names live in a disjoint namespace from word tokens, exactly like "w1~w2".
//
//  Fabric construction only β€” hebbian_lesson binds them to outcome anchors
//  like any other node, decide() injects the ones the fabric carries, and
//  OLD fabrics contain none, so every decide-side block is a no-op on them
//  (the replay contract, unit-tested both ways like the bigrams).
//  Default OFF at the engine (a seed lexicon is not yet a general grammar);
//  --typed-lanes on|off overrides. The reversal probe measurement is part
//  of the v3.7 record.
// ============================================================================
#pragma once
#include "si_substrate.hpp"

#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>

namespace si {
namespace roles {

inline bool& typed_lanes_enabled() { static bool on = false; return on; }

// -- closed-class function words (normalized/stemmed forms) ------------------
// -- M9-LEARNED FUNCTION WORDS -------------------------------------------------
// The hardcoded kFn[] list below is a RULEBOOK in the inference path: it decides
// who may be a role anchor, which is exactly the job the architecture should not
// be delegating to a person. It is now a FALLBACK ONLY.
//
// The primary source is the FABRIC: a concept whose document frequency exceeds a
// fraction of all lessons is a function word, because function words are exactly
// the things that co-occur with everything. That statistic is already computed
// for the CMD/MIMS rarity weighting (note_df / the IDF5 tail) -- it was simply
// never consulted here. Loading it puts the decision in the MODEL, where the user
// wants it: `decide` becomes a runner over learned structure instead of a reader
// of a hardcoded table.
inline std::unordered_set<std::string>& learned_fn_words() {
    static std::unordered_set<std::string> w;
    return w;
}
inline bool fn_words_loaded() { return !learned_fn_words().empty(); }
inline void load_function_words(std::vector<std::string> words) {
    learned_fn_words().clear();
    for (auto& w : words) learned_fn_words().insert(std::move(w));
}

inline bool is_function_word(const std::string& t) {
    // PRIMARY: learned from the substrate's own document frequencies.
    if (fn_words_loaded() && learned_fn_words().count(t)) return true;
    if (fn_words_loaded()) return false;   // learned table is authoritative
    static const char* const kFn[] = {
        "the", "a", "an", "of", "to", "for", "with", "on", "at", "by", "from",
        "in", "into", "about", "as", "is", "are", "was", "were", "be", "been",
        "am", "my", "your", "hi", "his", "her", "it", "our", "their", "this",
        "that", "these", "those", "he", "she", "we", "they", "i", "you",
        "do", "did", "have", "had", "will", "would", "can", "could", "should",
        "shall", "may", "might", "must", "and", "or", "but", "if", "then",
        "than", "so", "very", "realli", "just", "also", "again", "there",
        "here", "what", "which", "who", "whom", "when", "where", "whi", "how",
        "pleas", "kindli", "now", "yet", "not",
        // M9: STEMS of function words that porter_stem() produces and that were
        // NOT in the list above, so they escaped as CONTENT words. Measured
        // (tools/probe: are->ar, was->wa, this->thi, they->thei, may->mai).
        // "was->wa" is the worst of these: in "the radio WAS found by Tariq" the
        // fragment "wa" was being tagged Role::S β€” i.e. a piece of the copula was
        // elected the subject while the real agent Tariq got Role::O. That single
        // miss is the root cause of the last-mentioned-entity failure measured on
        // tools/reason30.py. A stemmed function word must never be a role anchor.
        "ar", "wa", "thi", "thei", "mai", nullptr};
    for (int i = 0; kFn[i]; ++i) if (t == kFn[i]) return true;
    return false;
}

// negation cues (checked BEFORE the function list: "not"/"no" are negation)
inline bool is_negation_cue(const std::string& t) {
    return t == "not" || t == "no" || t == "never" || t == "nt" || t == "cannot";
}

// -- seed verb-cue lexicon (stemmed). Compact, inspectable, extensible. -----
struct VerbLex {
    bool loaded = false;
    std::vector<std::string> cues = {
        // transfer / commerce (STEMED forms β€” normalize() runs Porter first:
        // pay->pai, buy->bui, say->sai, lose->los)
        "giv", "gave", "sent", "send", "receiv", "paid", "pai", "pay",
        "charg", "refund", "purchas", "bought", "bui", "buy", "order",
        "ship", "deliver", "cancel", "return", "ow", "owe", "swip",
        "billed", "bill", "sold", "offer", "offered",
        // action / change
        "fix", "repair", "break", "broke", "open", "close", "start",
        "stop", "updat", "delet", "creat", "make", "made", "move",
        // communication
        "call", "told", "tell", "said", "sai", "ask", "answer", "report",
        "notif", "inform", "confirm", "promis", "complain",
        // perception / cognition
        "found", "find", "saw", "see", "heard", "hear", "know", "knew",
        "think", "thought", "want", "need", "trie", "tri", "us", "use",
        "used",
        // conflict / evaluation (the reversal probes)
        "beat", "won", "win", "lost", "los", "lose", "defeat", "bit",
        "bite", "prais", "blame", "help", "hurt", "hit", "struck", "kick",
        "push", "love", "hate", "lik", "dislik", "trust", "doubt",
        "verifi", "approv", "deni"};
};
inline VerbLex& verb_lex() {
    static VerbLex lex;
    return lex;
}

// optional override file: one stemmed verb cue per line, '#' comments
inline void load_verb_lexicon(const std::string& path) {
    std::ifstream f(path);
    if (!f) return;
    VerbLex& lex = verb_lex();
    lex.cues.clear();
    std::string line;
    while (std::getline(f, line)) {
        if (!line.empty() && line[0] != '#') {
            while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back();
            if (!line.empty()) lex.cues.push_back(line);
        }
    }
    lex.loaded = true;
}

inline bool is_verb_cue(const std::string& t) {
    const VerbLex& lex = verb_lex();
    for (const auto& c : lex.cues) if (t == c) return true;
    return false;
}

// ---------------------------------------------------------------------------
// Role tagging over an ALREADY-NORMALIZED token stream (what learn_example
// and decide() both hold). Deterministic; single-clause scope.
// ---------------------------------------------------------------------------
enum class Role { S, V, O, M, F };

// M9: CLAUSE SEGMENTATION.
//
// tag() was single-clause: S came from before the FIRST verb and O from after
// the LAST verb, which silently drops every intermediate subject. On
//     "Tariq picked up the red key. Salma took the blue key."
// S = Tariq (before the first verb), O = "blue" (after the last verb), so
// SALMA -- the subject of the second clause -- received NO role at all.
// Measured on tools/reason30.py (model-mega-v2): 7 of 13 misses answered the
// final-mentioned entity, because only the final clause's words were ever bound
// to a role.
//
// The fix segments on clause boundaries and tags each clause with the original
// single-clause rule, then splices the results back. Deterministic and
// order-stable; a single-clause input (the common case) is unchanged, so the
// existing unit tests still hold.
inline bool is_clause_break(const std::string& t) {
    return t == "." || t == "!" || t == "?" || t == ";" || t == "then";
}

// tag one already-bounded clause: the pre-existing logic, verbatim.
inline std::vector<Role> tag_clause(const std::vector<std::string>& words) {
    const std::size_t n = words.size();
    std::vector<Role> r(n, Role::M);
    if (n == 0) return r;
    for (std::size_t i = 0; i < n; ++i) {
        if (is_function_word(words[i])) r[i] = Role::F;
        else if (is_verb_cue(words[i])) r[i] = Role::V;
    }
    // first / last verb
    std::ptrdiff_t v0 = -1, vl = -1;
    for (std::size_t i = 0; i < n; ++i)
        if (r[i] == Role::V) { if (v0 < 0) v0 = static_cast<std::ptrdiff_t>(i); vl = static_cast<std::ptrdiff_t>(i); }
    if (v0 < 0) {
        // no verb cue: first content token = S, last content token (if another) = O
        std::ptrdiff_t s = -1;
        for (std::size_t i = 0; i < n; ++i)
            if (r[i] != Role::F) { s = static_cast<std::ptrdiff_t>(i); break; }
        if (s >= 0) {
            r[static_cast<std::size_t>(s)] = Role::S;
            for (std::size_t i = n; i-- > static_cast<std::size_t>(s) + 1;)
                if (r[i] != Role::F && r[i] != Role::S) { r[i] = Role::O; break; }
        }
        return r;
    }
    // S: nearest content token before the FIRST verb
    for (std::ptrdiff_t i = v0 - 1; i >= 0; --i)
        if (r[static_cast<std::size_t>(i)] != Role::F) { r[static_cast<std::size_t>(i)] = Role::S; break; }
    // O: prefer the PREPOSITIONAL PATIENT β€” the content token right after
    // "to"/"for" following the verb ("gave the book TO bob": bob is the
    // patient the reversal turns on; the direct object "book" is shared by
    // both readings). Without a to/for phrase: nearest content token after
    // the LAST verb (never the S slot).
    bool o_set = false;
    for (std::size_t i = static_cast<std::size_t>(vl) + 1; i + 1 < n; ++i) {
        if ((words[i] == "to" || words[i] == "for")
            && r[i + 1] != Role::F && r[i + 1] != Role::S) {
            r[i + 1] = Role::O;
            o_set = true;
            break;
        }
    }
    if (!o_set)
        for (std::size_t i = static_cast<std::size_t>(vl) + 1; i < n; ++i)
            if (r[i] != Role::F && r[i] != Role::S) { r[i] = Role::O; break; }
    return r;
}

// Segment, tag each clause independently, splice back. Clause-final
// punctuation is left as Role::F so it can never become an anchor.
inline std::vector<Role> tag(const std::vector<std::string>& words) {
    std::vector<Role> out(words.size(), Role::F);
    std::vector<std::string> cur;
    std::size_t out_at = 0;
    auto flush = [&]() {
        if (cur.empty()) return;
        const std::vector<Role> cr = tag_clause(cur);
        for (std::size_t i = 0; i < cr.size(); ++i) out[out_at + i] = cr[i];
        out_at += cr.size();
        cur.clear();
    };
    for (const std::string& w : words) {
        if (is_clause_break(w)) { flush(); if (out_at < out.size()) { out[out_at] = Role::F; ++out_at; } }
        else cur.push_back(w);
    }
    flush();
    return out;
}

// negated-verb detection: a negation cue within 2 tokens before the first V
inline bool verb_negated(const std::vector<std::string>& words) {
    const std::vector<Role> r = tag(words);
    for (std::size_t i = 0; i < words.size(); ++i) {
        if (r[i] != Role::V) continue;
        for (std::size_t j = i >= 2 ? i - 2 : 0; j < i; ++j)
            if (is_negation_cue(words[j])) return true;
        return false;
    }
    return false;
}

inline std::string join_typed(const std::string& a, const char* ra,
                              const std::string& b, const char* rb) {
    std::string g;
    g.reserve(a.size() + b.size() + 6);
    g.append(a); g.push_back('#'); g.append(ra);
    g.push_back('>'); g.append(b); g.push_back('#'); g.append(rb);
    return g;
}

// ---------------------------------------------------------------------------
// Typed pair nodes of a normalized stream, in deterministic emission order:
// S->V, V->O, S->O, then the negation marker when the verb is negated.
// Empty when the tagging found no verb or no S/O counterpart.
// ---------------------------------------------------------------------------
inline std::vector<std::string> typed_pairs_of(const std::vector<std::string>& words) {
    std::vector<std::string> out;
    const std::size_t n = words.size();
    if (n < 2) return out;
    const std::vector<Role> r = tag(words);
    std::ptrdiff_t s = -1, v = -1, o = -1;
    for (std::size_t i = 0; i < n; ++i) {
        if (r[i] == Role::S) s = static_cast<std::ptrdiff_t>(i);
        else if (r[i] == Role::V) v = static_cast<std::ptrdiff_t>(i);
        else if (r[i] == Role::O) o = static_cast<std::ptrdiff_t>(i);
    }
    if (s < 0 || o < 0) return out;                 // need both parties
    if (v >= 0) {
        out.push_back(join_typed(words[static_cast<std::size_t>(s)], "s",
                                 words[static_cast<std::size_t>(v)], "v"));
        out.push_back(join_typed(words[static_cast<std::size_t>(v)], "v",
                                 words[static_cast<std::size_t>(o)], "o"));
    }
    out.push_back(join_typed(words[static_cast<std::size_t>(s)], "s",
                             words[static_cast<std::size_t>(o)], "o"));
    if (v >= 0 && verb_negated(words))
        out.push_back(std::string("!") + words[static_cast<std::size_t>(v)] + "#v");
    return out;
}

// ============================================================================
// v3.8.0 (TASK 2 of the physics-native thinking spec) β€” CAUSAL SIGNATURES.
// WHAT/WHY/HOW relation types on lanes. The typed pairs above encode WHO DID
// WHAT TO WHOM (scene grammar); they do not encode WHY it happened or HOW.
// Cross-domain reasoning β€” the analogy class β€” needs relation types that
// survive the domain nouns: "refund because overcharge" (tickets) and
// "restart because crash" (tech) share the CAUSE?>EFFECT signature even
// when no token overlaps, so a lane typed ?> between a cause and its effect
// composes with the same signature in another domain.
//
// Deterministic connective scan (stemmed forms β€” normalize() runs Porter):
//   CauseFirst   "so, therefore/thus, cause(s/d), lead(s), trigger(s),
//                 produc(e/ed)"   ->  pair "L?>R"   (L causes R)
//   EffectFirst  "because, since, due" -> pair "R?>L" (R causes L)
//   Instrumental "by, via, through, using, how" -> "R!>L" (R is the means
//                 to L; goal before the cue, means after)
// L/R = nearest non-function, non-cue tokens on each side (one pair per cue
// hit). Node names live in the same disjoint '#>'-mangled namespace as the
// typed pairs; OLD fabrics contain none, so every decide-side block is a
// no-op on them (replay contract, same as bigrams/typed).
// Default OFF (--causal-lanes on|off) β€” a connective table is a seed
// lexicon, disclosed as such.
// ============================================================================
inline bool& causal_lanes_enabled() { static bool on = false; return on; }

enum class CausalKind { CauseFirst, EffectFirst, Instrumental };

inline bool causal_cue(const std::string& t, CausalKind* kind) {
    static const struct { const char* form; CausalKind k; } kCues[] = {
        {"so", CausalKind::CauseFirst},
        {"therefor", CausalKind::CauseFirst}, {"therefore", CausalKind::CauseFirst},
        {"thu", CausalKind::CauseFirst}, {"thus", CausalKind::CauseFirst},
        {"caus", CausalKind::CauseFirst}, {"cause", CausalKind::CauseFirst},
        {"lead", CausalKind::CauseFirst}, {"leads", CausalKind::CauseFirst},
        {"trigger", CausalKind::CauseFirst}, {"triggers", CausalKind::CauseFirst},
        {"produc", CausalKind::CauseFirst}, {"produce", CausalKind::CauseFirst},
        {"becaus", CausalKind::EffectFirst}, {"because", CausalKind::EffectFirst},
        {"sinc", CausalKind::EffectFirst}, {"since", CausalKind::EffectFirst},
        {"due", CausalKind::EffectFirst},
        {"by", CausalKind::Instrumental}, {"via", CausalKind::Instrumental},
        {"through", CausalKind::Instrumental},
        {"us", CausalKind::Instrumental}, {"using", CausalKind::Instrumental},
        {"how", CausalKind::Instrumental},
    };
    for (const auto& c : kCues)
        if (t == c.form) { if (kind) *kind = c.k; return true; }
    return false;
}

inline std::vector<std::string> causal_pairs_of(const std::vector<std::string>& words) {
    std::vector<std::string> out;
    const std::size_t n = words.size();
    if (n < 3) return out;
    for (std::size_t i = 0; i < n; ++i) {
        CausalKind kind;
        if (!causal_cue(words[i], &kind)) continue;
        std::ptrdiff_t L = -1, R = -1;
        for (std::ptrdiff_t j = static_cast<std::ptrdiff_t>(i); j-- > 0;) {
            const std::string& w = words[static_cast<std::size_t>(j)];
            if (!is_function_word(w) && !causal_cue(w, nullptr)) { L = j; break; }
        }
        for (std::size_t j = i + 1; j < n; ++j) {
            const std::string& w = words[j];
            if (!is_function_word(w) && !causal_cue(w, nullptr)) { R = static_cast<std::ptrdiff_t>(j); break; }
        }
        if (L < 0 || R < 0) continue;
        const std::string& lw = words[static_cast<std::size_t>(L)];
        const std::string& rw = words[static_cast<std::size_t>(R)];
        switch (kind) {
            case CausalKind::CauseFirst:
                out.push_back(lw + "?>" + rw); break;      // L causes R
            case CausalKind::EffectFirst:
                out.push_back(rw + "?>" + lw); break;      // R causes L
            case CausalKind::Instrumental:
                out.push_back(rw + "!>" + lw); break;      // R is the means to L
        }
    }
    return out;
}

} // namespace roles
} // namespace si