// ============================================================================ // 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 #include #include #include 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& learned_fn_words() { static std::unordered_set w; return w; } inline bool fn_words_loaded() { return !learned_fn_words().empty(); } inline void load_function_words(std::vector 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 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 tag_clause(const std::vector& words) { const std::size_t n = words.size(); std::vector 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(i); vl = static_cast(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(i); break; } if (s >= 0) { r[static_cast(s)] = Role::S; for (std::size_t i = n; i-- > static_cast(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(i)] != Role::F) { r[static_cast(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(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(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 tag(const std::vector& words) { std::vector out(words.size(), Role::F); std::vector cur; std::size_t out_at = 0; auto flush = [&]() { if (cur.empty()) return; const std::vector 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& words) { const std::vector 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 typed_pairs_of(const std::vector& words) { std::vector out; const std::size_t n = words.size(); if (n < 2) return out; const std::vector 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(i); else if (r[i] == Role::V) v = static_cast(i); else if (r[i] == Role::O) o = static_cast(i); } if (s < 0 || o < 0) return out; // need both parties if (v >= 0) { out.push_back(join_typed(words[static_cast(s)], "s", words[static_cast(v)], "v")); out.push_back(join_typed(words[static_cast(v)], "v", words[static_cast(o)], "o")); } out.push_back(join_typed(words[static_cast(s)], "s", words[static_cast(o)], "o")); if (v >= 0 && verb_negated(words)) out.push_back(std::string("!") + words[static_cast(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 causal_pairs_of(const std::vector& words) { std::vector 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(i); j-- > 0;) { const std::string& w = words[static_cast(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(j); break; } } if (L < 0 || R < 0) continue; const std::string& lw = words[static_cast(L)]; const std::string& rw = words[static_cast(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