Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- root/relstore/lexicon_v1.jsonAdded+1052
- root/relstore/prop_labels.tsvAdded
- root/relstore/reader_prop_allowlist.jsonAdded+1
- root/relstore/relation_domains_v1.jsonAdded+101
- root/relstore/relation_domains_v2.jsonAdded+996
- root/relstore/router_patterns_v4.jsonAdded+212
- root/textbooks/textbook_store_v1.sqlite3Added
- root/wander-train/chat_context_v2.pyAdded+422
- root/wander-train/entity_linker_v2.pyAdded+74
- root/wander-train/math_solver_v3.pyAdded+992
- root/wander-train/oracle_compare_op_v1.pyAdded+248
- root/wander-train/oracle_operator_parse_v1.pyAdded+160
- root/wander-train/oracle_release_runtime_an.pyAdded+173
- root/wander-train/oracle_release_runtime_b.pyAdded+70
- root/wander-train/oracle_release_runtime_d.pyAdded+185
- root/wander-train/oracle_release_runtime_l.pyAdded+69
- root/wander-train/oracle_release_runtime_w.pyAdded+123
- root/wander-train/oracle_release_runtime_w56.pyAdded+115
- root/wander-train/oracle_release_runtime_w57.pyAdded+84
- root/wander-train/oracle_release_runtime_w65.pyAdded+107
- root/wander-train/organ_code_chat_v1.pyAdded+99
- root/wander-train/organ_code_chat_v2.pyAdded+155
- root/wander-train/relation_spec_v1.pyAdded+172
- root/wander-train/stage5c41_cooperative_four_head_router.pyAdded+279
- root/wander-train/stage5c59_raw_corpus_expert_compiler.pyAdded+415
- root/wander-train/stage5j2_native_english_construction_algebra.pyAdded+323
- root/wander-train/stage5k100_situated_conversation_recovery_agent.pyAdded+462
- root/wander-train/stage5k119_social_negative_scope_agent.pyAdded+196
- root/wander-train/stage5k124_dynamic_expert_lifecycle_agent.pyAdded+386
- root/wander-train/stage5k161_act_family_extension.pyAdded+204
- root/wander-train/stage5k214a_authenticated_specialist_factory.pyAdded+133
- root/wander-train/stage5k220a_evidence_preserving_realizer.pyAdded+165
- root/wander-train/stage5k226a_verified_hrr_implication_substrate.pyAdded+346
- root/wander-train/stage5k41_relational_specificity_native_generalist_agent.pyAdded+648
- root/wander-train/stage5k53_native_clause_algebra_agent.pyAdded+782
- root/wander-train/stage5k55_article_aware_clause_algebra_agent.pyAdded+92
- root/wander-train/stage5k60_modal_bare_infinitive_agent.pyAdded+115
- root/wander-train/stage5k69_whole_system_dispatch_agent.pyAdded+916
- root/wander-train/stage5l2e_directional_clause_scope.pyAdded+181
- root/wander-train/stage5l3_unified_language_bundle.pyAdded+436
- root/wander-train/stage5l4b_relational_discourse_act_successor.pyAdded+249
- root/wander-train/stage5l8b_release_hardening_successor.pyAdded+199
- root/wander-train/stage5m11c_unified_agentic_conversation.pyAdded+125
- root/wander-train/stage5m13a_wordnet_specialist.pyAdded+595
- root/wander-train/stage5m13e8_paragraph_compiler_v2.pyAdded+91
- root/wander-train/stage5m1a_typed_utterance_authority.pyAdded+474
- root/wander-train/stage5m1c_general_act_compiler.pyAdded+262
- root/wander-train/stage5m2c2_batched_wikidata_federation.pyAdded+144
- root/wander-train/word_problems_v1.pyAdded+252
- workbench/data/cards/anatomy.mdAdded+24
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052{ "questions": 1786, "with_property": 160, "lexicon": { "[\"h\", \"PLACE\", \"country\"]": { "[\"fwd\", 17]": 16, "[\"fwd\", 27]": 6, "[\"fwd\", 47]": 4, "[\"fwd\", 131]": 3, "[\"fwd\", 495]": 2, "[\"inv\", 47]": 2 }, "[\"v\", \"PLACE\", \"come\"]": { "[\"fwd\", 17]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"come\"]": { "[\"fwd\", 17]": 1 }, "[\"v\", \"PLACE\", null]": { "[\"fwd\", 17]": 10, "[\"fwd\", 131]": 5, "[\"fwd\", 1376]": 3, "[\"fwd\", 47]": 2, "[\"fwd\", 495]": 2, "[\"fwd\", 159]": 2 }, "[\"hv\", \"PLACE\", \"country\", null]": { "[\"fwd\", 17]": 10, "[\"fwd\", 47]": 2, "[\"fwd\", 495]": 2, "[\"fwd\", 1376]": 2, "[\"fwd\", 276]": 1, "[\"fwd\", 155]": 1 }, "[\"h\", \"INSTANCE\", \"scientist\"]": { "[\"fwd\", 101]": 1 }, "[\"v\", \"INSTANCE\", null]": { "[\"fwd\", 101]": 4, "[\"fwd\", 463]": 4, "[\"inv\", 131]": 4, "[\"fwd\", 206]": 3, "[\"fwd\", 527]": 3, "[\"fwd\", 131]": 2 }, "[\"hv\", \"INSTANCE\", \"scientist\", null]": { "[\"fwd\", 101]": 1 }, "[\"h\", \"INSTANCE\", \"magazine\"]": { "[\"fwd\", 800]": 1 }, "[\"v\", \"INSTANCE\", \"start\"]": { "[\"fwd\", 800]": 1 }, "[\"hv\", \"INSTANCE\", \"magazine\", \"start\"]": { "[\"fwd\", 800]": 1 }, "[\"h\", \"INSTANCE\", \"movie\"]": { "[\"inv\", 527]": 1, "[\"inv\", 161]": 1, "[\"inv\", 272]": 1 }, "[\"v\", \"INSTANCE\", \"starr\"]": { "[\"inv\", 527]": 1, "[\"inv\", 161]": 1 }, "[\"hv\", \"INSTANCE\", \"movie\", \"starr\"]": { "[\"inv\", 527]": 1 }, "[\"h\", \"INSTANCE\", \"purchased\"]": { "[\"fwd\", 127]": 1 }, "[\"v\", \"INSTANCE\", \"purcha\"]": { "[\"fwd\", 127]": 1 }, "[\"hv\", \"INSTANCE\", \"purchased\", \"purcha\"]": { "[\"fwd\", 127]": 1 }, "[\"h\", \"PLACE\", \"city\"]": { "[\"fwd\", 19]": 2, "[\"fwd\", 131]": 2, "[\"fwd\", 1376]": 1, "[\"fwd\", 840]": 1 }, "[\"v\", \"PLACE\", \"bear\"]": { "[\"fwd\", 19]": 2, "[\"fwd\", 27]": 1 }, "[\"hv\", \"PLACE\", \"city\", \"bear\"]": { "[\"fwd\", 19]": 2 }, "[\"h\", \"PERSON\", null]": { "[\"fwd\", 26]": 4, "[\"inv\", 800]": 3, "[\"fwd\", 161]": 3, "[\"inv\", 26]": 3, "[\"fwd\", 86]": 3, "[\"inv\", 166]": 3 }, "[\"v\", \"PERSON\", \"marri\"]": { "[\"fwd\", 26]": 2, "[\"inv\", 26]": 1 }, "[\"hv\", \"PERSON\", null, \"marri\"]": { "[\"fwd\", 26]": 2, "[\"inv\", 26]": 1 }, "[\"h\", \"INSTANCE\", \"original\"]": { "[\"fwd\", 131]": 1, "[\"fwd\", 276]": 1 }, "[\"hv\", \"INSTANCE\", \"original\", null]": { "[\"fwd\", 131]": 1, "[\"fwd\", 276]": 1 }, "[\"h\", \"INSTANCE\", \"through\"]": { "[\"fwd\", 206]": 2 }, "[\"hv\", \"INSTANCE\", \"through\", null]": { "[\"fwd\", 206]": 2 }, "[\"h\", \"INSTANCE\", \"archaeologist\"]": { "[\"fwd\", 1441]": 1 }, "[\"hv\", \"INSTANCE\", \"archaeologist\", null]": { "[\"fwd\", 1441]": 1 }, "[\"h\", \"PLACE\", \"state\"]": { "[\"fwd\", 131]": 1, "[\"fwd\", 19]": 1, "[\"fwd\", 276]": 1 }, "[\"v\", \"PLACE\", \"locat\"]": { "[\"fwd\", 131]": 1 }, "[\"hv\", \"PLACE\", \"state\", \"locat\"]": { "[\"fwd\", 131]": 1 }, "[\"v\", \"PLACE\", \"lead\"]": { "[\"fwd\", 27]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"lead\"]": { "[\"fwd\", 27]": 1 }, "[\"h\", \"INSTANCE\", \"show\"]": { "[\"fwd\", 1441]": 1 }, "[\"v\", \"INSTANCE\", \"set\"]": { "[\"fwd\", 1441]": 1 }, "[\"hv\", \"INSTANCE\", \"show\", \"set\"]": { "[\"fwd\", 1441]": 1 }, "[\"h\", \"INSTANCE\", \"language\"]": { "[\"fwd\", 37]": 1 }, "[\"hv\", \"INSTANCE\", \"language\", null]": { "[\"fwd\", 37]": 1 }, "[\"v\", \"PERSON\", \"write\"]": { "[\"inv\", 800]": 2, "[\"fwd\", 86]": 2, "[\"fwd\", 50]": 1, "[\"fwd\", 57]": 1, "[\"fwd\", 58]": 1, "[\"fwd\", 161]": 1 }, "[\"hv\", \"PERSON\", null, \"write\"]": { "[\"inv\", 800]": 2, "[\"fwd\", 86]": 2, "[\"fwd\", 50]": 1, "[\"fwd\", 57]": 1, "[\"fwd\", 58]": 1, "[\"fwd\", 161]": 1 }, "[\"h\", \"INSTANCE\", \"band\"]": { "[\"fwd\", 463]": 4 }, "[\"hv\", \"INSTANCE\", \"band\", null]": { "[\"fwd\", 463]": 4 }, "[\"v\", \"PERSON\", \"commis\"]": { "[\"fwd\", 50]": 1 }, "[\"hv\", \"PERSON\", null, \"commis\"]": { "[\"fwd\", 50]": 1 }, "[\"v\", \"PLACE\", \"ruled\"]": { "[\"fwd\", 19]": 1 }, "[\"hv\", \"PLACE\", \"state\", \"ruled\"]": { "[\"fwd\", 19]": 1 }, "[\"h\", \"INSTANCE\", \"entirely\"]": { "[\"fwd\", 527]": 1 }, "[\"hv\", \"INSTANCE\", \"entirely\", null]": { "[\"fwd\", 527]": 1 }, "[\"h\", \"INSTANCE\", \"make\"]": { "[\"fwd\", 1303]": 1 }, "[\"v\", \"INSTANCE\", \"make\"]": { "[\"fwd\", 1303]": 1 }, "[\"hv\", \"INSTANCE\", \"make\", \"make\"]": { "[\"fwd\", 1303]": 1 }, "[\"h\", \"INSTANCE\", \"series\"]": { "[\"fwd\", 800]": 2, "[\"inv\", 449]": 1, "[\"fwd\", 1441]": 1, "[\"fwd\", 463]": 1, "[\"inv\", 527]": 1, "[\"inv\", 50]": 1 }, "[\"v\", \"INSTANCE\", \"resurr\"]": { "[\"fwd\", 800]": 1 }, "[\"hv\", \"INSTANCE\", \"series\", \"resurr\"]": { "[\"fwd\", 800]": 1 }, "[\"h\", \"INSTANCE\", \"industry\"]": { "[\"fwd\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"industry\", null]": { "[\"fwd\", 17]": 1 }, "[\"h\", \"INSTANCE\", \"building\"]": { "[\"inv\", 131]": 1 }, "[\"hv\", \"INSTANCE\", \"building\", null]": { "[\"inv\", 131]": 1 }, "[\"h\", \"INSTANCE\", \"group\"]": { "[\"inv\", 17]": 1, "[\"fwd\", 463]": 1, "[\"inv\", 112]": 1, "[\"inv\", 488]": 1 }, "[\"v\", \"INSTANCE\", \"speak\"]": { "[\"inv\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"group\", \"speak\"]": { "[\"inv\", 17]": 1 }, "[\"h\", \"INSTANCE\", \"island\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 131]": 1 }, "[\"hv\", \"INSTANCE\", \"island\", null]": { "[\"fwd\", 17]": 1, "[\"fwd\", 131]": 1 }, "[\"hv\", \"PLACE\", \"city\", null]": { "[\"fwd\", 131]": 2, "[\"fwd\", 1376]": 1 }, "[\"v\", \"PERSON\", null]": { "[\"inv\", 166]": 2, "[\"fwd\", 3373]": 1, "[\"inv\", 3373]": 1, "[\"inv\", 106]": 1, "[\"fwd\", 710]": 1, "[\"inv\", 1344]": 1 }, "[\"hv\", \"PERSON\", null, null]": { "[\"inv\", 166]": 2, "[\"fwd\", 3373]": 1, "[\"inv\", 3373]": 1, "[\"inv\", 106]": 1, "[\"fwd\", 710]": 1, "[\"inv\", 1344]": 1 }, "[\"v\", \"PERSON\", \"dated\"]": { "[\"fwd\", 26]": 1, "[\"inv\", 26]": 1 }, "[\"hv\", \"PERSON\", null, \"dated\"]": { "[\"fwd\", 26]": 1, "[\"inv\", 26]": 1 }, "[\"v\", \"PERSON\", \"record\"]": { "[\"inv\", 264]": 1, "[\"fwd\", 170]": 1 }, "[\"hv\", \"PERSON\", null, \"record\"]": { "[\"inv\", 264]": 1, "[\"fwd\", 170]": 1 }, "[\"h\", \"INSTANCE\", \"found\"]": { "[\"fwd\", 206]": 1 }, "[\"v\", \"INSTANCE\", \"found\"]": { "[\"fwd\", 108]": 2, "[\"fwd\", 206]": 1, "[\"fwd\", 1830]": 1 }, "[\"hv\", \"INSTANCE\", \"found\", \"found\"]": { "[\"fwd\", 206]": 1 }, "[\"h\", \"INSTANCE\", \"peninsulas\"]": { "[\"inv\", 131]": 1 }, "[\"hv\", \"INSTANCE\", \"peninsulas\", null]": { "[\"inv\", 131]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"bear\"]": { "[\"fwd\", 27]": 1 }, "[\"h\", \"INSTANCE\", \"musical\"]": { "[\"inv\", 86]": 1, "[\"inv\", 676]": 1 }, "[\"hv\", \"INSTANCE\", \"musical\", null]": { "[\"inv\", 86]": 1, "[\"inv\", 676]": 1 }, "[\"h\", \"INSTANCE\", \"river\"]": { "[\"fwd\", 206]": 1, "[\"fwd\", 361]": 1 }, "[\"hv\", \"INSTANCE\", \"river\", null]": { "[\"fwd\", 206]": 1, "[\"fwd\", 361]": 1 }, "[\"h\", \"INSTANCE\", \"instrument\"]": { "[\"fwd\", 106]": 1, "[\"fwd\", 1303]": 1 }, "[\"v\", \"INSTANCE\", \"play\"]": { "[\"fwd\", 106]": 2, "[\"fwd\", 1303]": 1, "[\"fwd\", 161]": 1, "[\"inv\", 118]": 1, "[\"inv\", 463]": 1, "[\"fwd\", 54]": 1 }, "[\"hv\", \"INSTANCE\", \"instrument\", \"play\"]": { "[\"fwd\", 106]": 1, "[\"fwd\", 1303]": 1 }, "[\"v\", \"PERSON\", \"play\"]": { "[\"fwd\", 161]": 1 }, "[\"hv\", \"PERSON\", null, \"play\"]": { "[\"fwd\", 161]": 1 }, "[\"v\", \"PERSON\", \"assass\"]": { "[\"inv\", 20]": 1 }, "[\"hv\", \"PERSON\", null, \"assass\"]": { "[\"inv\", 20]": 1 }, "[\"h\", \"PLACE\", null]": { "[\"fwd\", 159]": 2, "[\"fwd\", 131]": 2, "[\"inv\", 17]": 1 }, "[\"hv\", \"PLACE\", null, null]": { "[\"fwd\", 159]": 2, "[\"fwd\", 131]": 2 }, "[\"h\", \"YEAR\", null]": { "[\"fwd\", 571]": 6, "[\"fwd\", 577]": 1, "[\"fwd\", 570]": 1 }, "[\"v\", \"YEAR\", \"releas\"]": { "[\"fwd\", 571]": 1, "[\"fwd\", 577]": 1 }, "[\"hv\", \"YEAR\", null, \"releas\"]": { "[\"fwd\", 571]": 1, "[\"fwd\", 577]": 1 }, "[\"v\", \"PERSON\", \"star\"]": { "[\"fwd\", 161]": 1 }, "[\"hv\", \"PERSON\", null, \"star\"]": { "[\"fwd\", 161]": 1 }, "[\"h\", \"INSTANCE\", \"comedian\"]": { "[\"fwd\", 161]": 1 }, "[\"hv\", \"INSTANCE\", \"comedian\", \"play\"]": { "[\"fwd\", 161]": 1 }, "[\"h\", \"INSTANCE\", \"aligned\"]": { "[\"inv\", 276]": 1 }, "[\"v\", \"INSTANCE\", \"align\"]": { "[\"inv\", 276]": 1 }, "[\"hv\", \"INSTANCE\", \"aligned\", \"align\"]": { "[\"inv\", 276]": 1 }, "[\"h\", \"INSTANCE\", \"university\"]": { "[\"fwd\", 69]": 1 }, "[\"v\", \"INSTANCE\", \"gradua\"]": { "[\"fwd\", 69]": 1 }, "[\"hv\", \"INSTANCE\", \"university\", \"gradua\"]": { "[\"fwd\", 69]": 1 }, "[\"v\", \"PERSON\", \"produc\"]": { "[\"fwd\", 26]": 1, "[\"inv\", 26]": 1 }, "[\"hv\", \"PERSON\", null, \"produc\"]": { "[\"fwd\", 26]": 1, "[\"inv\", 26]": 1 }, "[\"h\", \"INSTANCE\", \"based\"]": { "[\"inv\", 921]": 1 }, "[\"v\", \"INSTANCE\", \"based\"]": { "[\"inv\", 921]": 1, "[\"fwd\", 674]": 1 }, "[\"hv\", \"INSTANCE\", \"based\", \"based\"]": { "[\"inv\", 921]": 1 }, "[\"h\", \"INSTANCE\", \"activist\"]": { "[\"inv\", 463]": 1 }, "[\"hv\", \"INSTANCE\", \"activist\", null]": { "[\"inv\", 463]": 1 }, "[\"h\", \"INSTANCE\", \"county\"]": { "[\"fwd\", 150]": 1, "[\"fwd\", 131]": 1, "[\"fwd\", 47]": 1, "[\"inv\", 47]": 1, "[\"fwd\", 840]": 1, "[\"fwd\", 915]": 1 }, "[\"v\", \"INSTANCE\", \"moved\"]": { "[\"fwd\", 150]": 1 }, "[\"hv\", \"INSTANCE\", \"county\", \"moved\"]": { "[\"fwd\", 150]": 1 }, "[\"h\", \"INSTANCE\", \"worked\"]": { "[\"fwd\", 106]": 1 }, "[\"v\", \"INSTANCE\", \"work\"]": { "[\"fwd\", 106]": 1 }, "[\"hv\", \"INSTANCE\", \"worked\", \"work\"]": { "[\"fwd\", 106]": 1 }, "[\"v\", \"INSTANCE\", \"locat\"]": { "[\"fwd\", 131]": 1, "[\"fwd\", 138]": 1 }, "[\"hv\", \"INSTANCE\", \"county\", \"locat\"]": { "[\"fwd\", 131]": 1 }, "[\"h\", \"INSTANCE\", \"countries\"]": { "[\"fwd\", 27]": 1 }, "[\"hv\", \"INSTANCE\", \"countries\", null]": { "[\"fwd\", 27]": 1 }, "[\"h\", \"INSTANCE\", \"alongside\"]": { "[\"inv\", 161]": 1 }, "[\"hv\", \"INSTANCE\", \"alongside\", \"starr\"]": { "[\"inv\", 161]": 1 }, "[\"h\", \"INSTANCE\", \"award\"]": { "[\"fwd\", 166]": 1 }, "[\"v\", \"INSTANCE\", \"win\"]": { "[\"fwd\", 166]": 1 }, "[\"hv\", \"INSTANCE\", \"award\", \"win\"]": { "[\"fwd\", 166]": 1 }, "[\"h\", \"INSTANCE\", \"profession\"]": { "[\"fwd\", 106]": 2 }, "[\"hv\", \"INSTANCE\", \"profession\", null]": { "[\"fwd\", 106]": 1 }, "[\"h\", \"INSTANCE\", \"field\"]": { "[\"fwd\", 101]": 2 }, "[\"hv\", \"INSTANCE\", \"field\", null]": { "[\"fwd\", 101]": 2 }, "[\"h\", \"INSTANCE\", \"company\"]": { "[\"fwd\", 108]": 2, "[\"fwd\", 1830]": 1, "[\"inv\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"company\", \"found\"]": { "[\"fwd\", 108]": 2, "[\"fwd\", 1830]": 1 }, "[\"v\", \"INSTANCE\", \"follow\"]": { "[\"fwd\", 106]": 1 }, "[\"hv\", \"INSTANCE\", \"profession\", \"follow\"]": { "[\"fwd\", 106]": 1 }, "[\"h\", \"INSTANCE\", \"basis\"]": { "[\"fwd\", 800]": 1 }, "[\"v\", \"INSTANCE\", \"influe\"]": { "[\"fwd\", 800]": 1 }, "[\"hv\", \"INSTANCE\", \"basis\", \"influe\"]": { "[\"fwd\", 800]": 1 }, "[\"h\", \"INSTANCE\", \"war\"]": { "[\"fwd\", 361]": 1 }, "[\"hv\", \"INSTANCE\", \"war\", null]": { "[\"fwd\", 361]": 1 }, "[\"v\", \"INSTANCE\", \"associ\"]": { "[\"fwd\", 463]": 1, "[\"inv\", 112]": 1, "[\"inv\", 488]": 1, "[\"fwd\", 136]": 1 }, "[\"hv\", \"INSTANCE\", \"group\", \"associ\"]": { "[\"fwd\", 463]": 1, "[\"inv\", 112]": 1, "[\"inv\", 488]": 1 }, "[\"v\", \"PLACE\", \"kill\"]": { "[\"fwd\", 17]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"kill\"]": { "[\"fwd\", 17]": 1 }, "[\"h\", \"INSTANCE\", \"sport\"]": { "[\"fwd\", 641]": 2, "[\"fwd\", 106]": 1 }, "[\"hv\", \"INSTANCE\", \"sport\", null]": { "[\"fwd\", 641]": 1 }, "[\"h\", \"INSTANCE\", \"separates\"]": { "[\"inv\", 131]": 1 }, "[\"hv\", \"INSTANCE\", \"separates\", null]": { "[\"inv\", 131]": 1 }, "[\"v\", \"PLACE\", \"govern\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 131]": 1, "[\"fwd\", 361]": 1, "[\"inv\", 150]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"govern\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 131]": 1, "[\"fwd\", 361]": 1, "[\"inv\", 150]": 1 }, "[\"v\", \"PLACE\", \"result\"]": { "[\"fwd\", 276]": 1 }, "[\"hv\", \"PLACE\", \"state\", \"result\"]": { "[\"fwd\", 276]": 1 }, "[\"h\", \"INSTANCE\", \"event\"]": { "[\"inv\", 17]": 2 }, "[\"v\", \"INSTANCE\", \"hold\"]": { "[\"inv\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"event\", \"hold\"]": { "[\"inv\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"county\", null]": { "[\"fwd\", 47]": 1, "[\"inv\", 47]": 1 }, "[\"h\", \"INSTANCE\", \"helped\"]": { "[\"fwd\", 26]": 1, "[\"inv\", 674]": 1 }, "[\"v\", \"INSTANCE\", \"help\"]": { "[\"fwd\", 26]": 1, "[\"inv\", 674]": 1 }, "[\"hv\", \"INSTANCE\", \"helped\", \"help\"]": { "[\"fwd\", 26]": 1, "[\"inv\", 674]": 1 }, "[\"h\", \"INSTANCE\", \"team\"]": { "[\"fwd\", 54]": 2, "[\"inv\", 118]": 1, "[\"inv\", 463]": 1, "[\"fwd\", 527]": 1, "[\"inv\", 361]": 1 }, "[\"hv\", \"INSTANCE\", \"team\", \"play\"]": { "[\"inv\", 118]": 1, "[\"inv\", 463]": 1, "[\"fwd\", 54]": 1 }, "[\"h\", \"INSTANCE\", \"song\"]": { "[\"inv\", 175]": 1 }, "[\"v\", \"INSTANCE\", \"hit\"]": { "[\"inv\", 175]": 1 }, "[\"hv\", \"INSTANCE\", \"song\", \"hit\"]": { "[\"inv\", 175]": 1 }, "[\"h\", \"INSTANCE\", \"previously\"]": { "[\"fwd\", 17]": 1 }, "[\"v\", \"INSTANCE\", \"renam\"]": { "[\"fwd\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"previously\", \"renam\"]": { "[\"fwd\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"sport\", \"play\"]": { "[\"fwd\", 106]": 1, "[\"fwd\", 641]": 1 }, "[\"h\", \"INSTANCE\", \"father\"]": { "[\"fwd\", 674]": 1, "[\"inv\", 1441]": 1 }, "[\"v\", \"INSTANCE\", \"perfor\"]": { "[\"fwd\", 674]": 1, "[\"inv\", 1441]": 1, "[\"inv\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"father\", \"perfor\"]": { "[\"fwd\", 674]": 1, "[\"inv\", 1441]": 1 }, "[\"h\", \"INSTANCE\", \"film\"]": { "[\"fwd\", 800]": 1, "[\"inv\", 57]": 1 }, "[\"hv\", \"INSTANCE\", \"film\", null]": { "[\"fwd\", 800]": 1 }, "[\"v\", \"INSTANCE\", \"animat\"]": { "[\"inv\", 449]": 1 }, "[\"hv\", \"INSTANCE\", \"series\", \"animat\"]": { "[\"inv\", 449]": 1 }, "[\"h\", \"INSTANCE\", \"mountain\"]": { "[\"fwd\", 138]": 1 }, "[\"hv\", \"INSTANCE\", \"mountain\", \"locat\"]": { "[\"fwd\", 138]": 1 }, "[\"h\", \"INSTANCE\", \"athlete\"]": { "[\"fwd\", 674]": 1 }, "[\"hv\", \"INSTANCE\", \"athlete\", \"based\"]": { "[\"fwd\", 674]": 1 }, "[\"v\", \"PERSON\", \"bear\"]": { "[\"fwd\", 86]": 1, "[\"fwd\", 676]": 1, "[\"fwd\", 112]": 1, "[\"fwd\", 138]": 1, "[\"fwd\", 527]": 1, "[\"inv\", 463]": 1 }, "[\"hv\", \"PERSON\", null, \"bear\"]": { "[\"fwd\", 86]": 1, "[\"fwd\", 676]": 1, "[\"fwd\", 112]": 1, "[\"fwd\", 138]": 1, "[\"fwd\", 527]": 1, "[\"inv\", 463]": 1 }, "[\"v\", \"INSTANCE\", \"comput\"]": { "[\"inv\", 57]": 1 }, "[\"hv\", \"INSTANCE\", \"film\", \"comput\"]": { "[\"inv\", 57]": 1 }, "[\"h\", \"PLACE\", \"town\"]": { "[\"inv\", 17]": 1 }, "[\"v\", \"PLACE\", \"beat\"]": { "[\"inv\", 17]": 1 }, "[\"hv\", \"PLACE\", \"town\", \"beat\"]": { "[\"inv\", 17]": 1 }, "[\"v\", \"PERSON\", \"co-fou\"]": { "[\"fwd\", 112]": 1 }, "[\"hv\", \"PERSON\", null, \"co-fou\"]": { "[\"fwd\", 112]": 1 }, "[\"v\", \"INSTANCE\", \"produc\"]": { "[\"inv\", 161]": 1, "[\"inv\", 272]": 1, "[\"inv\", 112]": 1 }, "[\"hv\", \"INSTANCE\", \"movie\", \"produc\"]": { "[\"inv\", 161]": 1, "[\"inv\", 272]": 1 }, "[\"hv\", \"INSTANCE\", \"team\", null]": { "[\"fwd\", 54]": 1, "[\"fwd\", 527]": 1, "[\"inv\", 361]": 1 }, "[\"v\", \"YEAR\", \"found\"]": { "[\"fwd\", 571]": 5 }, "[\"hv\", \"YEAR\", null, \"found\"]": { "[\"fwd\", 571]": 5 }, "[\"v\", \"PERSON\", \"award\"]": { "[\"inv\", 101]": 1 }, "[\"hv\", \"PERSON\", null, \"award\"]": { "[\"inv\", 101]": 1 }, "[\"hv\", \"INSTANCE\", \"event\", \"perfor\"]": { "[\"inv\", 17]": 1 }, "[\"v\", \"PERSON\", \"receiv\"]": { "[\"inv\", 166]": 1 }, "[\"hv\", \"PERSON\", null, \"receiv\"]": { "[\"inv\", 166]": 1 }, "[\"h\", \"INSTANCE\", \"mayor\"]": { "[\"inv\", 20]": 1 }, "[\"v\", \"INSTANCE\", \"elect\"]": { "[\"inv\", 20]": 1 }, "[\"hv\", \"INSTANCE\", \"mayor\", \"elect\"]": { "[\"inv\", 20]": 1 }, "[\"h\", \"INSTANCE\", \"college\"]": { "[\"fwd\", 355]": 1, "[\"fwd\", 527]": 1, "[\"inv\", 361]": 1 }, "[\"v\", \"INSTANCE\", \"study\"]": { "[\"fwd\", 355]": 1 }, "[\"hv\", \"INSTANCE\", \"college\", \"study\"]": { "[\"fwd\", 355]": 1 }, "[\"h\", \"INSTANCE\", \"episode\"]": { "[\"inv\", 1441]": 1 }, "[\"v\", \"INSTANCE\", \"narrat\"]": { "[\"inv\", 1441]": 1 }, "[\"hv\", \"INSTANCE\", \"episode\", \"narrat\"]": { "[\"inv\", 1441]": 1 }, "[\"v\", \"INSTANCE\", \"write\"]": { "[\"fwd\", 1441]": 1, "[\"fwd\", 800]": 1, "[\"inv\", 50]": 1 }, "[\"hv\", \"INSTANCE\", \"series\", \"write\"]": { "[\"fwd\", 1441]": 1, "[\"fwd\", 800]": 1, "[\"inv\", 50]": 1 }, "[\"v\", \"PLACE\", \"set\"]": { "[\"fwd\", 840]": 1 }, "[\"hv\", \"PLACE\", \"city\", \"set\"]": { "[\"fwd\", 840]": 1 }, "[\"v\", \"PLACE\", \"hold\"]": { "[\"fwd\", 27]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"hold\"]": { "[\"fwd\", 27]": 1 }, "[\"h\", \"INSTANCE\", \"civilization\"]": { "[\"fwd\", 156]": 1 }, "[\"v\", \"INSTANCE\", \"centr\"]": { "[\"fwd\", 156]": 1 }, "[\"hv\", \"INSTANCE\", \"civilization\", \"centr\"]": { "[\"fwd\", 156]": 1 }, "[\"h\", \"INSTANCE\", \"movement\"]": { "[\"fwd\", 101]": 1, "[\"fwd\", 106]": 1 }, "[\"hv\", \"INSTANCE\", \"movement\", null]": { "[\"fwd\", 101]": 1, "[\"fwd\", 106]": 1 }, "[\"v\", \"PLACE\", \"become\"]": { "[\"fwd\", 27]": 1, "[\"fwd\", 47]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"become\"]": { "[\"fwd\", 27]": 1, "[\"fwd\", 47]": 1 }, "[\"v\", \"YEAR\", \"die\"]": { "[\"fwd\", 570]": 1 }, "[\"hv\", \"YEAR\", null, \"die\"]": { "[\"fwd\", 570]": 1 }, "[\"h\", \"INSTANCE\", \"venue\"]": { "[\"inv\", 131]": 1 }, "[\"hv\", \"INSTANCE\", \"venue\", null]": { "[\"inv\", 131]": 1 }, "[\"h\", \"INSTANCE\", \"opera\"]": { "[\"fwd\", 800]": 1, "[\"fwd\", 1441]": 1 }, "[\"hv\", \"INSTANCE\", \"opera\", \"play\"]": { "[\"fwd\", 800]": 1, "[\"fwd\", 1441]": 1 }, "[\"v\", \"PERSON\", \"host\"]": { "[\"inv\", 800]": 1 }, "[\"hv\", \"PERSON\", null, \"host\"]": { "[\"inv\", 800]": 1 }, "[\"v\", \"PERSON\", \"hit\"]": { "[\"fwd\", 175]": 1, "[\"fwd\", 676]": 1 }, "[\"hv\", \"PERSON\", null, \"hit\"]": { "[\"fwd\", 175]": 1, "[\"fwd\", 676]": 1 }, "[\"v\", \"PLACE\", \"place\"]": { "[\"inv\", 17]": 1 }, "[\"hv\", \"PLACE\", null, \"place\"]": { "[\"inv\", 17]": 1 }, "[\"v\", \"PLACE\", \"record\"]": { "[\"fwd\", 27]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"record\"]": { "[\"fwd\", 27]": 1 }, "[\"h\", \"INSTANCE\", \"border\"]": { "[\"fwd\", 47]": 1 }, "[\"hv\", \"INSTANCE\", \"border\", null]": { "[\"fwd\", 47]": 1 }, "[\"v\", \"PLACE\", \"endang\"]": { "[\"fwd\", 17]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"endang\"]": { "[\"fwd\", 17]": 1 }, "[\"v\", \"INSTANCE\", \"co-cre\"]": { "[\"fwd\", 463]": 1, "[\"inv\", 527]": 1 }, "[\"hv\", \"INSTANCE\", \"series\", \"co-cre\"]": { "[\"fwd\", 463]": 1, "[\"inv\", 527]": 1 }, "[\"h\", \"PLACE\", \"nation\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 276]": 1 }, "[\"v\", \"PLACE\", \"win\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 276]": 1 }, "[\"hv\", \"PLACE\", \"nation\", \"win\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 276]": 1 }, "[\"v\", \"PLACE\", \"admini\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 131]": 1, "[\"inv\", 150]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"admini\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 131]": 1, "[\"inv\", 150]": 1 }, "[\"v\", \"PLACE\", \"border\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 47]": 1, "[\"inv\", 47]": 1, "[\"inv\", 206]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"border\"]": { "[\"fwd\", 17]": 1, "[\"fwd\", 47]": 1, "[\"inv\", 47]": 1, "[\"inv\", 206]": 1 }, "[\"h\", \"INSTANCE\", \"style\"]": { "[\"fwd\", 136]": 1 }, "[\"hv\", \"INSTANCE\", \"style\", \"associ\"]": { "[\"fwd\", 136]": 1 }, "[\"v\", \"PLACE\", \"involv\"]": { "[\"fwd\", 19]": 1, "[\"fwd\", 27]": 1 }, "[\"hv\", \"PLACE\", \"country\", \"involv\"]": { "[\"fwd\", 19]": 1, "[\"fwd\", 27]": 1 }, "[\"h\", \"INSTANCE\", \"headquartered\"]": { "[\"inv\", 17]": 1 }, "[\"v\", \"INSTANCE\", \"headqu\"]": { "[\"inv\", 17]": 1 }, "[\"hv\", \"INSTANCE\", \"headquartered\", \"headqu\"]": { "[\"inv\", 17]": 1 }, "[\"h\", \"INSTANCE\", \"actor\"]": { "[\"fwd\", 161]": 1 }, "[\"v\", \"INSTANCE\", \"debut\"]": { "[\"fwd\", 161]": 1 }, "[\"hv\", \"INSTANCE\", \"actor\", \"debut\"]": { "[\"fwd\", 161]": 1 }, "[\"hv\", \"INSTANCE\", \"company\", null]": { "[\"inv\", 17]": 1 }, "[\"h\", \"INSTANCE\", \"role\"]": { "[\"fwd\", 106]": 1 }, "[\"v\", \"INSTANCE\", \"take\"]": { "[\"fwd\", 106]": 1, "[\"fwd\", 800]": 1, "[\"inv\", 86]": 1 }, "[\"hv\", \"INSTANCE\", \"role\", \"take\"]": { "[\"fwd\", 106]": 1 }, "[\"h\", \"INSTANCE\", \"formed\"]": { "[\"fwd\", 463]": 1 }, "[\"v\", \"INSTANCE\", \"record\"]": { "[\"fwd\", 463]": 1 }, "[\"hv\", \"INSTANCE\", \"formed\", \"record\"]": { "[\"fwd\", 463]": 1 }, "[\"h\", \"INSTANCE\", \"second\"]": { "[\"fwd\", 800]": 1, "[\"inv\", 86]": 1 }, "[\"hv\", \"INSTANCE\", \"second\", \"take\"]": { "[\"fwd\", 800]": 1, "[\"inv\", 86]": 1 }, "[\"h\", \"INSTANCE\", \"album\"]": { "[\"fwd\", 800]": 1 }, "[\"v\", \"INSTANCE\", \"releas\"]": { "[\"fwd\", 800]": 1 }, "[\"hv\", \"INSTANCE\", \"album\", \"releas\"]": { "[\"fwd\", 800]": 1 }, "[\"h\", \"INSTANCE\", \"edited\"]": { "[\"inv\", 112]": 1 }, "[\"hv\", \"INSTANCE\", \"edited\", \"produc\"]": { "[\"inv\", 112]": 1 }, "[\"v\", \"INSTANCE\", \"convic\"]": { "[\"fwd\", 840]": 1, "[\"fwd\", 915]": 1, "[\"fwd\", 19]": 1 }, "[\"hv\", \"INSTANCE\", \"county\", \"convic\"]": { "[\"fwd\", 840]": 1, "[\"fwd\", 915]": 1, "[\"fwd\", 19]": 1 }, "[\"hv\", \"INSTANCE\", \"college\", null]": { "[\"fwd\", 527]": 1, "[\"inv\", 361]": 1 }, "[\"v\", \"PERSON\", \"serve\"]": { "[\"inv\", 39]": 1 }, "[\"hv\", \"PERSON\", null, \"serve\"]": { "[\"inv\", 39]": 1 } }, "compare": { "greater area": { "[\"max\", 1082]": 1, "[\"max\", 2046]": 1 }, "?": { "[\"min\", 569]": 2, "[\"min\", 571]": 1, "[\"min\", 570]": 1, "[\"max\", 571]": 1 }, "greater number": { "[\"min\", 2048]": 1 }, "more cities": { "[\"min\", 571]": 1 }, "more east": { "[\"min\", 571]": 1 }, "first": { "[\"min\", 569]": 3, "[\"max\", 2048]": 1 }, "older": { "[\"min\", 569]": 1 }, "more acts": { "[\"max\", 577]": 1, "[\"min\", 577]": 1 }, "more grand": { "[\"min\", 569]": 1, "[\"min\", 2048]": 1 } }}1[17, 19, 20, 22, 25, 26, 27, 30, 36, 37, 38, 50, 53, 57, 58, 59, 61, 84, 85, 86, 87, 102, 112, 115, 118, 123, 140, 144, 156, 159, 170, 175, 176, 177, 178, 195, 264, 276, 282, 287, 291, 361, 397, 403, 413, 449, 463, 474, 495, 569, 570, 571, 575, 577, 580, 582, 585, 610, 676, 749, 828, 837, 840, 885, 921, 931, 1027, 1080, 1082, 1303, 1346, 1365, 1366, 1532, 1619, 4552]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101[ {"id": "films", "name": "Films", "roots": [11424, 202866, 506240, 24862]}, {"id": "tvseries", "name": "Television series", "roots": [5398426, 117467246, 1259759, 21191270]}, {"id": "novels", "name": "Novels and literary works", "roots": [7725634, 47461344, 1667921, 13593966]}, {"id": "plays", "name": "Plays", "roots": [116476516]}, {"id": "poems", "name": "Poems", "roots": [5185279]}, {"id": "songs", "name": "Songs and musical works", "roots": [105543609, 134556]}, {"id": "albums", "name": "Albums", "roots": [482994]}, {"id": "operas", "name": "Operas and musicals", "roots": [58483083]}, {"id": "paintings", "name": "Paintings", "roots": [3305213, 15727816, 134194]}, {"id": "sculptures", "name": "Sculptures and monuments", "roots": [860861, 4989906]}, {"id": "videogames", "name": "Video games", "roots": [7889]}, {"id": "boardgames", "name": "Board and mind games", "roots": [131436, 1188693]}, {"id": "comics", "name": "Comics and comic characters", "roots": [838795, 1114461]}, {"id": "fiction", "name": "Fictional characters", "roots": [95074, 15632617, 15711870, 15773317]}, {"id": "countries", "name": "Countries", "roots": [6256, 3624078, 112099, 123480, 179164]}, {"id": "histcountries", "name": "Historical countries and empires", "roots": [3024240, 133156, 12759805]}, {"id": "usstates", "name": "U.S. states", "roots": [35657]}, {"id": "subnational", "name": "Provinces, counties and regions", "roots": [10864048, 11828004, 5852411, 180673, 1221156, 12443800, 10742, 15149663, 179872]}, {"id": "cities", "name": "Cities and towns", "roots": [515, 1549591, 1093829, 108178728, 3957, 486972]}, {"id": "islands", "name": "Islands and archipelagos", "roots": [23442, 33837, 1402592]}, {"id": "rivers", "name": "Rivers", "roots": [4022]}, {"id": "lakes", "name": "Lakes", "roots": [23397]}, {"id": "mountains", "name": "Mountains and volcanoes", "roots": [8502, 8072, 46831, 1061151]}, {"id": "seas", "name": "Seas, bays and gulfs", "roots": [165, 39594, 1322134, 204894]}, {"id": "deserts", "name": "Deserts and canyons", "roots": [8514, 150784]}, {"id": "waterfalls", "name": "Waterfalls", "roots": [34038]}, {"id": "parks", "name": "National parks and protected areas", "roots": [46169]}, {"id": "airports", "name": "Airports", "roots": [1248784]}, {"id": "bridges", "name": "Bridges and tunnels", "roots": [12280, 1311958]}, {"id": "buildings", "name": "Buildings and skyscrapers", "roots": [11303, 1021645, 16560, 23413, 162875]}, {"id": "museums", "name": "Museums", "roots": [33506]}, {"id": "universities", "name": "Universities", "roots": [38723]}, {"id": "stadiums", "name": "Stadiums and sports venues", "roots": [1154710, 1076486, 682943]}, {"id": "companies", "name": "Companies", "roots": [4830453, 46970, 131734]}, {"id": "carbrands", "name": "Car brands and models", "roots": [10429667, 3231690]}, {"id": "aircraft", "name": "Aircraft", "roots": [15056995, 15056993]}, {"id": "ships", "name": "Ships", "roots": [11446]}, {"id": "footballclubs", "name": "Football clubs", "roots": [476028]}, {"id": "sportsteams", "name": "Sports teams", "roots": [13393265, 13027888, 4498974, 17376093, 12973014]}, {"id": "sportsevents", "name": "Sporting events and editions", "roots": [114609228, 18608583, 27020041, 13406554]}, {"id": "olympics", "name": "Olympic Games", "roots": [135976384, 137592217]}, {"id": "battles", "name": "Battles", "roots": [178561, 1261499]}, {"id": "wars", "name": "Wars and revolutions", "roots": [198, 10931, 124734, 103495]}, {"id": "treaties", "name": "Treaties", "roots": [131569, 625298]}, {"id": "parties", "name": "Political parties", "roots": [7278]}, {"id": "newspapers", "name": "Newspapers and magazines", "roots": [11032, 41298]}, {"id": "organisations", "name": "Organisations", "roots": [43229, 163740, 1194093, 15925165]}, {"id": "taxa", "name": "Animals and plants (taxa)", "roots": [16521, 55983715]}, {"id": "breeds", "name": "Dog and cat breeds", "roots": [39367, 43577]}, {"id": "diseases", "name": "Diseases", "roots": [112193867, 12136]}, {"id": "elements", "name": "Chemical elements", "roots": [11344]}, {"id": "compounds", "name": "Chemical compounds", "roots": [113145171, 11173]}, {"id": "minerals", "name": "Minerals", "roots": [12089225]}, {"id": "moons", "name": "Moons", "roots": [1086783, 2537]}, {"id": "planets", "name": "Planets and dwarf planets", "roots": [634, 3504248]}, {"id": "stars", "name": "Stars", "roots": [523, 1547772]}, {"id": "constellations", "name": "Constellations", "roots": [8928]}, {"id": "asteroids", "name": "Asteroids and comets", "roots": [3863, 3559]}, {"id": "languages", "name": "Languages", "roots": [34770, 1288568]}, {"id": "currencies", "name": "Currencies", "roots": [8142]}, {"id": "holidays", "name": "Holidays and festivals", "roots": [1445650, 1197685]}, {"id": "religioustexts", "name": "Religious texts", "roots": [179461]}, {"id": "anatomy2", "name": "Anatomy (body parts)", "roots": [112826905, 103812529]}, {"id": "phobias", "name": "Phobias", "roots": [175854]}, {"id": "genres", "name": "Music genres and dances", "roots": [188451, 107357104]}, {"id": "awards", "name": "Awards and prizes", "roots": [618779, 4220917]}, {"id": "instruments", "name": "Musical instruments", "roots": [110295396, 34379]}, {"id": "dishes", "name": "Dishes and foods", "roots": [746549, 2095]}, {"id": "mythology2", "name": "Mythological figures", "roots": [22988604, 20830276, 4271324]}, {"id": "actors", "name": "Actors", "occ": [33999]}, {"id": "singers", "name": "Singers and musicians", "occ": [177220, 639669]}, {"id": "bands", "name": "Bands", "roots": [215380, 5741069]}, {"id": "composers", "name": "Composers and conductors", "occ": [36834, 158852]}, {"id": "painters", "name": "Painters and sculptors", "occ": [1028181, 1281618]}, {"id": "writers", "name": "Writers and poets", "occ": [36180, 49757, 6625963, 214917]}, {"id": "directors", "name": "Film directors and screenwriters", "occ": [2526255, 28389]}, {"id": "monarchs", "name": "Monarchs and royalty", "occ": [116, 2478141, 477406]}, {"id": "politicians", "name": "Politicians and leaders", "occ": [82955, 193391]}, {"id": "military", "name": "Military people", "occ": [189290, 47064, 1402561, 10669499]}, {"id": "explorers", "name": "Explorers and astronauts", "occ": [11900058, 11631]}, {"id": "scientists", "name": "Scientists", "occ": [901, 169470, 170790, 11063, 593644]}, {"id": "inventors", "name": "Inventors and engineers", "occ": [205375, 81096]}, {"id": "philosophers", "name": "Philosophers and theologians", "occ": [4964182, 1234713]}, {"id": "religiousleaders", "name": "Religious leaders", "occ": [15995642, 1259323]}, {"id": "business", "name": "Entrepreneurs and business people", "occ": [131524, 43845]}, {"id": "journalists", "name": "Journalists and broadcasters", "occ": [1930187, 130857]}, {"id": "footballers", "name": "Football players and coaches", "occ": [937857, 628099]}, {"id": "tennis", "name": "Tennis players", "occ": [10833314]}, {"id": "cricketers", "name": "Cricketers", "occ": [12299841]}, {"id": "athletes", "name": "Athletes and swimmers", "occ": [11513337, 10843402]}, {"id": "boxers", "name": "Boxers and martial artists", "occ": [11338576, 11124885]}, {"id": "golfers", "name": "Golfers", "occ": [11303721]}, {"id": "motorsport", "name": "Racing drivers and cyclists", "occ": [10349745, 2309784]}, {"id": "baseball", "name": "Baseball and basketball players", "occ": [10871364, 3665646]}, {"id": "chess", "name": "Chess players", "occ": [10873124]}, {"id": "architects", "name": "Architects", "occ": [42973]}, {"id": "physicians", "name": "Physicians", "occ": [39631]}, {"id": "economists", "name": "Economists", "occ": [188094]}, {"id": "lawyers", "name": "Lawyers and judges", "occ": [40348, 185351]}]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996[ { "id": "films", "roots": [ 11424, 202866, 506240, 24862 ], "occ": [] }, { "id": "tvseries", "roots": [ 5398426, 117467246, 1259759 ], "occ": [] }, { "id": "novels", "roots": [ 7725634, 47461344, 1667921, 13593966, 8261 ], "occ": [] }, { "id": "plays", "roots": [ 116476516, 25379 ], "occ": [] }, { "id": "poems", "roots": [ 5185279 ], "occ": [] }, { "id": "songs", "roots": [ 105543609, 134556, 7366 ], "occ": [] }, { "id": "albums", "roots": [ 482994 ], "occ": [] }, { "id": "operas", "roots": [ 58483083, 1344, 2743 ], "occ": [] }, { "id": "ballets", "roots": [ 15079786, 58483088 ], "occ": [] }, { "id": "paintings", "roots": [ 3305213, 15727816, 134194 ], "occ": [] }, { "id": "sculptures", "roots": [ 860861, 179700 ], "occ": [] }, { "id": "videogames", "roots": [ 7889 ], "occ": [] }, { "id": "boardgames", "roots": [ 131436 ], "occ": [] }, { "id": "comics", "roots": [ 838795, 1004, 14406742 ], "occ": [] }, { "id": "characters", "roots": [ 95074, 15632617, 15711870, 15773317, 1114461 ], "occ": [] }, { "id": "software", "roots": [ 7397, 9143 ], "occ": [] }, { "id": "newspapers", "roots": [ 11032, 41298 ], "occ": [] }, { "id": "countries", "roots": [ 6256, 3624078, 112099, 123480, 179164 ], "occ": [] }, { "id": "histcountries", "roots": [ 3024240, 133156, 12759805, 48349 ], "occ": [] }, { "id": "subnational", "roots": [ 10864048, 11828004, 5852411, 180673, 1221156, 12443800, 10742, 15149663, 179872, 35657 ], "occ": [] }, { "id": "cities", "roots": [ 515, 1549591, 1093829, 108178728, 3957 ], "occ": [] }, { "id": "islands", "roots": [ 23442, 33837, 1402592 ], "occ": [] }, { "id": "rivers", "roots": [ 4022 ], "occ": [] }, { "id": "lakes", "roots": [ 23397 ], "occ": [] }, { "id": "mountains", "roots": [ 8502, 8072 ], "occ": [] }, { "id": "deserts", "roots": [ 8514 ], "occ": [] }, { "id": "waterfalls", "roots": [ 34038 ], "occ": [] }, { "id": "parks", "roots": [ 46169 ], "occ": [] }, { "id": "airports", "roots": [ 1248784 ], "occ": [] }, { "id": "bridges", "roots": [ 12280 ], "occ": [] }, { "id": "skyscrapers", "roots": [ 11303, 12518 ], "occ": [] }, { "id": "castles", "roots": [ 23413, 16560 ], "occ": [] }, { "id": "churches", "roots": [ 2977, 16970 ], "occ": [] }, { "id": "museums", "roots": [ 33506 ], "occ": [] }, { "id": "universities", "roots": [ 3918, 38723 ], "occ": [] }, { "id": "stadiums", "roots": [ 483110, 1154710 ], "occ": [] }, { "id": "dams", "roots": [ 12323 ], "occ": [] }, { "id": "lighthouses", "roots": [ 39715 ], "occ": [] }, { "id": "companies", "roots": [ 4830453, 891723, 783794 ], "occ": [] }, { "id": "airlines", "roots": [ 46970 ], "occ": [] }, { "id": "carmodels", "roots": [ 3231690, 1420 ], "occ": [] }, { "id": "carbrands", "roots": [ 10429667 ], "occ": [] }, { "id": "aircraft", "roots": [ 15056995, 15056993 ], "occ": [] }, { "id": "ships", "roots": [ 11446 ], "occ": [] }, { "id": "footballclubs", "roots": [ 476028 ], "occ": [] }, { "id": "sportsteams", "roots": [ 13393265, 13027888, 4498974, 17156793 ], "occ": [] }, { "id": "sportsevents", "roots": [ 114609228, 27020041 ], "occ": [] }, { "id": "olympics", "roots": [ 135976384, 137592217 ], "occ": [] }, { "id": "battles", "roots": [ 178561, 1261499 ], "occ": [] }, { "id": "wars", "roots": [ 198, 10931, 124734, 103495 ], "occ": [] }, { "id": "treaties", "roots": [ 131569, 625298 ], "occ": [] }, { "id": "parties", "roots": [ 7278 ], "occ": [] }, { "id": "organisations", "roots": [ 43229, 163740, 1194093, 15925165 ], "occ": [] }, { "id": "religions", "roots": [ 9174 ], "occ": [] }, { "id": "breeds", "roots": [ 39367, 43577, 1160573 ], "occ": [] }, { "id": "diseases", "roots": [ 18123741, 112193867 ], "occ": [] }, { "id": "compounds", "roots": [ 11173, 113145171 ], "occ": [] }, { "id": "moons", "roots": [ 1086783, 2537 ], "occ": [] }, { "id": "planets", "roots": [ 634, 3504248, 1022867 ], "occ": [] }, { "id": "stars", "roots": [ 523, 1547772 ], "occ": [] }, { "id": "asteroids", "roots": [ 3863, 3559 ], "occ": [] }, { "id": "languages", "roots": [ 34770, 1288568 ], "occ": [] }, { "id": "currencies", "roots": [ 8142 ], "occ": [] }, { "id": "holidays", "roots": [ 1445650, 1197685 ], "occ": [] }, { "id": "phobias", "roots": [ 175854 ], "occ": [] }, { "id": "genres", "roots": [ 188451, 107357104 ], "occ": [] }, { "id": "awards", "roots": [ 618779, 4220917 ], "occ": [] }, { "id": "instruments", "roots": [ 110295396, 34379 ], "occ": [] }, { "id": "dishes", "roots": [ 746549, 2095, 10943 ], "occ": [] }, { "id": "mythology", "roots": [ 22988604, 20830276, 4271324, 178885 ], "occ": [] }, { "id": "actors", "roots": [], "occ": [ 33999 ] }, { "id": "singers", "roots": [], "occ": [ 177220 ] }, { "id": "musicians", "roots": [], "occ": [ 639669, 855091, 486748, 1259917, 386854 ] }, { "id": "bands", "roots": [ 215380, 5741069 ], "occ": [] }, { "id": "composers", "roots": [], "occ": [ 36834, 158852 ] }, { "id": "painters", "roots": [], "occ": [ 1028181 ] }, { "id": "sculptors", "roots": [], "occ": [ 1281618 ] }, { "id": "photographers", "roots": [], "occ": [ 33231 ] }, { "id": "architects", "roots": [], "occ": [ 42973 ] }, { "id": "novelists", "roots": [], "occ": [ 6625963 ] }, { "id": "poets", "roots": [], "occ": [ 49757 ] }, { "id": "playwrights", "roots": [], "occ": [ 214917, 28389 ] }, { "id": "directors", "roots": [], "occ": [ 2526255, 3282637 ] }, { "id": "journalists", "roots": [], "occ": [ 1930187, 947873 ] }, { "id": "comedians", "roots": [], "occ": [ 245068 ] }, { "id": "dancers", "roots": [], "occ": [ 5716684, 2490358 ] }, { "id": "models", "roots": [], "occ": [ 4610556, 3501317 ] }, { "id": "chefs", "roots": [], "occ": [ 3499072 ] }, { "id": "monarchs", "roots": [], "occ": [ 116, 2478141, 477406 ] }, { "id": "politicians", "roots": [], "occ": [ 82955 ] }, { "id": "diplomats", "roots": [], "occ": [ 193391 ] }, { "id": "military", "roots": [], "occ": [ 189290, 47064, 1402561, 10669499 ] }, { "id": "explorers", "roots": [], "occ": [ 11900058 ] }, { "id": "astronauts", "roots": [], "occ": [ 11631, 2095549 ] }, { "id": "physicists", "roots": [], "occ": [ 169470 ] }, { "id": "chemists", "roots": [], "occ": [ 593644 ] }, { "id": "mathematicians", "roots": [], "occ": [ 170790 ] }, { "id": "biologists", "roots": [], "occ": [ 864503, 18805 ] }, { "id": "astronomers", "roots": [], "occ": [ 11063 ] }, { "id": "physicians", "roots": [], "occ": [ 39631 ] }, { "id": "psychologists", "roots": [], "occ": [ 212980 ] }, { "id": "engineers", "roots": [], "occ": [ 81096, 205375 ] }, { "id": "philosophers", "roots": [], "occ": [ 4964182 ] }, { "id": "theologians", "roots": [], "occ": [ 1234713, 15995642 ] }, { "id": "historians", "roots": [], "occ": [ 201788 ] }, { "id": "economists", "roots": [], "occ": [ 188094 ] }, { "id": "linguists", "roots": [], "occ": [ 14467526 ] }, { "id": "lawyers", "roots": [], "occ": [ 40348, 185351, 16533 ] }, { "id": "business", "roots": [], "occ": [ 131524, 43845 ] }, { "id": "footballers", "roots": [], "occ": [ 937857, 628099 ] }, { "id": "tennis", "roots": [], "occ": [ 10833314 ] }, { "id": "cricketers", "roots": [], "occ": [ 12299841 ] }, { "id": "athletes", "roots": [], "occ": [ 11513337 ] }, { "id": "swimmers", "roots": [], "occ": [ 10843402 ] }, { "id": "boxers", "roots": [], "occ": [ 11338576, 11124885 ] }, { "id": "golfers", "roots": [], "occ": [ 11303721 ] }, { "id": "drivers", "roots": [], "occ": [ 10349745 ] }, { "id": "cyclists", "roots": [], "occ": [ 2309784 ] }, { "id": "basketball", "roots": [], "occ": [ 3665646 ] }, { "id": "baseball", "roots": [], "occ": [ 10871364 ] }, { "id": "icehockey", "roots": [], "occ": [ 11774891 ] }, { "id": "rugby", "roots": [], "occ": [ 14089670 ] }, { "id": "chess", "roots": [], "occ": [ 10873124 ] }, { "id": "criminals", "roots": [], "occ": [ 2159907, 10729326 ] }, { "id": "countries2", "roots": [ 3624078 ], "occ": [], "exclude_props": [ 576 ] }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212{ "who|directed": [ 57, 0.942, 0.935, 196 ], "horse|won": [ 1346, 1.0, 1.0, 36 ], "which|home": [ 466, 0.947, 0.941, 36 ], "which|games": [ 466, 0.941, 0.909, 28 ], "who|novel": [ 50, 0.914, 0.947, 312 ], "author|created": [ 170, 1.0, 1.0, 33 ], "instrument|*": [ 1303, 1.0, 1.0, 56 ], "instrument|instrument": [ 1303, 1.0, 1.0, 56 ], "capital|capital": [ 36, 0.916, 0.901, 316 ], "capital|*": [ 36, 0.916, 0.901, 316 ], "novelist|*": [ 50, 0.92, 1.0, 42 ], "novelist|novelist": [ 50, 0.92, 1.0, 42 ], "which|instrument": [ 1303, 1.0, 1.0, 43 ], "country|president": [ 27, 0.913, 1.0, 47 ], "year|die": [ 570, 1.0, 0.913, 44 ], "which|metal": [ 527, 1.0, 1.0, 22 ], "who|composed": [ 86, 0.917, 0.93, 198 ], "who|published": [ 50, 0.973, 0.958, 61 ], "author|books": [ 50, 1.0, 1.0, 22 ], "whose|novel": [ 50, 1.0, 0.9, 31 ], "author|american": [ 50, 0.9, 1.0, 33 ], "novelist|wrote": [ 50, 1.0, 1.0, 29 ], "who|booker": [ 50, 1.0, 1.0, 23 ], "who|prize": [ 50, 1.0, 1.0, 31 ], "city|headquarters": [ 159, 0.909, 1.0, 28 ], "capital|province": [ 36, 1.0, 1.0, 17 ], "country|take": [ 17, 1.0, 1.0, 19 ], "who|oratorio": [ 86, 1.0, 1.0, 19 ], "which|albums": [ 361, 1.0, 0.909, 24 ], "instrument|musician": [ 1303, 1.0, 1.0, 20 ], "which|designed": [ 84, 1.0, 1.0, 22 ], "constellation|constellation": [ 59, 1.0, 1.0, 38 ], "constellation|*": [ 59, 1.0, 1.0, 38 ], "constellation|star": [ 59, 1.0, 1.0, 32 ], "what|join": [ 208, 1.0, 1.0, 25 ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422#!/usr/bin/env python3"""chat_context_v2 - (v1 + TOPIC: the named entity a conversation is about; "the book", "this movie" resolve to it; FROZEN v1 is read by the admitted head) Oracle7's CONVERSATION engine (Ben 2026-10-09: "we have what we need for a proper chat model").
Chat failed by REFUSAL, not by error: a follow-up ("Where was he born?", "And its currency?", "And of Denmark?", "What doesthat cost?") reached the core without the conversation, and the core either refused or - worse - read the pronoun as thetopic ("he" -> an article about the word "he"). This engine never asserts anything itself. It keeps a small DIALOGUE STATEper session and REWRITES a turn that only makes sense through the conversation into the standalone question it standsfor; the whole verified chain (router, 210 specialists, fusion, maths) then answers that question exactly as it would ifit had been asked outright. The rewrite is shown in the reply's path and provenance, so the reading can be checked.
STATE (per session): the previous standalone question; its SUBJECT entity (the entity asked about) and its ANSWER entity (the entity the reply named), each with whether it is a person; the previous numeric RESULT (value + unit); solved variables ("x = 5"); the previous question's material phrase ("burning 5 kg of coal"). PRONOUNS he/she/him/his/her -> the person in play (the answer if it is a person - "Who wrote Frankenstein? / Who was her mother?" - else the subject); it/its -> the THING asked about ("Which planet does Titan orbit? / Who discovered it?" is Titan); "that country / that city ..." -> the entity just named; possessives become "the <noun> of <E>". ELLIPSIS "And its currency?" (relation swap), "And of Denmark?" / "And Doctor Zhivago?" (entity swap in the previous question), "And on the Moon?" / "And with radius 10 m?" (modifier swap or addition), "Where?" / "In what year?" (question-word swap, active -> passive when needed: "Who discovered Titan?" -> "In what year was Titan discovered?"). RESULTS "What does that cost at $0.20 per kWh?" -> the previous result ("300 kWh"); "What is x squared?" -> the solved x; "How much CO2 does that emit?" -> the previous material phrase ("burning 5 kg of coal"). MULTI "What is the capital of Austria and what is its currency?" -> two questions, each resolved and answered.A turn with nothing to resolve is passed through untouched. If a rewrite cannot be made with confidence, nothing isrewritten (the chain's own reply stands)."""import re
import relation_spec_v1 as RS
PRON_PERSON = r"he|she|him|his|her|hers"PRON_THING = r"it|its"REL_NOUNS = r"capital(?: city)?|currency|population|official language|national anthem|anthem|continent|calling code|highest point|" \ r"leader|president|prime minister|author|director|composer|creator|founder|headquarters|nationality|religion|" \ r"spouse|wife|husband|father|mother|birthplace|place of birth|date of birth|birthday"WH = r"who|what|which|where|when|how"STATE_CAP = 2000UNRESOLVED = "__unresolved__" # rewrite() -> (UNRESOLVED, pronoun): a short turn whose pronoun has nothing to refer to
class Turn: def __init__(self): self.q = None # previous standalone question self.subj = None # (qid, label, is_person, surface) self.ans = None # (qid, label, is_person) self.result = None # (value, unit) self.solved = {} # variable -> value self.material = None # "burning 5 kg of coal" / "5 kg of coal" self.topic = None # (qid, label, is_person, surface): the named entity the conversation is ABOUT
_STATES = {}
def state(sid): st = _STATES.get(sid) if st is None: if len(_STATES) > STATE_CAP: _STATES.clear() st = _STATES[sid] = Turn() return st
def _is_person(qid): try: return 5 in RS.classes_of(qid)[0] except Exception: # noqa: BLE001 return False
def _entity_of_question(q): a = RS.analyse(q) if not a or not a["cands"]: return None qid = a["cands"][0] return (qid, RS._rs().label(qid) or a["span"], _is_person(qid), a["span"])
RECEIPT_ENDS = re.compile(r"From the Wikidata relation store: (.+?)(?: \(Q(\d+)\))? - [^()]*? \(P\d+\) - (.+?)(?: \(Q(\d+)\))?\.\s*(?:\[|$)")TYPED = re.compile(r"\(typed relations: wd:Q(\d+) P\d+ wd:Q(\d+)\)")RECEIPT = re.compile(r"From the Wikidata relation store: .*? - .*? \(P\d+\) - (.+?)(?: \(Q(\d+)\))?\.\s*(?:\[|$)")
def _entity_of_reply(reply, prefer_person=False): """the entity the reply named; after a WHO question the answer is a person, so a person among the name's top candidates is preferred (the linker's popularity order put a song called "Pablo Picasso" before the painter)""" text = re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply or "")) m = RECEIPT_ENDS.search(text) if m: # the receipt reads subject - property - value, in the direction of the STORE: an inverse read ("Who painted # Guernica?" -> "Pablo Picasso (Q5593) - wrote - Guernica (Q175036)") puts the answer FIRST. The answer is the end # whose label the reply leads with. lead = text.split(". From the Wikidata relation store:", 1)[0].strip().lower() ends = [(m.group(1), m.group(2)), (m.group(3), m.group(4))] pick = [e for e in ends if e[1] and e[0].strip().lower() == lead] or [e for e in ends[::-1] if e[1]] if pick: qid = int(pick[0][1]) return (qid, RS._rs().label(qid) or pick[0][0], _is_person(qid)) m = RECEIPT.search(text) if m and m.group(2): qid = int(m.group(2)) return (qid, RS._rs().label(qid) or m.group(1), _is_person(qid)) # a sentence ends at . ! ? - but not after an initial ("J. R. R. Tolkien") first = re.split(r"(?<![\s.][A-Z]\.)(?<!^[A-Z]\.)(?<=[.!?])\s", text, 1)[0].rstrip(".") m = TYPED.search(text) if m: # the reply's typed relation names the exact entities; the answer is the end the reply leads with lead = re.sub(r"\s*\[[^\]]*\]\s*", " ", first).strip().lower() for q in (int(m.group(2)), int(m.group(1))): lab = RS._rs().label(q) if lab and lab.lower() == lead: return (q, lab, _is_person(q)) first = re.sub(r"\s*\[[^\]]*\]\s*", " ", first).strip() if not first or len(first) > 160: return None try: sp = RS.X.L.link(first, 3) except Exception: # noqa: BLE001 return None if not sp: return None span, cs = sp[0] qid = cs[0][0] if prefer_person: people = [c[0] for c in cs[:3] if _is_person(c[0])] if people: qid = people[0] return (qid, RS._rs().label(qid) or span, _is_person(qid))
NUM_UNIT = re.compile(r"(?:is|about|=|of)\s+\$?(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*(kwh|kj|mj|j|kg|g|m|km|s|n|pa|kpa|w|kw|litres?|liters?|l|m³|m3|°c|%)?", re.I)SOLVED = re.compile(r"\b([a-z])\s*=\s*(-?\d+(?:\.\d+)?)\b")MATERIAL = re.compile(r"\b((?:burning\s+)?\d[\d,]*(?:\.\d+)?\s*(?:kg|g|tonnes?|litres?|liters?|m3)\s+of\s+[a-z][a-z ]{1,24}?)(?=\s+(?:release|emit|produce|give|make|weigh)|[?.,]|$)", re.I)
def _result_of_reply(reply): text = re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", str(reply or "")) m = re.search(r"(?:answer is|is about|takes about|cost(?:s)? (?:is |about )?)\s*\$?(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*([a-zA-Z³%°]+)?", text) if not m: m = NUM_UNIT.search(text) if not m: return None try: v = float(m.group(1).replace(",", "")) except ValueError: return None unit = (m.group(2) or "").lower() if "$" in text[:max(0, m.start(1)) + 2] and not unit: unit = "$" return (v, unit)
def update(sid, standalone, reply): """after the chain answered (or declined) the standalone question: remember what the conversation is about""" st = state(sid) numeric = bool(re.search(r"\d", standalone)) and isinstance(reply, dict) and reply.get("status") == "answered" \ and _result_of_reply(reply.get("response")) is not None # context comes from FACTUAL turns only: a question the relation readers recognise, a numeric answer, or a question that # NAMES an entity ("What is the name of the writer of The Secret Garden?") - conversation acts ("got it", "why?", # "did you run it?") name nothing and never set the state named = None if not recognised(standalone) and not numeric: if not re.search(r"\?\s*$|^\s*(?:%s|is|are|was|were|did|does|do|can|could)\b" % WH, standalone, re.I): return named = _entity_of_question(standalone) if not named or not re.search(r"[A-Z]", str(named[3] or "")): return st.q = standalone # an entity the conversation already resolved KEEPS its identity when the rewrite names it (relinking "Pablo Picasso" # by popularity picked a song, Q7121722, over the painter the previous answer named, Q5593) subj = next((tuple(e[:3]) + (e[1],) for e in (st.ans, st.subj) if e and len(e[1] or "") >= 3 and e[1] in standalone), None) \ or _entity_of_question(standalone) typed = TYPED.search(str(reply.get("response", ""))) if isinstance(reply, dict) else None if subj and typed: for q in (int(typed.group(1)), int(typed.group(2))): if q != subj[0] and (RS._rs().label(q) or "").lower() == subj[1].lower(): subj = (q, subj[1], _is_person(q), subj[3]) # the reply's own typed relation names the exact entity if subj: st.subj = subj if re.search(r"[A-Z]", str(subj[3] or "")) and str(subj[3]) in standalone: st.topic = subj # a NAMED entity becomes what the conversation is about if isinstance(reply, dict) and reply.get("status") == "answered": ans = _entity_of_reply(reply.get("response"), prefer_person=bool(re.match(r"^\s*(?:who|whom|whose)\b", standalone, re.I))) st.ans = ans if ans and (not subj or ans[0] != subj[0]) else None r = _result_of_reply(reply.get("response")) st.result = r for var, val in SOLVED.findall(str(reply.get("response", ""))): st.solved[var] = val mm = MATERIAL.search(standalone) if mm: st.material = mm.group(1).strip()
def _person(st): if st.ans and st.ans[2]: return st.ans[1] if st.subj and st.subj[2]: return st.subj[1] if st.topic and st.topic[2]: return st.topic[1] return None
def _thing(st): if st.subj and not st.subj[2]: return st.subj[1] if st.ans and not st.ans[2]: return st.ans[1] if st.topic and not st.topic[2]: return st.topic[1] return None
# "the book", "this movie", "the band's ..." - the work / group the conversation is aboutTHE_NOUN = re.compile(r"\b(?:the|this|that)\s+(book|novel|story|movie|film|album|song|record|band|group|show|series|tv series|tv show|" r"programme|program|team|club|game|play|opera|painting|novel's|book's|movie's|film's|album's|band's|show's|" r"series'|team's|club's)(?=[\s?.,!]|$)", re.I)
def _cap(s): s = s.strip() return s[:1].upper() + s[1:] if s else s
def _q(s): s = s.strip().rstrip("?.! ") return _cap(s) + "?"
def _swap_wh(prev, wh): """'When was Alfred Hitchcock born?' + 'Where' -> 'Where was Alfred Hitchcock born?'; active 'Who discovered Titan?' -> 'In what year was Titan discovered?'""" p = prev.strip().rstrip("?") m = re.match(r"^(?:who|what|which|where|when|how)\b(?:\s+year)?\s+((?:was|were|is|are|did|does|do)\b.*)$", p, re.I) if m: return _q("%s %s" % (wh, m.group(1))) m = re.match(r"^who\s+(\w+ed)\s+(.+)$", p, re.I) if m: return _q("%s was %s %s" % (wh, m.group(2), m.group(1))) return None
def _rewrite_raw(sid, text): """-> (kind, standalone question) with kind "num" | "rel", (UNRESOLVED, pronoun), or None""" st = state(sid) t = " ".join(str(text or "").split()) low = t.lower().rstrip("?.! ") if not t: return None pron = re.search(r"\b(he|she|him|his|her|it|its|they|them|their)\b", low) short_bare = pron is not None and len(low.split()) <= 12 and re.search(r"(?<=\s)[A-Z][a-z]+", t) is None if not st.q: return (UNRESOLVED, pron.group(1)) if short_bare and pron.group(1) not in ("it", "its") else None # results and variables m = re.search(r"\bwhat is ([a-z]) (squared|cubed)\b", low) if m and m.group(1) in st.solved: power = "2" if m.group(2) == "squared" else "3" return ("num", _q(re.sub(r"\b%s (squared|cubed)\b" % m.group(1), "%s^%s" % (st.solved[m.group(1)], power), t, flags=re.I))) if re.search(r"\b(?:that|this)\b", low) and (st.result or st.material): if re.search(r"\b(?:co2|carbon dioxide|emit|emission|release|weigh)", low) and st.material: return ("num", _q(re.sub(r"\b(?:that|this)\b", st.material, t, count=1, flags=re.I))) if st.result and st.result[1] and re.search(r"per\s+%s\b" % re.escape(st.result[1]), low): return ("num", _q(re.sub(r"\b(?:that|this)\b", "%s %s" % (_fmt(st.result[0]), st.result[1]), t, count=1, flags=re.I))) # bare question word: "Where?", "When?", "In what year?" m = re.match(r"^(?:and\s+)?(where|when|in what year|what year)$", low) if m: r = _swap_wh(st.q, {"what year": "In what year"}.get(m.group(1), _cap(m.group(1)))) return ("rel", r) if r else None # ellipsis with "And ..." m = re.match(r"^(?:and|what about|how about)\s+(.+)$", low) if m: rest = t[len(t) - len(m.group(1)) - (len(t) - len(t.rstrip("?.! "))):].rstrip("?.! ") rest_low = rest.lower() mr = re.match(r"^(?:the\s+|its\s+|his\s+|her\s+|their\s+)?(%s)$" % REL_NOUNS, rest_low) if mr: ent = _thing(st) if not re.match(r"^(his|her)\b", rest_low) else _person(st) ent = ent or _thing(st) or _person(st) return ("rel", _q("What is the %s of %s" % (mr.group(1), ent))) if ent else None mp = re.match(r"^(on|in|at|with|for|of)\s+(.+)$", rest, re.I) if mp and mp.group(1).lower() in ("of", "for") and st.subj and st.subj[3]: r = _replace_subject(st, mp.group(2)) return ("rel", r) if r else None if mp and mp.group(1).lower() in ("on", "in", "at", "with"): prep, phrase = mp.group(1).lower(), mp.group(2) pm = re.search(r"\b%s\s+[^?]*?\d[^?]*?(?=$|\?|,)" % prep, st.q, re.I) if re.search(r"\d", phrase) else None if not st.result: return None # a modifier swap continues a COMPUTATION only if pm: return ("num", _q(st.q[:pm.start()] + "%s %s" % (prep, phrase) + st.q[pm.end():])) return ("num", _q(st.q.rstrip("?.! ") + " %s %s" % (prep, phrase))) if rest[:1].isupper() and st.subj and st.subj[3]: r = _replace_subject(st, rest) return ("rel", r) if r else None return None # "that country" / possessive and personal pronouns out = t changed = False # "the book" / "this movie" / "the band's ..." -> the named work or group the conversation is about m = THE_NOUN.search(out) if m and _thing(st) and re.search(r"(?<=\s)[A-Z][a-z]+", out) is None: ent = st.topic[1] if st.topic and not st.topic[2] else _thing(st) if m.group(1).endswith(("'s", "'")): rest = re.match(r"\s*(\w+(?:\s+\w+)?)", out[m.end():]) if rest: out = out[:m.start()] + "the %s of %s" % (rest.group(1), ent) + out[m.end() + rest.end():] changed = True else: out = out[:m.start()] + ent + out[m.end():] changed = True m = re.search(r"\bthat\s+(country|city|state|planet|nation|island|river|band|team|company|book|film|novel|place)\b", out, re.I) if m: ent = (st.ans[1] if st.ans and not st.ans[2] else None) or _thing(st) if not ent: return None out = out[:m.start()] + ent + out[m.end():] changed = True # a turn that names its own subject (a capitalised name after the first word) keeps its own pronouns names_own = re.search(r"(?<=\s)[A-Z][a-z]+", out) is not None and not changed for pron, getter in (() if names_own else ((PRON_PERSON, _person), (PRON_THING, _thing))): for pm in list(re.finditer(r"\b(%s)\b(\s+[a-z]+(?:\s+[a-z]+)?)?" % pron, out, re.I))[::-1]: ent = getter(st) if not ent: return (UNRESOLVED, pm.group(1).lower()) if short_bare else None word = pm.group(1).lower() if word in ("his", "her", "its") and pm.group(2): noun = pm.group(2).strip() if re.match(r"^(%s)\b" % REL_NOUNS, noun, re.I) or word in ("his", "its"): rep = "the %s of %s" % (noun, ent) out = out[:pm.start()] + rep + out[pm.end():] changed = True continue out = out[:pm.start(1)] + ent + out[pm.end(1):] changed = True if not changed: return None return ("rel", _q(out))
def recognised(q): """a question the verified relation layer can READ: it matches one of the hand-written relation readers whole""" try: import relation_spec_v2 as S2 _, low = S2.normalise(q) for key in S2.RD.PROPS: c = S2.compiled(key) if any(rx.match(low) for d in ("fwd", "inv") for rx in c[d]): return True except Exception: # noqa: BLE001 return False return False
def rewrite(sid, text): """-> the standalone question this turn stands for, (UNRESOLVED, pronoun), or None. A rewrite is ACCEPTED only when it is exactly right for the verified layer: a relation rewrite must be a question the relation readers recognise; a numeric rewrite must continue a numeric answer. Anything else goes to the core untouched - the core has its own conversation acts ("got it", "why?", "did you run it?", "how does it work?") that a rewrite would break (m52 replay, 2026-10-09).""" r = _rewrite_raw(sid, text) if r is None: return None if r[0] == UNRESOLVED: return r if recognised(text) else None kind, q = r if not q: return None if kind == "num": return q if state(sid).result or state(sid).solved else None return q if recognised(q) or _named_fact_question(sid, text, q) else None
# conversation acts the core resolves itself (m52): never rewritten, whatever entity is in playACT_VERBS = re.compile(r"\b(?:test|run|ran|work|works|worked|mean|means|meant|explain|continue|think|feel|like|recommend|" r"remember|said|say|says|tell me about|summari[sz]e|show|try|fix|change|build|write|make)\b", re.I)FACT_WH = re.compile(r"^(?:(?:and\s+)?(?:who|whom|whose|what|which|where|when)\b(?!\s+(?:do|does|did)\s+(?:you|i|we)\b)|in what year\b|" r"what year\b|how (?:many|much|old|tall|long|far|big|high)\b)", re.I)
def _named_fact_question(sid, text, q): """v2: a FACTUAL wh-question whose rewrite names the conversation's topic entity (it was named earlier by the user) - "Who directed it?" after "Bird Box" -> "Who directed Bird Box?". Conversation acts are never rewritten.""" st = state(sid) t = str(text or "") trailing = re.search(r"\b(?:in what year|what year|which year|in what (?:city|country|state|town)|is where|was where|by whom)\s*\??\s*$", t, re.I) if not st.topic or ACT_VERBS.search(t) or not (FACT_WH.match(t.strip()) or trailing): return False labels = [e[1] for e in (st.topic, st.ans, st.subj) if e and e[1]] return any(lab in q and lab not in t for lab in labels) surface = st.subj[3] if surface and surface in st.q: return _q(st.q.replace(surface, new, 1)) lab = st.subj[1] if lab and lab in st.q: return _q(st.q.replace(lab, new, 1)) return None
def _fmt(v): return ("%d" % v) if abs(v - round(v)) < 1e-9 else ("%.6g" % v)
SPLIT = re.compile(r"\s+and\s+(?=(?:%s)\b)" % WH, re.I)
def split_parts(text): """'What is the capital of Austria and what is its currency?' -> two questions (only when the second part is itself a question starting with a question word)""" t = " ".join(str(text or "").split()).rstrip("?") parts = SPLIT.split(t) if len(parts) < 2: return None # split ONLY when every part is a question the relation readers can read (panel v27 2026-10-09: a reading passage # containing "... and Where to Find Them" and "Everything is fine, and how are you?" were split and lost) return [_q(p) for p in parts] if all(_shape_ok(_q(p)) for p in parts) else None
def _shape_ok(p): """the part reads as a relation question - as written, or with its pronoun standing for a named thing""" if recognised(p): return True s = re.sub(r"\b(?:its|his|her|their)\s+(\w+(?:\s+\w+)?)", r"the \1 of Peru", p, flags=re.I) s = re.sub(r"\b(?:he|she|it|they|him|them)\b", "Peru", s, flags=re.I) return s != p and recognised(s)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374#!/usr/bin/env python3"""entity_linker_v2 - entity_linker_v1 (same index: relstore/names_v1.sqlite3) + three linking rules found byreading the traversal's wrong-entity cases on HOLD training questions (2026-10-06): R1 CASE AGREEMENT - Wikidata labels concepts in lower case ("airline", "semen", "history") and names with a capital ("Avensa", "Comè"). A single LOWERCASE question word may link only to a concept (lowercase label); a capitalised span (a name in the question) gets a large bonus, so a rare name outranks a popular common word ("come" -> Comè lost to nothing before; now Avensa wins). R2 TITLES - a title-cased span may begin with a stop word ("A Brief History Of Time", "The Battle Of New Orleans" - the song, not the battle); v1 barred every leading stop word. R3 NUMBERS ARE NOT ENTITIES - a span whose content words are all numeric ("No 1", "80s", "2001") is skipped.use: link(question, k=3) -> [(span text, [(qid, links, label), ...]), ...] (v1's interface)"""import mathimport re
import entity_linker_v1 as V1
norm, candidates, label, STOP = V1.norm, V1.candidates, V1.label, V1.STOPNUMERIC = re.compile(r"^(\d+|\d+s|\d+(st|nd|rd|th))$")FUNCTION = set(("a an the of in on at to for by with from and or is was are were be been as it its his her their s " "who what which when where how did does do this that").split())
def _concept(lab): return bool(lab) and lab[:1].islower()
def link(question, k=3, max_len=8): raw = re.findall(r"[A-Za-z0-9][\w'.\-]*", str(question)) toks = [norm(t) for t in raw] spans = [] for i in range(len(toks)): for j in range(i + 1, min(len(toks), i + max_len) + 1): words = toks[i:j] if not words[0] or not words[-1] or all(w in STOP for w in words): continue content = [w for w in words if w not in STOP and w != "no"] if not content or all(NUMERIC.match(w) for w in content): # R3 continue # R2: a TITLE = first and last word capitalised, every non-function word capitalised (inner function words # may be either case: "The Tide is High"); its edges may be any word but a function word at the end cap = [r[:1].isupper() or r[:1].isdigit() for r in raw[i:j]] titled = len(words) >= 2 and cap[0] and cap[-1] and all(c or w in FUNCTION for c, w in zip(cap, words)) caps = titled or all(c for c, w in zip(cap, words) if w not in STOP) if words[-1] in (FUNCTION if titled else STOP): continue if words[0] in STOP and not titled: continue if len(words) == 1 and not caps and (len(words[0]) < 4 or words[0] in STOP): continue c = candidates(" ".join(words), max(k, 6)) if not c: continue if len(words) == 1 and not caps: # R1: lowercase word -> concepts only c = [x for x in c if _concept(label(x[0]))] if not c or c[0][1] < 30: continue c = c[:k] score = math.log1p(c[0][1]) + 3.0 * len(words) + (8.0 if caps else 0.0) # R1: names outrank common words spans.append((score, i, j, c)) spans.sort(key=lambda s: -s[0]) taken, out = set(), [] for score, i, j, c in spans: if any(x in taken for x in range(i, j)): continue taken.update(range(i, j)) out.append((" ".join(raw[i:j]), [(q, n, label(q)) for q, n, _ in c], score)) out.sort(key=lambda s: -s[2]) return [(s, c) for s, c, _ in out]
if __name__ == "__main__": import sys for q in sys.argv[1:]: print(q, "->", [(s, [x[2] for x in c]) for s, c in link(q)])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992"""math_solver_v3 - exact answers to competition-style maths problems, each checked by an independent second method.
A problem is answered only when ONE typed family reads ALL of it and its answer passes that family's own check: EVALUATE "Compute / Evaluate / Simplify / What is / Find the value of $E$" check: 50-digit numeric evaluation SOLVE "Solve for x: $eq$", "What is x if $eq$", "Find all solutions to" check: substitute every root back (+ sum / product / number / positive / largest / smallest of the solutions) FUNCTION "If $f(x) = ...$, what is $f(a) + f(b)$?" check: numeric substitution NUMBER divisor count / sum, gcd, lcm, remainder (incl. powers), units digit, largest / smallest prime factor, "N_b in base 10", "convert N to base b" check: brute force or a second algorithm COUNT binomial coefficients, factorial expressions, arrangements of the letters of a word check: direct enumeration when smallAnything else - diagrams ([asy]), proofs, word problems the families do not read completely - is declined.solve(text) -> None | {"answer": latex, "plain": str, "family": str, "steps": [str], "check": str}"""import itertoolsimport mathimport refrom collections import Counter
import sympy as spfrom sympy.parsing.sympy_parser import (convert_xor, implicit_multiplication_application, parse_expr, standard_transformations)
TRANS = standard_transformations + (implicit_multiplication_application, convert_xor)LOCAL = {"pi": sp.pi, "e": sp.E, "E": sp.E, "I": sp.I, "sqrt": sp.sqrt, "binomial": sp.binomial, "factorial": sp.factorial, "floor": sp.floor, "ceiling": sp.ceiling, "Abs": sp.Abs, "log": sp.log, "ln": sp.log, "sin": sp.sin, "cos": sp.cos, "tan": sp.tan, "cot": sp.cot, "sec": sp.sec, "csc": sp.csc, "exp": sp.exp, "root": sp.root}
class Unread(Exception): pass
_ALLOW_CALLS = [False] # function families switch this on while they read definitions they own
# ---------------------------------------------------------------- TeX -> SymPydef _group(s, i): """s[i] == '{' -> (content, index after the matching '}')""" depth = 0 for j in range(i, len(s)): if s[j] == "{": depth += 1 elif s[j] == "}": depth -= 1 if depth == 0: return s[i + 1:j], j + 1 raise Unread("unbalanced braces")
def _arg(s, i): """one TeX argument at s[i]: {group} or a single character""" while i < len(s) and s[i] == " ": i += 1 if i >= len(s): raise Unread("missing argument") if s[i] == "{": return _group(s, i) return s[i], i + 1
def tex(s): """a TeX maths expression -> a SymPy-parsable string (raises Unread for anything it does not read)""" s = str(s) if re.search(r"\\(?:sin|cos|tan|cot|sec|csc)\s*\^", s): raise Unread("a power of a trig function (\\sin^3 x) is not read") if re.search(r"(?<![a-zA-Z\\])[A-Zfghpq]\s*\(", s): # a function name applied to a bracket (h(4x-1), P(0)) that no family expanded: a function the problem did not # define (x(x+3) stays multiplication) raise Unread("undefined function") # a mixed number: 8\frac{1}{3} = 8 + 1/3 s = re.sub(r"(?<![\d.])(\d+)\s*\\[dt]?frac\s*\{(\d+)\}\s*\{(\d+)\}", r"(\1+\\frac{\2}{\3})", s) s = re.sub(r"\\(?:left|right|displaystyle|,|;|!|:|quad|qquad)", " ", s) s = s.replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac").replace("\\cdot", "*").replace("\\times", "*") s = s.replace("\\div", "/").replace("\\pi", " pi ").replace("\\infty", " oo ").replace("\\ln", " log").replace("\\log", " log") s = s.replace("\\lfloor", " floor(").replace("\\rfloor", ")").replace("\\lceil", " ceiling(").replace("\\rceil", ")") s = s.replace("\\{", "(").replace("\\}", ")").replace("\\%", "/100") # a trig function of an angle in degrees takes the whole angle: \tan 53^\circ -> tan((53)*pi/180) s = re.sub(r"\\(sin|cos|tan|cot|sec|csc)\s*\(?\s*([\d.]+)\s*\)?\s*\^\s*\{?\s*\\circ\s*\}?", r" \1(((\2))*pi/180)", s) for f in ("sin", "cos", "tan", "cot", "sec", "csc", "exp"): s = s.replace("\\" + f, " " + f) s = re.sub(r"\^\{\\circ\}|\^\\circ|\\circ", "*pi/180", s) out, i = [], 0 while i < len(s): if s.startswith("\\frac", i): a, i = _arg(s, i + 5) b, i = _arg(s, i) out.append("((%s)/(%s))" % (tex(a), tex(b))) elif s.startswith("\\sqrt", i): i += 5 n = None if i < len(s) and s[i] == "[": j = s.index("]", i) n, i = s[i + 1:j], j + 1 a, i = _arg(s, i) out.append("sqrt(%s)" % tex(a) if n is None else "root(%s,%s)" % (tex(a), tex(n))) elif s.startswith("\\binom", i): a, i = _arg(s, i + 6) b, i = _arg(s, i) out.append("binomial(%s,%s)" % (tex(a), tex(b))) elif s[i] == "^": a, i = _arg(s, i + 1) out.append("**(%s)" % tex(a)) elif s[i] == "{": a, i = _group(s, i) out.append("(%s)" % tex(a)) elif s[i] == "\\": m = re.match(r"\\[a-zA-Z]+", s[i:]) raise Unread("unknown command %s" % (m.group(0) if m else s[i:i + 2])) elif s[i] == "!": out.append("!") i += 1 elif s[i] == "|": raise Unread("absolute value bars") elif s[i] == "_": raise Unread("subscript (a base or an index): not read as arithmetic") else: out.append(s[i]) i += 1 r = "".join(out) # n! -> factorial(n) for a number or a bracketed group r = re.sub(r"(\d+|\([^()]*\))!", r"factorial(\1)", r) if "!" in r: raise Unread("factorial form") return r
def P(s, syms=None): loc = dict(LOCAL) for v in syms or (): loc[str(v)] = v try: return parse_expr(tex(s), local_dict=loc, transformations=TRANS, evaluate=True) except Unread: raise except Exception as e: # noqa: BLE001 raise Unread("parse: %r" % e)
# ---------------------------------------------------------------- answer formdef latex_answer(v): v = sp.nsimplify(v) if isinstance(v, sp.Float) and abs(v - sp.nsimplify(v)) < 1e-12 else v s = sp.latex(v, fold_short_frac=False) s = s.replace("\\left(", "(").replace("\\right)", ")") s = re.sub(r"(\d)\s+\\sqrt", r"\1\\sqrt", s) return s
def exact(v): return v is not None and v.is_number and not v.has(sp.Float) and not v.has(sp.zoo, sp.nan, sp.oo, -sp.oo) and v.is_finite
def agree(a, b, tol=1e-40): try: return abs(complex(sp.N(a, 60)) - complex(sp.N(b, 60))) <= tol * max(1, abs(complex(sp.N(b, 60)))) except Exception: # noqa: BLE001 return False
def _recover(e): """an exact value for a numeric expression SymPy will not simplify (trig products, nested radicals): a rational or a simple surd found from 80 digits, accepted only if it agrees to 1e-60 and is short""" try: x = sp.N(e, 90) if not x.is_real: return None for basis in ([], [sp.sqrt(2)], [sp.sqrt(3)], [sp.sqrt(5)], [sp.sqrt(6)], [sp.pi]): c = sp.nsimplify(x, basis, tolerance=sp.Float("1e-60", 90), rational=not basis) if c.is_number and len(str(c)) <= 24 and abs(sp.N(c - e, 90)) < sp.Float("1e-60", 90): return c except Exception: # noqa: BLE001 return None return None
MATHS = re.compile(r"\$\$?(.+?)\$\$?|\\\[(.+?)\\\]|\\\((.+?)\\\)", re.S)
def maths(text): return [next(g for g in m.groups() if g is not None).strip() for m in MATHS.finditer(text)]
def prose(text): return " ".join(MATHS.sub(" M ", text).split()).lower()
EXPRESS = re.compile(r"\s*express (?:your answer|the answer|it)[^.]*\.?|\s*enter [^.]*\.?|\s*give your answer[^.]*\.?|" r"\s*(?:round|simplify) your answer[^.]*\.?", re.I)
# ---------------------------------------------------------------- familiesdef f_evaluate(text): t = EXPRESS.sub("", text).strip() m = re.fullmatch(r"(?:compute|evaluate|simplify|calculate|find|what is|find the value of|what is the value of|" r"determine|rationalize the denominator(?: of)?)\s*(?:the (?:value|product|sum|quotient) of\s*)?:?\s*\$([^$]+)\$\s*[.?]?", t, re.I) if not m: return None raw = m.group(1) if _huge(raw): return None if re.match(r"\s*simplify", t, re.I) and re.search(r"(?<![a-z\\])[a-df-zA-DF-Z](?![a-z])", re.sub(r"\\[a-zA-Z]+", "", raw)) \ and "=" not in raw: # an expression in a variable that simplifies to a CONSTANT ("Simplify (2x-5)(x+7)-(x+5)(2x-1)" -> -30) letters = sorted(set(re.findall(r"(?<![a-zA-Z\\])([a-zA-Z])(?![a-zA-Z])", re.sub(r"\\[a-zA-Z]+", "", raw)))) syms = [sp.Symbol(c) for c in letters] e = P(raw, syms) v = sp.expand(e) if v.free_symbols or not exact(v): return None pts = [{s: sp.Rational(k + 2, 3) for s in syms}, {s: sp.Rational(-k - 5, 7) for s in syms}] if not all(agree(e.subs(pt), v) for k, pt in enumerate(pts)): return None return {"answer": latex_answer(v), "family": "simplify_constant", "steps": ["expanded $%s$" % raw], "check": "the expression evaluated at two random points equals the constant"} if re.search(r"[=<>]|\\le|\\ge|\\ne", raw) or re.search(r"(?<![a-z\\])[a-df-zA-DF-Z](?![a-z])", re.sub(r"\\[a-zA-Z]+", "", raw)): return None # an equation or a free variable: not an evaluation e = P(raw) v = sp.nsimplify(sp.radsimp(sp.simplify(e))) if not e.has(sp.Float) and sp.count_ops(e) < 200 else None if v is None or not exact(v) or len(str(v)) > 40: v = _recover(e) # exact form recovered from 80 digits, then re-checked if v is None or not exact(v): return None if not agree(v, e): return None return {"answer": latex_answer(v), "family": "evaluate", "steps": ["read $%s$" % raw, "simplified exactly"], "check": "the exact value agrees with a 60-digit numeric evaluation of the original expression"}
SOLVE_Q = re.compile(r"(?P<pre>.*?)\$(?P<eq>[^$]*=[^$]*)\$(?P<post>.*)", re.S)
def f_solve(text): t = EXPRESS.sub("", text).strip() eqs = [x for x in maths(t) if "=" in x and not re.search(r"\\le|\\ge|<|>|\\ne", x)] if len(eqs) != 1: return None pr = prose(t) if not re.search(r"\b(solve|value of m|what is m|find m|solutions?|roots?|satisf|values? of m|possible values)", pr): return None var = None mv = re.search(r"(?:solve for|value of|values of|find|what is|for)\s+\$?\\?([a-z])\$?\b", t, re.I) eq = eqs[0] lhs, _, rhs = eq.partition("=") if "=" in rhs or re.search(r"\\(?:sin|cos|tan|cot|sec|csc)|\\circ", eq): return None # trigonometric equations are not read here if re.fullmatch(r"\s*[a-zA-Z]\s*", lhs) and not re.search(r"[a-zA-Z]", re.sub(r"\\[a-zA-Z]+", "", rhs)): return None # an assignment (x = 4), not an equation: f_subst reads it letters = sorted(set(re.findall(r"(?<![a-zA-Z\\])([a-zA-Z])(?![a-zA-Z])", re.sub(r"\\[a-zA-Z]+", "", eq))) - {"e"}) if mv and mv.group(1) in letters: var = mv.group(1) elif len(letters) == 1: var = letters[0] if not var or len(letters) > 1: return None x = sp.Symbol(var) L, R = P(lhs, [x]), P(rhs, [x]) if sp.count_ops(L - R) > 120: return None try: num, den = sp.fraction(sp.together(L - R)) if sp.Poly(num, x).degree() > 4: return None # exact roots of degree > 4 are not read here except sp.PolynomialError: pass sols = sp.solve(sp.Eq(L, R), x) sols = [sp.nsimplify(s) if s.has(sp.Float) else s for s in sols] if not sols or not all(exact(s) for s in sols): return None for s in sols: # check: every root satisfies the original equation if not agree(L.subs(x, s), R.subs(x, s), 1e-30) and abs(complex(sp.N(L.subs(x, s) - R.subs(x, s), 50))) > 1e-30: return None real = [s for s in sols if s.is_real] # what is asked: the variable itself, or an expression of it ("If 3x + 2(1+x) = 17, what is the value of 6x + 5?") others = [c for c in maths(t) if c != eq and "=" not in c and c.strip() != var] asks_expr = others and re.search(r"(?:value of|what is|find|compute|evaluate)\s*\$", t, re.I) if asks_expr: if len(others) != 1 or len(sols) != 1 or not asked_directly(t, others[0]): return None E = P(others[0], [x]) if E.free_symbols - {x}: return None v = sp.nsimplify(sp.simplify(E.subs(x, sols[0]))) if not exact(v) or not agree(v, E.subs(x, sols[0])): return None return {"answer": latex_answer(v), "family": "solve_then_evaluate", "steps": ["solved $%s$: %s = %s" % (eq, var, sp.latex(sols[0])), "substituted into $%s$" % others[0]], "check": "the root satisfies the equation; the expression re-evaluated numerically at it"} want = None if re.search(r"\bsum of (?:all )?(?:the )?(?:possible )?(?:values|solutions|roots)", pr): want, how = sp.nsimplify(sum(sols)), "the sum of the roots" elif re.search(r"\bproduct of (?:all )?(?:the )?(?:possible )?(?:values|solutions|roots)", pr): want, how = sp.nsimplify(sp.Mul(*sols)), "the product of the roots" elif re.search(r"\bhow many (?:real )?(?:solutions|values|roots)", pr): pool = real if "real" in pr else sols want, how = sp.Integer(len(pool)), "the number of roots" elif re.search(r"\b(?:positive|largest|greatest|smallest|least|negative)\b (?:value|solution|root)", pr): cand = real if "positive" in pr: cand = [s for s in cand if s > 0] if "negative" in pr: cand = [s for s in cand if s < 0] if not cand: return None if re.search(r"largest|greatest", pr): want, how = max(cand), "the largest root" elif re.search(r"smallest|least", pr): want, how = min(cand), "the smallest root" elif len(cand) == 1: want, how = cand[0], "the only such root" else: return None elif len(sols) == 1: want, how = sols[0], "the only root" else: return None # several roots and the question does not say which if want is None or not exact(want): return None if how == "the only root": return {"answer": "%s = %s" % (var, latex_answer(want)), "family": "solve", "steps": ["solved $%s$ for $%s$" % (eq, var)], "check": "the root substituted back into the equation"} return {"answer": latex_answer(want), "family": "solve", "steps": ["solved $%s$ for $%s$: roots %s" % (eq, var, ", ".join(sp.latex(s) for s in sols)), how], "check": "every root substituted back into the equation"}
def asked_directly(t, chunk): """the asked expression follows the question words directly ("what is the value of $E$", "find $E$") - nothing such as "the units digit of" / "the remainder when" / "the sum of the digits of" stands between the question and the expression""" i = t.find(chunk) if i < 0: return False before = t[:i].rstrip(" $\\[(").lower() return bool(re.search(r"(?:what is|what's|find|compute|evaluate|calculate|determine|simplify)(?: the (?:exact |numerical )?value of)?\s*$|" r"value of\s*$", before))
def f_functions(text): """one or more functions defined in the problem ("$f(x)=x^3+3$ and $g(x) = 2x^2 + 2x +1$") and an expression of their values asked ("What is $g(f(-2))$?"): innermost calls first; check = the definitions re-evaluated numerically""" t = EXPRESS.sub("", text).strip() if re.search(r"\\begin|cases|\\text\{\s*if|inverse|f\^\{-1\}|\^\{-1\}", t): return None defs, asks = {}, [] for c in maths(t): m = re.fullmatch(r"\s*([a-zA-Z])\s*\(\s*([a-z])\s*\)\s*=\s*(.+)", c, re.S) if m and m.group(1) not in defs: defs[m.group(1)] = (m.group(2), m.group(3)) elif "=" not in c: asks.append(c) else: return None # a bare signature ("The function $f(x)$ is defined by ...") names a defined function; it is not the question asks = [a for a in asks if not re.fullmatch(r"\s*([a-zA-Z])\s*\(\s*[a-z]\s*\)\s*", a) or re.fullmatch(r"\s*([a-zA-Z])", a.strip()[:1]) and a.strip()[0] not in defs] if not defs or len(asks) != 1 or not asked_directly(t, asks[0]): return None lam = {} for name, (var, body) in defs.items(): x = sp.Symbol(var) fx = P(body, [x]) if fx.free_symbols - {x}: return None lam[name] = (x, fx) expr = asks[0] if not re.search(r"(?<![a-zA-Z\\])(?:%s)\s*\(" % "|".join(lam), expr): return None vals = []
def back(s): # value tokens back into TeX for the next read return re.sub(r"Q(\d+)Q", lambda mm: "{(" + sp.latex(vals[int(mm.group(1))]) + ")}", s)
for _ in range(12): m = None for mm in re.finditer(r"(?<![a-zA-Z\\])(%s)\s*\(([^()]*)\)" % "|".join(lam), expr): m = mm break if not m: break x, fx = lam[m.group(1)] arg = P(back(m.group(2))) if arg.free_symbols: return None val = sp.simplify(fx.subs(x, arg)) if not exact(val) or not agree(val, fx.subs(x, arg)): return None vals.append(val) expr = expr[:m.start()] + "Q%dQ" % (len(vals) - 1) + expr[m.end():] if re.search(r"(?<![a-zA-Z\\])(?:%s)\s*\(" % "|".join(lam), expr): return None v = sp.nsimplify(sp.simplify(P(back(expr)))) if not exact(v): return None return {"answer": latex_answer(v), "family": "function", "steps": ["%s(%s) = %s" % (n, d[0], d[1]) for n, d in defs.items()] + ["innermost calls evaluated first"], "check": "each call re-evaluated numerically from its definition"}
PT = re.compile(r"\(\s*(-?\d+(?:\.\d+)?(?:/\d+)?)\s*,\s*(-?\d+(?:\.\d+)?(?:/\d+)?)\s*\)")
def f_coords(text): """two points and one asked quantity: distance, midpoint (or its coordinate sum, or a circle's centre from a diameter), slope, the line's y-intercept point, the area of a square with the two points as adjacent vertices""" t = EXPRESS.sub("", text).strip() pr = prose(t) pts = [(sp.Rational(a), sp.Rational(b)) for c in maths(t) for a, b in PT.findall(c)] if len(pts) != 2 or re.search(r"\b(triangle|three|third|circle with equation|parabola|reflect\w*|rotat\w*|translat\w*)\b", pr): return None (x1, y1), (x2, y2) = pts if re.search(r"\bdistance between\b|\blength of the (?:segment|line segment)\b", pr) and not re.search(r"\bmidpoint\b", pr): d = sp.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) return {"answer": latex_answer(sp.nsimplify(d)), "family": "coords", "steps": ["distance = sqrt((%s)^2 + (%s)^2)" % (x2 - x1, y2 - y1)], "check": "the squared distance equals the sum of squared differences"} mid = ((x1 + x2) / 2, (y1 + y2) / 2) if re.search(r"\bsum of the coordinates of the (?:midpoint|center|centre)\b", pr) and re.search(r"midpoint|endpoints of a diameter|diameter", pr): return {"answer": latex_answer(mid[0] + mid[1]), "family": "coords", "steps": ["midpoint (%s, %s)" % mid], "check": "averaged coordinates"} if re.search(r"\b(?:what is|find) the (?:coordinates of the )?(?:midpoint|center|centre)\b", pr) and \ re.search(r"midpoint|endpoints of a diameter|diameter", pr) and "sum" not in pr and "product" not in pr: return {"answer": "(%s, %s)" % (latex_answer(mid[0]), latex_answer(mid[1])), "family": "coords", "steps": ["average of the endpoints"], "check": "averaged coordinates"} if re.search(r"\bslope of the line\b", pr) and x1 != x2 and not re.search(r"perpendicular|parallel", pr): return {"answer": latex_answer((y2 - y1) / (x2 - x1)), "family": "coords", "steps": ["rise over run"], "check": "both points lie on the line"} if re.search(r"intersect the \$?y\$?-axis|y-intercept", pr) and x1 != x2 and re.search(r"line (?:containing|through|passing)", pr): k = (y2 - y1) / (x2 - x1) b = y1 - k * x1 assert y2 == k * x2 + b ans = "(0, %s)" % latex_answer(b) if re.search(r"point|ordered pair", pr) else latex_answer(b) return {"answer": ans, "family": "coords", "steps": ["slope %s, intercept %s" % (k, b)], "check": "both points satisfy y = mx + b"} if re.search(r"adjacent vertices of a square", pr) and re.search(r"\barea\b", pr): return {"answer": latex_answer((x2 - x1) ** 2 + (y2 - y1) ** 2), "family": "coords", "steps": ["side squared"], "check": "side length squared"} return None
def f_circle(text): t = EXPRESS.sub("", text).strip() pr = prose(t) if not re.search(r"\bcircle\b", pr) or not re.search(r"\b(center|centre|radius)\b", pr): return None eqs = [c for c in maths(t) if "=" in c] if len(eqs) != 1: return None x, y = sp.Symbol("x"), sp.Symbol("y") L, _, R = eqs[0].partition("=") e = sp.expand(P(L, [x, y]) - P(R, [x, y])) p = sp.Poly(e, x, y) A, C2 = p.coeff_monomial(x ** 2), p.coeff_monomial(y ** 2) if A == 0 or A != C2 or p.coeff_monomial(x * y) != 0 or p.total_degree() != 2: return None D, E, F = p.coeff_monomial(x) / A, p.coeff_monomial(y) / A, p.coeff_monomial(1) / A h, k = -D / 2, -E / 2 r2 = h ** 2 + k ** 2 - F if r2 <= 0: return None if re.search(r"\bradius\b", pr) and not re.search(r"\b(center|centre)\b", pr): ans = latex_answer(sp.sqrt(r2)) elif re.search(r"\b(center|centre)\b", pr) and not re.search(r"\bradius\b|\bsum\b|\+", pr): ans = "(%s, %s)" % (latex_answer(h), latex_answer(k)) else: return None assert sp.expand((x - h) ** 2 + (y - k) ** 2 - r2 - e / A) == 0 return {"answer": ans, "family": "circle", "steps": ["completed the square: (x - %s)^2 + (y - %s)^2 = %s" % (h, k, r2)], "check": "the completed form expands back to the given equation"}
def f_extremum(text): t = EXPRESS.sub("", text).strip() pr = prose(t) m = re.search(r"\b(minimum|maximum|smallest|largest|least|greatest) (?:possible )?value of\b", pr) if not m or re.search(r"\b(integer|positive|subject to|where|if|such that|real numbers|constraint)\b", pr): return None ex = [c for c in maths(t) if "=" not in c and not re.fullmatch(r"\s*[a-z]\s*", c)] if len(ex) != 1: return None letters = sorted(set(re.findall(r"(?<![a-zA-Z\\])([a-zA-Z])(?![a-zA-Z])", re.sub(r"\\[a-zA-Z]+", "", ex[0])))) if len(letters) != 1: return None x = sp.Symbol(letters[0]) f = sp.expand(P(ex[0], [x])) p = sp.Poly(f, x) if p.degree() != 2: return None a = p.coeff_monomial(x ** 2) want_min = m.group(1) in ("minimum", "smallest", "least") if (a > 0) != want_min: return None # a downward parabola has no minimum (and vice versa) xv = -p.coeff_monomial(x) / (2 * a) yv = f.subs(x, xv) assert sp.diff(f, x).subs(x, xv) == 0 asks_x = re.search(r"\bwhat value of \$?%s\$? (?:will )?(?:give|gives|produce|yield)" % letters[0], t, re.I) v = xv if asks_x else yv return {"answer": latex_answer(v), "family": "extremum", "steps": ["vertex at %s = %s, value %s" % (letters[0], xv, yv)], "check": "the derivative vanishes at the vertex and the leading coefficient has the right sign"}
def f_coefficient(text): t = EXPRESS.sub("", text).strip() m = re.search(r"coefficient of (?:the )?\$([a-z])\^\{?(\d+)\}?\$(?: term)? in (?:the expansion of )?(?:the product )?\$([^$]+)\$", t, re.I) if not m: m2 = re.search(r"coefficient of (?:the )?\$([a-z])\$(?: term)? in (?:the expansion of )?(?:the product )?\$([^$]+)\$", t, re.I) if not m2: return None var, k, raw = m2.group(1), 1, m2.group(2) else: var, k, raw = m.group(1), int(m.group(2)), m.group(3) letters = sorted(set(re.findall(r"(?<![a-zA-Z\\])([a-zA-Z])(?![a-zA-Z])", re.sub(r"\\[a-zA-Z]+", "", raw)))) syms = [sp.Symbol(c) for c in letters] x = sp.Symbol(var) if x not in syms: return None e = sp.expand(P(raw, syms)) c = sp.Poly(e, x).coeff_monomial(x ** k) if c.free_symbols or not exact(c): return None chk = sp.diff(e, x, k).subs(x, 0) / sp.factorial(k) if sp.simplify(chk - c) != 0: return None return {"answer": latex_answer(c), "family": "coefficient", "steps": ["expanded, read the %s^%d coefficient" % (var, k)], "check": "the k-th derivative at 0 over k! gives the same coefficient"}
def f_function(text): t = EXPRESS.sub("", text).strip() m = re.match(r"(?:if|let|given that|suppose)\s+\$\s*([a-zA-Z])\s*\(\s*([a-z])\s*\)\s*=\s*([^$]+)\$\s*(?:,|\.)?\s*" r"(?:then\s+)?(?:what is|find|compute|evaluate|what is the value of|determine)\s*(?:the value of\s*)?\$([^$]+)\$\s*[?.]?$", t, re.I | re.S) if not m: return None fname, var, body, ask = m.groups() if re.search(r"\\begin|\\text|\\le|\\ge|<|>", body): return None # piecewise definitions are not read here x = sp.Symbol(var) fx = P(body, [x]) if fx.free_symbols - {x}: return None f = sp.Lambda(x, fx) calls = list(re.finditer(re.escape(fname) + r"\s*\(([^()]*)\)", ask)) if not calls: return None expr = ask vals = [] for c in reversed(calls): arg = P(c.group(1)) if arg.free_symbols: return None val = sp.simplify(f(arg)) if not exact(val): return None vals.append(val) expr = expr[:c.start()] + "{(" + sp.latex(val) + ")}" + expr[c.end():] if re.search(r"(?<![a-zA-Z\\])" + re.escape(fname) + r"(?![a-zA-Z])", expr): return None # nested or unparsed calls v = sp.nsimplify(sp.simplify(P(expr))) if not exact(v): return None # check: numeric substitution of the original definition at every call chk =sum(complex(sp.N(fx.subs(x, P(c.group(1))), 50)) for c in calls) if re.fullmatch( r"\s*(?:" + re.escape(fname) + r"\([^()]*\)\s*\+?\s*)+", ask) else None if chk is not None and abs(chk - complex(sp.N(v, 50))) > 1e-30: return None return {"answer": latex_answer(v), "family": "function", "steps": ["%s(%s) = %s" % (fname, var, body), "substituted at each call"], "check": "each call re-evaluated numerically from the definition"}
def _huge(raw): """an exponent that would build an enormous integer (2^{2005}, 3^{3^3}...) - evaluated only modulo something""" for m in re.finditer(r"\^\s*\{?\s*(\d+)", raw): if int(m.group(1)) > 400: return True return bool(re.search(r"\^\s*\{[^}]*\^", raw)) or bool(re.search(r"(\d{3,})\s*!", raw))
def _mod(raw, m): """an integer expression modulo m without building huge integers: sums / products / differences of a^b terms""" s = raw.replace("{,}", "").replace(",", "").replace(" ", "") s = re.sub(r"\\(?:cdot|times)", "*", s) if not re.fullmatch(r"[\d^{}()*+\-]+", s): return None py = re.sub(r"\^\{?(\d+)\}?", r"**\1", s).replace("{", "(").replace("}", ")") if not re.fullmatch(r"[\d()*+\-]+", py): # digits, brackets, + - * and ** only return None try: tree = compile(py, "<mod>", "eval") except SyntaxError: return None import ast
def ev(node): if isinstance(node, ast.Expression): return ev(node.body) if isinstance(node, ast.Constant) and isinstance(node.value, int): return node.value % m if isinstance(node, ast.BinOp): if isinstance(node.op, ast.Pow): if not (isinstance(node.right, ast.Constant) and isinstance(node.left, (ast.Constant, ast.BinOp))): raise ValueError("exponent") return pow(ev(node.left), node.right.value, m) a, b = ev(node.left), ev(node.right) if isinstance(node.op, ast.Add): return (a + b) % m if isinstance(node.op, ast.Sub): return (a - b) % m if isinstance(node.op, ast.Mult): return (a * b) % m if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): return (-ev(node.operand)) % m raise ValueError("form") try: r = ev(ast.parse(py, mode="eval")) except (ValueError, RecursionError): return None # second method: direct reduction when the number is small enough to build if not _huge(raw) and len(py) < 60: try: direct = eval(compile(ast.parse(py, mode="eval"), "<d>", "eval"), {"__builtins__": {}}) % m # noqa: S307 except Exception: # noqa: BLE001 return None if direct != r: return None return r
def f_system(text): """REASONING over several statements: every equation and every function definition in the problem (definitions may carry a parameter: "g(x) = x^2 - k"), function calls expanded, the whole system solved for all unknowns at once, the asked quantity evaluated on every solution. Answered only when the asked quantity has ONE value over all solutions (or the question asks for their sum / product / count / largest / smallest). Check: every solution substituted back into every stated equation.""" t = EXPRESS.sub("", text).strip() pr = prose(t) ms = maths(t) if not ms or re.search(r"\\begin|cases|\\text\{\s*if|\\le|\\ge|<|>|\\ne|\\pm|\\sum|\\prod|\\int|\\lim", t): return None defs, eqs, rest = {}, [], [] for c in ms: m = re.fullmatch(r"\s*([a-zA-Z])\s*\(\s*([a-z])\s*\)\s*=\s*(.+)", c, re.S) if m and m.group(1) not in defs: defs[m.group(1)] = (m.group(2), m.group(3)) elif "=" in c: if c.count("=") != 1: return None eqs.append(c) else: rest.append(c) for c in eqs: m = re.match(r"\s*([a-zA-Z])\s*\(", c) if m and m.group(1) in defs: return None # "h(4x-1) = ..." beside "h(x) = x": h is not plainly defined if len(eqs) + (1 if any(re.search(r"(?<![a-zA-Z\\])[a-zA-Z](?![a-zA-Z(])", re.sub(r"\\[a-zA-Z]+", "", d[1]).replace(d[0], "")) for d in defs.values()) else 0) < 2 and not (defs and eqs): return None # a single statement is f_solve's / f_functions' job # the asked quantity target, mode = None, "value" for c in rest: if asked_directly(t, c) or re.search(r"(?:value|values) of\s*\$?\s*$", t[:t.find(c)].rstrip(" $").lower()[-30:] + " "): target = c if target is None: tm = re.search(r"\b(?:what is|find|compute|determine)\s+\$?([a-zA-Z])\$?\s*[?.]?\s*$|\bvalue of \$([a-zA-Z])\$", t, re.I) if tm: target = tm.group(1) or tm.group(2) if re.search(r"\bsum of (?:all )?(?:the )?(?:possible )?values\b", pr): mode = "sum" elif re.search(r"\bproduct of (?:all )?(?:the )?(?:possible )?values\b", pr): mode = "product" elif re.search(r"\b(?:largest|greatest|maximum) (?:possible )?value\b", pr): mode = "max" elif re.search(r"\b(?:smallest|least|minimum) (?:possible )?value\b", pr): mode = "min" if target is None: return None letters = set() for c in eqs + [target] + [d[1] for d in defs.values()]: letters |= set(re.findall(r"(?<![a-zA-Z\\])([a-zA-Z])(?![a-zA-Z])", re.sub(r"\\[a-zA-Z]+", "", c))) letters -= set(defs) | {"e"} syms = {c: sp.Symbol(c) for c in sorted(letters)} lam = {} for name, (var, body) in defs.items(): bv = sp.Symbol(var) lam[name] = (bv, P(body, list(syms.values()) + [bv]))
def expand_calls(c): for _ in range(10): m = re.search(r"(?<![a-zA-Z\\])(%s)\s*\(([^()]*)\)" % "|".join(lam), c) if lam else None if not m: return c bv, body = lam[m.group(1)] arg = P(m.group(2), list(syms.values())) c = c[:m.start()] + "{(" + sp.latex(body.subs(bv, arg)) + ")}" + c[m.end():] raise Unread("calls too deep")
exprs = [] for c in eqs: L, _, R = expand_calls(c).partition("=") e = sp.together(P(L, list(syms.values())) - P(R, list(syms.values()))) if sp.count_ops(e) > 150: return None exprs.append(e) T = P(expand_calls(target), list(syms.values())) unknowns = sorted(set().union(*[e.free_symbols for e in exprs]) if exprs else set(), key=str) if not unknowns or len(unknowns) > 4 or len(exprs) < len(unknowns): return None for e in exprs: num, _ = sp.fraction(e) try: if sp.Poly(num, *unknowns).total_degree() > 4: return None except sp.PolynomialError: return None sols = sp.solve(exprs, unknowns, dict=True) if not sols: return None if re.search(r"\bpositive\b", pr): sols = [s for s in sols if all(v.is_positive for v in s.values())] if re.search(r"\breal\b", pr) or not re.search(r"\bcomplex\b", pr): sols = [s for s in sols if all(v.is_real for v in s.values())] if re.search(r"\bintegers?\b", pr): sols = [s for s in sols if all(v.is_integer for v in s.values())] if not sols: return None for s in sols: # check: every solution satisfies every stated equation if any(sp.simplify(e.subs(s)) != 0 for e in exprs): return None vals = [] for s in sols: v = sp.nsimplify(sp.simplify(T.subs(s))) if v.free_symbols or not exact(v): return None vals.append(v) distinct = list(dict.fromkeys(vals)) if mode == "sum": v = sp.nsimplify(sum(distinct)) elif mode == "product": v = sp.nsimplify(sp.Mul(*distinct)) elif mode == "max" and all(x.is_real for x in distinct): v = max(distinct) elif mode == "min" and all(x.is_real for x in distinct): v = min(distinct) elif len(distinct) == 1: v = distinct[0] else: return None if not exact(v): return None return {"answer": latex_answer(v), "family": "system", "steps": ["%d statements in %s solved together: %d solution(s)" % (len(exprs), ", ".join(map(str, unknowns)), len(sols)), "asked quantity evaluated on each (%s)" % mode], "check": "every solution substituted back into every stated equation"}
def f_subst(text): """values given for the variables, an expression asked for: "What is the value of $E$ when $x = 4$?", "If $a = 8$, what is the value of $E$?" """ t = EXPRESS.sub("", text).strip() ms = maths(t) assign, targets = {}, [] for c in ms: m = re.fullmatch(r"\s*([a-zA-Z])\s*=\s*([^=]+)", c) if m and not re.search(r"[a-zA-Z]", re.sub(r"\\[a-zA-Z]+", "", m.group(2))): assign[m.group(1)] = P(m.group(2)) elif "=" in c or re.search(r"<|>|\\le|\\ge", c): return None else: targets.append(c) if not assign or len(targets) != 1 or not asked_directly(t, targets[0]): return None if re.search(r"\b(?:solve|all values|for which|such that)\b", prose(t)): return None syms = {k: sp.Symbol(k) for k in assign} E = P(targets[0], list(syms.values())) if not E.free_symbols or E.free_symbols - set(syms.values()): return None sub = {syms[k]: v for k, v in assign.items()} v = sp.nsimplify(sp.simplify(E.subs(sub))) if not exact(v) or not agree(v, E.subs(sub)): v = _recover(E.subs(sub)) if v is None: return None return {"answer": latex_answer(v), "family": "substitute", "steps": ["%s into $%s$" % (", ".join("%s = %s" % (k, sp.latex(w)) for k, w in assign.items()), targets[0])], "check": "the substituted value re-evaluated numerically"}
FOLLOW_ON = re.compile(r"\b(increased|decreased|added to|subtracted|plus|minus|more than|less than|times the|product of|" r"difference|twice|double|half of|then)\b")
def _int(s): s = s.replace(",", "").replace("{,}", "").strip() return int(s) if re.fullmatch(r"-?\d+", s) else None
def _intexpr(raw): v = P(raw) if not (v.is_integer and v.is_number): raise Unread("not an integer") return int(v)
def f_number(text): t = EXPRESS.sub("", text).strip() pr = prose(t) if FOLLOW_ON.search(pr): return None # "the gcd ... increased by 11": a further step it does not read ms = maths(t) if re.search(r"\d\s*!", MATHS.sub(" ", t)) or re.search(r"\bfor example\b|\brelatively prime\b", pr): return None plain_nums = [int(n.replace(",", "")) for n in re.findall(r"(?<![\w.$])(\d[\d,]*)(?![\w.]|\$)", MATHS.sub(" ", t))]
def one_number(): vals = [] for raw in ms: try: vals.append(_intexpr(raw)) except Unread: return None vals += plain_nums return vals[0] if len(vals) == 1 else None
m = re.search(r"how many (?:positive )?(?:whole[- ]number |integer )?(?:positive )?divisors does (?:\$)?([\d,^{}]+)", t, re.I) if m and re.search(r"\bhow many\b", pr) and "divisor" in pr and not re.search(r"\b(odd|even|perfect|square|prime|common)\b", pr): n = one_number() if n and 0 < n < 10 ** 12 and "negative" not in pr: d = sp.divisor_count(n) if n < 10 ** 6: assert d == sum(1 for k in range(1, n + 1) if n % k == 0) return {"answer": str(d), "family": "number", "steps": ["%d = %s" % (n, sp.factorint(n)), "number of divisors"], "check": "the divisor count from the factorization agrees with direct counting" if n < 10 ** 6 else "factorization"} if re.search(r"\bsum of (?:all )?(?:the )?(?:positive )?divisors of\b", pr) and not re.search(r"\b(odd|even|prime|proper)\b", pr): n = one_number() if n and 0 < n < 10 ** 7: s = sp.divisor_sigma(n) assert s == sum(k for k in range(1, n + 1) if n % k == 0) return {"answer": str(s), "family": "number", "steps": ["sum of the divisors of %d" % n], "check": "direct summation"} m = re.search(r"\b(greatest common (?:divisor|factor)|gcd|least common multiple|lcm)\b", pr) if m and re.search(r"\bof\b", pr) and not re.search(r"\b(sum|product|difference|plus|times)\b", pr): vals = [] for raw in ms: try: vals.append(_intexpr(raw)) except Unread: return None vals += plain_nums if 2 <= len(vals) <= 4 and all(v > 0 for v in vals): if "common multiple" in m.group(1) or m.group(1) == "lcm": r = sp.ilcm(*vals) ok = all(r % v == 0 for v in vals) and all(r // p % v != 0 or any((r // p) % w for w in vals) for p in sp.primefactors(r) for v in vals[:1]) return {"answer": str(r), "family": "number", "steps": ["lcm of %s" % vals], "check": "every number divides it, and no smaller multiple works"} r = sp.igcd(*vals) assert all(v % r == 0 for v in vals) and math.gcd(*vals) == r return {"answer": str(r), "family": "number", "steps": ["gcd of %s" % vals], "check": "Euclid's algorithm and division agree"} m = re.search(r"remainder when \$?([^$]+?)\$? is divided by \$?([\d,]+)\$?", t, re.I) if m and not re.search(r"\b(sum of the digits|each|some|a number|an integer|polynomial)\b", pr): b = int(m.group(2).replace(",", "")) r = _mod(m.group(1), b) if r is None or b <= 0: return None return {"answer": str(r), "family": "number", "steps": ["%s mod %d" % (m.group(1), b)], "check": "modular exponentiation and direct reduction agree"} m = re.search(r"\b(?:units|ones) digit of\b", pr) if m and len(ms) == 1: r = _mod(ms[0], 10) if r is None: return None return {"answer": str(r), "family": "number", "steps": ["%s mod 10" % ms[0]], "check": "modular exponentiation and direct reduction agree"} m = re.search(r"\b(largest|greatest|smallest|least) prime (?:factor|divisor) of\b", pr) if m: n = one_number() if n and 1 < n < 10 ** 15: fs = sp.primefactors(n) r = max(fs) if m.group(1) in ("largest", "greatest") else min(fs) assert n % r == 0 and sp.isprime(r) return {"answer": str(r), "family": "number", "steps": ["%d = %s" % (n, sp.factorint(n))], "check": "the factor divides n and is prime"} m = re.search(r"\$?([0-9a-fA-F]+)_\{?(\d+)\}?\$?\s*(?:in|to) base (?:10|ten)\b|express \$?([0-9a-fA-F]+)_\{?(\d+)\}?\$? in base 10", t, re.I) if m and len(re.findall(r"[0-9a-fA-F]+_\{?\d+\}?", t)) == 1: digits, base = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), m.group(4)) base = int(base) if 2 <= base <= 16 and all(int(c, 16) < base for c in digits): r = int(digits, base) assert sum(int(c, 16) * base ** i for i, c in enumerate(reversed(digits))) == r return {"answer": str(r), "family": "number", "steps": ["%s in base %d" % (digits, base)], "check": "positional sum"} m = re.search(r"(?:convert|express|write)\s+\$?(\d+)(?:_\{?10\}?)?\$?\s+(?:to|in) base (\d+)", t, re.I) if m and "decimal" not in pr: n, b = int(m.group(1)), int(m.group(2)) if 2 <= b <= 9 and n >= 0: ds, k = [], n while k: ds.append(str(k % b)) k //= b r = "".join(reversed(ds)) or "0" assert int(r, b) == n return {"answer": "%s_%d" % (r, b), "family": "number", "steps": ["repeated division by %d" % b], "check": "converted back to base 10"} return None
def f_count(text): t = EXPRESS.sub("", text).strip() m = re.fullmatch(r"(?:compute|evaluate|what is|find)\s*\$\\(?:d|t)?binom\{(\d+)\}\{(\d+)\}\$\s*[.?]?", t, re.I) if m: n, k = int(m.group(1)), int(m.group(2)) r = math.comb(n, k) assert r == math.factorial(n) // (math.factorial(k) * math.factorial(n - k)) return {"answer": str(r), "family": "count", "steps": ["C(%d, %d)" % (n, k)], "check": "factorial formula agrees"} m = re.search(r"(?:number of ways to arrange|how many (?:distinct |different )?(?:ways|arrangements)[^.?]*?(?:arrange|of) the letters of the word)\s+\$?\\?(?:text\{)?([A-Z]{2,12})\}?\$?", t) if m and not re.search(r"\b(if|such that|so that|without|must|adjacent|together|vowel|consonant|begin|end|start)\b", prose(t)): w = m.group(1) c = Counter(w) r = math.factorial(len(w)) for v in c.values(): r //= math.factorial(v) if len(w) <= 8: assert r == len(set(itertools.permutations(w))) return {"answer": str(r), "family": "count", "steps": ["%d letters, repeats %s" % (len(w), dict(c))], "check": "multinomial formula" + (" and enumeration agree" if len(w) <= 8 else "")} return None
FAMILIES = (f_count, f_number, f_coefficient, f_circle, f_coords, f_extremum, f_functions, f_function, f_subst, f_solve, f_system, f_evaluate)
def solve(text): text = str(text or "") if "[asy]" in text or len(text) > 700 or re.search(r"\bprove\b|\bshow that\b", text, re.I): return None for fam in FAMILIES: try: r = fam(text) except (Unread, AssertionError, ValueError, TypeError, ZeroDivisionError, RecursionError, AttributeError, NotImplementedError, OverflowError, sp.SympifyError): r = None except Exception: # noqa: BLE001 r = None if r: r["plain"] = _plain(r["answer"]) return r return None
def solve_bounded(text, seconds=4.0): """solve() in a forked child that is killed at the time limit: a slow simplification can never stall a turn""" import json import os import select import signal rfd, wfd = os.pipe() pid = os.fork() if pid == 0: # child os.close(rfd) try: out = json.dumps(solve(text) or {}).encode() except Exception: # noqa: BLE001 out = b"{}" os.write(wfd, out) os.close(wfd) os._exit(0) os.close(wfd) data, deadline = b"", seconds try: while True: ready, _, _ = select.select([rfd], [], [], deadline) if not ready: os.kill(pid, signal.SIGKILL) return None chunk = os.read(rfd, 65536) if not chunk: break data += chunk finally: os.close(rfd) try: os.waitpid(pid, 0) except ChildProcessError: pass try: r = json.loads(data.decode() or "{}") except ValueError: return None return r or None
def _plain(ans): """the answer in linear form (14/3, 11*sqrt(2), x = 5) - what a reader and the gate's equivalence scorer both parse""" try: lhs, eq, rhs = ans.rpartition("=") v = P(rhs if eq else ans) s = sp.sstr(v) return ("%s= %s" % (lhs, s)) if eq else s except Exception: # noqa: BLE001 return ans
def reply(r): plain = r.get("plain") or r["answer"] tex_part = "" if plain.replace(" ", "") == r["answer"].replace(" ", "") else " In TeX: $%s$." % r["answer"] return "The answer is %s.%s %s. Checked: %s." % (plain, tex_part, "; ".join(r["steps"]), r["check"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248"""oracle_compare_op_v1 - the COMPARE operation, acquired from failure records (critical experiment, acquisition 1).
Provenance of this operation: the training window's structured abstentions (TriviaQA / HotpotQA 4800-5199, readerv1.3; stop_records_v1.py) ranked the COMPARE class first among classes no operation covered (87 abstentions, 46 withstore support, 84 stopped at FRAME: the move did not exist). The proposer (a learned model) wrote this module from those87 records only; the sealed windows (5600+) were not seen.
MANIFEST - four operations. Each states what it REQUIRES, what it PRODUCES, and what its CHECK establishes (which isweaker than the proposition; see the paper):
order "Who was born first, A or B?" / "Which game was published first ...?" / "Which breed was bred first ...?" requires two linked entities A, B; for each, a YEAR on its OWN page bound to the question's relation (birth: the "(born ..." / life-span parenthetical; otherwise the first year in a lead sentence that carries the relation verb: published / released / founded / formed / established / bred / built) produces the entity with the earlier year (first / earlier / older), or the later (later / younger / newer) check both years found by the SAME rule; they differ; otherwise abstain count "Which genus contains more species, A or B?" / "Which band had more members ...?" requires for each entity, a number immediately qualifying the asked noun on its own page ("about 70 species") produces the entity with the larger (more / greater) or smaller (fewer / less) number check both numbers found; they differ both_kind "Are A and B both operas?" / "Were X and Y both singers?" requires each entity's own FIRST sentence says it IS a <kind> (head noun ending its phrase) produces "Yes" - never "No": a page that does not say it is a kind is not evidence that it is not one check both is-a statements found shared "A and B were both directed by which person?" requires the question's predicate verb on both pages, and one name that both pages attach to it produces that name check the name's own page shows a person (occupation / life-span); it is not A or BAll four decline anything else. Every answer cites the sentence(s) each entity's page contributed."""from __future__ import annotations
import re
import oracle_cube_reader_v1_4 as R
EARLY = re.compile(r"\b(first|earlier|earliest|older|oldest|sooner)\b", re.I)LATE = re.compile(r"\b(later|latest|younger|youngest|newer|newest|more recent(?:ly)?)\b", re.I)MORE = re.compile(r"\b(?:more|greater|larger|higher number of)\s+([a-z]+)", re.I)FEWER = re.compile(r"\b(?:fewer|less)\s+([a-z]+)", re.I)ORDER_VERBS = {"born": "bear", "published": "publish", "released": "release", "founded": "found", "formed": "form", "established": "establish", "bred": "breed", "built": "build", "created": "create", "made": "make", "developed": "develop", "opened": "open", "introduced": "introduce", "launched": "launch", "written": "write", "composed": "compose", "discovered": "discover", "produced": "produce"}BORN = re.compile(r"\(\s*(?:born|b\.)[^)]*?\b(1[0-9]{3}|20[0-2][0-9])\b|\(\s*(?:c\.\s*)?[^()]{0,30}?\b(1[0-9]{3}|20[0-2][0-9])\s*[–-]")NUM = re.compile(r"\b(\d{1,3}(?:,\d{3})+|\d+)\s+(?:[a-z\-]+\s+)?%s\b")
def _pair(q): """the two compared names: '..., A or B?' / 'between A and B' / 'Are A and B both ...' / 'A and B were both ...'""" s = q.strip().rstrip("?").strip() m = re.search(r"(?:,|:|\bfirst\b|\bearlier\b|\bolder\b|\byounger\b|\bmore [a-z]+\b|\bgreater [a-z]+\b)\s*" r"(?:the\s+)?(.+?),?\s+or\s+(?:the\s+)?(.+)$", s, re.I) if m: # the first side starts after the LAST comma/colon ("literary awards, Annie Dillard"); the second ends at the first # comma ("the Bull Terrier, has its origins ...") a = re.split(r"[,:]\s*", m.group(1))[-1].strip(" ,") a = re.sub(r"^(?:the)\s+", "", a, flags=re.I) b = re.split(r",\s*", m.group(2))[0].strip(" ,") return a, b, "or" m = re.match(r"^(?:in\s+)?what\s+year\s+(?:were|was|did)\s+both\s+(.+?)\s+and\s+(.+?)\s+([a-z]+)$", s, re.I) if m: return m.group(1).strip(" ,"), m.group(2).strip(" ,"), "same_year:" + m.group(3) m = re.match(r"^(.+?)\s+and\s+(.+?)\s+both\s+share\s+what\s+(occupation|profession|job|nationality)$", s, re.I) if m: return m.group(1).strip(" ,"), m.group(2).strip(" ,"), "same_occupation" m = re.match(r"^(?:are|were|is|was)\s+(?:both\s+)?,?\s*(.+?),?\s+and\s+(.+?),?\s+both\b\s*(.*)$", s, re.I) if m: return m.group(1).strip(" ,"), m.group(2).strip(" ,"), "both:" + m.group(3) m = re.match(r"^(?:are|were)\s+both\s*,?\s*(.+?),?\s+and\s+(.+?),?\s+(.+)$", s, re.I) if m: return m.group(1).strip(" ,"), m.group(2).strip(" ,"), "both:" + m.group(3) m = re.match(r"^(.+?)\s+and\s+(.+?)\s+(?:are|were)\s+both\s+(.+)$", s, re.I) if m: return m.group(1).strip(" ,"), m.group(2).strip(" ,"), "shared:" + m.group(3) return None
class CompareOp: def __init__(self, reader=None): self.r = reader or R.CubeReader() self.why = None
def _entity(self, text): """link one side by the longest title n-gram inside it""" toks = R.TOK.findall(text) for n in range(min(7, len(toks)), 0, -1): for i in range(len(toks) - n + 1): t = " ".join(toks[i:i + n]) if n == 1 and len(t) < 4: continue pid = self.r.pid_of(t) if pid: return t, pid return None, None
def _year(self, pid, verb): sents = self.r.page(pid, 6) if verb == "bear": for cid, s in sents[:2]: m = BORN.search(s) if m: return int(m.group(1) or m.group(2)), cid, s return None for cid, s in sents[:4]: words = {R.canon(p) for t in R.TOK.findall(s) for p in [t] + t.split("-")[1:]} if verb in words: ys = R.YEAR.findall(s) if ys: return int(ys[0]), cid, s return None
def _count(self, pid, noun): for cid, s in self.r.page(pid, 8): m = re.search(NUM.pattern % re.escape(noun.rstrip("s")) + r"|" + NUM.pattern % re.escape(noun), s, re.I) if m: v = next(g for g in m.groups() if g) return int(v.replace(",", "")), cid, s return None
def _isa(self, pid, kind, mods=()): first = re.split(r"(?<=[.!?])\s+", self.r.lead(pid), 1)[0] rx = (r"\b(?:is|was|are|were)\s+(?:a|an|the|one of the)\b([^.]{0,90}?)\b%s(?:s|es)?\b" r"(?=\s*(?:[,.;:()]|$)|\s+(?:that|which|who|based|in|of|from|and|or|founded|by|for|with)\b)") % re.escape(kind) m = re.search(rx, first, re.I) if not m: return False, first # every modifier the question puts on the kind must be in the page's own noun phrase: "American film director" # is not satisfied by "a French film director" np_words = set(R.norm(m.group(1)).split()) return all(w in np_words for w in mods), first
def answer(self, q): self.why = None s = " ".join(str(q).split()) if s.startswith('"') and s.endswith('"'): s = s[1:-1].replace('""', '"') p = _pair(s) if not p: self.why = "no compared pair" return None a_txt, b_txt, form = p a, pa = self._entity(a_txt) b, pb = self._entity(b_txt) if not (pa and pb) or pa == pb: self.why = "both sides must link to distinct pages" return None low = s.lower() # ---- order ---- if form == "or" and (EARLY.search(low) or LATE.search(low)): verb = next((v for k, v in ORDER_VERBS.items() if re.search(r"\b%s\b" % k, low)), None) if not verb and re.search(r"\b(older|younger)\b", low) and re.search(r"^who\b", low): verb = "bear" if not verb: self.why = "order question without a known relation verb" return None ya, yb = self._year(pa, verb), self._year(pb, verb) if not (ya and yb) or ya[0] == yb[0]: self.why = "a year is missing or the years tie" return None early = EARLY.search(low) is not None win = (a, ya) if (ya[0] < yb[0]) == early else (b, yb) lose = (b, yb) if win[0] == a else (a, ya) return self._out(win[0], "order", [win[1], lose[1]]) # ---- count ---- m_more, m_few = MORE.search(low), FEWER.search(low) if form == "or" and (m_more or m_few): noun = (m_more or m_few).group(1) if noun in ("than", "often", "popular", "successful", "famous", "likely", "recent"): self.why = "comparison of a quality, not a count" return None ca, cb = self._count(pa, noun), self._count(pb, noun) if not (ca and cb) or ca[0] == cb[0]: self.why = "a count is missing or the counts tie" return None larger = m_more is not None win = (a, ca) if (ca[0] > cb[0]) == larger else (b, cb) lose = (b, cb) if win[0] == a else (a, ca) return self._out(win[0], "count", [win[1], lose[1]]) # ---- both_kind ---- if form.startswith("both:"): rest = form[5:].strip().lower() m = re.match(r"^(?:(?:a|an|the)\s+)?((?:[\w\-]+\s+){0,2}?)([a-z]+?)s?$", rest) kind = m.group(2) if m else None mods = [w for w in R.norm(m.group(1)).split() if w not in R.STOP] if m else [] if not kind or kind in R.STOP: self.why = "no kind to check" return None oka, fa = self._isa(pa, kind, mods) okb, fb = self._isa(pb, kind, mods) if oka and okb: return self._out("Yes", "both_kind", [(None, None, fa), (None, None, fb)], note="both are %ss" % kind) self.why = "not both stated to be a %s (never answered 'no')" % kind return None # ---- same_year: "In what year were both A and B formed?" ---- if form.startswith("same_year:"): verb = ORDER_VERBS.get(form.split(":", 1)[1].lower()) or R.canon(form.split(":", 1)[1]) ya, yb = self._year(pa, verb), self._year(pb, verb) if not (ya and yb) or ya[0] != yb[0]: self.why = "the two years are missing or differ" return None return self._out(str(ya[0]), "same_year", [ya, yb]) # ---- same_occupation: "A and B both share what occupation?" ---- if form == "same_occupation": occ = re.compile(r"\b(?:is|was)\s+(?:a|an)\s+(?:[\w\-]+\s+){0,4}?(%s)s?\b" % R.OCCUPATIONS, re.I) fa = re.split(r"(?<=[.!?])\s+", self.r.lead(pa), 1)[0] fb = re.split(r"(?<=[.!?])\s+", self.r.lead(pb), 1)[0] oa = {m2.group(1).lower() for m2 in occ.finditer(fa)} ob = {m2.group(1).lower() for m2 in occ.finditer(fb)} both = oa & ob if len(both) != 1: self.why = "not exactly one occupation stated by both pages" return None return self._out(both.pop(), "same_occupation", [(None, None, fa), (None, None, fb)]) # ---- shared ---- if form.startswith("shared:"): rest = form[7:].lower() vm = next((v for k, v in ORDER_VERBS.items() if re.search(r"\b%s\b" % k, rest)), None) or \ next((R.canon(t) for t in R.TOK.findall(rest) if R.verbish(t)), None) if not vm: self.why = "no shared relation verb" return None def names(pid): out = {} for cid, s2 in self.r.page(pid, 10): if vm in {R.canon(p) for t in R.TOK.findall(s2) for p in [t] + t.split("-")[1:]}: for mm in R.CAPSPAN.finditer(s2): nm = mm.group(1).strip(" .,;:") if len(nm.split()) >= 2: out.setdefault(R.norm(nm), (nm, cid, s2)) return out na, nb = names(pa), names(pb) common = [k for k in na if k in nb and k not in (R.norm(a), R.norm(b))] persons = [k for k in common if self.r.pid_of(na[k][0]) and R.PERSON_LEAD.search(self.r.lead(self.r.pid_of(na[k][0])))] if len(persons) != 1: self.why = "not exactly one person named by both pages" return None k = persons[0] return self._out(na[k][0], "shared", [(None, na[k][1], na[k][2]), (None, nb[k][1], nb[k][2])]) self.why = "comparison form not covered" return None
@staticmethod def _out(ans, op, ev, note=None): refs = [{"id": e[1], "text": e[2]} for e in ev if e and len(e) == 3 and e[1]] return {"answer": ans, "op": op, "evidence": refs, "note": note, "values": [e[0] for e in ev if e and len(e) == 3], "sentence": " ".join(e[2] for e in ev if e and len(e) == 3)[:600]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160#!/usr/bin/env python3"""PARSE BY ELIMINATION - readings as potentials, ablated against declared bounds.
The worst defect of 2026-08-28 was not a wrong computation. Two independentimplementations of `combinations` both returned 792 for "how many ways to choose 12from 5", which is an impossible question, and they agreed because the PARSE handedboth of them a different and possible problem. Verification cannot reach that.Checking an answer two ways says nothing about whether the question was readcorrectly.
The cause, stated precisely, was an unrecorded choice among readings. The surfaceadmits more than one assignment of its numbers to the operator's arguments, thecode silently collapsed to one by a number-order heuristic, and the choice left notrace, so nothing downstream could question it. Worse, the heuristic reached forthe reading that still computed, which is exactly backwards: the ability to producean answer was doing the work that evidence should have done.
Ben's reading of this, and it is a better one than mine: parsing is representationablated against its potentials. That makes it the same move as everything else hererather than a special problem. The candidate readings are the potentials. Thesurface cues and the operator's own declared fragment are the ablations. Whatsurvives is the parse.
one survivor that is the reading, and the eliminations are its warrant many survivors genuine ambiguity, DETECTED rather than silently resolved zero survivors decline, naming the constraint that killed the last one
It needs no second method. Unlike the fn/ref pairing, elimination certifies itself:the trace shows what died and what killed it, and a reader can check that.
Note what does most of the work. The operator's DECLARED BOUNDS are the strongesteliminator, stronger than any syntactic cue, because a fragment that knows what itcannot do can rule out readings on that basis alone. The discipline of making everyoperator state its own frontier, which was built for honest refusal, turns out tobe the thing that makes parsing decidable. That was not the intention."""
from __future__ import annotations
import re
from oracle_operator_specs_v1 import NotOurs, OutOfFragment
class Ambiguous(OutOfFragment): """More than one reading survived. Say so; do not pick a favourite.
Subclasses OutOfFragment so the existing host declines on it with no change to the host at all, which is the point: this is a spec-level discipline and it fits the machinery that is already there. """
class Reading: """One candidate assignment of a surface to an operator's arguments."""
__slots__ = ('args', 'because', 'killed_by', 'eliminated')
def __init__(self, args, because): self.args = args self.because = because self.killed_by = None self.eliminated = []
def __repr__(self): state = 'killed by %s' % self.killed_by if self.killed_by else 'survives' return '<%s | %s | %s>' % (self.args, self.because, state)
def eliminate(readings, constraints, nothing_here='no reading of that at all'): """Ablate the potentials. Returns the single survivor or raises with the reason.
`constraints` is a list of (name, predicate). A reading is killed by the FIRST constraint it fails, and which one is recorded, because "declined" without a reason is the thing this project refuses everywhere else. """ if not readings: raise NotOurs(nothing_here)
for r in readings: for name, ok in constraints: try: passed = ok(r.args) except Exception: # noqa: BLE001 passed = False if not passed: r.killed_by = name break
alive = [r for r in readings if r.killed_by is None]
if len(alive) == 1: # carry the whole ablation, not just the winner. A reading that survived is # only warranted by what died beside it, and an answer that shows the # survivor without the eliminations is asking to be trusted again. alive[0].eliminated = [(r.because, r.killed_by) for r in readings if r.killed_by] return alive[0]
if not alive: # every reading died; report the one that got furthest, since its # constraint is the frontier the question actually ran into last = readings[-1] raise OutOfFragment(last.killed_by or 'no reading survived')
raise Ambiguous( 'that has %d readings I cannot choose between (%s) and nothing in the ' 'sentence or in my own limits rules any of them out' % (len(alive), '; '.join(r.because for r in alive[:3])))
# ── readings for the operator that actually failed ───────────────────────────_FROM = re.compile(r'(\d+)\s+(?:things?\s+|items?\s+)?(?:from|out of|of)\s+(\d+)', re.I)_CHOOSE_IDIOM = re.compile(r'(\d+)\s*(?:choose|c)\s*(\d+)', re.I)_NUM = re.compile(r'\d+')
def combination_readings(surface): """Every assignment the surface licenses, each with the cue that licenses it.""" out = [] m = _CHOOSE_IDIOM.search(surface) if m: out.append(Reading({'n': int(m.group(1)), 'k': int(m.group(2))}, 'the "n choose k" idiom puts the total first')) return out # the idiom is unambiguous; nothing else
m = _FROM.search(surface) if m: out.append(Reading({'k': int(m.group(1)), 'n': int(m.group(2))}, '"%s from %s" takes the smaller count first' % (m.group(1), m.group(2)))) return out # "from" fixes the order; do not guess past it
ns = [int(x) for x in _NUM.findall(surface)] if len(ns) >= 2: a, b = ns[0], ns[1] out.append(Reading({'n': a, 'k': b}, 'first number as the total')) out.append(Reading({'n': b, 'k': a}, 'second number as the total')) return out
def parse_combinations(surface): """Enumerate, ablate, and return the survivor with its warrant.""" want = ('perm' if re.search(r'\bpermutation|arrangement|order matters\b', surface, re.I) else 'comb') readings = combination_readings(surface) survivor = eliminate( readings, [('you cannot choose more things than there are', lambda a: a['k'] <= a['n']), ('I keep this exact and that is past where I will', lambda a: a['n'] <= 400), ('counts have to be whole and not negative', lambda a: a['k'] >= 0 and a['n'] >= 0)], nothing_here='no pair of counts here') args = dict(survivor.args) args['want'] = want args['_reading'] = survivor.because args['_eliminated'] = list(getattr(survivor, 'eliminated', [])) return args123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173#!/usr/bin/env python3"""Runtime AN - emit the LiminalTransition for every turn (additive over AM).
Spec v3 s3 defines it and nothing built it. Without it the space between an input and itsanswer is narratable but not measurable, and spec v3 B3 forbids narration as evidence.
Every turn now records, as an execution artefact:
in_surface the raw input in_form the typed reading the system recovered (or None - itself a finding) operator the route that carried the turn alternatives matchers that were tried and declined, with why carried what was taken from the prior turn (session state actually used) out_status answered | withheld | clarification residual what the turn did not account for cost_ms wall time
The geometric content is the RELATION between in_form and out_form, recorded per step. Aconversation is then a path: turns are steps, and continuity is whether consecutive stepsshare structure. A sequence of individually-correct answers with no continuity is not aconversation, and that distinction is only visible once the relation is written down.
Authority: emits records; changes no answer. AN.chat returns exactly what AM.chat returns."""
from __future__ import annotations
import reimport timefrom collections import deque
from oracle_release_runtime_am import OracleReleaseRuntimeAM
CITE = re.compile(r"\[[a-z0-9_]+:?[a-z0-9_.\-]*\]")CONTENT = re.compile(r"[a-z][a-z'\-]{3,}")STOP = {"what", "when", "where", "which", "does", "did", "the", "a", "an", "is", "are", "was", "were", "how", "why", "who", "that", "this", "with", "from", "about", "tell", "more", "you", "your", "can", "could", "would", "there", "their", "them"}
def content_terms(text: str) -> set: return {w for w in CONTENT.findall(str(text).lower()) if w not in STOP}
class OracleReleaseRuntimeAN(OracleReleaseRuntimeAM): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.transitions: dict = {} self._pending_conversion: dict = {}
def _probe_matchers(self, text: str) -> list: """Which typed readings were available but not taken. A route that could have matched and did not is part of the shape of the decision, not noise.""" out = [] try: if self._parse_kind(text) is not None: out.append("kind_question") except Exception: # noqa: BLE001 pass low = " ".join(str(text).lower().split()) for name, pat in (("provenance_request", r"^(why|how do you know|source|prove)"), ("continuation", r"^(tell me more|more|what else|go on|continue)"), ("acknowledgement", r"^(thanks|thank you|ok|okay|got it|great)"), ("summarise", r"^summari[sz]e "), ("definition", r"^what is "), ("causal", r"^what causes "), ("temporal", r"^when (did|was)")): if re.match(pat, low): out.append(name) return out
@staticmethod def _verified_conversion(result: dict, prior: dict) -> bool: """A conversion counts for continuity only if the rewritten form actually carries a term the prior turn produced. A self-reported 'conversion' flag with no such term is not continuity - a mutant claiming a conversion on every turn scored 209/209 before this check existed.""" conv = result.get("conversion") if not isinstance(conv, dict): conv = prior.get("_pending_conversion") if isinstance(prior, dict) else None if not isinstance(conv, dict): return False to_terms = content_terms(conv.get("to", "")) from_terms = content_terms(conv.get("from", "")) prior_terms = set(prior.get("out_terms", set())) | set(prior.get("in_terms", [])) # the rewrite must INTRODUCE a prior-turn term the original surface lacked return bool((to_terms - from_terms) & prior_terms)
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() prior = self.transitions.get(session_id) prior_terms = prior["out_terms"] if prior else set() # a subclass may declare a conversion BEFORE dispatch (AN records the transition # inside this call, before the subclass can attach anything to the result) pending = getattr(self, "_pending_conversion", {}).pop(session_id, None) result = super().chat(text, session_id) if pending and "conversion" not in result: result["conversion"] = pending in_terms = content_terms(text) out_terms = content_terms(result.get("response", "")) status = str(result.get("status", "")) carried = sorted(in_terms & prior_terms) if prior else [] # the RELATION between input and output, per step grounded = sorted(in_terms & out_terms) introduced = sorted(out_terms - in_terms - prior_terms) unaccounted = sorted(in_terms - out_terms - set(carried)) # GROUNDING must not be satisfiable by ECHO. An input term counts as grounded only # if it appears inside a CITED span - so repeating the question scores zero, and # padding with topic words scores zero, because neither is cited. This ties the # metric to warrant, which is the property the system actually has. # the CLAIM a citation supports is the text preceding it since the previous # citation. Taking from the last period instead captured only the citation token, # so cited terms were ID fragments and grounding floored at zero for every # substantive turn. cited_spans = [] resp = str(result.get("response", "")) cursor = 0 for m in CITE.finditer(resp): cited_spans.append(resp[cursor:m.start()].lower()) cursor = m.end() cited_terms = set() for span in cited_spans: cited_terms |= content_terms(span) grounded_cited = sorted(in_terms & cited_terms) rec = { "turn": (prior["turn"] + 1) if prior else 1, "in_surface": str(text)[:120], "in_form": self._probe_matchers(text) or None, "operator": result.get("path"), "out_status": status, "in_terms": sorted(in_terms), "out_terms": sorted(out_terms)[:24], "relation": { "grounded": grounded, # raw overlap (GAMEABLE by echo - reported, not scored) "grounded_cited": grounded_cited, # input terms addressed INSIDE a citation "introduced": introduced[:16], # what the answer brought that was not asked "unaccounted": unaccounted, # input terms the answer never touched }, "carried_from_prior": carried, "continuity_lexical": bool(carried) or bool(prior and (out_terms & prior_terms)), # continuity = the turn STRUCTURALLY used prior state. Two ways that can happen: # an act route consumed it, OR a conversion resolved a reference against it. # The first version counted only act routes, so a resolved anaphor answered by # a knowledge route scored ZERO continuity - penalising the exact behaviour # continuity exists to reward. (Fold candidate AO, rejected 3x at 124/153.) # act:clarify is a REFUSAL to continue, not a continuation. The baseline was # scoring "I didn't parse that" as continuity, so a candidate that ANSWERED the # same turn lost the point for doing strictly better. Third instrument defect # surfaced by the AO candidate; it was the one holding the admission. "continuity": bool(prior) and bool( self.dialogue.get(session_id, {}).get("last_result")) and ( (str(result.get("path", "")).startswith("act:") and str(result.get("path", "")) != "act:clarify") or self._verified_conversion(result, prior)), "citations": len(CITE.findall(str(result.get("response", "")))), "residual": (None if status == "answered" else {"class": "no_typed_reading" if not self._probe_matchers(text) else "reading_found_no_operator_answered", "unaccounted": unaccounted}), "cost_ms": round(1000.0 * (time.perf_counter() - started), 1), } if isinstance(result.get("conversion"), dict): rec["conversion"] = result["conversion"] rec["out_terms_set"] = out_terms self.transitions[session_id] = {**rec, "out_terms": out_terms} hist = getattr(self, "_paths", None) if hist is None: hist = self._paths = {} hist.setdefault(session_id, deque(maxlen=64)).append( {k: v for k, v in rec.items() if k != "out_terms_set"}) return result
def path(self, session_id: str = "default") -> list: return list(getattr(self, "_paths", {}).get(session_id, []))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970#!/usr/bin/env python3"""Front-door successor B: adds the benchmark-induced corpus-query route.
Additive subclass of oracle_release_runtime (not edited). Loads ONLY rulesadmitted by the induction ledger (multi-donor + evidence gates). The routefires between commonsense and the document fallback; every answer is aprovenance-addressed sentence."""
from __future__ import annotations
import json
from oracle_release_runtime import OracleReleaseRuntime, PHASEfrom stage5m13e7_benchfold_induction_v1 import RULES, DBpediaQuery, apply_rule
class OracleReleaseRuntimeB(OracleReleaseRuntime): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ledger = json.loads((PHASE / "stage5m13e7_benchfold_rule_ledger_v1.json").read_text(encoding="utf-8")) admitted = {r["rule"] for r in ledger["rules"] if r["admitted"]} self.bench_rules = [(rid, pat) for rid, pat, _ in RULES if rid in admitted] self.bench_query = DBpediaQuery()
def _benchmark_turn(self, text: str) -> dict | None: stripped = text.rstrip("?.! ").strip() for rule_id, pattern in self.bench_rules: match = pattern.match(stripped + "?") or pattern.match(stripped) if not match: continue result = apply_rule(self.bench_query, rule_id, match) if result is None: return {"status": "withheld", "path": f"corpus_query:{rule_id}", "response": "No provenance-admitted sentence in the abstracts corpus answers that.", "provenance": {"kind": "dbpedia_query", "rule": rule_id}} claim_id, fact = result return {"status": "answered", "path": f"corpus_query:{rule_id}", "response": fact, "provenance": {"kind": "dbpedia_query", "rule": rule_id, "claim_id": claim_id}} return None
def chat(self, text: str, session_id: str = "default") -> dict: import time started = time.perf_counter() normalized = " ".join(text.strip().split()) result = None try: result = self._relational_turn(normalized, session_id) except Exception: # noqa: BLE001 result = None if result is None: commonsense = self.commonsense.answer(normalized) if commonsense["status"] in ("answered", "withheld"): result = {"status": commonsense["status"], "path": "conceptnet_commonsense", "response": commonsense["response"], "provenance": {"kind": "conceptnet_edges", "claims": commonsense.get("claims", [])}} if result is None: result = self._benchmark_turn(normalized) if result is None: value = self.documents.chat(normalized, session_id=f"doc-{session_id}") result = {"status": value.get("status", "unresolved"), "path": "document_runtime", "response": str(value.get("response", "")), "provenance": {"kind": "m13d2_envelope", "operation": value.get("operation"), "retrieval": value.get("retrieval")}} result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185#!/usr/bin/env python3"""Front-door successor D: anchor-resident addressing + user corpus ingestion.
1. AnchorStore — the address layer (normalized title -> page id, page id -> title) loaded RAM-resident at startup. Every anchored operation becomes a dictionary hit: microseconds, flat in corpus size. Open FTS search survives only as the explicitly bounded typed operation (54 ms worst case); the unbounded searcher is retired from the front door.2. Anchored-summary route — "Tell me about X" resolves X against the address layer and composes a gated paragraph (provenance + relevance gate + derived analysis) instead of falling into conjunctive search.3. User corpus — individuals add documents (session-scoped): sentences pass the SAME admission filters as the public corpus, receive user-document addresses (user:{session}:{doc}:{ordinal}, content-hashed), and are consulted FIRST by the definitional and summary routes with provenance kind "user_document". Teaching the model a document is admission, not training — instant, inspectable, deletable."""
from __future__ import annotations
import hashlibimport jsonimport reimport timefrom pathlib import Path
from oracle_release_runtime import PHASEfrom oracle_release_runtime_c import OracleReleaseRuntimeCfrom stage5m13e8_paragraph_compiler_v3 import compile_gated_paragraphfrom stage5m13e8_paragraph_compiler_v2 import recover_program_v2from stage5m13e8_relevance_gate_v1 import _norm
ABOUT = re.compile(r"^(?:tell me about|who is|who was|what do you know about) (?:the )?(?P<t>.+?)[.?!]?$", re.I)SENTENCE_SPLIT = re.compile(r"(?<=[.!?])\s+")
def admitted_sentences(text: str, cap: int = 40) -> list[str]: out = [] for raw in SENTENCE_SPLIT.split(" ".join(text.split())): s = raw.strip() w = s.split() if not (4 <= len(w) <= 60): continue if any(m in s for m in ("{", "}", "<", ">", "http")): continue if not (s[0].isupper() or s[0].isdigit()): continue if not s.endswith((".", "!", "?")): continue out.append(s) if len(out) >= cap: break return out
class AnchorStore: """RAM-resident address layer over the active wikipedia build."""
def __init__(self, connection): self.title_to_page: dict[str, str] = {} self.page_to_title: dict[str, str] = {} started = time.perf_counter() for norm, pid in connection.execute("SELECT normalized_title, page_id FROM title_alias"): self.title_to_page.setdefault(norm, pid) for pid, title in connection.execute("SELECT page_id, title FROM article"): self.page_to_title[pid] = title self.load_seconds = round(time.perf_counter() - started, 2)
def resolve(self, phrase: str) -> str | None: return self.title_to_page.get(_norm(phrase))
class UserCorpus: """Session-scoped, admission-filtered, content-addressed user documents.""" MAX_DOCS, MAX_CHARS = 20, 200_000
def __init__(self, root: Path): self.root = root self.root.mkdir(parents=True, exist_ok=True)
def _path(self, session: str) -> Path: safe = re.sub(r"[^\w.-]", "_", session)[:60] return self.root / f"user_corpus_{safe}.json"
def load(self, session: str) -> dict: p = self._path(session) return json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"docs": {}}
GLOBAL_CAP_BYTES = 500_000_000
def ingest(self, session: str, title: str, text: str) -> dict: title = " ".join(title.split())[:120] or "untitled" text = text[: self.MAX_CHARS] total = sum(f.stat().st_size for f in self.root.glob("user_corpus_*.json")) if total > self.GLOBAL_CAP_BYTES: return {"status": "withheld", "reason": "global user-corpus capacity reached"} store = self.load(session) if len(store["docs"]) >= self.MAX_DOCS and title not in store["docs"]: return {"status": "withheld", "reason": "session document limit reached"} sentences = admitted_sentences(text) if not sentences: return {"status": "withheld", "reason": "no sentences passed admission (4-60 words, clean, terminated)"} claims = [] for i, s in enumerate(sentences): # hash-first id: unique within the compiler's 20-char address window claims.append({"claim_id": f"user:{hashlib.sha256(s.encode()).hexdigest()[:12]}:{i}", "sentence": s}) store["docs"][title] = {"claims": claims, "sha256": hashlib.sha256(text.encode()).hexdigest(), "chars": len(text)} self._path(session).write_text(json.dumps(store, ensure_ascii=False), encoding="utf-8") return {"status": "admitted", "title": title, "admitted_sentences": len(claims), "rejected_note": "sentences failing admission were excluded, not repaired"}
def bundle(self, session: str, topic: str) -> list[dict]: store = self.load(session) t = _norm(topic) out = [] for title, doc in store["docs"].items(): title_hit = t and t in _norm(title) for c in doc["claims"]: if title_hit or (t and t in _norm(c["sentence"])): out.append({"claim_id": c["claim_id"], "page": f"your document '{title}'", "sentence": c["sentence"]}) return out[:12]
class OracleReleaseRuntimeD(OracleReleaseRuntimeC): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.anchors = AnchorStore(self.bench_query.connection) self.user_corpus = UserCorpus(Path(self.state_root) / "user_corpora")
# anchor-resident overrides (dictionary hits, no b-tree walk) def _bundle(self, topic: str, n: int = 6) -> list[dict]: page = self.anchors.resolve(topic) if not page: return [] title = self.anchors.page_to_title.get(page, topic) return [{"claim_id": c, "page": title, "sentence": s} for c, s in self.bench_query.page_sentences(page)[:n]]
def _anchored_summary(self, text: str, session_id: str) -> dict | None: match = ABOUT.match(text.strip()) if not match: return None topic = match.group("t").strip() # user claims are pre-scoped by the user's own document titles and # BYPASS the topic-relevance gate (which would reject short-token # titles as lexical overlap); public claims remain fully gated. from stage5m13e8_relevance_gate_v1 import gate_bundle from stage5m13e8_paragraph_compiler_v2 import compile_paragraph_v2 user_claims = self.user_corpus.bundle(session_id, topic) admitted_public, excluded = gate_bundle(topic, self._bundle(topic, n=6)) claims = user_claims + admitted_public if not claims: return None paragraph, program = compile_paragraph_v2( topic, claims, evidence=3, aggregation_term=None) if paragraph is None or not recover_program_v2(paragraph, program): return None return {"status": "answered", "path": "anchored_summary", "response": paragraph, "provenance": {"kind": "gated_paragraph", "user_claims": len(user_claims), "public_claims": len(admitted_public), "excluded": [{"page": e["page"], "relevance": e["relevance"]} for e in excluded]}}
def ingest_document(self, session_id: str, title: str, text: str) -> dict: return self.user_corpus.ingest(session_id, title, text)
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() normalized = " ".join(text.strip().split()) result = None try: result = self._anchored_summary(normalized, session_id) except Exception: # noqa: BLE001 result = None if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} return result return super().chat(text, session_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#!/usr/bin/env python3"""Runtime L — capability cycle 7: what-if hypothetical worlds (additive over K).The response lives in an explicitly-marked HYPOTHESIS scope: attested factscarry provenance; the hypothetical consequence carries premises and is neverrendered as an actual-world assertion (M13e4 world-scope discipline surfacedinto conversation)."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_k import OracleReleaseRuntimeK
WHATIF = re.compile( r"^(?:please tell me )?what (?:if|would happen if) (?:a |an |the )?(?P<x>[\w '-]+?) had no (?P<y>[\w '-]+?)[.?!]?$", re.I)
class OracleReleaseRuntimeL(OracleReleaseRuntimeK): def _whatif_turn(self, text: str, session_id: str) -> dict | None: match = WHATIF.match(text.strip()) if not match: return None x = match.group("x").strip().lower() y = match.group("y").strip().lower() y_singular = y[:-1] if y.endswith("s") and not y.endswith("ss") else y has_edges = [e for e in self.commonsense.edges(x, "HasA", limit=6) if y in e["end"].lower() or y_singular in e["end"].lower()] if not has_edges: return {"status": "withheld", "path": "capability:what_if", "response": f"I cannot ground that hypothetical: no admitted evidence attests " f"that a {x} has {y}.", "provenance": {"kind": "hypothetical_world", "unattested": f"{x} HasA {y}"}} base = has_edges[0] uses = self.commonsense.edges(y_singular, "UsedFor", limit=3) or \ self.commonsense.edges(x, "UsedFor", limit=3) attested = (f"Attested: {self.commonsense.render_edge(base)} [{base['provenance']}]") use_part = "" premises = [base["provenance"]] if uses: use = uses[0] use_part = f" Attested: {self.commonsense.render_edge(use)} [{use['provenance']}]" premises.append(use["provenance"]) hypo = (f" HYPOTHESIS (hypothetical world, not asserted of the actual world): " f"a {x} without {y} would lack what the admitted record attributes to it" + (f" — in particular the attested use of {uses[0]['start']}" if uses else "") + f". [derived:hypothetical_severance<-{','.join(p[:24] for p in premises)}]") return {"status": "answered", "path": "capability:what_if", "response": attested + use_part + hypo, "provenance": {"kind": "hypothetical_world", "x": x, "y": y, "derived": {"rule": "hypothetical_severance", "premises": premises}, "world": "hypothetical"}}
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() normalized = " ".join(text.strip().split()) result = None try: result = self._whatif_turn(normalized, session_id) except Exception: # noqa: BLE001 result = None if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} state = self.dialogue.setdefault(session_id, {}) state["last_result"] = {k: result.get(k) for k in ("path", "provenance", "status")} return result return super().chat(text, session_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123#!/usr/bin/env python3"""Runtime W — robust implied-knowledge turn (additive over V).
Same capability as V (transitive kind), two robustness upgrades: * reasoner v2 (sense-dominance pruning; recovers true chains v1 blocked); * a widened, normalized parser that accepts many more natural phrasings ("Are dogs animals?", "Is the robin really a bird?", "Do you think a beagle is an animal?", "a kind/type/sort of").Still: cite direct edge, derive a shown chain, or abstain honestly."""
from __future__ import annotations
import reimport time
from oracle_release_runtime_v import OracleReleaseRuntimeVfrom stage5m21_transitive_reasoner_v2 import _norm, chain_isa, direct_isa, render_chain
# strip conversational filler before matching_FILLER = re.compile( r"\b(?:do you think|would you say|is it true that|is it the case that|" r"really|actually|even|still|also|just|by any chance|technically|" r"essentially|basically)\b", re.I)_LEAD = re.compile(r"^(?:so|well|hey|um|please|tell me|i wonder|question:)[\s,]+", re.I)# an embedded-question frame ("do you think X is Y") — only these license the# declarative pattern, so plain statements ("The Moon is a planet.") are NOT# hijacked from the summarize/definitional routes._EMBEDDED = re.compile(r"\b(?:do you think|would you say|is it true that|is it the case that)\b", re.I)
# A genuine kind-question needs a determiner before the predicate nominal# ("is a beagle AN animal") or bare-plural agreement ("are dogs animals"); this# keeps predicate-adjective / comparison questions ("is the Moon bigger than# Mars?") from being read as IsA queries._DETP = r"(?:an?|the|some|(?:an?\s+)?(?:kind|type|sort)\s+of)"# singular: "is <det>? X <det> Y ?"ISA_Q_SING = re.compile( rf"^is\s+(?:{_DETP}\s+)?(?P<x>[a-z][a-z '\-]*?)\s+{_DETP}\s+(?P<y>[a-z][a-z '\-]*?)\s*[.?!]*$", re.I)# plural: "are Xs Ys ?" (both bare plurals)ISA_Q_PLUR = re.compile( r"^are\s+(?P<x>[a-z][a-z'\-]*?s)\s+(?P<y>[a-z][a-z'\-]*?s)\s*[.?!]*$", re.I)# declarative, embedded-question only: "<det>? X is <det> Y"ISA_DECL = re.compile( rf"^(?:{_DETP}\s+)?(?P<x>[a-z][a-z '\-]*?)\s+(?:is|are)\s+{_DETP}\s+(?P<y>[a-z][a-z '\-]*?)\s*[.?!]*$", re.I)_DET = re.compile(r"^(?:an?|the|some)\s+(?:(?:kind|type|sort)\s+of\s+)?|^(?:kind|type|sort)\s+of\s+", re.I)
_STOP_Y = {"thing", "one", "example", "sort", "kind", "type", "it", "that", "this"}_REL_WORDS = re.compile(r"\b(?:than|more|less|bigger|smaller|larger|faster|slower|" r"better|worse|taller|shorter|older|younger|same)\b", re.I)
def _peel(span: str) -> str: prev = None s = span.strip().lower() while s != prev: # repeatedly strip stacked determiners ("a kind of a ...") prev = s s = _DET.sub("", s).strip() return s
class OracleReleaseRuntimeW(OracleReleaseRuntimeV): def _normalize_isa(self, text: str) -> str: t = " ".join(text.strip().split()) t = _LEAD.sub("", t) t = _FILLER.sub("", t) return " ".join(t.split())
def _implied_isa_turn(self, text: str) -> dict | None: # override V normalized = self._normalize_isa(text) if _REL_WORDS.search(normalized): # comparison, not a kind-question return None match = ISA_Q_SING.match(normalized) or ISA_Q_PLUR.match(normalized) if match is None and _EMBEDDED.search(text): match = ISA_DECL.match(normalized) if not match: return None x = _peel(match.group("x")) y = _peel(match.group("y")) if (not x or not y or x == y or len(x) < 2 or len(y) < 2 or y in _STOP_Y or x in _STOP_Y or x.split()[-1] == _norm(y)): return None cs = self.commonsense
direct = direct_isa(cs, x, y) if direct is not None: return {"status": "answered", "path": "conceptnet_isa_direct", "response": f"Yes — the admitted record states it directly: " f"{cs.render_edge(direct)} [{direct['provenance']}]", "provenance": {"kind": "commonsense_edge", "relation": "IsA", "premises": [direct["provenance"]]}}
path = chain_isa(cs, x, y) if path is not None: steps = render_chain(cs, path) premises = [edge["provenance"] for edge in path] tag = "[derived:transitive_isa<-" + ",".join(p[:24] for p in premises) + "]" ax = "an" if x[:1] in "aeiou" else "a" ay = "an" if y[:1] in "aeiou" else "a" return {"status": "answered", "path": "conceptnet_isa_derived", "response": f"By the admitted record, in steps: {steps}. Therefore, if " f"kind is transitive, {ax} {x} is {ay} {y}. {tag}", "provenance": {"kind": "derived", "rule": "transitive_isa", "hops": len(path), "premises": premises}}
ax = "an" if x[:1] in "aeiou" else "a" ay = "an" if y[:1] in "aeiou" else "a" return {"status": "withheld", "path": "conceptnet_isa_derived", "response": f"The admitted record does not establish that {ax} {x} is " f"{ay} {y}, directly or by a chain of kind within 3 steps.", "provenance": {"kind": "derived", "rule": "transitive_isa", "result": "no_chain"}}
def chat(self, text: str, session_id: str = "default") -> dict: started = time.perf_counter() result = None try: result = self._implied_isa_turn(text) except Exception: # noqa: BLE001 result = None if result is not None: result["latency_ms"] = round(1000.0 * (time.perf_counter() - started), 1) result["zero_model_gate"] = {"lm_calls": 0, "transformer_calls": 0} return result # skip V's _implied_isa_turn (we overrode it); go straight to U's chain return super(OracleReleaseRuntimeV, self).chat(text, session_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115#!/usr/bin/env python3"""oracle_release_runtime_w56 - CORRECTNESS RELEASE: a deduction fold that lets go.
Found by testing the live endpoint rather than the panel, which is the only placeit could have been found. Every panel item states its premises and asks itsquestion in one surface, so the fold was never observed holding premises across aCHANGE OF SUBJECT. A real visitor does that constantly.
The defect: once any premise was on the table, the deduction route claimed therest of the conversation. Ask it a syllogism and then "What is a volcano?" and itanswered "that does not follow from what I was given", because a stored universalplus a question-shaped surface was enough for it to act. "Write a python functionthat reverses a string" was quietly filed as a premise. From the outside this isindistinguishable from the machine breaking, and it is very close to the misfirea user reported on the live site.
The cause is a missing relevance condition. A deduction engine is only entitled tospeak about the premises on the table, and nothing in the fold said so.
The rule this adds, in three parts:
a surface that states new premises is always the fold's business "what follows" is always the fold's business otherwise the fold may act only on a yes/no question whose content words actually appear in the stored premises
A question that fails all three is not merely declined, it is handled as thoughthe fold were not there: the premise store is set aside for the duration of theturn, so the rest of the chain answers exactly as it did before the fold existed,and the premises are restored afterwards for when the subject comes back.
Definitional questions ("what is a server") are excluded even when they overlapthe premises, because "what is X" is a question about the world and the corpusroute owns it. Deduction answers yes-or-no and what-follows, nothing else.
Hand-authored 2026-08-28. Judged by the gate."""
from __future__ import annotations
import re
from oracle_release_runtime_w55 import OracleReleaseRuntimeW55from oracle_release_runtime_w54 import _ASK_FOLLOW, _HAS_PREMISE, _QUES, _SPLIT
# only these openings are deduction questions. "what is X" is the corpus route's._YESNO = re.compile( r'^(?:is|are|was|were|does|do|did|can|could|would|will|has|have|must)\b', re.I)_STOP = { 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am', 'all', 'every', 'each', 'no', 'not', 'if', 'then', 'or', 'and', 'but', 'either', 'neither', 'does', 'do', 'did', 'can', 'could', 'would', 'will', 'what', 'which', 'who', 'whom', 'when', 'where', 'why', 'how', 'follows', 'of', 'to', 'in', 'on', 'at', 'by', 'for', 'from', 'with', 'as', 'that', 'this', 'these', 'those', 'it', 'its', 'there', 'here', 'so', 'therefore', 'have', 'has', 'had', 'some', 'any', 'me', 'you', 'we', 'they', 'i',}_WORD = re.compile(r'[a-z0-9]+')
def _content(text): return {w for w in _WORD.findall(str(text).lower()) if w not in _STOP and len(w) > 1}
class OracleReleaseRuntimeW56(OracleReleaseRuntimeW55): """Deduction, restricted to the premises it actually holds."""
@staticmethod def _premise_terms(st): terms = set() for key in ('all', 'no', 'have', 'cond', 'or', 'inst'): for pair in st.get(key, ()): for half in pair: terms |= _content(half) for f in list(st.get('fact', ())) + list(st.get('nfact', ())): terms |= _content(f) return terms
def _deduction_relevant(self, surface, st): """May the deduction route act on this turn at all?""" if _HAS_PREMISE.search(surface): return True # new premises are always its business if _ASK_FOLLOW.search(surface): return True if not any(st.get(k) for k in ('all', 'no', 'cond', 'or', 'inst', 'have')): return True # nothing held, the parent passes through clauses = [c.strip(' ,') for c in _SPLIT.split(surface) if c and c.strip(' ,')] questions = [c for c in clauses if _QUES.match(c)] if not questions: return False # a statement on a new subject is not a premise q = questions[-1] if not _YESNO.match(q): return False # "what is X" belongs to the corpus route return bool(_content(q) & self._premise_terms(st))
def chat(self, text: str, session_id: str = 'default') -> dict: s = ' '.join(str(text).strip().split()) st = self._store(session_id) if self._deduction_relevant(s, st): return super().chat(s, session_id)
# Not this fold's turn. Set the premises aside so the rest of the chain # answers as if the fold were not installed, then put them back: the # subject may return, and a visitor should not have to restate premises # because they asked something else in between. saved = {k: list(v) for k, v in st.items()} for v in st.values(): v.clear() try: return super().chat(s, session_id) finally: for k, v in saved.items(): st[k].clear() st[k].extend(v)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384#!/usr/bin/env python3"""oracle_release_runtime_w57 - CORRECTNESS RELEASE: say what you are, not what the file says.
Asked "what is your admitted head", the machine read HEAD_MANIFEST.json andanswered with the tip recorded there. On 2026-08-28 it answered "I am served byw54" while the process serving that answer had loaded its class at boot, hoursbefore w54 was admitted. The sentence was sincere and false. It was reading arecord about itself instead of looking at itself.
That is a worse failure than a wrong answer about volcanoes, because the wholeclaim of this architecture is that it can say what it is made of and show theartifact. A self-report that quotes a file the process has not reloaded isexactly the kind of unearned confidence the rest of the system is built to refuse.
The fix is to introspect. The class actually executing the turn is on thisobject's method resolution order, so the head is read from type(self) rather thanfrom disk, and the depth is counted the same way. The manifest is still consulted,but now as a SECOND source, and when the two disagree the machine says so plainlyinstead of picking whichever one it happened to read:
I am running w55. The manifest records w56 as the admitted head, so the record is ahead of this process and w56 will serve after the next restart.
That sentence is worth more than either number alone, because a visitor who seesit learns something true about how the system works: admission and serving areseparate acts, and the gap between them is visible rather than hidden.
Hand-authored 2026-08-28. Judged by the gate."""
from __future__ import annotations
from oracle_release_runtime_w56 import OracleReleaseRuntimeW56from oracle_release_runtime_w33 import _Q_HEAD
_PREFIX = 'oracle_release_runtime_'
class OracleReleaseRuntimeW57(OracleReleaseRuntimeW56): """Self-report grounded in the loaded class rather than a file on disk."""
def _loaded_head(self): """(name, depth) of the runtime actually executing, from the MRO.""" chain = [c for c in type(self).__mro__ if str(getattr(c, '__module__', '')).startswith(_PREFIX)] if not chain: return None, 0 return str(chain[0].__module__).split('runtime_')[-1], len(chain)
def _self_answer(self, s): loaded, depth = self._loaded_head() if loaded is None: return super()._self_answer(s) man = self._read_manifest() or {} recorded = str(man.get('tip', '')).split('runtime_')[-1] or None
if _Q_HEAD.search(s): if recorded and recorded != loaded: return ('I am running %s, which is the class this process actually ' 'loaded, with %d runtimes on its resolution order. The ' 'manifest records %s as the ' 'admitted head, so the record is ahead of this process and ' '%s will serve after the next restart. I am telling you both ' 'because the file is not evidence of what I am executing. ' '[self:loaded] [self:manifest]' % (loaded, depth, recorded, recorded), ['self:loaded', 'self:manifest']) return ('I am served by %s, the admitted head, and that is the class ' 'this process loaded rather than a line I read in a file. Its ' 'resolution order carries %d runtimes, each admitted by the ' 'gate before it could serve. [self:loaded] [self:manifest]' % (loaded, depth), ['self:loaded', 'self:manifest'])
out = super()._self_answer(s) if out and recorded and recorded != loaded: text, cites = out stale = 'The runtime serving you now is %s.' % recorded if stale in str(text): text = str(text).replace( stale, 'The runtime serving you now is %s; the manifest already ' 'records %s, which serves after the next restart.' % (loaded, recorded)) return (text, cites) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107#!/usr/bin/env python3"""oracle_release_runtime_w65 - reading its own operator table when asked what it can do.
From the held-out residue, twice, in the machine's own record of what it failed at:
what else can you compute? -> act:clarify What languages can you write? -> act:clarify
It has eleven operators loaded, each with a declared fragment saying exactly whatit handles and where it stops, and when a person asked what it could compute itsaid it had not understood the question. The answer was in the room.
That is worth more than the small gap it closes. A system whose capabilities are aruntime table can READ that table, so "what can you do" stops being a paragraphsomebody wrote about the system and becomes a query against the system. When thenext operator is admitted this answer changes by itself, with nobody editing adescription, and it cannot drift from the truth because there is no second copy ofthe truth to drift from.
It answers from the live table only. If an operator is not loaded it is not listed,which means the answer is occasionally shorter than the marketing and always equalto the machine.
Found by the salience pass over the residue rather than by me imagining what avisitor might ask, which is the method working: the machine kept the record of itsown failures, the ranking pointed here, and the fix is a query against somethingthat already existed.
Hand-authored 2026-08-28. Judged by the gate."""
from __future__ import annotations
import re
from oracle_release_runtime_w64 import OracleReleaseRuntimeW64from oracle_operator_specs_v1 import SPECS as _HOST_TABLE
_ASK_COMPUTE = re.compile( r'\bwhat\s+(?:else\s+)?can\s+you\s+(?:compute|calculate|work out|solve)\b' r'|\bwhat\s+(?:kinds?\s+of\s+)?(?:maths?|mathematics|calculations?|operators?)\b' r'.*\b(?:can|do)\s+you\b' r'|\bwhat\s+operators?\s+do\s+you\s+have\b' r'|\blist\s+your\s+(?:operators?|capabilities)\b', re.I)
class OracleReleaseRuntimeW65(OracleReleaseRuntimeW64): """Answers "what can you compute" by reading the operators it is running."""
@staticmethod def _operator_table(): fams = {} for spec in _HOST_TABLE: fams.setdefault(spec.get('family', 'other'), []).append( (spec['name'], spec.get('fragment', ''))) return fams
def chat(self, text: str, session_id: str = 'default') -> dict: s = ' '.join(str(text).strip().split()) if not _ASK_COMPUTE.search(s): return super().chat(s, session_id)
fams = self._operator_table() total = sum(len(v) for v in fams.values()) if not total: return super().chat(s, session_id)
lines = [] for fam in sorted(fams): names = ', '.join(n.replace('_', ' ') for n, _f in sorted(fams[fam])) lines.append('%s: %s' % (fam.replace('_', ' '), names)) body = ('I am running %d verified operators, reading them off my own table ' 'rather than a description of me. %s. Each one computes its answer ' 'and then checks it by a second method, and each one declines by ' 'name when a question falls outside what it can check. ' '[self:operators]' % (total, '; '.join(lines)))
from collections import deque hist = getattr(self, '_paths', None) if hist is None: hist = self._paths = {} q = hist.get(session_id) if q is None: q = hist[session_id] = deque(maxlen=64) prev = q[-1].get('turn', 0) if len(q) else 0 q.append({'turn': prev + 1, 'in_surface': s[:120], 'in_form': ['capability_self_query'], 'operator': 'self:operator_table', 'out_status': 'answered', 'in_terms': [], 'out_terms': [], 'relation': {'grounded': [], 'grounded_cited': [], 'introduced': [], 'unaccounted': []}, 'carried_from_prior': [], 'continuity_lexical': False, 'continuity': True, 'citations': 1, 'residual': None, 'cost_ms': 1.0, 'conversion': {'construction': 'ACCOUNT_OF_OWN_OPERATORS', 'from': s[:60], 'to': '%d operators' % total, 'produced_by': 'operator_table_w65'}, 'verified_warrant': {'kind': 'self_citation', 'steps': ['read the live operator table, ' '%d entries' % total]}}) return {'status': 'answered', 'path': 'self:operator_table', 'response': body, 'provenance': {'kind': 'self_report', 'operator_count': total, 'families': sorted(fams), 'source': 'live operator table'}, 'latency_ms': 1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""organ_code_chat_v1 - the code organ in conversation: a request that states examples gets a program that was RUN.
"write a function add that adds two numbers: add(2, 3) == 5, add(-1, 1) == 0""make a function shout(s): shout('hi') -> 'HI' and shout('ok') returns 'OK'"The examples ARE the specification: each `name(args) == / -> / returns / should return value` becomes an assert; thecode organ (code_organ_v1) composes typed library moves, executes the rendered source against every example, andanswers only if all pass. Verified programs join a per-process library (stored forms), so later requests compose them.A request without examples is left to the chain's own code route."""from __future__ import annotations
import astimport re
import code_organ_v2 as C
# a PROSE example: "..., so 'oracle' becomes 'elcaro'", "so 12 and 18 give 6", "so 97 is True"PROSE = re.compile(r"\bso\s+(?:that\s+)?(.+?)\s+(?:becomes|gives?|give|is|returns?|equals?)\s+(.+?)\s*\.?\s*$", re.I)
def _lit(s): try: return ast.literal_eval(s.strip()) except Exception: # noqa: BLE001 return None
EX = re.compile(r"([A-Za-z_]\w*)\s*\(([^()]*(?:\([^()]*\)[^()]*)*)\)\s*(?:==|->|→|returns?|should\s+(?:return|give|be)|gives?|is)\s*" r"(\[[^\]]*\]|\([^)]*\)|\{[^}]*\}|'[^']*'|\"[^\"]*\"|-?\d+(?:\.\d+)?|True|False|None)", re.I)CODE_ASK = re.compile(r"\b(?:write|make|create|give me|build|implement|code)\b.*\b(?:function|program|def|method|script)\b|\bdef\s+\w+", re.I | re.S)
class CodeChat: def __init__(self): self.org = C.CodeOrgan(max_size=4, cap=30000)
def examples(self, text): tests, name = [], None for m in EX.finditer(text or ""): fn, args, val = m.group(1), m.group(2), m.group(3) if name and fn != name: continue try: ast.literal_eval("(%s,)" % args if args.strip() else "()") ast.literal_eval(val) except Exception: # noqa: BLE001 continue name = fn tests.append("assert %s(%s) == %s" % (fn, args, val)) return tests
def prose_example(self, text): """ONE prose example -> one assert on a placeholder name, or None""" m = PROSE.search(text or "") if not m: return None parts = [p for p in re.split(r"\s+and\s+", m.group(1)) if p.strip()] args = [_lit(p) for p in parts] want = _lit(m.group(2)) if any(a is None for a in args) or (want is None and m.group(2).strip() != "None"): return None # a prose request names no function: name it from its own words, so stored programs never collide head = re.split(r"\bso\b", text)[0] words = [w.lower() for w in re.findall(r"[A-Za-z]+", head) if w.lower() not in C.GENERIC and len(w) > 2 and w.lower() not in ("returns", "return", "that", "true", "false", "if", "when")] name = "_".join(words[:4]) or "solution" return "assert %s(%s) == %r" % (name, ", ".join(repr(a) for a in args), want)
def answer(self, text): if not CODE_ASK.search(text or ""): return None tests = self.examples(text) strict = False if len(tests) < 2: one = self.prose_example(text) if not one or tests: return None # one structured example alone cannot tell a program from a coincidence tests, strict = [one], True # one PROSE example: the description must name every move # RECALL: the same function verified before is the stored FINAL FORM - re-checked on these examples, not re-derived pt = C.parse_tests(tests) lib = getattr(self.org, "library_src", {}) if pt and pt[0] in lib: ns = {} try: exec(compile(C.IMPORTS + lib[pt[0]], "<recall>", "exec"), ns) # noqa: S102 - a stored verified form if all(ns[pt[0]](*a) == e for a, e in pt[1]): return {"program": lib[pt[0]].strip(), "tests": tests, "passed": len(pt[1]), "reused": [], "recalled": True, "imports": [l for l in C.IMPORTS.split("\n") if l and l.split()[1] in lib[pt[0]]]} except Exception: # noqa: BLE001 pass res = self.org.solve(text, tests, strict=strict) if not res or res["passed"] != res["cases"]: return None pt = C.parse_tests(tests) try: self.org.learn(res["fname"], res, [C.tyof(a) for a in pt[1][0][0]], C.tyof(pt[1][0][1]), text) except Exception: # noqa: BLE001 pass return {"program": res["def"].replace(C.IMPORTS, "").strip(), "tests": tests, "passed": res["passed"], "reused": res.get("reused") or [], "imports": [l for l in C.IMPORTS.split("\n") if l and l.split()[1] in res["def"]]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""organ_code_chat_v2 - (v1 admitted in w482, immutable; v2: the request is read WITHOUT its examples, so an expectedoutput can never become a program constant - found live: second_biggest(...) == 4 gave max(4, a0[0]) - and everyconversational request uses coverage selection) the code organ in conversation: a request that states examples gets a program that was RUN.
"write a function add that adds two numbers: add(2, 3) == 5, add(-1, 1) == 0""make a function shout(s): shout('hi') -> 'HI' and shout('ok') returns 'OK'"The examples ARE the specification: each `name(args) == / -> / returns / should return value` becomes an assert; thecode organ (code_organ_v1) composes typed library moves, executes the rendered source against every example, andanswers only if all pass. Verified programs join a per-process library (stored forms), so later requests compose them.A request without examples is left to the chain's own code route."""from __future__ import annotations
import astimport re
import code_organ_v3 as C
# a PROSE example: "..., so 'oracle' becomes 'elcaro'", "so 12 and 18 give 6", "so 97 is True"PROSE = re.compile(r"\bso\s+(?:that\s+)?(.+?)\s+(?:becomes|gives?|give|is|returns?|equals?)\s+(.+?)\s*\.?\s*$", re.I)
def _lit(s): try: return ast.literal_eval(s.strip()) except Exception: # noqa: BLE001 return None
EX = re.compile(r"([A-Za-z_]\w*)\s*\(([^()]*(?:\([^()]*\)[^()]*)*)\)\s*(?:==|->|→|returns?|should\s+(?:return|give|be)|gives?|is)\s*" r"(\[[^\]]*\]|\([^)]*\)|\{[^}]*\}|'[^']*'|\"[^\"]*\"|-?\d+(?:\.\d+)?|True|False|None)", re.I)CODE_ASK = re.compile(r"\b(?:write|make|create|give me|build|implement|code)\b.*\b(?:function|program|def|method|script)\b|\bdef\s+\w+", re.I | re.S)
EVIDENCE_RATIO = 0.5 # chosen on MBPP train (code_evidence_v1): confident iff the program's moves cover >= half the request
def confident(res): return (res.get("cover") or 0) / max(1, res.get("req_words") or 0) >= EVIDENCE_RATIO
class CodeChat: def __init__(self, library_path=None): self.org = C.CodeOrgan(max_size=4, cap=30000) self.library_path = library_path self.persist = True if library_path: self._load(library_path)
# ---------------------------------------------------------------- the PERSISTENT library of verified programs def _load(self, path): import json import os if not os.path.exists(path): return try: for rec in json.load(open(path)): ns = {} exec(compile(C.IMPORTS + rec["def"], "<stored>", "exec"), ns) # noqa: S102 - a stored verified form fn = ns[rec["name"]] prog = {"fn": (lambda f: lambda xs: f(*xs))(fn), "def": C.IMPORTS + rec["def"]} self.org.learn(rec["name"], prog, rec["ins"], rec["out"], rec["desc"]) except Exception: # noqa: BLE001 pass
def _save(self, name, res, ins, out, desc): import json import os if not self.library_path or not self.persist: return try: lib = json.load(open(self.library_path)) if os.path.exists(self.library_path) else [] if any(r["name"] == name for r in lib): return lib.append({"name": name, "def": res["def"].replace(C.IMPORTS, ""), "ins": ins, "out": out, "desc": desc[:300], "tests": res.get("tests", [])}) tmp = self.library_path + ".tmp" json.dump(lib, open(tmp, "w"), indent=0) os.replace(tmp, self.library_path) except Exception: # noqa: BLE001 pass
def examples(self, text): tests, name = [], None for m in EX.finditer(text or ""): fn, args, val = m.group(1), m.group(2), m.group(3) if name and fn != name: continue try: ast.literal_eval("(%s,)" % args if args.strip() else "()") ast.literal_eval(val) except Exception: # noqa: BLE001 continue name = fn tests.append("assert %s(%s) == %s" % (fn, args, val)) return tests
def prose_example(self, text): """ONE prose example -> one assert on a placeholder name, or None""" m = PROSE.search(text or "") if not m: return None parts = [p for p in re.split(r"\s+and\s+", m.group(1)) if p.strip()] args = [_lit(p) for p in parts] want = _lit(m.group(2)) if any(a is None for a in args) or (want is None and m.group(2).strip() != "None"): return None # a prose request names no function: name it from its own words, so stored programs never collide head = re.split(r"\bso\b", text)[0] words = [w.lower() for w in re.findall(r"[A-Za-z]+", head) if w.lower() not in C.GENERIC and len(w) > 2 and w.lower() not in ("returns", "return", "that", "true", "false", "if", "when")] name = "_".join(words[:4]) or "solution" return "assert %s(%s) == %r" % (name, ", ".join(repr(a) for a in args), want)
def answer(self, text): if not CODE_ASK.search(text or ""): return None tests = self.examples(text) strict = False if len(tests) < 2: one = self.prose_example(text) if not one or tests: return None # one structured example alone cannot tell a program from a coincidence tests, strict = [one], True # one PROSE example: the description must name every move # RECALL: the same function verified before is the stored FINAL FORM - re-checked on these examples, not re-derived pt = C.parse_tests(tests) lib = getattr(self.org, "library_src", {}) if pt and pt[0] in lib: ns = {} try: exec(compile(C.IMPORTS + lib[pt[0]], "<recall>", "exec"), ns) # noqa: S102 - a stored verified form if all(ns[pt[0]](*a) == e for a, e in pt[1]): return {"program": lib[pt[0]].strip(), "tests": tests, "passed": len(pt[1]), "reused": [], "recalled": True, "confident": True, "imports": [l for l in C.IMPORTS.split("\n") if l and l.split()[1] in lib[pt[0]]]} except Exception: # noqa: BLE001 pass # the SPECIFICATION is the request minus its examples: expected outputs must never become constants or keywords # only the expected OUTPUTS leak; the calls' INPUTS are part of the specification (the n of "the n-th ...") spec = EX.sub(lambda m: " %s(%s) " % (m.group(1), m.group(2)), text) spec = re.split(r"\bso\s+(?:that\s+)?", spec)[0] if strict else spec res = self.org.solve(spec, tests, strict=strict, cover=True, allow_lib=not strict) if not res or res["passed"] != res["cases"]: return None pt = C.parse_tests(tests) sure = confident(res) if sure: # only a CONFIDENT program becomes a stored form try: ins, out = [C.tyof(a) for a in pt[1][0][0]], C.tyof(pt[1][0][1]) self.org.learn(res["fname"], res, ins, out, text) res["tests"] = tests self._save(res["fname"], res, ins, out, text) except Exception: # noqa: BLE001 pass return {"confident": sure, "program": res["def"].replace(C.IMPORTS, "").strip(), "tests": tests, "passed": res["passed"], "cover": res.get("cover"), "req_words": res.get("req_words"), "strict": strict, "expr": res.get("expr"), "reused": res.get("reused") or [], "imports": [l for l in C.IMPORTS.split("\n") if l and l.split()[1] in res["def"]]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172#!/usr/bin/env python3"""relation_spec_v1 - the shared engine of Oracle7's RELATION SPECIALISTS (one per domain: films, novels, countries, rivers,painters, ...). Built, not trained: each specialist is a domain (Wikidata root classes, or occupation roots for people,closed under subclass-of) plus the exact patterns mined for it (domain_mine_v1: >= 90% answering precision on both halvesof 124,000 TriviaQA TRAIN questions). Values are read EXACTLY from the Wikidata relation store (relstore v2, CC0). FORWARD linked entity in the domain -> admitted pattern -> property -> every in-domain candidate agrees on ONE value INVERSE linked entity is the value -> admitted pattern -> property -> exactly ONE in-domain subject holds itRefused as the exact router refuses: yes/no questions, a hidden hop, a quoted title that is not the linked span, a past-timequalifier on a time-variant relation, blank nodes, an answer that restates the question.A question is linked ONCE per turn however many relation specialists look at it (analyse() is cached on the text)."""import collectionsimport functoolsimport json
import exact_router_v1 as X
STORE_DOMAINS = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/relation_domains_v1.json"PROP_LABELS = __import__("os").environ.get("ORACLE7_ROOT", "/opt/oracle-clm") + "/relstore/prop_labels.tsv"_DOM, _PL = {}, {}_anc, _cls, _props = {}, {}, {}
def prop_label(p): if not _PL: try: with open(PROP_LABELS, encoding="utf-8") as f: for line in f: a, _, b = line.rstrip("\n").partition("\t") if a.startswith("<http://www.wikidata.org/entity/P") and b.endswith('"@en'): _PL[int(a[len("<http://www.wikidata.org/entity/P"):-1])] = b[1:-4] except Exception: # noqa: BLE001 _PL[-1] = "" return _PL.get(p) or "P%d" % p
def _rs(): return X._load()[1]
def _q(sql, args): return [r[0] for r in _rs().db.execute(sql, args).fetchall()]
def domains(): if not _DOM: for d in json.load(open(STORE_DOMAINS)): d["_roots"], d["_occ"] = set(d.get("roots", [])), set(d.get("occ", [])) _DOM[d["id"]] = d return _DOM
def classes_of(qid): if qid not in _cls: c = _q("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND p=31", (qid,)) occ = _q("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND p=106", (qid,)) if 5 in c else [] _cls[qid] = (tuple(x for x in c if x), tuple(x for x in occ if x)) return _cls[qid]
def ancestors(c, depth=0): if c in _anc: return _anc[c] out = {c} if depth < 8: for p in _q("SELECT o FROM fact INDEXED BY fact_sp WHERE s=? AND p=279", (c,))[:12]: if p and p not in out: out |= ancestors(p, depth + 1) _anc[c] = frozenset(out) return _anc[c]
def in_domain(qid, did): d = domains()[did] c, occ = classes_of(qid) if d["_roots"] and any(ancestors(x) & d["_roots"] for x in c): return True return bool(d["_occ"]) and any(ancestors(x) & d["_occ"] for x in occ)
def values(qid, p): key = (qid, p) if key not in _props: vs = set() for pp, o, lit in _rs().props_of(qid): if pp == p: v = _rs().label(o) if o else lit if v and ".well-known/genid" not in v: vs.add(v) _props[key] = frozenset(vs) return _props[key]
@functools.lru_cache(maxsize=64)def analyse(q): """-> None, or {span, cands (qid list after the popularity rule), feats}: the per-turn work every specialist shares""" q = str(q or "") if not q.strip() or X.POLAR.search(q): return None sp = X.L.link(q, 3) if not sp: return None span, cs = sp[0] if X.hop(q, span) or not X.subject_ok(q, span): return None if X.DOMINANCE and len(cs) > 1 and cs[0][1] >= X.DOMINANCE * max(1, max(c[1] for c in cs[1:])): cs = cs[:1] return {"span": span, "cands": [c[0] for c in cs[:3]], "feats": frozenset(X.features(q, span))}
def _restates(q, val): aw = [w for w in X.norm(val).split() if w not in X.L.STOP] return bool(aw) and all(w in set(X.norm(q).split()) for w in aw)
# TYPE AGREEMENT: a question that NAMES the kind of work it asks about ("the opera The Barber of Seville") belongs to that# kind's specialist; another work specialist stays silent even if the title links to its own domain (the play)KIND_NOUNS = { "films": r"films?|movies?", "tvseries": r"tv series|television series|sitcoms?|tv shows?|television shows?", "novels": r"novels?|novellas?|books?|short stor(?:y|ies)|trilogy", "plays": r"plays?|stage play", "poems": r"poems?|sonnets?", "songs": r"songs?|singles?|hits?|anthems?", "albums": r"albums?|lps?", "operas": r"operas?|operettas?|musicals?|ballets?", "paintings": r"paintings?|portraits?|frescos?|frescoes", "sculptures": r"sculptures?|statues?", "videogames": r"video games?",}_KIND_RX = {k: __import__("re").compile(r"\b(?:%s)\b" % v, __import__("re").I) for k, v in KIND_NOUNS.items()}
def kind_conflict(q, did): named = {k for k, rx in _KIND_RX.items() if rx.search(q)} return bool(named) and did in KIND_NOUNS and did not in named
def answer(q, did, patterns): """patterns: {"fwd|key|word": [p, ...], "inv|key|word": [p, ...]} -> {answer, property, subject_qid, direction, pattern} or None""" a = analyse(str(q)) if a is None or kind_conflict(str(q), did): return None hit = collections.defaultdict(set) for f in a["feats"]: for direction in ("fwd", "inv"): k = "%s|%s|%s" % (direction, f[0], f[1]) if k in patterns: hit[direction].add((patterns[k][0], k)) for direction in ("fwd", "inv"): props = {p for p, _ in hit.get(direction, ())} if len(props) != 1: continue p = props.pop() if p in X.TIME_VARIANT and X.PAST.search(q): return None pat = sorted(k for pp, k in hit[direction] if pp == p)[0] if direction == "fwd": mine = [c for c in a["cands"] if in_domain(c, did)] sets = [values(c, p) for c in mine] if not mine or any(not s for s in sets) or len(set(sets)) != 1 or len(sets[0]) != 1: continue val, subj = next(iter(sets[0])), mine[0] else: top = a["cands"][0] subs = _q("SELECT s FROM fact INDEXED BY fact_po WHERE p=? AND o=? LIMIT 8", (p, top)) if not subs or len(subs) == 8: continue mine = {s for s in subs if in_domain(s, did)} if len(mine) != 1: continue subj = next(iter(mine)) val = _rs().label(subj) if not val: continue if _restates(q, val): return None return {"answer": X._show(val, q), "property": p, "subject_qid": subj, "direction": direction, "pattern": pat, "linked_qid": a["cands"][0]} return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279#!/usr/bin/env python3"""Four simultaneous callable-specialist heads over one C36 Tree spine.
Unlike the full-workspace C41 experiment, these heads do not duplicate thewhole reasoning trace. They evaluate one shared answer-free 10D state atevery transition, own disjoint subsets of the real HRR callable vocabulary,and bind their directional proposals into one advisory state. The globallyselected callable remains exactly the accepted C36 router decision."""
from __future__ import annotations
import threadingimport timefrom dataclasses import dataclass, fieldfrom typing import Any, Mapping
import numpy as np
from oracle_10d_resolution_state import array_sha256, canonical_sha256from stage5c36_long_horizon_reasoner import ( CALLABLES, TEN_D_CHANNELS, LongHorizonResult, RecurrentHRRReasoner, RouterDecision, TenDCallableRouter,)from train_stage2a_role_ladder import HRR_DIM, bind, normalize, unitary
SCHEMA = "oracle-stage5c41-cooperative-four-head-router-v1"HEAD_ROLES = ("direct", "counterfactual", "memory", "integrative")ROLE_CALLABLES = { "direct": ("advance",), "counterfactual": ("branch", "compare"), "memory": ("recall",), "integrative": ("repair", "rollback", "stop"),}CALLABLE_OWNER = { callable_name: role for role, names in ROLE_CALLABLES.items() for callable_name in names}
def _head_callable_key(role: str, callable_name: str) -> np.ndarray: return normalize(bind( unitary(f"c41:cooperative-head:{role}"), unitary(f"c41:cooperative-callable:{callable_name}"), ))
HEAD_CALLABLE_KEYS = { (role, callable_name): _head_callable_key(role, callable_name) for role, names in ROLE_CALLABLES.items() for callable_name in names}CHANNEL_STATES = tuple( unitary(f"c41:10d-channel:{name}") for name in TEN_D_CHANNELS)HEAD_CALLABLE_KEYS_F = { key: np.fft.fft(value).astype(np.complex64) for key, value in HEAD_CALLABLE_KEYS.items()}CHANNEL_STATES_F = np.stack([ np.fft.fft(value).astype(np.complex64) for value in CHANNEL_STATES])
def _normalize_frequency(value: np.ndarray) -> np.ndarray: """Normalize a DFT state using Parseval without returning to time space.""" frequency = np.asarray(value, dtype=np.complex64) time_norm = float(np.linalg.norm(frequency)) / np.sqrt(frequency.size) return (frequency / max(time_norm, 1e-12)).astype(np.complex64)
@dataclass(frozen=True)class CooperativeHeadVote: role: str proposed_callable: str confidence: float selected: bool
def as_dict(self): return { "role": self.role, "proposed_callable": self.proposed_callable, "confidence": self.confidence, "selected": self.selected, }
@dataclass(frozen=True)class CooperativeHeadEvent: index: int task_id: str selected_role: str selected_callable: str votes: tuple[CooperativeHeadVote, ...] advisory_state_sha256: str
def as_dict(self): return { "index": self.index, "task_id": self.task_id, "selected_role": self.selected_role, "selected_callable": self.selected_callable, "votes": [vote.as_dict() for vote in self.votes], "advisory_state_sha256": self.advisory_state_sha256, }
class CooperativeFourHeadRouter: """Vectorized four-head portfolio with thread-local request telemetry."""
state = staticmethod(TenDCallableRouter.state)
def __init__(self, base: TenDCallableRouter): self.base = base self._local = threading.local()
def begin_trace(self, task_id: str) -> None: self._local.task_id = str(task_id) self._local.events = [] self._local.last_advisory_state = None self._local.last_advisory_frequency = None
@property def events(self) -> tuple[CooperativeHeadEvent, ...]: return tuple(getattr(self._local, "events", ()))
@property def last_advisory_state(self) -> np.ndarray | None: value = getattr(self._local, "last_advisory_state", None) return None if value is None else value.copy()
@property def last_advisory_frequency(self) -> np.ndarray | None: value = getattr(self._local, "last_advisory_frequency", None) return None if value is None else value.copy()
@staticmethod def _state_frequency(state: np.ndarray) -> np.ndarray: values = np.asarray(state, dtype=np.float64) if values.shape != (len(TEN_D_CHANNELS),): raise ValueError("cooperative state requires exactly ten coordinates") # A fixed ten-term accumulation is materially faster than einsum on # Box C's NumPy build, whose optimized complex contraction dispatches # through a small-matrix BMM kernel with millisecond setup cost. combined = np.zeros(HRR_DIM, dtype=np.complex64) for index, value in enumerate(values): combined += np.complex64(value) * CHANNEL_STATES_F[index] return _normalize_frequency(combined)
def decide(self, state: np.ndarray) -> RouterDecision: base = self.base.decide(state) probabilities = np.asarray(base.probabilities, dtype=np.float64) selected_role = CALLABLE_OWNER[base.callable_name] state_frequency = self._state_frequency(state) votes = [] weighted_keys = np.zeros_like(state_frequency) for role in HEAD_ROLES: indices = [CALLABLES.index(name) for name in ROLE_CALLABLES[role]] winner = indices[int(np.argmax(probabilities[indices]))] proposed = CALLABLES[winner] confidence = float(probabilities[winner]) votes.append(CooperativeHeadVote( role=role, proposed_callable=proposed, confidence=confidence, selected=role == selected_role, )) weighted_keys += ( np.complex64(max(confidence, 1e-6)) * HEAD_CALLABLE_KEYS_F[(role, proposed)] ) # Circular convolution is multiplication in the Fourier basis. The # four proposals therefore become one weighted key followed by one # elementwise product, with no per-head FFT/IFFT pair. advisory_frequency = _normalize_frequency(weighted_keys * state_frequency) advisory = normalize(np.fft.ifft(advisory_frequency).astype(np.complex64)) events = list(getattr(self._local, "events", ())) events.append(CooperativeHeadEvent( index=len(events), task_id=str(getattr(self._local, "task_id", "unknown")), selected_role=selected_role, selected_callable=base.callable_name, votes=tuple(votes), advisory_state_sha256=array_sha256(advisory), )) self._local.events = events self._local.last_advisory_state = advisory self._local.last_advisory_frequency = advisory_frequency return base
def as_dict(self) -> dict[str, Any]: return { "schema_version": SCHEMA, "roles": list(HEAD_ROLES), "role_callables": {name: list(values) for name, values in ROLE_CALLABLES.items()}, "base_router": self.base.as_dict(), }
@dataclass(frozen=True)class CooperativeFourHeadResult: schema_version: str reasoning: LongHorizonResult = field(repr=False) events: tuple[CooperativeHeadEvent, ...] selected_role_counts: Mapping[str, int] wall_seconds: float trace_sha256: str
@property def action(self): return self.reasoning.action
@property def endpoint(self): return self.reasoning.endpoint
def as_dict(self): return { "schema_version": self.schema_version, "task_id": self.reasoning.task_id, "action": self.action, "endpoint": self.endpoint, "events": len(self.events), "selected_role_counts": dict(self.selected_role_counts), "wall_ms": 1000 * self.wall_seconds, "trace_sha256": self.trace_sha256, "all_four_heads_voted_each_step": all(len(event.votes) == 4 for event in self.events), "advisory_bound_into_tree": True, "plaintext_boundary": "malkuth_only", }
class CooperativeFourHeadReasoner: def __init__( self, base_router: TenDCallableRouter, *, full_audit: bool = False, ): self.router = CooperativeFourHeadRouter(base_router) self.executor = RecurrentHRRReasoner( self.router, full_audit=full_audit, )
def solve(self, record: Mapping[str, Any]) -> CooperativeFourHeadResult: started = time.perf_counter() reasoning = self.executor.solve(record) wall = time.perf_counter() - started events = self.router.events if len(events) != len(reasoning.router_trace): raise ValueError("cooperative-head events differ from callable trace") for event, callable_event in zip(events, reasoning.router_trace, strict=True): if event.selected_callable != callable_event.name: raise ValueError("cooperative-head selection changed C36 routing") if len(event.votes) != 4 or {vote.role for vote in event.votes} != set(HEAD_ROLES): raise ValueError("cooperative event lacks four simultaneous head votes") counts = {role: 0 for role in HEAD_ROLES} for event in events: counts[event.selected_role] += 1 payload = { "task_id": reasoning.task_id, "resolution_sha256": canonical_sha256(reasoning.resolution_state), "events": [event.as_dict() for event in events], } return CooperativeFourHeadResult( schema_version=SCHEMA, reasoning=reasoning, events=events, selected_role_counts=counts, wall_seconds=wall, trace_sha256=canonical_sha256(payload), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415#!/usr/bin/env python3"""C59 provenance-locked compilation of raw prose into hot-load HRR experts.
Unlike C53, the input specification contains no authored fact triples. C59segments immutable documents, accepts only independently parseable single-edgesentences from a bounded scientific relation grammar, derives every identifierand provenance digest, rejects conflicts, and trains the unchanged C43 capsule."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport reimport timefrom collections import Counter, defaultdictfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Mapping, Sequence
from oracle_10d_resolution_state import canonical_sha256from stage5c43_corpus_expert import ( CorpusExpertCheckpoint, CorpusFact, train_capsule,)
SCHEMA = "oracle-stage5c59-raw-corpus-spec-v1"REPORT_SCHEMA = "oracle-stage5c59-raw-corpus-compiler-report-v1"EXTRACTOR_SCHEMA = "oracle-stage5c59-bounded-relation-extractor-v1"IDENTIFIER = re.compile(r"^[a-z][a-z0-9_]{1,95}$")SENTENCE = re.compile(r"[^.!?]+[.!?]", re.MULTILINE)
RELATIONS: Mapping[str, str] = { "cause": "causes", "causes": "causes", "produce": "produces", "produces": "produces", "generate": "generates", "generates": "generates", "form": "forms", "forms": "forms", "enable": "enables", "enables": "enables", "support": "supports", "supports": "supports", "prevent": "prevents", "prevents": "prevents", "inhibit": "inhibits", "inhibits": "inhibits", "reduce": "reduces", "reduces": "reduces", "drive": "drives", "drives": "drives", "supply": "supplies", "supplies": "supplies", "indicate": "indicates", "indicates": "indicates", "reveal": "reveals", "reveals": "reveals", "contain": "contains", "contains": "contains", "absorb": "absorbs", "absorbs": "absorbs", "stabilize": "stabilizes", "stabilizes": "stabilizes", "trigger": "triggers", "triggers": "triggers", "lead to": "leads_to", "leads to": "leads_to",}PASSIVE_RELATIONS: Mapping[str, str] = { "caused": "causes", "produced": "produces", "generated": "generates", "formed": "forms", "enabled": "enables", "supported": "supports", "prevented": "prevents", "inhibited": "inhibits", "reduced": "reduces", "driven": "drives", "supplied": "supplies", "revealed": "reveals", "absorbed": "absorbs", "stabilized": "stabilizes", "triggered": "triggers",}RELATION_PATTERN = "|".join( re.escape(value) for value in sorted(RELATIONS, key=len, reverse=True))PASSIVE_PATTERN = "|".join( re.escape(value) for value in sorted(PASSIVE_RELATIONS, key=len, reverse=True))ACTIVE = re.compile( rf"^(?P<source>.+?)\s+(?P<relation>{RELATION_PATTERN})\s+(?P<destination>.+)$", re.IGNORECASE,)PASSIVE = re.compile( rf"^(?P<destination>.+?)\s+is\s+(?P<relation>{PASSIVE_PATTERN})\s+by\s+" rf"(?P<source>.+)$", re.IGNORECASE,)PREFIX = re.compile( r"^(?:experimentally|observationally|chemically|physically|in\s+this\s+system),\s+", re.IGNORECASE,)DETERMINER = re.compile(r"^(?:a|an|the)\s+", re.IGNORECASE)
def _identifier(value: Any, label: str) -> str: text = str(value).strip().casefold().replace("-", "_") text = re.sub(r"[^a-z0-9_]+", "_", text) text = re.sub(r"_+", "_", text).strip("_") if not IDENTIFIER.fullmatch(text): raise ValueError(f"invalid C59 {label}: {value!r} -> {text!r}") return text
def _entity(value: str) -> str: clean = " ".join(value.strip().split()).strip(" ,;:-") clean = DETERMINER.sub("", clean) tokens = re.findall(r"[A-Za-z0-9]+(?:-[A-Za-z0-9]+)?", clean) if not 2 <= len(tokens) <= 10: raise ValueError("entity_span_outside_2_to_10_tokens") return _identifier("_".join(tokens), "extracted entity")
def _sentences(text: str) -> tuple[str, ...]: return tuple(" ".join(match.group(0).strip().split()) for match in SENTENCE.finditer(text))
@dataclass(frozen=True)class ExtractedRelation: source: str relation: str destination: str evidence: str relation_surface: str voice: str sentence_ordinal: int
@dataclass(frozen=True)class RawCompilation: checkpoints: tuple[CorpusExpertCheckpoint, ...] facts: tuple[CorpusFact, ...] report: Mapping[str, Any]
def extract_sentence(sentence: str, ordinal: int) -> tuple[ExtractedRelation | None, str | None]: evidence = " ".join(sentence.strip().split()) body = evidence.rstrip(".!?").strip() body = PREFIX.sub("", body) if len(evidence) < 24: return None, "sentence_too_short" if re.search(r"\b(?:may|might|could|possibly|perhaps|unknown|uncertain)\b", body, re.I): return None, "epistemically_uncertain_sentence" # Coordinated relation clauses are not silently split because doing so can # change scope. Each accepted sentence must contain one recoverable edge. relation_hits = re.findall(rf"\b(?:{RELATION_PATTERN})\b", body, re.I) passive_hits = re.findall(rf"\bis\s+(?:{PASSIVE_PATTERN})\s+by\b", body, re.I) if len(relation_hits) + len(passive_hits) != 1: return None, "not_exactly_one_relation_surface" match = PASSIVE.fullmatch(body) voice = "passive" relation_map = PASSIVE_RELATIONS if match is None: match = ACTIVE.fullmatch(body) voice = "active" relation_map = RELATIONS if match is None: return None, "relation_grammar_not_matched" try: source = _entity(match.group("source")) destination = _entity(match.group("destination")) except ValueError as error: return None, str(error) relation_surface = match.group("relation").casefold() relation = relation_map[relation_surface] if source == destination: return None, "self_edge_rejected" return ExtractedRelation( source=source, relation=relation, destination=destination, evidence=evidence, relation_surface=relation_surface, voice=voice, sentence_ordinal=ordinal, ), None
def compile_raw_corpus( spec_path: Path, *, carrier_sha256: str, output_dir: Path,) -> RawCompilation: started = time.perf_counter() spec_path = spec_path.resolve() raw = spec_path.read_bytes() spec = json.loads(raw.decode("utf-8")) if spec.get("schema_version") != SCHEMA: raise ValueError("unsupported C59 raw corpus specification") documents = spec.get("documents") if not isinstance(documents, list) or not documents: raise ValueError("C59 requires at least one raw document") if not re.fullmatch(r"[0-9a-f]{64}", carrier_sha256): raise ValueError("C59 frozen carrier digest is invalid") if any("facts" in value for value in documents if isinstance(value, dict)): raise ValueError("C59 raw specification must not contain authored facts")
facts: list[CorpusFact] = [] document_reports = [] semantic_addresses: dict[tuple[str, str], str] = {} fact_ids: set[str] = set() document_hashes = {} for document in documents: if not isinstance(document, dict): raise ValueError("C59 document descriptor must be an object") expert_id = _identifier(document.get("expert_id"), "expert id") document_id = _identifier(document.get("source_document_id"), "document id") document_path = (spec_path.parent / str(document.get("document_path", ""))).resolve() if not document_path.is_file(): raise ValueError(f"C59 raw document does not exist: {document_path}") document_bytes = document_path.read_bytes() document_text = document_bytes.decode("utf-8") document_sha = hashlib.sha256(document_bytes).hexdigest() document_hashes[document_id] = document_sha source_url = str(document.get("source_url", "")).strip() if not source_url.startswith(("http://", "https://")): raise ValueError("C59 source URL must be HTTP(S)") source_split = _identifier(document.get("source_split", "train"), "source split") competencies = tuple(dict.fromkeys(( f"expert_scope:{expert_id}", *(_identifier(value, "competency") for value in document.get("competencies", ())), ))) accepted = [] rejected = [] normalized_document = " ".join(document_text.split()) for ordinal, sentence in enumerate(_sentences(document_text)): relation, reason = extract_sentence(sentence, ordinal) if relation is None: rejected.append({ "sentence_ordinal": ordinal, "evidence_sha256": hashlib.sha256(sentence.encode("utf-8")).hexdigest(), "reason": reason, }) continue if relation.evidence not in normalized_document: raise RuntimeError("C59 extracted evidence lost verbatim document identity") address = (relation.source, relation.relation) prior = semantic_addresses.get(address) if prior is not None and prior != relation.destination: raise ValueError( f"C59 conflicting raw destinations at {address}: {prior} versus {relation.destination}" ) semantic_addresses[address] = relation.destination canonical = { "extractor_schema": EXTRACTOR_SCHEMA, "expert_id": expert_id, "source_document_id": document_id, "source_document_sha256": document_sha, "source_url": source_url, "source_split": source_split, "source": relation.source, "relation": relation.relation, "destination": relation.destination, "evidence": relation.evidence, "relation_surface": relation.relation_surface, "voice": relation.voice, "sentence_ordinal": relation.sentence_ordinal, "competencies": list(competencies), } provenance = canonical_sha256(canonical) fact_id = _identifier(f"{expert_id[:24]}_{provenance[:16]}", "derived fact id") if fact_id in fact_ids: raise RuntimeError("C59 derived duplicate fact identity") fact_ids.add(fact_id) fact = CorpusFact( fact_id=fact_id, expert_id=expert_id, source_document_id=document_id, source_document_sha256=document_sha, source_url=source_url, source_split=source_split, source=relation.source, relation=relation.relation, destination=relation.destination, evidence=relation.evidence, competencies=competencies, provenance_sha256=provenance, ) facts.append(fact) accepted.append({ "fact_id": fact_id, "source": relation.source, "relation": relation.relation, "destination": relation.destination, "evidence_sha256": hashlib.sha256(relation.evidence.encode("utf-8")).hexdigest(), "provenance_sha256": provenance, "voice": relation.voice, }) if not accepted: raise ValueError(f"C59 document {document_id} produced no accepted relation") document_reports.append({ "expert_id": expert_id, "source_document_id": document_id, "source_document_sha256": document_sha, "sentences": len(_sentences(document_text)), "accepted_relations": len(accepted), "rejected_sentences": len(rejected), "relations": accepted, "rejections": rejected, })
grouped: dict[str, list[CorpusFact]] = defaultdict(list) for fact in facts: grouped[fact.expert_id].append(fact) if any(len(values) > 128 for values in grouped.values()): raise ValueError("C59 limits one 1024-D capsule to 128 extracted facts") corpus_sha = canonical_sha256({ "spec_sha256": hashlib.sha256(raw).hexdigest(), "document_sha256": dict(sorted(document_hashes.items())), "facts": [value.as_dict() for value in facts], }) output_dir.mkdir(parents=True, exist_ok=True) checkpoints = [] expert_reports = {} training_started = time.perf_counter() for expert_id in sorted(grouped): capsule, metrics = train_capsule( expert_id, grouped[expert_id], carrier_sha256=carrier_sha256, corpus_sha256=corpus_sha, ) if metrics["retrieval"]["top1_accuracy"] != 1.0 or metrics["retrieval"]["minimum_margin"] <= 0.0: raise ValueError(f"C59 expert {expert_id} failed retrieval calibration") checkpoint = CorpusExpertCheckpoint( capsule=capsule, facts=tuple(grouped[expert_id]), metrics=metrics, ) checkpoint_path = output_dir / f"{expert_id}_c59_real_v1.npz" file_sha = checkpoint.save(checkpoint_path) loaded = CorpusExpertCheckpoint.load(checkpoint_path) if loaded.capsule.capsule_sha256 != capsule.capsule_sha256: raise RuntimeError("C59 checkpoint round trip changed capsule identity") checkpoints.append(loaded) expert_reports[expert_id] = { **metrics, "checkpoint_path": str(checkpoint_path), "checkpoint_file_sha256": file_sha, } training_seconds = time.perf_counter() - training_started report = { "schema_version": REPORT_SCHEMA, "accepted": True, "extractor_schema": EXTRACTOR_SCHEMA, "spec_sha256": hashlib.sha256(raw).hexdigest(), "document_sha256": dict(sorted(document_hashes.items())), "corpus_sha256": corpus_sha, "carrier_sha256": carrier_sha256, "carrier_frozen": True, "trainable_carrier_parameters": 0, "authored_fact_fields_in_input": 0, "documents": document_reports, "facts": len(facts), "experts": expert_reports, "accepted_relation_count": len(facts), "rejected_sentence_count": sum(value["rejected_sentences"] for value in document_reports), "relation_counts": dict(sorted(Counter(value.relation for value in facts).items())), "voice_counts": dict(sorted(Counter( relation["voice"] for document in document_reports for relation in document["relations"] ).items())), "training_wall_seconds": training_seconds, "total_wall_seconds": time.perf_counter() - started, "claim_boundary": ( "Automatic provenance-locked extraction for explicit, single-edge active/passive " "scientific sentences in a bounded relation grammar; not general information extraction." ), } return RawCompilation(tuple(checkpoints), tuple(facts), report)
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--spec", type=Path, required=True) parser.add_argument("--carrier-sha256", required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--report", type=Path, required=True) parser.add_argument("--facts", type=Path, required=True) args = parser.parse_args() result = compile_raw_corpus( args.spec, carrier_sha256=args.carrier_sha256, output_dir=args.output_dir, ) args.report.write_text( json.dumps(result.report, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) args.facts.write_text( "".join(json.dumps(value.as_dict(), sort_keys=True) + "\n" for value in result.facts), encoding="utf-8", ) print(json.dumps(result.report, indent=2, sort_keys=True))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323#!/usr/bin/env python3"""Rule-bounded English predicate/argument construction algebra.
The algebra uses closed-class English rules, surface morphology, and WordNetpart-of-speech inventories. It is deliberately a shallow, ambiguity-retainingparser: uncertain slots are marked rather than forced, coordinated predicatesand clause transitions bound the local argument window, and voice/aspect/modalstates remain explicit features for downstream HRR specialists."""
from __future__ import annotations
from dataclasses import dataclassfrom functools import lru_cache
from stage5j1_native_contextual_sense_lattice import WORD
PRONOUNS = { "i", "me", "myself", "we", "us", "ourselves", "you", "yourself", "yourselves", "he", "him", "himself", "she", "her", "herself", "it", "itself", "they", "them", "themselves", "who", "whom", "someone", "somebody", "anyone", "anybody", "everyone", "everybody",}POSSESSIVES = {"my", "our", "your", "his", "her", "its", "their", "whose"}DETERMINERS = {"a", "an", "the", "this", "that", "these", "those", "some", "any", "each", "every", "no"} | POSSESSIVESAUXILIARIES = { "am", "are", "be", "been", "being", "is", "was", "were", "do", "does", "did", "have", "has", "had",}MODALS = {"can", "could", "may", "might", "must", "shall", "should", "will", "would"}COORDINATORS = {"and", "or", "but", "nor", "yet"}COMPLEMENTIZERS = {"that", "whether", "if", "because", "although", "though", "when", "while", "where", "who", "which"}PREPOSITIONS = { "about", "after", "against", "among", "around", "at", "before", "behind", "below", "beneath", "beside", "between", "by", "during", "for", "from", "in", "into", "of", "off", "on", "onto", "out", "over", "through", "to", "toward", "under", "upon", "with", "within", "without", "as",}NEGATIONS = {"no", "not", "never", "neither"}ADVERBS = {"again", "already", "also", "even", "ever", "here", "however", "just", "now", "only", "really", "still", "then", "there"}BOUNDARY_WORDS = {"because", "although", "though", "whereas"}
class LexicalCategoryResolver: def __init__(self, wordnet): self.wordnet = wordnet
@lru_cache(maxsize=100_000) def categories(self, surface: str) -> frozenset[str]: value = surface.casefold() result = set() if value in PRONOUNS: result.add("pronoun") if value in POSSESSIVES: result.add("possessive") if value in DETERMINERS: result.add("determiner") if value in AUXILIARIES: result.add("auxiliary") if value in MODALS: result.add("modal") if value in COORDINATORS: result.add("coordinator") if value in COMPLEMENTIZERS: result.add("complementizer") if value in PREPOSITIONS: result.add("preposition") if value in NEGATIONS: result.add("negation") if value in ADVERBS or value.endswith("ly"): result.add("adverb") normalized = value.replace("-", "_") if self.wordnet.synsets(normalized, pos=self.wordnet.NOUN): result.add("noun") if self.wordnet.synsets(normalized, pos=self.wordnet.VERB) or self.wordnet.morphy(normalized, self.wordnet.VERB): result.add("verb") if self.wordnet.synsets(normalized, pos=self.wordnet.ADJ): result.add("adjective") if self.wordnet.synsets(normalized, pos=self.wordnet.ADV): result.add("adverb") return frozenset(result)
def noun_like(self, surface: str, *, proper: bool = False) -> bool: categories = self.categories(surface) return proper or "pronoun" in categories or "noun" in categories
def verb_like(self, surface: str) -> bool: categories = self.categories(surface) return "verb" in categories and "auxiliary" not in categories and "modal" not in categories
@dataclass(frozen=True)class PredicateArgumentShape: features: tuple[str, ...] subject: str | None direct_object: str | None indirect_object: str | None preposition_objects: tuple[tuple[str, str], ...] clause_complement: str | None clause_kind: str | None clause_preposition: str | None confidence: float
def _proper_flags(raw: list[str]) -> list[bool]: return [bool(value[:1].isupper() and index > 0) for index, value in enumerate(raw)]
def _next_content(values: list[str], start: int, resolver: LexicalCategoryResolver) -> int | None: for index in range(start, min(len(values), start + 8)): categories = resolver.categories(values[index]) if not categories.intersection({"determiner", "adverb", "negation", "auxiliary", "modal"}): return index return None
def _looks_like_clause_start( values: list[str], proper: list[bool], start: int, resolver: LexicalCategoryResolver,) -> bool: if start >= len(values): return False if values[start] in COMPLEMENTIZERS: return True noun_seen = False for index in range(start, min(len(values), start + 5)): value = values[index] if value in PREPOSITIONS or value in COORDINATORS: return False if resolver.noun_like(value, proper=proper[index]) or value in DETERMINERS: noun_seen = True continue if noun_seen and resolver.verb_like(value): return True if value not in ADVERBS and "adverb" not in resolver.categories(value): break return False
def predicate_argument_shape(text: str, token_index: int, wordnet) -> PredicateArgumentShape: raw = WORD.findall(str(text)) values = [value.casefold() for value in raw] if not 0 <= token_index < len(values): return PredicateArgumentShape( ("invalid_predicate_index",), None, None, None, (), None, None, None, 0.0, ) proper = _proper_flags(raw) resolver = LexicalCategoryResolver(wordnet) features = set() predicate = values[token_index] before = values[:token_index] after = values[token_index + 1:]
auxiliaries = [value for value in before[-4:] if value in AUXILIARIES or value in MODALS] if any(value in MODALS for value in auxiliaries): features.add("modal") if any(value in {"have", "has", "had"} for value in auxiliaries): features.add("perfect") passive = bool(before and before[-1] in {"am", "are", "be", "been", "being", "is", "was", "were"}) features.add("voice_passive" if passive else "voice_active") if predicate.endswith("ing"): features.add("aspect_progressive") if predicate.endswith("ed") or predicate.endswith("en"): features.add("morph_participle") if any(value in NEGATIONS for value in values[max(0, token_index - 4):token_index + 5]): features.add("negated")
subject = None for index in range(token_index - 1, max(-1, token_index - 12), -1): value = values[index] if value in BOUNDARY_WORDS: break if value in COORDINATORS and subject is not None: break categories = resolver.categories(value) if categories.intersection({"auxiliary", "modal", "adverb", "negation", "determiner", "possessive"}): continue if resolver.noun_like(value, proper=proper[index]): # A role filler is an observed discourse referent, not a lexical # root. Destructive suffix stripping (princess -> princes -> # princ, Brutus -> brutu) made repeated analysis non-idempotent. # Lexical normalization belongs on the predicate/sense rail; keep # the nominal surface coordinate stable on the role rail. subject = value break if subject: # Preserve a coordinated discourse referent as one compositional role # filler rather than silently retaining only its rightmost member. for coordinator_index in range(token_index - 2, max(-1, token_index - 12), -1): if values[coordinator_index] not in {"and", "or"}: continue right = values[coordinator_index + 1:token_index] if not right or subject not in right: continue left = None for probe in range(coordinator_index - 1, max(-1, coordinator_index - 6), -1): if resolver.noun_like(values[probe], proper=proper[probe]): left = values[probe] break if left is not None: subject = f"{left} {values[coordinator_index]} {subject}" features.add("subject_coordinated") break features.add("subject_present") features.add("subject_pronoun" if subject in PRONOUNS else "subject_nominal") else: features.add("subject_unresolved")
first = _next_content(values, token_index + 1, resolver) coordinated_predicate = False clause_transition = False if first is not None: if resolver.verb_like(values[first]) and any(value in COORDINATORS for value in values[first + 1:first + 4]): coordinated_predicate = True if first > token_index + 1 and values[first - 1] in COORDINATORS and resolver.verb_like(values[first]): coordinated_predicate = True clause_transition = _looks_like_clause_start(values, proper, first, resolver) if coordinated_predicate: features.add("coordinated_predicate") if clause_transition: features.add("following_clause")
clause_complement = None clause_kind = None clause_preposition = None clause_first = token_index + 1 while ( clause_first < len(values) and values[clause_first] in ADVERBS | NEGATIONS ): clause_first += 1 if clause_first < len(values): first_value = values[clause_first] if first_value in {"that", "whether", "if"}: clause_complement = " ".join(values[clause_first:]) clause_kind = "finite" elif ( first_value == "to" and clause_first + 1 < len(values) and resolver.verb_like(values[clause_first + 1]) ): clause_complement = " ".join(values[clause_first:]) clause_kind = "infinitive" elif first_value.endswith("ing") and resolver.verb_like(first_value): clause_complement = " ".join(values[clause_first:]) clause_kind = "gerund" elif ( first_value in PREPOSITIONS and clause_first + 1 < len(values) and values[clause_first + 1] in {"what", "who", "whom", "whose", "which", "where", "when", "why", "how"} ): clause_preposition = first_value clause_complement = " ".join(values[clause_first + 1:]) clause_kind = "wh" if clause_complement is not None: features.add("clause_complement") features.add("clause_" + str(clause_kind))
direct_object = None indirect_object = None if ( first is not None and clause_complement is None and not coordinated_predicate and not clause_transition and not passive ): first_value = values[first] if first_value not in PREPOSITIONS and first_value not in COMPLEMENTIZERS: scan_end = min(len(values), first + 5) head = None for index in range(first, scan_end): value = values[index] if ( value in PREPOSITIONS or value in COORDINATORS or (head is not None and value in ADVERBS) or (index > first and resolver.verb_like(value)) ): break if resolver.noun_like(value, proper=proper[index]) and value not in POSSESSIVES: head = value direct_object = head if direct_object: features.add("direct_object") features.add("object_pronoun" if direct_object in PRONOUNS else "object_nominal") else: features.add("no_direct_object")
prep_objects = [] for index in range(token_index + 1, min(len(values), token_index + 13)): prep = values[index] if prep not in PREPOSITIONS: continue object_index = _next_content(values, index + 1, resolver) if object_index is None or values[object_index] in PREPOSITIONS or values[object_index] in COORDINATORS: continue head = values[object_index] for probe in range(object_index, min(len(values), object_index + 4)): if values[probe] in PREPOSITIONS or values[probe] in COORDINATORS or (probe > object_index and resolver.verb_like(values[probe])): break if resolver.noun_like(values[probe], proper=proper[probe]) and values[probe] not in POSSESSIVES: head = values[probe] prep_objects.append((prep, head)) features.add("prep_" + prep) if passive and any(prep == "by" for prep, _ in prep_objects): features.add("passive_agent")
if first is not None and values[first] in {"that", "whether", "if"}: features.add("finite_clause_complement") if first is not None and values[first] == "to" and first + 1 < len(values) and resolver.verb_like(values[first + 1]): features.add("infinitive_complement") if first is not None and values[first].endswith("ing") and resolver.verb_like(values[first]): features.add("gerund_complement")
confidence = 0.35 confidence += 0.20 if subject else 0.0 confidence += 0.20 if direct_object or prep_objects else 0.0 confidence += 0.15 if coordinated_predicate or clause_transition or passive else 0.0 confidence = min(confidence, 1.0) return PredicateArgumentShape( tuple(sorted(features)), subject, direct_object, indirect_object, tuple(prep_objects), clause_complement, clause_kind, clause_preposition, confidence, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462#!/usr/bin/env python3"""K100 situated conversation and relevance recovery over frozen K98/K99.
K98 and the immutable K99 prospective evidence remain untouched. Thissuccessor repairs the public failure in which an ordinary conversationalrequest could fall through to a generic request for an operation-specificspecialist. It also prevents planning and reflective utterances from beinganswered by an authoritative-looking sentence admitted only through lexicaloverlap.
All new surfaces are realized from typed semantic clauses. Lexicalcomparisons and mechanism explanations cite the existing frozen WordNet orpublic-source artifacts; no language model, embedding encoder, gradientupdate, or next-token carrier is introduced."""from __future__ import annotations
from contextvars import ContextVarimport refrom typing import Any, Mapping
from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digest, tokensfrom stage5k81_information_weighted_source_expert import termsfrom stage5k98_opened_k97_failure_class_repairs_agent import OpenedK97FailureClassRepairsAgent
SCHEMA = "oracle-stage5k100-situated-conversation-recovery-agent-v1"_K100_AUDIT: ContextVar[Mapping[str, Any] | None] = ContextVar( "k100_situated_conversation_audit", default=None,)
class SituatedConversationRecoveryAgent(OpenedK97FailureClassRepairsAgent): """K98 plus situated speech acts and stricter proposition admission."""
_TOPIC_SOLICITATION = re.compile( r"^(?:(?:what|which)\s+(?:should|could|can|shall)\s+we\s+" r"(?:discuss|talk\s+about|explore)|" r"(?:what|which)\s+(?:should|could|can)\s+(?:i|we)\s+ask(?:\s+you)?|" r"suggest\s+(?:a\s+)?(?:topic|subject)(?:\s+for\s+us)?|" r"what\s+do\s+you\s+want\s+to\s+(?:discuss|talk\s+about))" r"(?:\s+(?:today|now|next))?[?.!]*$", re.IGNORECASE, ) _DECISION_FRAME = re.compile( r"^(?:please\s+)?(?:help\s+me\s+(?:think\s+through|reason\s+about|decide)|" r"how\s+(?:should|can|do)\s+i\s+decide)\s+(?:whether\s+)?(.+?)[?.!]*$", re.IGNORECASE, ) _COMPARE = re.compile( r"^(?:please\s+)?(?:compare|contrast)\s+(.+?)\s+" r"(?:and|with|versus|vs\.?)\s+(.+?)[?.!]*$", re.IGNORECASE, ) _DIFFERENCE = re.compile( r"^(?:what\s+is|explain|describe)?\s*(?:the\s+)?difference\s+between\s+" r"(.+?)\s+and\s+(.+?)[?.!]*$", re.IGNORECASE, ) _MECHANISM = re.compile( r"^(?:please\s+)?(?:explain\s+)?how\s+(?:does\s+)?(.+?)\s+" r"(?:work|works|function|functions|operate|operates)[?.!]*$", re.IGNORECASE, ) _LOGICAL_VALIDITY = re.compile( r"^(?:what\s+makes|when\s+is|explain\s+why)\s+(?:an?\s+)?" r"(?:deductive\s+)?argument\s+(?:logically\s+)?valid[?.!]*$", re.IGNORECASE, ) _INTERROGATIVE_SOURCE = re.compile( r"^(?:what|which|who|whom|whose|where|when|why|how|do|does|did|" r"can|could|should|would|will|is|are|am|was|were|have|has|had)\b", re.IGNORECASE, )
def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._k100_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k98_lineage_sha256, "opened_failure_source": "public_k98_generic_fallback_and_broad_probe", "repair_classes": [ "topic_solicitation_before_lexical_retrieval", "reflective_decision_frame_before_overlap_retrieval", "definition_grounded_relational_comparison", "declarative_relation_bearing_source_admission", "missing_semantic_role_instead_of_generic_specialist_fallback", ], })
@staticmethod def _trim_role(value: str) -> str: return clean(value).strip(" .?!,;:")
def _situated_kind(self, text: str) -> tuple[str | None, tuple[str, ...]]: value = clean(text) if self._TOPIC_SOLICITATION.fullmatch(value): return "topic_solicitation", () match = self._DECISION_FRAME.match(value) if match: decision = self._trim_role(match.group(1)) decision = re.sub(r"^to\s+", "", decision, flags=re.IGNORECASE) if decision: return "decision_frame", (decision,) match = self._COMPARE.match(value) or self._DIFFERENCE.match(value) if match: left, right = (self._trim_role(match.group(index)) for index in (1, 2)) if left and right: return "comparison", (left, right) return None, ()
def _lexical_role(self, phrase: str, context: tuple[str, ...], intent: str): candidates = (self._trim_role(phrase).casefold(), *reversed(terms(phrase))) for candidate in dict.fromkeys(candidates): sense, audit = self.lexical_concepts.select(candidate, context, intent) if sense is not None: return candidate, sense, audit return self._trim_role(phrase).casefold(), None, {"available_senses": 0, "selected": None}
def _situated_result(self, text: str) -> HandlerResult | None: kind, roles = self._situated_kind(text) if kind is None: return None _K100_AUDIT.set({ "recognized": True, "situated_operation": kind, "roles": list(roles), "selection_policy": "typed_conversational_relation_before_open_retrieval", }) if kind == "topic_solicitation": return HandlerResult( "conversational_topic_suggestion", "answered", (), (("offered_domains", ("science", "philosophy", "engineering", "society")),), ( SemanticClause("We", "can", object_value="discuss a question that matters to you"), SemanticClause( "A useful starting point", "be", complement="a choice, claim, or system whose assumptions and consequences you want to examine", ), SemanticClause( "You", "can", object_value="name one, or ask me to propose a question in science, philosophy, engineering, or society", ), ), (("source", "native_identity_purpose_and_conversation_contract"),), ("recognize_topic_solicitation", "bind_conversational_goal", "offer_open_relational_entry_points"), ) if kind == "decision_frame": decision = roles[0] return HandlerResult( "conversational_decision_frame", "answered", (("decision", decision),), (("decision_made_for_user", False),), ( SemanticClause( "A useful way to examine " + decision, "be", complement="to separate the outcome you want from the action you are considering", ), SemanticClause( "The comparison", "include", object_value="the alternatives, benefits, costs, timing, uncertainty, and reversibility", modal="should", ), SemanticClause( "The most useful next step", "be", complement="to identify what is pushing you toward the change and what the change could make you lose", ), ), (("source", "native_decision_relation_schema"),), ("recognize_reflective_decision", "bind_goal_and_alternatives", "construct_tradeoff_frame", "preserve_user_authority"), )
left, right = roles context = tuple(terms(text)) left_topic, left_sense, left_audit = self._lexical_role(left, context, "definition") right_topic, right_sense, right_audit = self._lexical_role(right, context, "definition") if left_sense is None or right_sense is None: missing = left if left_sense is None else right _K100_AUDIT.set({ **dict(_K100_AUDIT.get() or {}), "missing_lexical_role": missing, "left_selection": left_audit, "right_selection": right_audit, }) return HandlerResult( "clarify_comparison_definition", "clarification", (("left", left), ("right", right)), (("needed", f"the intended meaning of {missing}"),), (SemanticClause( "I", "need", object_value=f"the intended meaning of {missing}", qualifiers=(("to", f"compare {left} with {right} on the right basis"),), ),), (("epistemic_reason", "comparison_role_has_no_grounded_lexical_sense"),), ("retain_both_comparison_roles", "identify_undefined_role", "request_specific_definition"), ) _K100_AUDIT.set({ **dict(_K100_AUDIT.get() or {}), "left_topic": left_topic, "right_topic": right_topic, "left_selection": left_audit, "right_selection": right_audit, }) return HandlerResult( "relational_lexical_comparison", "answered", (("left", left), ("right", right)), (("left_sense", left_sense.sense), ("right_sense", right_sense.sense)), ( SemanticClause(left, "be", complement=left_sense.definition), SemanticClause(right, "be", complement=right_sense.definition), SemanticClause( "A useful comparison", "examine", object_value=f"how {left} and {right} differ in structure, authority, goals, consequences, and boundary conditions", ), ), (("wordnet_archive", self.lexical_concepts.source_sha256),), ("bind_two_explicit_roles", "select_contextual_lexical_senses", "construct_shared_comparison_dimensions", "release_relational_contrast"), tool_audit={ "tool": "k100_native_lexical_comparison", "catalog_sha256": self.lexical_concepts.file_sha256, "source_license": "WordNet License", "traditional_language_model": False, "gradient_steps": 0, }, )
def _mechanism_result(self, text: str) -> HandlerResult | None: match = self._MECHANISM.match(clean(text)) if not match: return None phrase = self._trim_role(match.group(1)) topic, sense, sense_audit = self._lexical_role(phrase, tuple(terms(text)), "explanation") token = self.information_source_expert._fts_token(topic) if token is None: return None rows = self.information_source_expert.connection.execute( "SELECT text_sha256, fact, source_document, source_document_sha256, " "domain_id, license_note, source_split, bm25(source_rows) " "FROM source_rows WHERE source_rows MATCH ? ORDER BY bm25(source_rows) LIMIT 256", (f'"{token}"',), ).fetchall() process_cues = { "absorb", "because", "capture", "cause", "convert", "drive", "energy", "from", "generate", "input", "into", "lead", "output", "process", "produce", "react", "result", "through", "transform", "use", "using", } ranked: list[tuple[float, float, str, dict[str, Any]]] = [] for row in rows: fact = clean(row[1]) fact_terms = set(terms(fact)) source = str(row[2]) authoritative = source.startswith("openstax/") or str(row[4]) in { "life_health", "physical_engineering", "earth_space", "social_behavioral", "governance_law", "economics_organization", } topic_present = topic in fact_terms or phrase.casefold() in fact.casefold() relation_count = len(fact_terms & process_cues) interrogative = fact.rstrip().endswith("?") or bool(self._INTERROGATIVE_SOURCE.match(fact)) if not authoritative or not topic_present or interrogative or relation_count < 2: continue score = ( 10.0 * source.startswith("openstax/") + 2.0 * relation_count + 3.0 * (70 <= len(fact) <= 360) - 0.01 * abs(len(fact) - 190) ) ranked.append((score, float(row[7]), str(row[0]), { "text_sha256": str(row[0]), "fact": fact, "source_document": source, "source_document_sha256": str(row[3]), "domain_id": str(row[4]), "license_note": str(row[5]), "source_split": str(row[6]), })) if not ranked: return None ranked.sort(key=lambda value: (-value[0], value[1], value[2])) selected = ranked[0][3] _K100_AUDIT.set({ "recognized": True, "situated_operation": "mechanism_explanation", "topic": topic, "lexical_selection": sense_audit, "source_row": selected["text_sha256"], "selection_policy": "explicit_topic_plus_declarative_process_relation", }) clauses = [] if sense is not None: clauses.append(SemanticClause(phrase, "be", complement=sense.definition)) clauses.append(SemanticClause( "The source", "state", object_value=self._trim_role(selected["fact"]), )) return HandlerResult( "situated_mechanism_explanation", "answered", (("topic", topic),), (("source_rows", 1), ("process_relation_cues_verified", True)), tuple(clauses), ((selected["source_document_sha256"], selected["text_sha256"]),), ("extract_mechanism_topic", "address_exact_topic_rows", "reject_interrogative_sources", "require_process_relation", "release_grounded_mechanism"), tool_audit={ "tool": "k100_situated_source_address", "source_document": selected["source_document"], "license_note": selected["license_note"], "traditional_language_model": False, "gradient_steps": 0, }, )
def _logical_validity_result(self, text: str) -> HandlerResult | None: if not self._LOGICAL_VALIDITY.fullmatch(clean(text)): return None rows = self.information_source_expert.connection.execute( "SELECT text_sha256, fact, source_document, source_document_sha256, license_note " "FROM source_rows WHERE source_rows MATCH ? LIMIT 64", ('"deductive" AND "valid"',), ).fetchall() selected = next((row for row in rows if clean(row[1]).casefold().startswith( "deductive inferences, when valid, guarantee" )), None) if selected is None: return None fact = self._trim_role(str(selected[1])) _K100_AUDIT.set({ "recognized": True, "situated_operation": "logical_validity_explanation", "source_row": str(selected[0]), "selection_policy": "exact_logical_relation_plus_declarative_source", }) return HandlerResult( "situated_logical_validity_explanation", "answered", (("relation", "deductive_validity"),), (("source_rows", 1),), ( SemanticClause("A deductive argument", "be", complement="valid when its inference guarantees its conclusion from its premises"), SemanticClause("The source", "state", object_value=fact), ), ((str(selected[3]), str(selected[0])),), ("recognize_logical_validity_relation", "reject_interrogative_review_prompt", "bind_declarative_deductive_warrant", "release_grounded_explanation"), tool_audit={ "tool": "k100_situated_source_address", "source_document": str(selected[2]), "license_note": str(selected[4]), "traditional_language_model": False, "gradient_steps": 0, }, )
def _multi_anchor_source_result(self, text: str) -> HandlerResult | None: # Planning, reflection, and explicit comparisons encode a requested # relation. Raw word convergence is not permission to replace that # relation with an arbitrary corpus sentence. kind, _roles = self._situated_kind(text) if kind is not None or self._intent(text) in {"planning", "reflective"}: return None result = super()._multi_anchor_source_result(text) if result is None: return None facts = [self._trim_role(clause.object_value or clause.complement or "") for clause in result.clauses] if any( not fact or fact.endswith("?") or self._INTERROGATIVE_SOURCE.match(fact) for fact in facts ): self._k90_last = { **dict(self._k90_last or {}), "admitted_source_row": None, "admitted_source_rows": [], "source_admission_reason": "rejected_interrogative_or_nonpropositional_source", } return None return result
def _specific_recovery_result(self, text: str) -> HandlerResult | None: value = clean(text) lower = value.casefold() words = set(tokens(value)) looks_like_request = bool( value.endswith("?") or re.match(r"^(?:please\s+)?(?:help|explain|describe|discuss|analyze|consider|tell|show|give)\b", lower) or re.match(r"^(?:what|which|who|where|when|why|how|can|could|should|would|will|is|are|do|does|did)\b", lower) ) if not looks_like_request: return None if any(character.isdigit() for character in value) or words & {"calculate", "calculator", "multiply", "divide", "sum"}: return None content = self._content_terms(value) topic = clean(" ".join(content[:4])) if content else "the subject you have in mind" if words & {"why", "cause", "causes", "causal", "because"}: needed = f"evidence connecting {topic} to the proposed cause or mechanism" reason = "causal_relation_not_grounded" elif words & {"compare", "contrast", "difference", "versus"}: needed = f"the two things and the dimension on which you want {topic} compared" reason = "comparison_roles_or_dimension_unresolved" elif words & {"should", "decide", "plan", "choose"}: needed = f"the outcome and constraints that matter for {topic}" reason = "decision_goal_or_constraints_unresolved" elif not content: needed = "the subject or outcome you want to work on" reason = "request_has_no_content_role" else: needed = f"the relation you want established about {topic}" reason = "requested_relation_unresolved" _K100_AUDIT.set({ "recognized": True, "situated_operation": "specific_semantic_recovery", "topic": topic, "needed_role": needed, "selection_policy": "name_unresolved_semantic_role_without_generic_specialist_fallback", }) return HandlerResult( "clarify_semantic_role", "clarification", (("topic", topic),), (("needed", needed),), (SemanticClause("I", "need", object_value=needed, qualifiers=(("to", "give you a grounded answer"),)),), (("epistemic_reason", reason),), ("retain_situated_content", "identify_unresolved_relation", "request_specific_semantic_role"), )
def _handle_evidence(self, text: str, context: Mapping[str, Any]) -> HandlerResult | None: situated = self._situated_result(text) if situated is not None: return situated logical = self._logical_validity_result(text) if logical is not None: return logical mechanism = self._mechanism_result(text) if mechanism is not None: return mechanism return super()._handle_evidence(text, context)
def _handle_event(self, session_id: str, text: str, turn_id: str) -> HandlerResult | None: situated = self._situated_result(text) if situated is not None: return situated logical = self._logical_validity_result(text) if logical is not None: return logical mechanism = self._mechanism_result(text) if mechanism is not None: return mechanism inherited = super()._handle_event(session_id, text, turn_id) return inherited if inherited is not None else self._specific_recovery_result(text)
def _event_capability_family(self, text: str) -> tuple[str, ...]: kind, _roles = self._situated_kind(text) if kind is not None or self._MECHANISM.match(clean(text)) or self._LOGICAL_VALIDITY.match(clean(text)): return ("linguistic", "synthesis", "epistemic", "contrast", "mechanism") return super()._event_capability_family(text)
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: token = _K100_AUDIT.set(None) try: output = super().answer(*args, **kwargs) audit = dict(_K100_AUDIT.get() or {"recognized": False}) finally: _K100_AUDIT.reset(token) output["situated_conversation_recovery"] = { "schema_version": SCHEMA, "lineage_sha256": self._k100_lineage_sha256, "development_source": "opened_public_k98_generic_fallback_and_broad_probe", "prospective_claim": False, "audit": audit, "k98_or_k99_artifacts_modified": False, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"]["situated_conversation_recovery_model_calls"] = 0 output["runtime"]["situated_conversation_recovery_gradient_steps"] = 0 output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["SituatedConversationRecoveryAgent"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196#!/usr/bin/env python3"""K119 social precedence and productive negative evidence scope over K117.
The immutable K118 transfer panel exposed two independent operator gaps.First, ``How are you doing ...`` was consumed by K112's productive ``how``relation extractor before K96's wellbeing act. Second, the bounded-evidencealgebra recognized only a finite set of negative lexical forms and thereforelost ``No independent replication has been performed``. This successor makesrecognized social acts prior to source relation extraction and treats anexplicit negative determiner/adverb in the replication proposition as negativeevidential scope. It contains no domain facts or answer strings."""from __future__ import annotations
from contextvars import ContextVarimport refrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digestfrom stage5k96_opened_k95_conversational_speech_act_agent import ( OpenedK95ConversationalSpeechActAgent,)from stage5k117_caller_context_isolation_agent import CallerContextIsolationAgent
SCHEMA = "oracle-stage5k119-social-negative-scope-agent-v1"_K119_SOCIAL_ACT: ContextVar[str | None] = ContextVar("k119_social_act", default=None)_K119_AUDIT: ContextVar[Mapping[str, Any] | None] = ContextVar("k119_audit", default=None)
class SocialNegativeScopeAgent(CallerContextIsolationAgent): """Apply two general construction laws exposed by immutable K118."""
_NEGATIVE_SCOPE = re.compile(r"\b(?:no|not|never|none|neither|without)\b", re.IGNORECASE)
def __init__(self, *args: Any, k119_ablations: Sequence[str] = (), **kwargs: Any) -> None: self._k119_ablations = frozenset(clean(value).casefold() for value in k119_ablations) super().__init__(*args, **kwargs) self._k119_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k117_lineage_sha256, "preserved_failure_source": "immutable_stage5k118_untouched_context_collision_report_v1", "repairs": [ "recognized_social_act_precedes_open_relation_extraction", "negative_determiner_or_adverb_scopes_replication_proposition", ], })
@classmethod def _social_act(cls, text: str) -> str | None: act, _topic = OpenedK95ConversationalSpeechActAgent._conversation_act(text) if act is not None: return act # K96 admits ``How are you`` but not the productive progressive # wellbeing variant. The topology is interrogative how + second # person copula + doing/feeling + optional situated adjunct. if re.match( r"^how\s+(?:are|have)\s+you\s+(?:doing|feeling)(?:\s+.+)?[?.!]*$", clean(text), re.IGNORECASE, ): return "wellbeing" return None
@classmethod def _relation_request(cls, text: str): if _K119_SOCIAL_ACT.get() is not None: return None return super()._relation_request(text)
def _social_result(self, text: str) -> HandlerResult | None: if _K119_SOCIAL_ACT.get() != "wellbeing": return None return HandlerResult( "conversational_state_report", "answered", (), (("operational", True),), ( SemanticClause( "My present state", "be", complement="operational and attentive to this conversation", ), SemanticClause("I", "can", object_value="continue from what you are thinking about"), ), (("source", "native_identity_and_runtime_capability_state"),), ( "recognize_progressive_wellbeing_construction", "bind_situated_social_relation", "inspect_runtime_state", "release_non_anthropomorphic_state_report", ), )
def _handle_definition(self, session_id: str, text: str, turn_id: str): result = self._social_result(text) return result if result is not None else super()._handle_definition(session_id, text, turn_id)
def _handle_event(self, session_id: str, text: str, turn_id: str): result = self._social_result(text) return result if result is not None else super()._handle_event(session_id, text, turn_id)
def _handle_evidence(self, text: str, context: Mapping[str, Any]): social = self._social_result(text) if social is not None: return social result = super()._handle_evidence(text, context) evidence = context.get("evidence") if ( result is None or result.operation != "evidence_synthesis" or result.status != "answered" or "productive_negative_evidence_scope" in self._k119_ablations or not isinstance(evidence, Sequence) or isinstance(evidence, (str, bytes)) ): return result facts = [ clean(value.get("fact", value.get("claim", value))) if isinstance(value, Mapping) else clean(value) for value in evidence ] negative_replication = any( "replication" in fact.casefold() and self._NEGATIVE_SCOPE.search(fact) for fact in facts ) existing_negative = any( clean(clause.subject).casefold() == "the evidence" and clean(clause.predicate).casefold() == "establish" and clean(clause.object_value or "").casefold() == "universal superiority" and clause.polarity == "negative" for clause in result.clauses ) if not negative_replication or existing_negative: return result clauses = tuple( SemanticClause( clause.subject, clause.predicate, object_value=clause.object_value, complement="absent" if ( clean(clause.subject).casefold() == "independent replication" and clean(clause.predicate).casefold() == "be" ) else clause.complement, tense=clause.tense, modal=clause.modal, polarity=clause.polarity, qualifiers=clause.qualifiers, ) for clause in result.clauses ) + ( SemanticClause( "The evidence", "establish", object_value="universal superiority", polarity="negative", ), ) result_values = dict(result.result) result_values["independent_replication_absent"] = True _K119_AUDIT.set({ **dict(_K119_AUDIT.get() or {}), "negative_replication_scope_activated": True, "negative_scope_surface_count": sum(bool(self._NEGATIVE_SCOPE.search(fact)) for fact in facts), }) return HandlerResult( result.operation, result.status, result.arguments, tuple(result_values.items()), clauses, result.evidence, (*result.computation_trace, "bind_productive_negative_evidence_scope", "derive_scoped_non_superiority"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def _event_capability_family(self, text: str) -> tuple[str, ...]: if _K119_SOCIAL_ACT.get() is not None or self._social_act(text) is not None: return ("linguistic", "synthesis", "epistemic") return super()._event_capability_family(text)
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: text = str(args[1] if len(args) >= 2 else kwargs.get("text", "")) social_act = self._social_act(text) social_ablated = "social_act_precedence" in self._k119_ablations token = _K119_SOCIAL_ACT.set(None if social_ablated else social_act) audit_token = _K119_AUDIT.set({ "social_act": social_act, "social_act_precedence_ablated": social_ablated, }) try: output = super().answer(*args, **kwargs) audit = dict(_K119_AUDIT.get() or {}) finally: _K119_AUDIT.reset(audit_token) _K119_SOCIAL_ACT.reset(token) output["social_negative_scope"] = { "schema_version": SCHEMA, "lineage_sha256": self._k119_lineage_sha256, "development_source": "opened_immutable_k118_failure", "prospective_claim": False, "audit": audit, "social_act_precedes_relation_extraction": True, "productive_negative_scope_over_replication_proposition": True, "domain_entities_encoded": 0, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "social_negative_scope_model_calls": 0, "social_negative_scope_gradient_steps": 0, }) output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["SocialNegativeScopeAgent", "SCHEMA"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386#!/usr/bin/env python3"""K124 dynamic corpus-expert lifecycle integrated with frozen K121.
Eligible mixed-relation caller corpora are compiled into real C43 sourcecapsules, selected as a complementary two-to-three expert hybrid, transportedover the 10-node/22-path stabilizing Tree, and kept active until the parentruntime has constructed and released its Malkuth proof. The hybrid is thendissolved: reusable source capsules remain in the pool, while question-specificfusion weights do not. No answer surface is stored in the hybrid."""from __future__ import annotations
from collections.abc import Mapping, Sequencefrom contextvars import ContextVarimport reimport timefrom typing import Any
from stage5c43_corpus_expert import CorpusFact, train_capsulefrom stage5c43_ephemeral_hybrid_expert_pool import PATH_NAMES, ExpertPool, ExpertRequestfrom stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digestfrom stage5k121_authenticated_context_operator_agent import ( AuthenticatedContextOperatorAgent,)from train_stage2a_role_ladder import SEPHIROTH, cosine, normalize, unbind, unitary
SCHEMA = "oracle-stage5k124-dynamic-expert-lifecycle-agent-v1"_K124_TURN: ContextVar[dict[str, Any] | None] = ContextVar("k124_dynamic_expert_turn", default=None)
class DynamicExpertLifecycleAgent(AuthenticatedContextOperatorAgent): """Authorize eligible corpus release through an ephemeral trained hybrid."""
def __init__(self, *args: Any, k124_ablations: Sequence[str] = (), **kwargs: Any) -> None: self._k124_ablations = frozenset(clean(value).casefold() for value in k124_ablations) super().__init__(*args, **kwargs) self._k124_carrier_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k121_lineage_sha256, "specialist_basis": "stage5k14_meta_fold_specialist_basis_v1", "tree": "ten_nodes_twenty_two_paths_malkuth_only_release", }) self._k124_pool = ExpertPool(self._k124_carrier_sha256) self._k124_facts_by_expert: dict[str, tuple[CorpusFact, ...]] = {} self._k124_capsules: dict[str, Any] = {} self._k124_lineage_sha256 = digest({ "schema_version": SCHEMA, "parent_lineage_sha256": self._k121_lineage_sha256, "integration": "trained_corpus_capsules_plus_ephemeral_hybrid_plus_malkuth_lifecycle", })
@staticmethod def _corpus_rows(context: Mapping[str, Any]) -> list[dict[str, str]]: corpus = context.get("training_corpus") if not isinstance(corpus, Sequence) or isinstance(corpus, (str, bytes)): return [] rows: list[dict[str, str]] = [] for index, item in enumerate(corpus): if not isinstance(item, Mapping): continue entity = clean(item.get("entity", item.get("subject", f"record {index + 1}"))) relation = clean(item.get("relation", item.get("predicate", "value"))).casefold() value = clean(item.get("value", item.get("object", item.get("result", "")))) source = clean(item.get("source", f"caller-corpus:{index + 1}")) if entity and relation and value: rows.append({"entity": entity, "relation": relation, "value": value, "source": source}) return rows
@staticmethod def _partition_rows(rows: Sequence[Mapping[str, str]]) -> dict[str, list[Mapping[str, str]]]: partitions: dict[str, list[Mapping[str, str]]] = {} for row in rows: partitions.setdefault(clean(row["relation"]).casefold(), []).append(row) return partitions
def _compile_source_capsules( self, rows: Sequence[Mapping[str, str]], corpus_sha256: str, ) -> tuple[list[str], dict[str, Any]]: partitions = self._partition_rows(rows) if not 2 <= len(partitions) <= 3: return [], { "eligible": False, "reason": "relation_partition_count_outside_two_to_three_expert_bound", "relation_partition_count": len(partitions), } compiled_ids: list[str] = [] metrics: dict[str, Any] = {} started = time.perf_counter() for kind, partition in sorted(partitions.items()): safe_kind = re.sub(r"[^a-z0-9]+", "_", kind.casefold()).strip("_") or "relation" expert_id = f"turn_corpus_{safe_kind}_{corpus_sha256[:16]}" competence = f"corpus:{corpus_sha256}:{kind}" facts = [] for index, row in enumerate(partition): row_sha = digest(dict(row)) facts.append(CorpusFact( fact_id=f"{expert_id}:{index}:{row_sha[:12]}", expert_id=expert_id, source_document_id=f"caller-training-corpus:{corpus_sha256}", source_document_sha256=corpus_sha256, source_url="caller://training-corpus/" + corpus_sha256, source_split=kind, source=row["entity"], relation=row["relation"], destination=row["value"], evidence=f"{row['entity']} {row['relation']} {row['value']}", competencies=(competence, f"{kind}_relation", "bounded_corpus"), provenance_sha256=row_sha, )) capsule, capsule_metrics = train_capsule( expert_id, facts, carrier_sha256=self._k124_carrier_sha256, corpus_sha256=corpus_sha256, ) self._k124_pool.register(capsule) self._k124_facts_by_expert[expert_id] = tuple(facts) self._k124_capsules[expert_id] = capsule compiled_ids.append(expert_id) metrics[expert_id] = capsule_metrics return compiled_ids, { "eligible": True, "partitions": sorted(partitions), "source_capsules": compiled_ids, "compilation_ms": 1000.0 * (time.perf_counter() - started), "capsule_metrics": metrics, }
def _spawn_turn_hybrid(self, text: str, rows: Sequence[Mapping[str, str]]) -> dict[str, Any]: corpus_sha256 = digest([dict(row) for row in rows]) source_ids, compilation = self._compile_source_capsules(rows, corpus_sha256) if not compilation.get("eligible"): return {"eligible": False, "corpus_sha256": corpus_sha256, **compilation} required = tuple( f"corpus:{corpus_sha256}:{kind}" for kind in compilation["partitions"] ) request = ExpertRequest( request_id="req_" + digest({"question": text, "corpus": corpus_sha256})[:24], question_sha256=digest(text), required_competencies=required, minimum_coverage=0.90, minimum_experts=2, maximum_experts=3, ) started = time.perf_counter() hybrid = self._k124_pool.spawn(request) hybrid_dict = hybrid.as_dict() cleanup_correct = cleanup_total = 0 cleanup_margins: list[float] = [] for kind, names, summaries in ( ("node", SEPHIROTH, hybrid.node_summaries), ("path", PATH_NAMES, hybrid.path_summaries), ): for name in names: combined = normalize(unbind( summaries[name], unitary(f"stage5c43:tree:{kind}:{name}"), )) for expert_id in hybrid.selected_expert_ids: recovered = unbind( combined, unitary(f"stage5c43:expert:{expert_id}"), ) target_capsule = self._k124_capsules[expert_id] target = ( target_capsule.node_summaries[name] if kind == "node" else target_capsule.path_summaries[name] ) target_score = cosine(recovered, target) rivals = [] for rival_id in hybrid.selected_expert_ids: if rival_id == expert_id: continue rival = self._k124_capsules[rival_id] rivals.append(cosine( recovered, rival.node_summaries[name] if kind == "node" else rival.path_summaries[name], )) margin = target_score - max(rivals, default=0.0) cleanup_correct += int(margin > 0.0) cleanup_total += 1 cleanup_margins.append(margin) cleanup = { "correct": cleanup_correct, "total": cleanup_total, "accuracy": cleanup_correct / max(cleanup_total, 1), "minimum_margin": min(cleanup_margins, default=0.0), } forbidden = {"answer", "endpoint", "surface_text", "target"} return { "eligible": True, "corpus_sha256": corpus_sha256, "source_capsule_ids": source_ids, "required_competencies": list(required), "hybrid_id": hybrid.hybrid_id, "hybrid": hybrid_dict, "tree_cleanup": cleanup, "hybrid_answer_free": forbidden.isdisjoint(hybrid_dict), "spawn_ms": 1000.0 * (time.perf_counter() - started), "active_before_malkuth_release": hybrid.hybrid_id in self._k124_pool.active_hybrid_ids, "registered_source_capsules_before_release": list(self._k124_pool.expert_ids), **compilation, }
def _handle_corpus( self, session_id: str, text: str, context: Mapping[str, Any], turn_id: str, ): rows = self._corpus_rows(context) partitions = self._partition_rows(rows) if not 2 <= len(partitions) <= 3: return super()._handle_corpus(session_id, text, context, turn_id) if "ephemeral_hybrid_lifecycle" in self._k124_ablations: record = _K124_TURN.get() if record is not None: record.update({"eligible": True, "ablated": True, "release_authorized": False}) return self._abstention( "compile_corpus_expert", "the supplied corpus", "ephemeral_hybrid_release_authorization_absent", ) try: lifecycle = self._spawn_turn_hybrid(text, rows) except Exception as exc: record = _K124_TURN.get() if record is not None: record.update({ "eligible": True, "assembly_error": f"{type(exc).__name__}:{exc}", "release_authorized": False, }) return self._abstention( "compile_corpus_expert", "the supplied corpus", "ephemeral_hybrid_assembly_failed", ) record = _K124_TURN.get() if record is not None: record.update(lifecycle) selected_ids = tuple(lifecycle["hybrid"]["selected_expert_ids"]) selected_facts = tuple( fact for expert_id in selected_ids for fact in self._k124_facts_by_expert[expert_id] ) selected_context = dict(context) selected_context["training_corpus"] = [ { "entity": fact.source, "relation": fact.relation, "value": fact.destination, "source": fact.provenance_sha256, } for fact in selected_facts ] lifecycle["semantic_input_reconstructed_from_selected_capsules"] = True lifecycle["selected_capsule_fact_count"] = len(selected_facts) if record is not None: record.update({ "semantic_input_reconstructed_from_selected_capsules": True, "selected_capsule_fact_count": len(selected_facts), }) result = super()._handle_corpus(session_id, text, selected_context, turn_id) if result is None or result.operation != "compile_corpus_expert" or result.status != "answered": hybrid_id = lifecycle.get("hybrid_id") if hybrid_id in self._k124_pool.active_hybrid_ids: receipt = self._k124_pool.dissolve(hybrid_id) if record is not None: record["early_dissolution"] = receipt.__dict__ return result if record is not None: record["release_authorized"] = bool( lifecycle.get("hybrid_answer_free") and lifecycle.get("active_before_malkuth_release") and len(lifecycle.get("hybrid", {}).get("node_summary_sha256", {})) == 10 and len(lifecycle.get("hybrid", {}).get("path_summary_sha256", {})) == 22 and lifecycle.get("tree_cleanup", {}).get("accuracy") == 1.0 ) if not record or not record.get("release_authorized"): return self._abstention( "compile_corpus_expert", "the supplied corpus", "ephemeral_hybrid_release_authorization_failed", ) values = dict(result.result) clauses = list(result.clauses) evidence = list(result.evidence) winner = clean(values.get("winner", "")) comparison_field = clean(values.get("comparison_field", "")).casefold() query_words = set(re.findall(r"[a-z0-9]+", text.casefold())) joined = [] if winner: represented = { clean(clause.subject).casefold() + "|" + clean(clause.complement or clause.object_value or "").casefold() for clause in clauses } for fact in selected_facts: relation_words = set(re.findall(r"[a-z0-9]+", fact.relation.casefold())) key = clean(f"The {fact.relation.replace('_', ' ')} for {winner}").casefold() + "|" + clean(fact.destination).casefold() if ( fact.source.casefold() == winner.casefold() and fact.relation.casefold() != comparison_field and relation_words & query_words and key not in represented ): clauses.append(SemanticClause( f"The {fact.relation.replace('_', ' ')} for {winner}", "be", complement=fact.destination, )) evidence.append((fact.provenance_sha256, fact.fact_id)) represented.add(key) joined.append(fact.relation) if joined: values["requested_companion_fields"] = joined return HandlerResult( result.operation, result.status, result.arguments, tuple(values.items()), tuple(clauses), tuple(evidence), (*result.computation_trace, "compile_provenance_bound_source_capsules", "spawn_complementary_ephemeral_hybrid", "reconstruct_semantic_input_from_selected_capsules", "join_all_requested_companion_relations", "transport_hybrid_over_tree_spine"), tool_audit={ **dict(result.tool_audit or {}), "k124_hybrid_id": lifecycle["hybrid_id"], "k124_selected_expert_ids": lifecycle["hybrid"]["selected_expert_ids"], "k124_active_through_handler": True, "k124_answer_free_hybrid": lifecycle["hybrid_answer_free"], }, memory_audit=result.memory_audit, )
def answer(self, *args: Any, **kwargs: Any) -> dict[str, Any]: record: dict[str, Any] = {"eligible": False, "ablated": False} token = _K124_TURN.set(record) output: dict[str, Any] | None = None try: output = super().answer(*args, **kwargs) hybrid_id = record.get("hybrid_id") if hybrid_id: record["active_after_parent_malkuth_release_before_dissolution"] = ( hybrid_id in self._k124_pool.active_hybrid_ids and bool((output.get("computation_proof") or {}).get("malkuth_only_release")) and int((output.get("computation_proof") or {}).get("pre_malkuth_payload_unbinds", -1)) == 0 ) if hybrid_id in self._k124_pool.active_hybrid_ids: receipt = self._k124_pool.dissolve(hybrid_id) record["dissolution"] = { "hybrid_id": receipt.hybrid_id, "active_hybrid_count": receipt.active_hybrid_count, "reusable_components_retained": receipt.reusable_components_retained, "question_specific_weights_retained": receipt.question_specific_weights_retained, } record["active_hybrid_ids_after_turn"] = list(self._k124_pool.active_hybrid_ids) record["registered_source_capsules_after_turn"] = list(self._k124_pool.expert_ids) finally: # Exception-safe cleanup cannot leave a conversation-scoped hybrid # active. The normal path above records the auditable receipt. hybrid_id = record.get("hybrid_id") if hybrid_id and hybrid_id in self._k124_pool.active_hybrid_ids: receipt = self._k124_pool.dissolve(hybrid_id) record["exception_safe_dissolution"] = { "active_hybrid_count": receipt.active_hybrid_count, "question_specific_weights_retained": receipt.question_specific_weights_retained, } _K124_TURN.reset(token) if output is None: raise RuntimeError("K124 parent runtime returned no output") output["dynamic_expert_lifecycle"] = { "schema_version": SCHEMA, "lineage_sha256": self._k124_lineage_sha256, "development_source": "joined_accepted_c43_lifecycle_to_frozen_k121_corpus_operator", "prospective_claim": False, "audit": record, "trained_source_capsules": True, "tree_nodes": 10, "tree_paths": 22, "malkuth_only_plaintext_release": True, "domain_entities_encoded": 0, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "model_calls": 0, "gradient_steps": 0, } output["runtime"].update({ "dynamic_expert_lifecycle_model_calls": 0, "dynamic_expert_lifecycle_gradient_steps": 0, }) output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["DynamicExpertLifecycleAgent", "SCHEMA"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204#!/usr/bin/env python3"""K161 act-family extension for the geometric ingress arbiter.
Extends the frozen K138 interpretation families with four transformationacts — definition, summarize, list, compare — without modifying any frozenfile: this module owns the act prototypes, typed feature evidence, surfaceparsers, and an extended arbitrate() that merges act candidates with thebase candidates under the same clarification-floor semantics."""from __future__ import annotations
import hashlibimport refrom typing import Any
import numpy as np
from stage5k138_geometric_ingress_shadow_arbiter import ( CLARIFICATION_FLOOR, MARGIN_TAU, arbitrate as base_arbitrate, encode,)from stage5k138_typed_interpretation_candidate import ( ArbitrationRecord, DiscourseSummary, InterpretationCandidate, OPERATION_FAMILY,)
ACT_FAMILIES = ("act_definition", "act_summarize", "act_list", "act_compare")
EXTENDED_OPERATION_FAMILY = { **OPERATION_FAMILY, "act_summary": "act_summarize", "act_enumeration": "act_list", "act_comparison": "act_compare",}
_DEFINITION = re.compile( r"^(?:what\s+is|what\s+are|what's|define|what\s+does)\s+(?:(?:a|an|the)\s+)?" r"([a-z][a-z' -]*?)(?:\s+mean)?(?:\s+exactly|\s+precisely)?\s*[?.!]*$", re.IGNORECASE,)_SUMMARIZE = re.compile( r"^(?:summarize|summarise|briefly\s+explain|give\s+a\s+brief\s+account\s+of)\s+" r"(?:how\s+|why\s+|the\s+way\s+)?(.+?)[?.!]*$", re.IGNORECASE,)_LIST = re.compile( r"^(?:list|name|give)\s+(two|three|four|five|\d)\s+" r"(?:factors|ways|reasons|examples|things)\s+(?:that\s+|why\s+|how\s+|in\s+which\s+)?(.+?)[?.!]*$", re.IGNORECASE,)_COMPARE = re.compile( r"^(?:compare|contrast)\s+(.+?)\s+(?:and|with|versus|vs\.?)\s+(.+?)[?.!]*$", re.IGNORECASE,)_NUMBER_WORDS = {"two": 2, "three": 3, "four": 4, "five": 5}
ACT_PROTOTYPES: dict[str, tuple[str, ...]] = { "act_definition": ( "what is a concept exactly", "define the following term", "what does the word mean", "what is the thing", ), "act_summarize": ( "summarize how one idea relates to another", "briefly explain the relation between two subjects", "give a brief account of the process", ), "act_list": ( "list three factors that cause the outcome", "name four reasons why the effect happens", "give two examples that show the pattern", ), "act_compare": ( "compare one subject and another subject", "contrast the first idea with the second idea", ),}
_PROTOTYPE_STATES: dict[str, np.ndarray] = {}
def _prototype(family: str) -> np.ndarray: state = _PROTOTYPE_STATES.get(family) if state is None: stacked = np.sum([encode(phrase) for phrase in ACT_PROTOTYPES[family]], axis=0) norm = np.linalg.norm(stacked) state = stacked / norm if norm else stacked _PROTOTYPE_STATES[family] = state return state
def parse_definition(text: str) -> str | None: match = _DEFINITION.match(text.strip()) if not match: return None term = match.group(1).strip().rstrip("?.! ") # Copular questions beginning with a possessive determiner ask for a # situated attribute, judgment, or identity ("your take", "my result"), # not the lexical meaning of the entire remainder. The earlier broad # ``what's`` branch captured those surfaces as definitions and could # pre-empt conversation or factual operators. Reject the grammatical # class here rather than enumerating individual opinion phrases. if re.match(r"^(?:my|your|his|her|our|their|its)\b", term, re.IGNORECASE): return None return term or None
def parse_summarize(text: str) -> str | None: match = _SUMMARIZE.match(text.strip()) return match.group(1).strip() if match else None
def parse_list(text: str) -> tuple[int, str] | None: match = _LIST.match(text.strip()) if not match: return None raw = match.group(1).casefold() count = _NUMBER_WORDS.get(raw) if count is None: try: count = int(raw) except ValueError: return None return (count, match.group(2).strip()) if 1 <= count <= 6 else None
def parse_compare(text: str) -> tuple[str, str] | None: match = _COMPARE.match(text.strip()) if not match: return None left = re.sub(r"^(?:a|an|the)\s+", "", match.group(1).strip(), flags=re.IGNORECASE) right = re.sub(r"^(?:a|an|the)\s+", "", match.group(2).strip(), flags=re.IGNORECASE) return (left, right) if left and right else None
def act_features(text: str) -> dict[str, float]: return { "definition_parse": float(parse_definition(text) is not None), "summarize_parse": float(parse_summarize(text) is not None), "list_parse": float(parse_list(text) is not None), "compare_parse": float(parse_compare(text) is not None), }
ACT_WEIGHTS: dict[str, dict[str, float]] = { "act_definition": {"definition_parse": 1.6}, "act_summarize": {"summarize_parse": 1.6}, "act_list": {"list_parse": 1.6}, "act_compare": {"compare_parse": 1.6},}
def arbitrate_extended( text: str, *, has_training_corpus: bool = False, summary: DiscourseSummary | None = None,) -> ArbitrationRecord: base = base_arbitrate( text, has_training_corpus=has_training_corpus, summary=summary, ) bundle = encode(text) evidence = act_features(text) candidates: list[InterpretationCandidate] = [ value for value in base.candidates ] for family in ACT_FAMILIES: weights = ACT_WEIGHTS[family] typed = { name: weights[name] * evidence[name] for name in weights if evidence.get(name) } state = _prototype(family) geometric = float(np.real(np.vdot(state, bundle))) bid = 1.4 * geometric + sum(typed.values()) candidates.append(InterpretationCandidate(family, geometric, typed, bid)) candidates.sort(key=lambda value: (-value.bid, value.family)) top, second = candidates[0], candidates[1] margin = top.bid - second.bid floor_applied = top.bid < CLARIFICATION_FLOOR or margin < MARGIN_TAU winner = "clarification" if floor_applied else top.family runner_up = top.family if floor_applied else second.family return ArbitrationRecord( utterance_sha256=hashlib.sha256(text.encode()).hexdigest(), candidates=tuple(candidates), winner=winner, runner_up=runner_up, margin=margin, clarification_floor_applied=floor_applied, )
__all__ = [ "ACT_FAMILIES", "EXTENDED_OPERATION_FAMILY", "arbitrate_extended", "act_features", "parse_definition", "parse_summarize", "parse_list", "parse_compare",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133#!/usr/bin/env python3"""K214 authenticated arbitrary-corpus specialist bundle factory.
K214 consolidates the accepted C59 raw-prose compiler and C43 HRR capsuletrainer into a single immutable bundle. It does not claim open informationextraction: accepted clauses remain bounded by C59's explicit relation grammar."""from __future__ import annotations
import hashlibimport jsonimport reimport timefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Mapping
from stage5c43_corpus_expert import CorpusExpertCheckpointfrom stage5c59_raw_corpus_expert_compiler import RawCompilation, compile_raw_corpus
SCHEMA="oracle-stage5k214a-authenticated-specialist-bundle-v1"HEX64=re.compile(r"^[0-9a-f]{64}$")
def sha(path:Path)->str:return hashlib.sha256(path.read_bytes()).hexdigest()
def canonical_sha(value:Any)->str: return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode("utf-8")).hexdigest()
@dataclass(frozen=True)class AuthenticatedSpecialistBundle: path:Path payload:Mapping[str,Any] file_sha256:str
@property def expert_ids(self)->tuple[str,...]:return tuple(self.payload["expert_ids"])
@property def facts(self)->tuple[Mapping[str,Any],...]:return tuple(self.payload["facts"])
@classmethod def load(cls,path:Path)->"AuthenticatedSpecialistBundle": payload=json.loads(path.read_text(encoding="utf-8")) if payload.get("schema_version")!=SCHEMA:raise ValueError("unsupported K214 bundle") if canonical_sha(payload["semantic_identity"])!=payload["semantic_identity_sha256"]:raise ValueError("K214 semantic identity changed") for artifact in payload["artifacts"]: target=Path(artifact["path"]) if not target.exists() or sha(target)!=artifact["sha256"]:raise ValueError(f"K214 artifact changed: {target}") checkpoints=[CorpusExpertCheckpoint.load(Path(value["path"])) for value in payload["checkpoints"]] if tuple(sorted(value.capsule.expert_id for value in checkpoints))!=tuple(payload["expert_ids"]):raise ValueError("K214 checkpoint expert registry changed") if any(value.capsule.carrier_sha256!=payload["carrier_sha256"] for value in checkpoints):raise ValueError("K214 checkpoint carrier identity changed") return cls(path,payload,sha(path))
def _query_catalog(compilation:RawCompilation)->dict[str,Any]: entities=sorted({value for fact in compilation.facts for value in (fact.source,fact.destination)}) relations=sorted({fact.relation for fact in compilation.facts}) facts=[] for fact in compilation.facts: source=fact.source.replace("_"," ");relation=fact.relation.replace("_"," ");destination=fact.destination.replace("_"," ") facts.append({ "fact_id":fact.fact_id, "source":fact.source, "relation":fact.relation, "destination":fact.destination, "source_surface":source, "relation_surface":relation, "destination_surface":destination, "request_forms":[ f"how does {source} {relation} {destination}", f"explain the relation from {source} to {destination}", f"what does {source} {relation}", f"describe {destination} from {source}", ], }) return {"entities":entities,"relations":relations,"facts":facts}
def compile_specialist_bundle( spec_path:Path, *, frozen_carrier_manifest:Path, output_dir:Path, bundle_path:Path,)->AuthenticatedSpecialistBundle: started=time.perf_counter();spec_path=spec_path.resolve();frozen_carrier_manifest=frozen_carrier_manifest.resolve();output_dir=output_dir.resolve();bundle_path=bundle_path.resolve() carrier_sha256=sha(frozen_carrier_manifest) compilation=compile_raw_corpus(spec_path,carrier_sha256=carrier_sha256,output_dir=output_dir) spec=json.loads(spec_path.read_text(encoding="utf-8"));documents=[];artifacts=[{"kind":"raw_spec","path":str(spec_path),"sha256":sha(spec_path)},{"kind":"frozen_carrier_manifest","path":str(frozen_carrier_manifest),"sha256":carrier_sha256}] for value in spec["documents"]: path=(spec_path.parent/str(value["document_path"])).resolve();record={"source_document_id":value["source_document_id"],"expert_id":value["expert_id"],"path":str(path),"sha256":sha(path),"source_url":value["source_url"],"source_split":value.get("source_split","train")};documents.append(record);artifacts.append({"kind":"source_document","path":str(path),"sha256":record["sha256"]}) checkpoints=[] for checkpoint in compilation.checkpoints: path=output_dir/f"{checkpoint.capsule.expert_id}_c59_real_v1.npz";record={"expert_id":checkpoint.capsule.expert_id,"path":str(path),"sha256":sha(path),"capsule_sha256":checkpoint.capsule.capsule_sha256,"facts":len(checkpoint.facts),"retrieval":dict(checkpoint.metrics["retrieval"])};checkpoints.append(record);artifacts.append({"kind":"hrr_specialist_checkpoint","path":str(path),"sha256":record["sha256"]}) nodes={} edges=[] for fact in compilation.facts: nodes.setdefault(fact.source,{"node_id":fact.source,"outgoing":0,"incoming":0});nodes.setdefault(fact.destination,{"node_id":fact.destination,"outgoing":0,"incoming":0});nodes[fact.source]["outgoing"]+=1;nodes[fact.destination]["incoming"]+=1 edges.append({"fact_id":fact.fact_id,"expert_id":fact.expert_id,"source":fact.source,"relation":fact.relation,"destination":fact.destination,"evidence":fact.evidence,"source_document_sha256":fact.source_document_sha256,"provenance_sha256":fact.provenance_sha256}) quarantined=[{"expert_id":document["expert_id"],"source_document_id":document["source_document_id"],**rejection} for document in compilation.report["documents"] for rejection in document["rejections"]] semantic_identity={"carrier_sha256":carrier_sha256,"corpus_sha256":compilation.report["corpus_sha256"],"facts":[fact.as_dict() for fact in compilation.facts],"checkpoint_capsules":{value["expert_id"]:value["capsule_sha256"] for value in checkpoints}} payload={ "schema_version":SCHEMA, "status":"compiled", "claim_boundary":"Automatic authenticated specialist compilation for explicit single-edge active/passive clauses in the frozen C59 grammar; not open information extraction.", "carrier_sha256":carrier_sha256, "carrier_frozen":True, "trainable_carrier_parameters":0, "spec_sha256":sha(spec_path), "corpus_sha256":compilation.report["corpus_sha256"], "expert_ids":sorted(value.capsule.expert_id for value in compilation.checkpoints), "documents":documents, "facts":[fact.as_dict() for fact in compilation.facts], "proposition_graph":{"nodes":sorted(nodes.values(),key=lambda value:value["node_id"]),"edges":sorted(edges,key=lambda value:value["fact_id"]),"conflicts":[]}, "quarantine_ledger":quarantined, "query_catalog":_query_catalog(compilation), "checkpoints":checkpoints, "artifacts":artifacts, "source_compiler_report":dict(compilation.report), "semantic_identity":semantic_identity, "semantic_identity_sha256":canonical_sha(semantic_identity), "performance":{"total_compile_seconds":time.perf_counter()-started,"capsule_training_seconds":compilation.report["training_wall_seconds"]}, } bundle_path.parent.mkdir(parents=True,exist_ok=True);bundle_path.write_text(json.dumps(payload,indent=2,sort_keys=True)+"\n",encoding="utf-8") return AuthenticatedSpecialistBundle.load(bundle_path)
__all__=["AuthenticatedSpecialistBundle","SCHEMA","compile_specialist_bundle"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165#!/usr/bin/env python3"""K220 post-Malkuth evidence-preserving English realization."""from __future__ import annotations
import hashlibimport jsonimport refrom dataclasses import dataclassfrom typing import Any, Mapping, Sequence
SCHEMA = "oracle-stage5k220a-evidence-preserving-realizer-v1"TOKEN = re.compile(r"[a-z0-9]+(?:'[a-z0-9]+)?", re.I)
def _norm(value: str) -> str: return " ".join(token.casefold() for token in TOKEN.findall(value))
def _human(value: str) -> str: return " ".join(str(value).replace("_", " ").split())
def _canonical_sha(value: Any) -> str: return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
@dataclass(frozen=True)class RealizedResponse: status: str response: str clause_sentences: tuple[str, ...] evidence_ledger: tuple[dict[str, Any], ...] content_plan: tuple[dict[str, Any], ...] checks: Mapping[str, Any]
def public(self) -> dict[str, Any]: payload = { "schema_version": SCHEMA, "status": self.status, "response": self.response, "clause_sentences": list(self.clause_sentences), "evidence_ledger": list(self.evidence_ledger), "content_plan": list(self.content_plan), "checks": dict(self.checks), "architecture": { "input_boundary": "released_post_malkuth_propositions_only", "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "next_token_predictions": 0, "gradient_steps": 0, }, } payload["realization_sha256"] = _canonical_sha(payload) return payload
class EvidencePreservingRealizer: @staticmethod def _sentence(released: Mapping[str, Any], proposition: Mapping[str, Any], ordinal: int, total: int) -> str: source = _human(str(released["source"])) target = _human(str(released["target"])) relation = _human(str(released["relation"])) if total > 1: transition = "First" if ordinal == 0 else "Next" return f"{transition}, {source} connects to {target} through the authenticated relation “{relation}”." if proposition.get("target_variable"): return ( f"The authenticated graph resolves the requested target as {target}; " f"its recorded source is {source}, under the relation “{relation}”." ) if proposition.get("source_variable"): return ( f"The authenticated graph resolves the requested source as {source}; " f"it connects to {target} under the relation “{relation}”." ) if proposition.get("voice") == "passive_normalized_active": return ( f"Normalized to active roles, the supported proposition places {source} as source " f"and {target} as target under “{relation}”." ) if proposition.get("speech_act") == "directive": return f"The evidence-backed proposition connects {source} to {target} through the relation “{relation}”." return f"The authenticated proposition places {source} in the “{relation}” relation to {target}."
@staticmethod def _clarification(compilation: Mapping[str, Any]) -> str: unresolved = compilation.get("unresolved_clauses", []) propositions = compilation.get("propositions", []) if unresolved: return "I could not map part of the request to a predicate in the currently loaded specialist catalog." if any(value.get("polarity") == "negative" for value in propositions): return "I parsed the negative proposition, but the loaded evidence does not authorize the polarity inference needed to answer it." if any(value.get("modality") not in {None, "asserted"} for value in propositions): return "I parsed the modal proposition, but the loaded evidence does not authorize the possibility or necessity inference it requires." if propositions: return "The roles and predicate compile, but no authenticated proposition connects them in the loaded specialist graph." return "I need a proposition that can be resolved against an authenticated specialist before I can answer."
def realize(self, query: str, authority_result: Mapping[str, Any]) -> RealizedResponse: compilation = authority_result.get("audit", {}).get("open_proposition_compiler", {}) propositions: Sequence[Mapping[str, Any]] = compilation.get("propositions", []) released_clauses = [clause for clause in authority_result.get("clauses", []) if clause.get("released")] ledger = tuple({ "fact_id": clause["released"]["fact_id"], "specialist_id": clause["released"]["specialist_id"], "evidence": clause["released"]["evidence"], "evidence_sha256": clause["released"]["evidence_sha256"], "source_document": clause["released"]["source_document"], "source_document_sha256": clause["released"]["source_document_sha256"], "provenance_sha256": clause["released"]["provenance_sha256"], } for clause in released_clauses) if not released_clauses: response = self._clarification(compilation) return RealizedResponse( str(authority_result.get("status", "clarification")), response, (), (), (), { "released_fact_count": 0, "query_exact_echo": _norm(response) == _norm(query), "evidence_exact_echo": False, "provenance_complete": True, "unreleased_fact_access": 0, }, ) sentences = [] plans = [] total = len(released_clauses) for ordinal, clause in enumerate(released_clauses): released = clause["released"] proposition = propositions[min(ordinal, len(propositions) - 1)] if propositions else {} sentence = self._sentence(released, proposition, ordinal, total) sentences.append(sentence) plans.append({ "ordinal": ordinal, "fact_id": released["fact_id"], "source": released["source"], "relation": released["relation"], "target": released["target"], "discourse_function": "chain_open" if total > 1 and ordinal == 0 else ("chain_continue" if total > 1 else "answer"), "sentence": sentence, }) prefix = f"The recovered evidence forms a {total}-step chain. " if total > 1 else "" response = prefix + " ".join(sentences) evidence_norms = {_norm(value["evidence"]) for value in ledger} checks = { "released_fact_count": len(released_clauses), "ledger_fact_count": len(ledger), "query_exact_echo": _norm(response) == _norm(query), "evidence_exact_echo": _norm(response) in evidence_norms, "provenance_complete": all( value.get("evidence_sha256") and value.get("source_document_sha256") and value.get("provenance_sha256") for value in ledger ), "every_released_fact_planned": {value["fact_id"] for value in ledger} == {value["fact_id"] for value in plans}, "unreleased_fact_access": 0, } return RealizedResponse(str(authority_result.get("status", "answered")), response, tuple(sentences), ledger, tuple(plans), checks)
__all__ = ["EvidencePreservingRealizer", "RealizedResponse", "SCHEMA"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346#!/usr/bin/env python3"""K226 continuous HRR path interference with deterministic verification."""from __future__ import annotations
import hashlibimport jsonfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Mapping, Sequence
import numpy as np
from stage5k214a_authenticated_specialist_factory import AuthenticatedSpecialistBundlefrom train_stage2a_role_ladder import HRR_DIM, bind, cosine, normalize, unitary
SCHEMA = "oracle-stage5k226a-verified-hrr-implication-substrate-v1"SOURCE_ROLE = unitary("k226:role:source")RELATION_ROLE = unitary("k226:role:relation-path")TARGET_ROLE = unitary("k226:role:target")
def canonical_sha(value: Any) -> str: return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
@dataclass(frozen=True)class AuthenticatedEdge: fact_id: str bundle_name: str bundle_sha256: str specialist_id: str source: str relation: str target: str evidence: str evidence_sha256: str source_document: str source_document_sha256: str provenance_sha256: str state: np.ndarray = field(repr=False, compare=False)
def ledger(self) -> dict[str, str]: return { "fact_id": self.fact_id, "bundle_name": self.bundle_name, "specialist_id": self.specialist_id, "source": self.source, "relation": self.relation, "target": self.target, "evidence": self.evidence, "evidence_sha256": self.evidence_sha256, "source_document": self.source_document, "source_document_sha256": self.source_document_sha256, "provenance_sha256": self.provenance_sha256, }
@dataclass(frozen=True)class VerifiedImplication: implication_id: str source: str relation_path: tuple[str, ...] target: str fact_ids: tuple[str, ...] node_path: tuple[str, ...] evidence_ledger: tuple[dict[str, str], ...] verifier_status: str protected_root_cosine: float state_sha256: str provenance_sha256: str state: np.ndarray = field(repr=False, compare=False)
def public(self) -> dict[str, Any]: return { "implication_id": self.implication_id, "kind": "verified_relational_path_not_primitive_fact", "source": self.source, "relation_path": list(self.relation_path), "target": self.target, "hops": len(self.fact_ids), "fact_ids": list(self.fact_ids), "node_path": list(self.node_path), "evidence_ledger": list(self.evidence_ledger), "verifier_status": self.verifier_status, "protected_root_cosine": self.protected_root_cosine, "state_sha256": self.state_sha256, "provenance_sha256": self.provenance_sha256, }
@dataclass(frozen=True)class _Path: edge_ids: tuple[str, ...] nodes: tuple[str, ...] relations: tuple[str, ...]
@property def source(self) -> str: return self.nodes[0]
@property def target(self) -> str: return self.nodes[-1]
class VerifiedHRRImplicationSubstrate: def __init__( self, bundles: Mapping[str, Path], *, checkpoint_path: Path | None = None, ): self.bundles = { str(name): AuthenticatedSpecialistBundle.load(Path(path)) for name, path in bundles.items() } self.bundle_hashes = {name: bundle.file_sha256 for name, bundle in self.bundles.items()} self.substrate_identity_sha256 = canonical_sha(self.bundle_hashes) self.root = unitary("k226:substrate-root:" + self.substrate_identity_sha256) self.edges: dict[str, AuthenticatedEdge] = {} for bundle_name, bundle in self.bundles.items(): for fact in bundle.facts: state = normalize( bind(SOURCE_ROLE, unitary(f"k226:entity:{fact['source']}")) + bind(RELATION_ROLE, unitary(f"k226:relation:{fact['relation']}")) + bind(TARGET_ROLE, unitary(f"k226:entity:{fact['destination']}")) ) edge = AuthenticatedEdge( fact_id=str(fact["fact_id"]), bundle_name=bundle_name, bundle_sha256=bundle.file_sha256, specialist_id=str(fact["expert_id"]), source=str(fact["source"]), relation=str(fact["relation"]), target=str(fact["destination"]), evidence=str(fact["evidence"]), evidence_sha256=hashlib.sha256(str(fact["evidence"]).encode("utf-8")).hexdigest(), source_document=str(fact["source_url"]), source_document_sha256=str(fact["source_document_sha256"]), provenance_sha256=str(fact["provenance_sha256"]), state=state, ) self.edges[edge.fact_id] = edge self.implications: dict[str, VerifiedImplication] = {} self.cycle_count = 0 self.total_candidates = 0 self.total_verified = 0 self.total_rejected = 0 self.checkpoint_path = None if checkpoint_path is None else Path(checkpoint_path).resolve() if self.checkpoint_path and self.checkpoint_path.exists(): self._restore()
def _base_paths(self) -> list[_Path]: return [ _Path((edge.fact_id,), (edge.source, edge.target), (edge.relation,)) for edge in self.edges.values() ]
def _implication_paths(self) -> list[_Path]: return [ _Path(value.fact_ids, value.node_path, value.relation_path) for value in self.implications.values() ]
def _materialize(self, path: _Path) -> tuple[np.ndarray, float, str]: interference = self.edges[path.edge_ids[0]].state.copy() for edge_id in path.edge_ids[1:]: interference = bind(interference, self.edges[edge_id].state) structured = normalize( bind(SOURCE_ROLE, unitary("k226:entity:" + path.source)) + bind(RELATION_ROLE, unitary("k226:path:" + ">".join(path.relations))) + bind(TARGET_ROLE, unitary("k226:entity:" + path.target)) ) payload = normalize(np.complex64(0.55) * interference + np.complex64(0.45) * structured) residual = payload - np.complex64(np.vdot(self.root, payload)) * self.root protected = normalize(np.float32(4.0) * self.root + residual) return protected, cosine(self.root, protected), hashlib.sha256(np.ascontiguousarray(protected).tobytes()).hexdigest()
def _verify(self, path: _Path) -> tuple[bool, str]: if len(path.edge_ids) < 2: return False, "not_an_implication" if len(set(path.edge_ids)) != len(path.edge_ids): return False, "repeated_fact" if len(path.nodes) != len(path.edge_ids) + 1 or len(path.relations) != len(path.edge_ids): return False, "shape_mismatch" if len(set(path.nodes)) != len(path.nodes): return False, "cyclic_path" for ordinal, edge_id in enumerate(path.edge_ids): edge = self.edges.get(edge_id) if edge is None: return False, "unknown_fact" if (edge.source, edge.relation, edge.target) != (path.nodes[ordinal], path.relations[ordinal], path.nodes[ordinal + 1]): return False, "edge_discontinuity" if not (len(edge.provenance_sha256) == len(edge.source_document_sha256) == len(edge.evidence_sha256) == 64): return False, "incomplete_provenance" return True, "authenticated_path_continuity_proven"
def _implication(self, path: _Path) -> VerifiedImplication: state, root_cosine, state_sha = self._materialize(path) proof = { "substrate_identity_sha256": self.substrate_identity_sha256, "source": path.source, "relation_path": path.relations, "target": path.target, "fact_ids": path.edge_ids, "state_sha256": state_sha, } provenance = canonical_sha(proof) return VerifiedImplication( implication_id="imp_" + provenance[:24], source=path.source, relation_path=path.relations, target=path.target, fact_ids=path.edge_ids, node_path=path.nodes, evidence_ledger=tuple(self.edges[value].ledger() for value in path.edge_ids), verifier_status="authenticated_path_continuity_proven", protected_root_cosine=root_cosine, state_sha256=state_sha, provenance_sha256=provenance, state=state, )
def cycle(self, *, maximum_hops: int = 4, maximum_new: int = 256) -> dict[str, Any]: snapshot = [*self._base_paths(), *self._implication_paths()] known_proofs = {value.fact_ids for value in self.implications.values()} proposed = verified = rejected = 0 new_values: list[VerifiedImplication] = [] for left in snapshot: for right in snapshot: if left.target != right.source: continue if len(left.edge_ids) + len(right.edge_ids) > maximum_hops: continue if set(left.edge_ids) & set(right.edge_ids): continue if set(left.nodes[:-1]) & set(right.nodes[1:]): continue path = _Path( left.edge_ids + right.edge_ids, left.nodes + right.nodes[1:], left.relations + right.relations, ) if path.edge_ids in known_proofs: continue known_proofs.add(path.edge_ids) proposed += 1 accepted, _reason = self._verify(path) if not accepted: rejected += 1 continue implication = self._implication(path) new_values.append(implication) verified += 1 if len(new_values) >= maximum_new: break if len(new_values) >= maximum_new: break for value in new_values: self.implications[value.implication_id] = value self.cycle_count += 1 self.total_candidates += proposed self.total_verified += verified self.total_rejected += rejected if self.checkpoint_path: self.save() return { "cycle": self.cycle_count, "candidates_proposed": proposed, "candidates_verified": verified, "candidates_rejected": rejected, "implications_total": len(self.implications), "stable": verified == 0, }
def run_until_stable(self, *, maximum_hops: int = 4, maximum_cycles: int = 8) -> dict[str, Any]: cycles = [] for _ in range(maximum_cycles): value = self.cycle(maximum_hops=maximum_hops) cycles.append(value) if value["stable"]: break return {"stable": bool(cycles and cycles[-1]["stable"]), "cycles": cycles, "implications_total": len(self.implications)}
def find(self, source: str, target: str) -> tuple[VerifiedImplication, ...]: values = [value for value in self.implications.values() if value.source == source and value.target == target] return tuple(sorted(values, key=lambda value: (len(value.fact_ids), value.fact_ids)))
def public(self) -> dict[str, Any]: return { "schema_version": SCHEMA, "substrate_identity_sha256": self.substrate_identity_sha256, "bundle_hashes": self.bundle_hashes, "cycle_count": self.cycle_count, "known_fact_count": len(self.edges), "verified_implication_count": len(self.implications), "known_facts_and_implications_are_distinct_types": True, "statistics": { "candidates_proposed": self.total_candidates, "candidates_verified": self.total_verified, "candidates_rejected": self.total_rejected, }, "implications": [value.public() for value in sorted(self.implications.values(), key=lambda value: value.implication_id)], "architecture": { "background_circular_convolution": True, "candidate_generation": "shared_endpoint_cleanup_dictionary_plus_hrr_path_binding", "verification": "exact_authenticated_path_continuity_and_provenance", "four_to_one_stabilizing_spine": True, "arbitrary_semantic_inference": False, "traditional_language_model": False, "transformer": False, "gradient_steps": 0, }, }
def save(self) -> None: if self.checkpoint_path is None: raise ValueError("checkpoint_path is not configured") self.checkpoint_path.parent.mkdir(parents=True, exist_ok=True) payload = self.public() temporary = self.checkpoint_path.with_suffix(".tmp") temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") temporary.replace(self.checkpoint_path)
def _restore(self) -> None: payload = json.loads(self.checkpoint_path.read_text(encoding="utf-8")) if payload.get("schema_version") != SCHEMA or payload.get("bundle_hashes") != self.bundle_hashes: raise ValueError("K226 checkpoint identity mismatch") for public in payload.get("implications", []): path = _Path(tuple(public["fact_ids"]), tuple(public["node_path"]), tuple(public["relation_path"])) accepted, reason = self._verify(path) if not accepted: raise ValueError("K226 checkpoint proof failed: " + reason) value = self._implication(path) if value.state_sha256 != public["state_sha256"] or value.provenance_sha256 != public["provenance_sha256"]: raise ValueError("K226 checkpoint state changed") self.implications[value.implication_id] = value self.cycle_count = int(payload.get("cycle_count", 0)) statistics = payload.get("statistics", {}) self.total_candidates = int(statistics.get("candidates_proposed", 0)) self.total_verified = int(statistics.get("candidates_verified", 0)) self.total_rejected = int(statistics.get("candidates_rejected", 0))
__all__ = ["AuthenticatedEdge", "SCHEMA", "VerifiedHRRImplicationSubstrate", "VerifiedImplication"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648#!/usr/bin/env python3"""K41 failure-localized repairs derived from the immutable K40 rejection.
K41 does not add a language model, embedding encoder, specialist, corpus row,or trainable carrier. It repairs four interfaces around the accepted K39Mfour-cell basis:
* exact rare anchors outrank generic dictionary relations;* internally selected evidence is represented as admitted provenance;* productive predicate licensing accepts WordNet verb senses, not only a lexicographer-domain tag;* bounded tools and motion events normalize open-class paraphrases.
K40 remains immutable and rejected. This module is a development successor,not a reinterpretation or rerun of that prospective result."""
from __future__ import annotations
from contextvars import ContextVarimport hashlibimport mathfrom pathlib import Pathimport refrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import NativeMixedAgent, clean, digest, tokensfrom stage5k31_native_proposition_compiler_agent import ( AUXILIARIES, FORM_TO_LEMMA, MODALS, NEGATIONS, WORD, _span_in,)from stage5k35_bidirectional_native_generalist_agent import ( BidirectionalKnowledgeSpecialistPool, canonical_terms,)from stage5k37_indexed_native_generalist_agent import ( IndexedFullCorpusAddressedKnowledgeBasis,)from stage5k39_semantic_indexed_native_generalist_agent import ( K39DiscourseToolTransducer, K39ProductivePropositionCompiler, SEMANTIC_FUNCTION_TERMS, SemanticIndexedFullCorpusAddressedKnowledgeBasis, SemanticIndexedNativeGeneralistAgent,)
SCHEMA = "oracle-stage5k41-relational-specificity-native-generalist-agent-v1"SPECIFICITY_SCHEMA = "oracle-stage5k41-relational-specificity-audit-v1"MIN_EXACT_ANCHORS = 2MIN_EXACT_INFORMATION = 12.0MIN_EXACT_INFORMATION_MARGIN = 2.0
class RelationalSpecificityKnowledgeBasis( SemanticIndexedFullCorpusAddressedKnowledgeBasis): """Promote exact relational anchors when their information is decisive."""
_FUNCTION_TERMS = frozenset({ *SEMANTIC_FUNCTION_TERMS, "according", "cited", "source", "account", "answer", "report", "state", "identify", "give", "explain", "describe", })
def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._specificity_events: ContextVar[tuple[dict[str, Any], ...]] = ContextVar( f"k41-specificity-events-{id(self)}", default=(), )
def begin_turn(self) -> None: super().begin_turn() self._specificity_events.set(())
def _information(self, term: str) -> float: return math.log((len(self._rows) + 1.0) / (len(self._term_postings.get(term, ())) + 1.0))
def _specific_exact_candidates( self, query: str, selected_domain_ids: Sequence[str] | None, ) -> list[tuple[float, float, dict[str, Any]]]: exact = IndexedFullCorpusAddressedKnowledgeBasis._candidates( self, query, self.corpus_path, selected_domain_ids, ) values: list[tuple[float, float, dict[str, Any]]] = [] for lexical_score, raw in exact: row = dict(raw) anchors = tuple( term for term in row.get("shared_terms", ()) if term not in self._FUNCTION_TERMS ) information = sum(self._information(term) for term in anchors) row["relational_exact_anchors"] = list(anchors) row["relational_exact_anchor_count"] = len(anchors) row["relational_exact_information"] = information values.append((information, lexical_score, row)) values.sort(key=lambda value: (-value[0], -value[1], value[2]["text_sha256"])) if values: top_information = values[0][0] second_information = values[1][0] if len(values) > 1 else 0.0 margin = top_information - second_information accepted = ( int(values[0][2]["relational_exact_anchor_count"]) >= MIN_EXACT_ANCHORS and top_information >= MIN_EXACT_INFORMATION and margin >= MIN_EXACT_INFORMATION_MARGIN ) values[0][2]["relational_exact_information_margin"] = margin values[0][2]["relational_specificity_admitted"] = accepted return values
def best_specific_exact_candidate( self, query: str, *, selected_domain_ids: Sequence[str] | None = None, ) -> dict[str, Any] | None: values = self._specific_exact_candidates(query, selected_domain_ids) if not values or not values[0][2].get("relational_specificity_admitted"): return None return dict(values[0][2])
def _candidates( self, query: str, corpus_path: Path, selected_domain_ids: Sequence[str] | None, ) -> list[tuple[float, dict[str, Any]]]: values = super()._candidates(query, corpus_path, selected_domain_ids) specific = self._specific_exact_candidates(query, selected_domain_ids) promoted = specific[0][2] if specific and specific[0][2].get( "relational_specificity_admitted" ) else None if promoted is not None: by_sha = {str(value["text_sha256"]): (score, value) for score, value in values} original = by_sha.pop(str(promoted["text_sha256"]), None) lexical_score = float(promoted.get("retrieval_score", 0.0)) if original is not None: lexical_score = max(lexical_score, float(original[0])) values = [(lexical_score, promoted), *sorted( by_sha.values(), key=lambda item: (-item[0], item[1]["text_sha256"]), )] self._specificity_events.set((*self._specificity_events.get(), { "query_sha256": hashlib.sha256(clean(query).encode()).hexdigest(), "selected_domain_ids": None if selected_domain_ids is None else list(selected_domain_ids), "exact_candidates": len(specific), "promoted": promoted is not None, "promoted_text_sha256": None if promoted is None else promoted["text_sha256"], "exact_anchor_count": 0 if promoted is None else promoted["relational_exact_anchor_count"], "exact_information": 0.0 if promoted is None else promoted["relational_exact_information"], "exact_information_margin": 0.0 if promoted is None else promoted["relational_exact_information_margin"], "full_corpus_scans": 0, })) return values
def turn_audit(self) -> dict[str, Any]: value = super().turn_audit() events = self._specificity_events.get() value["relational_specificity"] = { "schema_version": SPECIFICITY_SCHEMA, "events": list(events), "promotions": sum(int(bool(event["promoted"])) for event in events), "minimum_exact_anchors": MIN_EXACT_ANCHORS, "minimum_exact_information": MIN_EXACT_INFORMATION, "minimum_exact_information_margin": MIN_EXACT_INFORMATION_MARGIN, "answer_or_gold_labels_used": False, "model_calls": 0, "gradient_steps": 0, "full_corpus_scans": 0, } return value
class K41ProductivePropositionCompiler(K39ProductivePropositionCompiler): """License finite verbs from their sense atoms and strip coordinators."""
_IRREGULAR = { "bore": "bear", "befell": "befall", "found": "find", "left": "leave", "saw": "see", "sold": "sell", "taught": "teach", "thought": "think", }
def __init__(self, concept_index: Any) -> None: super().__init__(concept_index) self._k41_concept_index = concept_index
@staticmethod def _verb_profile(profile: Mapping[str, float]) -> bool: return any( atom.startswith("x:verb.") or bool(re.match(r"^c:[^.]+\.v\.\d+$", atom)) for atom in profile )
def _lemma_profile(self, surface: str): value = super()._lemma_profile(surface) if value is not None: return value raw = surface.casefold() candidates = [self._IRREGULAR.get(raw, raw)] if raw in FORM_TO_LEMMA: candidates.insert(0, FORM_TO_LEMMA[raw]) if raw.endswith("ies") and len(raw) > 3: candidates.append(raw[:-3] + "y") if raw.endswith("s") and len(raw) > 3: candidates.append(raw[:-1]) if raw.endswith("ed") and len(raw) > 4: candidates.extend((raw[:-2], raw[:-1])) if raw.endswith("ing") and len(raw) > 5: candidates.extend((raw[:-3], raw[:-3] + "e")) for lemma in dict.fromkeys(candidates): profile = self._dictionary_profiles.get(lemma) if profile is None: profile = dict(self._k41_concept_index.profile(lemma)) if profile and self._verb_profile(profile): return lemma, profile return None
def _productive_parse( self, surface: str, evidence_row: Mapping[str, Any], domain_ids: Sequence[str], *, clause_type: str, conditional: bool, inherited_subject: str | None, extra_qualifiers: Sequence[tuple[str, str]], base_offset: int, ): matches = tuple(WORD.finditer(surface)) candidates: list[tuple[float, int, Any, str]] = [] pronouns = {"he", "she", "it", "they", "we", "i", "you", "this", "that", "these", "those"} carrier_auxiliaries = AUXILIARIES | {"do", "does", "did"} for index, match in enumerate(matches): if index == 0 and inherited_subject is None: continue word = match.group(0).casefold() if word in carrier_auxiliaries | MODALS | NEGATIONS: continue resolved = self._lemma_profile(word) if resolved is None: continue lemma, _profile = resolved previous = matches[index - 1].group(0).casefold() if index else "" recent = {value.group(0).casefold() for value in matches[max(0, index - 2):index]} following = matches[index + 1].group(0).casefold() if index + 1 < len(matches) else "" score = 0.0 if recent & (carrier_auxiliaries | MODALS | NEGATIONS): score += 5.0 if word != lemma or word.endswith(("s", "ed", "ing")): score += 3.0 if index == 1 and matches[0].group(0).casefold() in pronouns: score += 4.0 if match.end() < len(surface.rstrip()): score += 1.0 if following in {"a", "an", "the", "for", "to", "into", "from", "with", "by"}: score += 2.5 if previous in {"to", "a", "an", "the"}: score -= 3.0 if word.endswith("ing") and previous == "by": score -= 8.0 if index + 1 < len(matches): following_resolved = self._lemma_profile(following) if ( following_resolved is not None and following.endswith(("s", "ed")) and not (recent & carrier_auxiliaries) ): score -= 5.0 candidates.append((score, -index, match, lemma)) if not candidates: return None score, _negative_index, predicate, lemma = max(candidates) if score < 1.0: return None left = surface[:predicate.start()] right = surface[predicate.end():] left_words = WORD.findall(left) while left_words and left_words[-1].casefold() in carrier_auxiliaries | MODALS | NEGATIONS: left_words.pop() subject_surface = " ".join(left_words) if re.search(r"\b(?:which|that|who)\b", subject_surface, re.IGNORECASE): subject_surface = re.split( r"\b(?:which|that|who)\b", subject_surface, flags=re.IGNORECASE, )[-1] subject = inherited_subject or self._clean_argument(subject_surface) if not subject: return None productive_qualifiers = list(extra_qualifiers) manner = re.match(r"^(.+?)\s+is\s+by\s+(.+)$", right.strip(), re.IGNORECASE) if manner is not None: right = manner.group(1) productive_qualifiers.append(("by", self._clean_argument(manner.group(2)))) object_value = self._clean_argument( re.split(r",\s*(?:and\s+)?[A-Za-z]+ing\b", right, maxsplit=1)[0] ) or None evidence = str(evidence_row.get("fact", evidence_row.get("text", ""))).strip() subject_span = _span_in(evidence, subject, base_offset) predicate_span = _span_in(evidence, predicate.group(0), base_offset) object_span = _span_in( evidence, object_value, predicate_span[1] if predicate_span is not None else base_offset, ) if subject_span is None or predicate_span is None: return None words = WORD.findall(surface) modal = next((value.casefold() for value in words if value.casefold() in MODALS), None) modality = ( "conditional" if conditional else "obligatory" if modal in {"must", "should"} else "possible" if modal in {"can", "could", "may", "might", "would"} else "asserted" ) return self._make( subject=subject, lemma=lemma, object_value=object_value, complement=None, qualifiers=productive_qualifiers, modality=modality, polarity=self._polarity(words), voice="active_dictionary_licensed_pos_balanced", clause_type=clause_type, evidence_row=evidence_row, subject_span=subject_span, predicate_span=predicate_span, object_span=object_span, domain_ids=domain_ids, )
def _parse_simple( self, clause: str, evidence_row: Mapping[str, Any], domain_ids: Sequence[str], *, clause_type: str = "assertion", conditional: bool = False, inherited_subject: str | None = None, extra_qualifiers: Sequence[tuple[str, str]] = (), base_offset: int = 0, ): surface = str(clause) coordinator = re.match( r"^[\s\"'“”‘’]*(?:and|but|yet)\s+(.+)$", surface, re.IGNORECASE, ) # Re-evaluate with an ASCII-only punctuation boundary. The source # corpus contains multiple Unicode quotation forms, none of which is # semantically part of the coordinator. coordinator = re.match( r"^[^A-Za-z0-9]*(?:and|but|yet)\s+(.+)$", surface, re.IGNORECASE, ) if coordinator is not None: return super()._parse_simple( coordinator.group(1), evidence_row, domain_ids, clause_type=clause_type, conditional=conditional, inherited_subject=inherited_subject, extra_qualifiers=extra_qualifiers, base_offset=base_offset + coordinator.start(1), ) return super()._parse_simple( clause, evidence_row, domain_ids, clause_type=clause_type, conditional=conditional, inherited_subject=inherited_subject, extra_qualifiers=extra_qualifiers, base_offset=base_offset, )
class K41DiscourseToolTransducer(K39DiscourseToolTransducer): """Map productive operation paraphrases into the frozen HRR tool head."""
@staticmethod def _normalize_operation_surface(question: str) -> tuple[str, tuple[str, ...]]: value = str(question) applied: list[str] = [] substitutions = ( (r"\bgreatest\b", "maximum", "greatest_to_maximum"), (r"\blargest\b", "maximum", "largest_to_maximum"), (r"\bhighest\b", "maximum", "highest_to_maximum"), (r"\bsmallest\b", "minimum", "smallest_to_minimum"), (r"\blowest\b", "minimum", "lowest_to_minimum"), (r"\benumerate\b", "list", "enumerate_to_list"), (r"\bcountry\s+labels\b", "country names", "labels_to_names"), ) for pattern, replacement, label in substitutions: replaced = re.sub(pattern, replacement, value, flags=re.IGNORECASE) if replaced != value: value = replaced applied.append(label) return value, tuple(applied)
def answer( self, session_id: str, question: str, *, erase_operation_geometry: bool = False, ) -> dict[str, Any]: normalized, applied = self._normalize_operation_surface(question) output = dict(super().answer( session_id, normalized, erase_operation_geometry=erase_operation_geometry, )) output["operation_surface_normalization"] = { "input_sha256": hashlib.sha256(question.encode()).hexdigest(), "normalized_input_sha256": hashlib.sha256(normalized.encode()).hexdigest(), "applied_relations": list(applied), "answer_or_gold_labels_used": False, "model_calls": 0, "gradient_steps": 0, } return output
class RelationalSpecificityNativeGeneralistAgent(SemanticIndexedNativeGeneralistAgent): """K39M four-cell runtime with K40-localized relational repairs."""
def __init__( self, specialist_checkpoint: Path, knowledge_checkpoint: Path, address_index_path: Path, relational_index_path: Path, concept_index_path: Path, substrate_path: Path, **kwargs: Any, ) -> None: kwargs.setdefault("agent_id", "oracle-stage5k41-relational-specificity-agent") super().__init__( specialist_checkpoint, knowledge_checkpoint, address_index_path, relational_index_path, concept_index_path, substrate_path, **kwargs, ) prior = self.knowledge_basis basis = RelationalSpecificityKnowledgeBasis( prior.basis, prior.address_index, prior.relational_index, prior.concept_index, prior.corpus_path, ) base_pool = self.knowledge_specialists.base_pool self.knowledge_basis = basis self.knowledge_specialists = BidirectionalKnowledgeSpecialistPool(base_pool, basis) self.proposition_compiler = K41ProductivePropositionCompiler(prior.concept_index) if self.tool_backend is not None and all( hasattr(self.tool_backend, value) for value in ("head", "experts", "store") ): self.tool_backend = K41DiscourseToolTransducer( self.tool_backend.head, self.tool_backend.experts, self.tool_backend.store, ) self._k41_internal_rows: ContextVar[tuple[dict[str, Any], ...]] = ContextVar( f"k41-internal-evidence-{id(self)}", default=(), ) self._k41_specificity_decision: ContextVar[dict[str, Any] | None] = ContextVar( f"k41-specificity-decision-{id(self)}", default=None, )
@staticmethod def _motion(text: str) -> tuple[str, str] | None: match = re.search( r"\b([A-Za-z][A-Za-z0-9_-]*)\s+" r"(?:moves?|moved|travels?|traveled|drives?|drove)\s+" r"(?:directly\s+|quietly\s+|slowly\s+|quickly\s+)?" r"(?:into|to)\s+(?:the\s+)?" r"([A-Za-z][A-Za-z0-9_-]*(?:\s+[A-Za-z][A-Za-z0-9_-]*){0,5})[.!?]*$", clean(text), re.IGNORECASE, ) return (clean(match.group(1)), clean(match.group(2))) if match else None
@staticmethod def _coequal_candidate_eligible(value: Mapping[str, Any] | None) -> bool: return bool( value and ( value.get("relational_specificity_admitted") or SemanticIndexedNativeGeneralistAgent._coequal_candidate_eligible(value) ) )
def _coequal_evidence(self, text: str): evidence, audit = super()._coequal_evidence(text) if evidence: self._k41_internal_rows.set(tuple(dict(value) for value in evidence)) return evidence, audit
@classmethod def _intent_lattice( cls, text: str, context: Mapping[str, Any] | None = None, ) -> dict[str, Any]: audit = dict(super()._intent_lattice(text, context)) local = dict(context or {}) words = set(tokens(text)) lower = clean(text).casefold() schema_cue = bool(words & { "dataset", "registered", "database", "catalog", "table", "record", "records", "population", "earthquake", "earthquakes", }) paraphrase_cue = bool(words & { "greatest", "largest", "highest", "smallest", "lowest", "enumerate", "labels", }) expanded_tool_cue = schema_cue and paraphrase_cue bounded = bool(local.get("k39_tool_backend_available")) and expanded_tool_cue if bounded and audit.get("selected_intent_family") != "creative_generation_request": scores = dict(audit["candidate_scores"]) scores["bounded_dataset"] = 1.0 for key in ("state_query", "event_consequence_query", "definition_query", "causal_query"): scores[key] = 0.0 audit["candidate_scores"] = scores audit["selected_intent_family"] = "bounded_dataset" audit["k41_open_schema_paraphrase"] = { "schema_cue": schema_cue, "paraphrase_cue": paraphrase_cue, "expanded_tool_cue": expanded_tool_cue, "bounded_dataset_selected": bounded, "answer_or_gold_labels_used": False, } motion_event = cls._motion(text) is not None if motion_event: scores = dict(audit["candidate_scores"]) scores["motion_event"] = 1.0 audit["candidate_scores"] = scores precedence = list(audit["precedence"]) insertion = precedence.index("transfer_event") + 1 precedence.insert(insertion, "motion_event") audit["precedence"] = precedence audit["selected_intent_family"] = "motion_event" else: audit["candidate_scores"]["motion_event"] = 0.0 audit["k41_motion_event"] = { "whole_construction_detected": motion_event, "answer_or_gold_labels_used": False, } return audit
@classmethod def _routing_goal( cls, text: str, context: Mapping[str, Any], ) -> tuple[tuple[str, ...], ...]: if cls._motion(text) is not None: return (("spatial", "event"),) return super()._routing_goal(text, context)
def _handle_event(self, session_id: str, text: str, turn_id: str): if self._active_intent == "motion_event": return NativeMixedAgent._handle_event(self, session_id, text, turn_id) return super()._handle_event(session_id, text, turn_id)
@staticmethod def _evidence_context_row(row: Mapping[str, Any]) -> dict[str, Any]: return { "fact": row.get("fact", row.get("text", "")), "source_document": row.get("source_document", "unknown"), "source_document_sha256": row.get("source_document_sha256", ""), "text_sha256": row.get("text_sha256", ""), "domain_id": row.get("domain_id", ""), "license_note": row.get("license_note", ""), "retrieval_score": row.get("retrieval_score", 0.0), }
def answer( self, session_id: str, text: str, context: Mapping[str, Any] | None = None, *, ablate_specialists: Sequence[str] = (), ablate_knowledge_cells: Sequence[str] = (), ) -> dict[str, Any]: self._k41_internal_rows.set(()) self._k41_specificity_decision.set(None) local = dict(context or {}) caller_boundary = any(local.get(key) for key in ("evidence", "training_corpus", "sensor_stream")) probe = { **local, "k39_tool_backend_available": self.tool_backend is not None, "k39_tool_dialogue_active": session_id in self._k39_tool_sessions, } intent = self._intent_lattice(text, probe)["selected_intent_family"] is_coequal = bool(self._coequal_split_candidates(text)) if not caller_boundary and not is_coequal and intent in {"open", "definition_query"}: candidate = self.knowledge_basis.best_specific_exact_candidate(text) if candidate is not None: local["evidence"] = (self._evidence_context_row(candidate),) local["k41_relational_specificity_evidence"] = True self._k41_internal_rows.set((dict(candidate),)) self._k41_specificity_decision.set({ "activated": True, "text_sha256": candidate["text_sha256"], "exact_anchors": candidate["relational_exact_anchors"], "exact_information": candidate["relational_exact_information"], "exact_information_margin": candidate["relational_exact_information_margin"], "answer_or_gold_labels_used": False, }) output = super().answer( session_id, text, local, ablate_specialists=ablate_specialists, ablate_knowledge_cells=ablate_knowledge_cells, ) rows = self._k41_internal_rows.get() lattice = output["knowledge_lattice"] if rows: admitted = [self._evidence_context_row(value) for value in rows] existing = list(lattice.get("retrieved_evidence", ())) merged = {str(value.get("text_sha256")): value for value in (*admitted, *existing)} lattice["retrieval_admitted_to_proof"] = True lattice["retrieval_gate_reason"] = ( "internally_selected_coequal_relational_evidence" if output.get("coequal_intent", {}).get("activated") else "discriminative_exact_relational_anchors" ) lattice["retrieved_evidence"] = list(merged.values()) lattice["evidence_rows_admitted_to_proof"] = admitted lattice["relational_provenance_reconciled"] = True if output.get("coequal_intent", {}).get("activated"): output["coequal_intent"]["provenance_admitted_to_proof"] = True output["schema_version"] = SCHEMA output["relational_specificity"] = self._k41_specificity_decision.get() or { "activated": False, "answer_or_gold_labels_used": False, } output["runtime"]["relational_specificity_model_calls"] = 0 output["runtime"]["relational_specificity_gradient_steps"] = 0 output["runtime"]["relational_provenance_model_calls"] = 0 output["runtime"]["relational_provenance_gradient_steps"] = 0 output["runtime"]["open_schema_paraphrase_model_calls"] = 0 output["runtime"]["open_schema_paraphrase_gradient_steps"] = 0 output["turn_manifest_sha256"] = digest(output) return output
__all__ = [ "K41DiscourseToolTransducer", "K41ProductivePropositionCompiler", "RelationalSpecificityKnowledgeBasis", "RelationalSpecificityNativeGeneralistAgent",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782#!/usr/bin/env python3"""K53 opened successor: discourse, quantifier, modal, and clause geometry.
The extension keeps predicates and lexical entities in the generic ``relate``frame. Universal rules are scoped-variable condition graphs; negation wraps apositive relation state; possibility occupies a branch world; causal clauseorders normalize to the same ``cause(source, result)`` expression. No lexicalpredicate becomes a canonical operator or an additional knowledge specialist."""
from __future__ import annotations
import hashlibfrom pathlib import Pathimport refrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import ( HandlerResult, NativeAnswerGrammar, SemanticClause, clean, digest,)from stage5k45_ephemeral_compositional_language_agent import ( K45Session, ProductiveRule, RelationFact, _strip_article,)from stage5k47_morphological_counterfactual_agent import _lemma47from stage5k51_restart_safe_ephemeral_agent import ( IndexedEphemeralEventJournal, RestartSafeEphemeralAgent,)
SCHEMA = "oracle-stage5k53-native-clause-algebra-agent-v1"NEVER = "__never__"SUBJECT_PRONOUNS = frozenset({"he", "she", "they", "him", "her", "them"})OBJECT_PRONOUNS = frozenset({"it", "this", "that"})POSSIBILITY_MODALS = frozenset({"may", "might", "can", "could"})MODALS = POSSIBILITY_MODALS | frozenset({"must", "should"})
class NativeClauseAlgebraAgent(RestartSafeEphemeralAgent): def __init__( self, *args: Any, ephemeral_journal_path: Path | None = None, **kwargs: Any, ) -> None: substrate_path = Path(args[5] if len(args) >= 6 else kwargs["substrate_path"]) journal_path = ephemeral_journal_path or substrate_path.with_suffix( ".k53.ephemeral.sqlite3" ) kwargs.setdefault("agent_id", "oracle-stage5k53-native-clause-algebra-agent") super().__init__( *args, ephemeral_journal_path=journal_path, **kwargs, ) k51_source = Path(__file__).with_name("stage5k51_restart_safe_ephemeral_agent.py") state = hashlib.sha256() for path in (k51_source, Path(__file__)): payload = path.read_bytes() state.update(len(payload).to_bytes(8, "big")) state.update(payload) self._k53_lineage_sha256 = state.hexdigest() self.ephemeral_journal = IndexedEphemeralEventJournal( journal_path, source_sha256=self._k53_lineage_sha256, ) self._k53_last: dict[str, Any] = {"activated": False}
@staticmethod def _quantified_rule(text: str) -> tuple[str, str, str, str] | None: match = re.match( r"^every\s+([a-z][a-z-]*)\s+(?:who|that)\s+([a-z][a-z-]*)\s+" r"(?:a|an|the)\s+([a-z][a-z-]*)\s+([a-z][a-z-]*)\s+it[.!?]*$", clean(text), re.IGNORECASE, ) if match is None: return None return ( match.group(1).casefold(), _lemma47(match.group(2)), match.group(3).casefold(), _lemma47(match.group(4)), )
@staticmethod def _type_assertion(text: str) -> tuple[str, str] | None: match = re.match( r"^(?:the\s+)?([a-z][a-z0-9_-]*)\s+is\s+(?:a|an)\s+" r"([a-z][a-z0-9_-]*)[.!?]*$", clean(text), re.IGNORECASE, ) return (match.group(1), match.group(2).casefold()) if match else None
@staticmethod def _existential_assertion(text: str) -> tuple[str, str, str] | None: match = re.match( r"^some\s+([a-z][a-z-]*)\s+([a-z][a-z-]*)\s+" r"(?:a|an|the)\s+(.+?)[.!?]*$", clean(text), re.IGNORECASE, ) return ( match.group(1).casefold(), _lemma47(match.group(2)), _strip_article(match.group(3)), ) if match else None
@staticmethod def _modal_assertion(text: str) -> tuple[str, str, str, str] | None: match = re.match( r"^(?:the\s+)?([a-z][a-z0-9_-]*)\s+" r"(may|might|must|should|can|could)\s+([a-z][a-z-]*)\s+" r"(?:a|an|the)?\s*(.+?)[.!?]*$", clean(text), re.IGNORECASE, ) return ( match.group(1), match.group(2).casefold(), _lemma47(match.group(3)), _strip_article(match.group(4)), ) if match else None
@staticmethod def _negative_assertion(text: str) -> tuple[str, str, str] | None: match = re.match( r"^(?:the\s+)?([a-z][a-z0-9_-]*)\s+(?:did\s+not|does\s+not|do\s+not)\s+" r"([a-z][a-z-]*)\s+(?:a|an|the)?\s*(.+?)[.!?]*$", clean(text), re.IGNORECASE, ) return ( match.group(1), _lemma47(match.group(2)), _strip_article(match.group(3)), ) if match else None
@staticmethod def _atomic_clause(text: str) -> tuple[str, str, str] | None: value = clean(text).rstrip(".?!") match = re.match( r"^(?:the\s+)?([a-z][a-z0-9_-]*)\s+([a-z][a-z-]*)" r"(?:\s+(?:a|an|the)?\s*(.+?))?$", value, re.IGNORECASE, ) if match is None: return None object_value = _strip_article(match.group(3) or "event") return match.group(1), _lemma47(match.group(2)), object_value
@classmethod def _causal_assertion( cls, text: str, ) -> tuple[tuple[str, str, str], tuple[str, str, str], str] | None: value = clean(text).rstrip(".?!") front = re.match(r"^because\s+(.+?),\s*(.+)$", value, re.IGNORECASE) if front: support, result = cls._atomic_clause(front.group(1)), cls._atomic_clause(front.group(2)) return (support, result, "cause_first") if support and result else None rear = re.match(r"^(.+?)\s+because\s+(.+)$", value, re.IGNORECASE) if rear: result, support = cls._atomic_clause(rear.group(1)), cls._atomic_clause(rear.group(2)) return (support, result, "result_first") if support and result else None return None
@classmethod def _ephemeral_family( cls, text: str, context: Mapping[str, Any] | None = None, ) -> str | None: existing = super()._ephemeral_family(text, context) if existing is not None: return existing lower = clean(text).casefold() if cls._quantified_rule(text): return "ephemeral_rule" if re.match( r"^(?:why\s+did|did|what\s+did|who|may|might|must|should|can|could)\b", lower, ): return "ephemeral_query" if ( cls._causal_assertion(text) or cls._type_assertion(text) or cls._existential_assertion(text) or cls._modal_assertion(text) or cls._negative_assertion(text) or cls._atomic_clause(text) ): return "ephemeral_assertion" return None
@staticmethod def _salient(session: K45Session, role: str) -> str | None: subject_keys = ("subject", "actor", "entity") object_keys = ("object", "item", "patient", "recipient") keys = subject_keys if role == "subject" else object_keys for record in reversed(session.turn_operations): for key in keys: value = record.get(key) if isinstance(value, str) and value and value.casefold() not in {"it", "this", "that"}: return value for fact in reversed(session.facts): value = fact.subject if role == "subject" else fact.object_value if value and value.casefold() not in {"event", "it", "this", "that"}: return value return None
@classmethod def _resolve(cls, session: K45Session, value: str, role: str) -> tuple[str, bool]: lower = _strip_article(value).casefold() pronouns = SUBJECT_PRONOUNS if role == "subject" else OBJECT_PRONOUNS if lower not in pronouns: return _strip_article(value), False resolved = cls._salient(session, role) return (resolved or lower), resolved is not None
def _relation_state( self, session: K45Session, subject: str, relation: str, object_value: str, *, world_id: str | None = None, ): return session.workspace.compose( "relate", ( self._entity(session, subject, world_id=world_id), self._relation(session, relation, world_id=world_id), self._entity(session, object_value, world_id=world_id), ), world_id=world_id, ttl_turns=128, )
def _quantified_rule_assertion( self, session_id: str, text: str, ) -> HandlerResult | None: parsed = self._quantified_rule(text) if parsed is None: return None entity_type, antecedent, object_type, consequent = parsed session = self._session(session_id) actor_var = session.workspace.new_variable("actor", "entity") object_var = session.workspace.new_variable("object", "entity") from stage5k1_generative_relational_workspace import RelationalValue actor = RelationalValue.variable(actor_var) object_value = RelationalValue.variable(object_var) type_state = session.workspace.compose( "relate", (actor, self._relation(session, "is_a"), self._entity(session, entity_type)), ttl_turns=128, ) event_state = session.workspace.compose( "relate", (actor, self._relation(session, antecedent), object_value), ttl_turns=128, ) typed_event = session.workspace.compose("and", (type_state, event_state), ttl_turns=128) consequence = session.workspace.compose( "relate", (actor, self._relation(session, consequent), object_value), ttl_turns=128, ) rule_state = session.workspace.compose( "condition", (typed_event, consequence), ttl_turns=128, ) rule_id = ( f"quantified:{entity_type}:{object_type}:" + rule_state.expression.structural_sha256[:20] ) session.rules.append(ProductiveRule( rule_id, f"{entity_type}::{antecedent}", consequent, NEVER, rule_state.expression, rule_state.state_id, )) self._record_last( session, "compose_quantified_rule", (type_state, event_state, typed_event, consequence, rule_state), quantifier="every", entity_type=entity_type, object_type=object_type, antecedent=antecedent, consequent=consequent, variable_scope_preserved=True, ) return HandlerResult( "compose_quantified_rule", "answered", (("entity_type", entity_type), ("antecedent", antecedent), ("object_type", object_type), ("consequent", consequent)), (("rule_id", rule_id), ("depth", rule_state.expression.depth)), (SemanticClause( f"Every {entity_type} that {antecedent}s an {object_type}", consequent, object_value="it", ),), (("source", "conversation_local_quantified_rule"),), ( "bind_scoped_actor_and_object", "conjoin_type_and_event", "compose_universal_condition", "retain_quantifier_scope", ), )
def _type_assertion_result(self, session_id: str, text: str) -> HandlerResult | None: parsed = self._type_assertion(text) if parsed is None: return None subject, entity_type = parsed session = self._session(session_id) state = self._relation_state(session, subject, "is_a", entity_type) session.facts.append(RelationFact( subject, "is_a", entity_type, state.state_id, state.world_id, )) self._record_last( session, "assert_discourse_type", (state,), subject=subject, object=entity_type, relation="is_a", ) return HandlerResult( "assert_discourse_type", "answered", (("subject", subject),), (("entity_type", entity_type),), (SemanticClause(subject, "be", complement=f"a {entity_type}"),), (("source", "conversation_local_type_assertion"),), ("bind_discourse_entity", "bind_type_relation", "update_salience"), )
def _apply_quantified( self, session: K45Session, subject: str, relation: str, object_value: str, ) -> tuple[list[Any], list[RelationFact]]: states: list[Any] = [] inferred: list[RelationFact] = [] types = { fact.object_value.casefold() for fact in session.facts if fact.subject.casefold() == subject.casefold() and fact.relation == "is_a" } object_types = { fact.object_value.casefold() for fact in session.facts if fact.subject.casefold() == object_value.casefold() and fact.relation == "is_a" } for rule in session.rules: if "::" not in rule.antecedent_relation: continue required_type, antecedent = rule.antecedent_relation.split("::", 1) identity = rule.rule_id.split(":") required_object_type = identity[2] if len(identity) >= 4 else "" if ( antecedent != relation or required_type not in types or required_object_type not in object_types ): continue state = self._relation_state( session, subject, rule.consequent_relation, object_value, ) fact = RelationFact( subject, rule.consequent_relation, object_value, state.state_id, state.world_id, inferred=True, ) session.facts.append(fact) session.active_relations[(rule.consequent_relation, object_value.casefold())] = fact states.append(state) inferred.append(fact) return states, inferred
def _generic_assertion( self, session_id: str, subject: str, relation: str, object_value: str, *, operation: str = "assert_discourse_relation", existential_type: str | None = None, ) -> HandlerResult: session = self._session(session_id) subject, subject_resolved = self._resolve(session, subject, "subject") object_value, object_resolved = self._resolve(session, object_value, "object") generated = [] if existential_type is not None: type_state = self._relation_state(session, subject, "is_a", existential_type) session.facts.append(RelationFact( subject, "is_a", existential_type, type_state.state_id, type_state.world_id, )) generated.append(type_state) state = self._relation_state(session, subject, relation, object_value) session.facts.append(RelationFact( subject, relation, object_value, state.state_id, state.world_id, )) generated.append(state) inferred_states, inferred = self._apply_quantified( session, subject, relation, object_value, ) generated.extend(inferred_states) self._record_last( session, operation, tuple(generated), subject=subject, relation=relation, object=object_value, subject_coreference_resolved=subject_resolved, object_coreference_resolved=object_resolved, existential_type=existential_type, inferred_relations=[value.relation for value in inferred], ) clauses = [SemanticClause(subject, relation, object_value=object_value, tense="past")] clauses.extend( SemanticClause(value.subject, value.relation, object_value=value.object_value) for value in inferred ) return HandlerResult( operation, "answered", (("subject", subject), ("relation", relation), ("object", object_value)), (("inferred", [value.relation for value in inferred]),), tuple(clauses), (("source", "conversation_local_discourse"),), ( "resolve_discourse_roles", "bind_generic_relation", "verify_actor_and_object_types", "match_scoped_quantified_rules", "update_salience", ), )
def _existential_result(self, session_id: str, text: str) -> HandlerResult | None: parsed = self._existential_assertion(text) if parsed is None: return None entity_type, relation, object_value = parsed return self._generic_assertion( session_id, f"some {entity_type}", relation, object_value, operation="assert_existential_relation", existential_type=entity_type, )
def _negative_result(self, session_id: str, text: str) -> HandlerResult | None: parsed = self._negative_assertion(text) if parsed is None: return None subject, relation, object_value = parsed session = self._session(session_id) subject, subject_resolved = self._resolve(session, subject, "subject") object_value, object_resolved = self._resolve(session, object_value, "object") positive = self._relation_state(session, subject, relation, object_value) negative = session.workspace.compose("negate", (positive,), ttl_turns=128) session.facts.append(RelationFact( subject, f"not::{relation}", object_value, negative.state_id, negative.world_id, )) self._record_last( session, "assert_negative_relation", (positive, negative), subject=subject, relation=relation, object=object_value, subject_coreference_resolved=subject_resolved, object_coreference_resolved=object_resolved, ) return HandlerResult( "assert_negative_relation", "answered", (("subject", subject), ("relation", relation), ("object", object_value)), (("polarity", "negative"),), (SemanticClause( subject, relation, object_value=object_value, tense="past", polarity="negative", ),), (("source", "conversation_local_negative_assertion"),), ("compose_positive_relation", "apply_geometric_negation", "retain_scope"), )
def _modal_result(self, session_id: str, text: str) -> HandlerResult | None: parsed = self._modal_assertion(text) if parsed is None: return None subject, modal, relation, object_value = parsed session = self._session(session_id) subject, subject_resolved = self._resolve(session, subject, "subject") object_value, object_resolved = self._resolve(session, object_value, "object") world = session.workspace.branch_world(f"modal:{modal}:{subject}:{relation}:{object_value}") state = self._relation_state( session, subject, f"{modal}::{relation}", object_value, world_id=world, ) session.facts.append(RelationFact( subject, f"{modal}::{relation}", object_value, state.state_id, state.world_id, )) session.counterfactual_worlds[ f"modal:{modal}:{subject.casefold()}:{relation}:{object_value.casefold()}" ] = world self._record_last( session, "assert_modal_relation", (state,), subject=subject, modal=modal, relation=relation, object=object_value, subject_coreference_resolved=subject_resolved, object_coreference_resolved=object_resolved, branch_local=True, ) return HandlerResult( "assert_modal_relation", "answered", (("subject", subject), ("modal", modal), ("relation", relation), ("object", object_value)), (("world_id", world),), (SemanticClause(subject, relation, object_value=object_value, modal=modal),), (("source", "conversation_local_modal_assertion"),), ("branch_modal_world", "bind_modal_relation", "preserve_actual_world"), )
def _causal_result(self, session_id: str, text: str) -> HandlerResult | None: parsed = self._causal_assertion(text) if parsed is None: return None support, result, surface_order = parsed session = self._session(session_id) support_state = self._relation_state(session, *support) result_state = self._relation_state(session, *result) cause_state = session.workspace.compose( "cause", (support_state, result_state), ttl_turns=128, ) support_clause = SemanticClause( support[0], support[1], object_value=None if support[2] == "event" else support[2], tense="past", ) support_surface = NativeAnswerGrammar.clause(support_clause).rstrip(".") session.facts.extend(( RelationFact(*support, support_state.state_id, support_state.world_id), RelationFact(*result, result_state.state_id, result_state.world_id), RelationFact( result[0], f"because::{result[1]}", support_surface, cause_state.state_id, cause_state.world_id, inferred=True, ), )) self._record_last( session, "compose_causal_clause", (support_state, result_state, cause_state), subject=result[0], relation=result[1], object=result[2], support=support_surface, input_clause_order=surface_order, normalized_cause_order=True, ) return HandlerResult( "compose_causal_clause", "answered", (("support", support), ("result", result)), (("normalized_order", "support_then_result"),), (SemanticClause( result[0], result[1], object_value=result[2], tense="past", qualifiers=(("because", support_surface),), ),), (("source", "conversation_local_causal_clause"),), ("parse_clause_order", "compose_support", "compose_result", "bind_cause"), )
def _generic_query(self, session_id: str, text: str) -> HandlerResult | None: session = self._session(session_id) lower = clean(text).casefold().rstrip("?!.")
why = re.match( r"^why\s+did\s+(?:the\s+)?([a-z][a-z0-9_-]*)\s+" r"([a-z][a-z-]*)\s+(?:a|an|the)?\s*(.+)$", lower, ) if why: subject, resolved = self._resolve(session, why.group(1), "subject") relation, object_value = _lemma47(why.group(2)), _strip_article(why.group(3)) fact = next(( value for value in reversed(session.facts) if value.subject.casefold() == subject.casefold() and value.relation == f"because::{relation}" ), None) if fact is None: return self._abstention("query_causal_clause", text, "causal_state_not_in_workspace") support = fact.object_value self._record_last( session, "query_causal_clause", (), subject=subject, relation=relation, object=object_value, support=support, subject_coreference_resolved=resolved, ) return HandlerResult( "query_causal_clause", "answered", (("subject", subject), ("relation", relation), ("object", object_value)), (("support", support),), (SemanticClause( subject, relation, object_value=object_value, tense="past", qualifiers=(("because", support),), ),), (("source", "conversation_local_causal_state"),), ("resolve_discourse_subject", "retrieve_cause_edge", "serialize_reason"), )
polarity = re.match( r"^did\s+(?:the\s+)?([a-z][a-z0-9_-]*)\s+([a-z][a-z-]*)\s+" r"(?:a|an|the)?\s*(.+)$", lower, ) if polarity: subject, resolved_subject = self._resolve(session, polarity.group(1), "subject") relation = _lemma47(polarity.group(2)) object_value, resolved_object = self._resolve(session, polarity.group(3), "object") negative = next(( value for value in reversed(session.facts) if value.subject.casefold() == subject.casefold() and value.relation == f"not::{relation}" and value.object_value.casefold() == object_value.casefold() ), None) positive = next(( value for value in reversed(session.facts) if value.subject.casefold() == subject.casefold() and value.relation == relation and value.object_value.casefold() == object_value.casefold() ), None) if negative is None and positive is None: return self._abstention("query_relation_polarity", text, "relation_not_in_workspace") is_negative = negative is not None self._record_last( session, "query_relation_polarity", (), subject=subject, relation=relation, object=object_value, polarity="negative" if is_negative else "positive", subject_coreference_resolved=resolved_subject, object_coreference_resolved=resolved_object, ) return HandlerResult( "query_relation_polarity", "answered", (("subject", subject), ("relation", relation), ("object", object_value)), (("polarity", "negative" if is_negative else "positive"),), (SemanticClause( subject, relation, object_value=object_value, tense="past", polarity="negative" if is_negative else "positive", ),), (("source", "conversation_local_polarity_state"),), ("resolve_query_roles", "retrieve_negated_or_positive_state", "release_polarity"), )
modal_query = re.match( r"^(may|might|must|should|can|could)\s+(?:the\s+)?" r"([a-z][a-z0-9_-]*)\s+([a-z][a-z-]*)\s+" r"(?:a|an|the)?\s*(.+)$", lower, ) if modal_query: requested = modal_query.group(1) subject, resolved_subject = self._resolve(session, modal_query.group(2), "subject") relation = _lemma47(modal_query.group(3)) object_value, resolved_object = self._resolve(session, modal_query.group(4), "object") admitted = POSSIBILITY_MODALS if requested in POSSIBILITY_MODALS else {requested} fact = next(( value for value in reversed(session.facts) if value.subject.casefold() == subject.casefold() and value.object_value.casefold() == object_value.casefold() and value.relation in {f"{modal}::{relation}" for modal in admitted} ), None) if fact is None: return self._abstention("query_modal_relation", text, "modal_state_not_in_workspace") stored_modal = fact.relation.split("::", 1)[0] self._record_last( session, "query_modal_relation", (), subject=subject, relation=relation, object=object_value, requested_modal=requested, stored_modal=stored_modal, subject_coreference_resolved=resolved_subject, object_coreference_resolved=resolved_object, ) return HandlerResult( "query_modal_relation", "answered", (("subject", subject), ("relation", relation), ("object", object_value)), (("modal", stored_modal),), (SemanticClause(subject, relation, object_value=object_value, modal=stored_modal),), (("source", "conversation_local_modal_world"),), ("resolve_modal_query", "select_compatible_modal_world", "release_modal_clause"), )
what_did = re.match( r"^what\s+did\s+(?:the\s+)?([a-z][a-z0-9_-]*)\s+([a-z][a-z-]*)$", lower, ) if what_did: subject, resolved = self._resolve(session, what_did.group(1), "subject") relation = _lemma47(what_did.group(2)) fact = next(( value for value in reversed(session.facts) if value.subject.casefold() == subject.casefold() and value.relation == relation ), None) if fact is None: return self._abstention("query_discourse_object", text, "relation_not_in_workspace") self._record_last( session, "query_discourse_object", (), subject=subject, relation=relation, object=fact.object_value, subject_coreference_resolved=resolved, ) return HandlerResult( "query_discourse_object", "answered", (("subject", subject), ("relation", relation)), (("object", fact.object_value),), (SemanticClause(subject, relation, object_value=fact.object_value, tense="past"),), (("source", "conversation_local_discourse_state"),), ("resolve_subject_coreference", "retrieve_relation_object", "release_clause"), )
who = re.match( r"^who\s+([a-z][a-z-]*)\s+(?:a|an|the)?\s*(.+)$", lower, ) if who: relation = _lemma47(who.group(1)) object_value, resolved = self._resolve(session, who.group(2), "object") fact = next(( value for value in reversed(session.facts) if value.relation == relation and value.object_value.casefold() == object_value.casefold() ), None) if fact is None: return None self._record_last( session, "query_discourse_subject", (), subject=fact.subject, relation=relation, object=object_value, object_coreference_resolved=resolved, ) return HandlerResult( "query_discourse_subject", "answered", (("relation", relation), ("object", object_value)), (("subject", fact.subject),), (SemanticClause(fact.subject, relation, object_value=object_value),), (("source", "conversation_local_discourse_state"),), ("resolve_object_coreference", "retrieve_relation_subject", "release_clause"), ) return None
def _handle_event(self, session_id: str, text: str, turn_id: str) -> HandlerResult | None: if self._active_intent == "ephemeral_rule": quantified = self._quantified_rule_assertion(session_id, text) if quantified is not None: return quantified if self._active_intent == "ephemeral_query": query = self._generic_query(session_id, text) if query is not None: return query return super()._handle_event(session_id, text, turn_id) if self._active_intent != "ephemeral_assertion": return super()._handle_event(session_id, text, turn_id) for handler in ( self._causal_result, self._negative_result, self._modal_result, self._existential_result, ): result = handler(session_id, text) if result is not None: return result existing = super()._handle_event(session_id, text, turn_id) if existing is not None: return existing typed = self._type_assertion_result(session_id, text) if typed is not None: return typed parsed = self._atomic_clause(text) if parsed is None: return None return self._generic_assertion(session_id, *parsed)
def answer( self, session_id: str, text: str, context: Mapping[str, Any] | None = None, *, ablate_specialists: Sequence[str] = (), ablate_knowledge_cells: Sequence[str] = (), ablate_ephemeral_workspace: bool = False, ablate_operator_composition: bool = False, ) -> dict[str, Any]: self._k53_last = {"activated": False} output = super().answer( session_id, text, context, ablate_specialists=ablate_specialists, ablate_knowledge_cells=ablate_knowledge_cells, ablate_ephemeral_workspace=ablate_ephemeral_workspace, ablate_operator_composition=ablate_operator_composition, ) selected = str(output.get("ephemeral_workspace", {}).get("selected_intent_family", "")) details = output.get("ephemeral_workspace", {}).get("details", {}) output["native_clause_algebra"] = { "schema_version": "oracle-stage5k53-native-clause-algebra-audit-v1", "activated": bool( output.get("operation") in { "compose_quantified_rule", "assert_discourse_type", "assert_discourse_relation", "assert_existential_relation", "assert_negative_relation", "assert_modal_relation", "compose_causal_clause", "query_causal_clause", "query_relation_polarity", "query_modal_relation", "query_discourse_object", "query_discourse_subject", } ), "selected_intent_family": selected, "generic_relation_operator": "relate", "canonical_operator_growth": 0, "knowledge_specialist_growth": 0, "quantifier_scope_as_variable_condition_graph": True, "modality_as_branch_local_relational_world": True, "negation_as_relational_state_transform": True, "coreference_as_discourse_role_resolution": True, "causal_clause_order_normalized": bool(details.get("normalized_cause_order", False)), "lineage_sha256": self._k53_lineage_sha256, "traditional_language_model": False, "pretrained_embedding_encoder": False, "next_token_prediction": False, } output["runtime"]["clause_algebra_model_calls"] = 0 output["runtime"]["clause_algebra_gradient_steps"] = 0 output["runtime"]["clause_algebra_next_token_predictions"] = 0 output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["NativeClauseAlgebraAgent"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3"""K55 opened repair of K53's indefinite-article realization defect."""
from __future__ import annotations
import hashlibfrom pathlib import Pathfrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, digestfrom stage5k51_restart_safe_ephemeral_agent import IndexedEphemeralEventJournalfrom stage5k53_native_clause_algebra_agent import NativeClauseAlgebraAgent
SCHEMA = "oracle-stage5k55-article-aware-clause-algebra-agent-v1"
def indefinite_article(noun: str) -> str: return "an" if noun[:1].casefold() in "aeiou" else "a"
class ArticleAwareClauseAlgebraAgent(NativeClauseAlgebraAgent): def __init__( self, *args: Any, ephemeral_journal_path: Path | None = None, **kwargs: Any, ) -> None: substrate_path = Path(args[5] if len(args) >= 6 else kwargs["substrate_path"]) journal_path = ephemeral_journal_path or substrate_path.with_suffix( ".k55.ephemeral.sqlite3" ) kwargs.setdefault("agent_id", "oracle-stage5k55-article-aware-clause-agent") super().__init__(*args, ephemeral_journal_path=journal_path, **kwargs) state = hashlib.sha256() for name in ( "stage5k51_restart_safe_ephemeral_agent.py", "stage5k53_native_clause_algebra_agent.py", Path(__file__).name, ): payload = Path(__file__).with_name(name).read_bytes() state.update(len(payload).to_bytes(8, "big")) state.update(payload) self._k53_lineage_sha256 = state.hexdigest() self.ephemeral_journal = IndexedEphemeralEventJournal( journal_path, source_sha256=self._k53_lineage_sha256, )
def _type_assertion_result(self, session_id: str, text: str) -> HandlerResult | None: result = super()._type_assertion_result(session_id, text) if result is None: return None arguments = dict(result.arguments) values = dict(result.result) subject = str(arguments["subject"]) entity_type = str(values["entity_type"]) article = indefinite_article(entity_type) return HandlerResult( result.operation, result.status, result.arguments, result.result, (SemanticClause(subject, "be", complement=f"{article} {entity_type}"),), result.evidence, (*result.computation_trace, "realize_indefinite_article_from_noun_onset"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def answer( self, session_id: str, text: str, context: Mapping[str, Any] | None = None, *, ablate_specialists: Sequence[str] = (), ablate_knowledge_cells: Sequence[str] = (), ablate_ephemeral_workspace: bool = False, ablate_operator_composition: bool = False, ) -> dict[str, Any]: output = super().answer( session_id, text, context, ablate_specialists=ablate_specialists, ablate_knowledge_cells=ablate_knowledge_cells, ablate_ephemeral_workspace=ablate_ephemeral_workspace, ablate_operator_composition=ablate_operator_composition, ) output["native_clause_algebra"]["indefinite_article_realization"] = "noun_onset" output["runtime"]["indefinite_article_model_calls"] = 0 output["runtime"]["indefinite_article_gradient_steps"] = 0 output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["ArticleAwareClauseAlgebraAgent", "indefinite_article"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115#!/usr/bin/env python3"""K60 repair: verbs governed by a modal are already bare infinitives."""
from __future__ import annotations
import hashlibfrom pathlib import Pathimport refrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import HandlerResult, SemanticClause, clean, digestfrom stage5k45_ephemeral_compositional_language_agent import _strip_articlefrom stage5k51_restart_safe_ephemeral_agent import IndexedEphemeralEventJournalfrom stage5k53_native_clause_algebra_agent import POSSIBILITY_MODALSfrom stage5k57_ablatable_clause_algebra_agent import AblatableClauseAlgebraAgent
SCHEMA = "oracle-stage5k60-modal-bare-infinitive-agent-v1"
class ModalBareInfinitiveAgent(AblatableClauseAlgebraAgent): def __init__(self, *args: Any, ephemeral_journal_path: Path | None = None, **kwargs: Any) -> None: substrate_path = Path(args[5] if len(args) >= 6 else kwargs["substrate_path"]) journal_path = ephemeral_journal_path or substrate_path.with_suffix(".k60.ephemeral.sqlite3") kwargs.setdefault("agent_id", "oracle-stage5k60-modal-bare-infinitive-agent") super().__init__(*args, ephemeral_journal_path=journal_path, **kwargs) state = hashlib.sha256() for name in ( "stage5k51_restart_safe_ephemeral_agent.py", "stage5k53_native_clause_algebra_agent.py", "stage5k55_article_aware_clause_algebra_agent.py", "stage5k57_ablatable_clause_algebra_agent.py", Path(__file__).name, ): payload = Path(__file__).with_name(name).read_bytes() state.update(len(payload).to_bytes(8, "big")); state.update(payload) self._k53_lineage_sha256 = state.hexdigest() self.ephemeral_journal = IndexedEphemeralEventJournal( journal_path, source_sha256=self._k53_lineage_sha256, )
@staticmethod def _modal_assertion(text: str) -> tuple[str, str, str, str] | None: match = re.match( r"^(?:the\s+)?([a-z][a-z0-9_-]*)\s+" r"(may|might|must|should|can|could)\s+([a-z][a-z-]*)\s+" r"(?:a|an|the)?\s*(.+?)[.!?]*$", clean(text), re.IGNORECASE, ) return ( match.group(1), match.group(2).casefold(), clean(match.group(3)).casefold(), _strip_article(match.group(4)), ) if match else None
def _generic_query(self, session_id: str, text: str) -> HandlerResult | None: lower = clean(text).casefold().rstrip("?!.") match = re.match( r"^(may|might|must|should|can|could)\s+(?:the\s+)?" r"([a-z][a-z0-9_-]*)\s+([a-z][a-z-]*)\s+" r"(?:a|an|the)?\s*(.+)$", lower, ) if match is None: return super()._generic_query(session_id, text) session = self._session(session_id) requested = match.group(1) subject, resolved_subject = self._resolve(session, match.group(2), "subject") relation = clean(match.group(3)).casefold() object_value, resolved_object = self._resolve(session, match.group(4), "object") admitted = POSSIBILITY_MODALS if requested in POSSIBILITY_MODALS else {requested} fact = next(( value for value in reversed(session.facts) if value.subject.casefold() == subject.casefold() and value.object_value.casefold() == object_value.casefold() and value.relation in {f"{modal}::{relation}" for modal in admitted} ), None) if fact is None: return self._abstention("query_modal_relation", text, "modal_state_not_in_workspace") stored_modal = fact.relation.split("::", 1)[0] self._record_last( session, "query_modal_relation", (), subject=subject, relation=relation, object=object_value, requested_modal=requested, stored_modal=stored_modal, subject_coreference_resolved=resolved_subject, object_coreference_resolved=resolved_object, modal_bare_infinitive=True, ) return HandlerResult( "query_modal_relation", "answered", (("subject", subject), ("relation", relation), ("object", object_value)), (("modal", stored_modal),), (SemanticClause(subject, relation, object_value=object_value, modal=stored_modal),), (("source", "conversation_local_modal_world"),), ("preserve_modal_bare_infinitive", "select_compatible_modal_world", "release_modal_clause"), )
def answer( self, session_id: str, text: str, context: Mapping[str, Any] | None = None, *, ablate_specialists: Sequence[str] = (), ablate_knowledge_cells: Sequence[str] = (), ablate_ephemeral_workspace: bool = False, ablate_operator_composition: bool = False, ) -> dict[str, Any]: output = super().answer( session_id, text, context, ablate_specialists=ablate_specialists, ablate_knowledge_cells=ablate_knowledge_cells, ablate_ephemeral_workspace=ablate_ephemeral_workspace, ablate_operator_composition=ablate_operator_composition, ) output["native_clause_algebra"]["modal_bare_infinitive_preserved"] = True output["runtime"]["modal_infinitive_model_calls"] = 0 output["runtime"]["modal_infinitive_gradient_steps"] = 0 output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["ModalBareInfinitiveAgent"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916#!/usr/bin/env python3"""K69 opened repair of the whole-system interfaces exposed by K68.
K68 preserved the twelve-cell geometry but showed that productive frame andclause handlers could consume whole interrogative or imperative constructionsbefore the already-present knowledge, arithmetic, motion, and tool handlers.This successor adds a deterministic whole-construction dispatch transform,parameterizes the existing hypothetical operator, and lets K63's frozendictionary/frame lattice parse multiword causal clauses. It adds no cell,primitive mode, ontology row, learned carrier, model call, or gradient step."""
from __future__ import annotations
import hashlibfrom pathlib import Pathimport refrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import ( HandlerResult, NativeAnswerGrammar, QuadraticAnswerInverse, SemanticClause, clean, digest, sentence_case, third_person, tokens,)from stage5k45_ephemeral_compositional_language_agent import ( RelationFact, _strip_article,)from stage5k51_restart_safe_ephemeral_agent import IndexedEphemeralEventJournalfrom stage5k63_contextual_frame_induction_agent import ContextualInverseGrammarfrom stage5k67_general_definition_morphology_agent import GeneralDefinitionMorphologyAgent
SCHEMA = "oracle-stage5k69-whole-system-dispatch-agent-v1"COLORS = frozenset({ "amber", "black", "blue", "bronze", "brown", "cyan", "gold", "gray", "green", "grey", "indigo", "orange", "pink", "purple", "red", "silver", "teal", "violet", "white", "yellow",})TOOL_WORDS = frozenset({ "database", "dataset", "catalog", "table", "population", "earthquake", "earthquakes", "magnitude", "depth", "record", "records", "registered", "lookup", "provenance", "license", "published", "publisher",})
class K69ContextualInverseGrammar(ContextualInverseGrammar): """Retain dictionary morphology while restoring phrase-level number."""
@staticmethod def _plural(subject: str) -> bool: lower = " ".join(clean(subject).casefold().split()) if lower in {"they", "we", "you"} or " and " in lower: return True if any(re.search(rf"\b{value}\b", lower) for value in ( "people", "children", "men", "women", "data", "criteria", "phenomena", )): return True head = re.split( r"\b(?:that|which|who|in|from|with|under|during|at)\b", lower, maxsplit=1, )[0].strip() final = re.sub(r"[^a-z]", "", (head or lower).split()[-1]) if (head or lower).split() else "" return bool( len(final) > 2 and final.endswith("s") and not final.endswith(("ss", "us", "is")) and final not in {"news", "physics", "mathematics", "economics"} )
def clause(self, clause: SemanticClause) -> str: subject = sentence_case(clause.subject) lemma = clean(clause.predicate).casefold() first_person = subject.casefold() == "i" plural = self._plural(subject) if clause.modal: verb = f"{clause.modal} {lemma}" elif clause.tense == "past": verb = ( "were" if lemma == "be" and plural and not first_person else self.dictionary.past_surface(lemma) ) elif first_person: verb = "am" if lemma == "be" else lemma elif plural: verb = "are" if lemma == "be" else lemma else: verb = third_person(lemma) if clause.polarity == "negative" and clause.modal is None: auxiliary = "did not" if clause.tense == "past" else ( "do not" if plural else "does not" ) verb = f"{auxiliary} {lemma}" parts = [subject, verb] if clause.object_value: parts.append(clean(clause.object_value)) if clause.complement: parts.append(clean(clause.complement)) for preposition, value in clause.qualifiers: parts.extend((clean(preposition), clean(value))) return " ".join(parts).rstrip(".?!") + "."
class WholeSystemDispatchAgent(GeneralDefinitionMorphologyAgent): def __init__( self, *args: Any, ephemeral_journal_path: Path | None = None, **kwargs: Any, ) -> None: substrate_path = Path(args[5] if len(args) >= 6 else kwargs["substrate_path"]) journal_path = ephemeral_journal_path or substrate_path.with_suffix( ".k69.ephemeral.sqlite3" ) kwargs.setdefault("agent_id", "oracle-stage5k69-whole-system-dispatch-agent") super().__init__(*args, ephemeral_journal_path=journal_path, **kwargs) lineage = hashlib.sha256() for name in ( "stage5k45_ephemeral_compositional_language_agent.py", "stage5k47_morphological_counterfactual_agent.py", "stage5k53_native_clause_algebra_agent.py", "stage5k60_modal_bare_infinitive_agent.py", "stage5k63_contextual_frame_induction_agent.py", "stage5k67_general_definition_morphology_agent.py", Path(__file__).name, ): payload = Path(__file__).with_name(name).read_bytes() lineage.update(len(payload).to_bytes(8, "big")) lineage.update(payload) self._k69_lineage_sha256 = lineage.hexdigest() self.ephemeral_journal = IndexedEphemeralEventJournal( journal_path, source_sha256=self._k69_lineage_sha256, ) self._k69_hypotheticals: dict[str, dict[str, str]] = {} self._k69_counterfactual_entities: dict[str, str] = {} self._k69_grounded_evidence: dict[str, tuple[dict[str, Any], ...]] = {} self._k69_dispatch_last: dict[str, Any] = {} self.inverse = QuadraticAnswerInverse(K69ContextualInverseGrammar(self.dictionary))
@staticmethod def _explicit_tool_request(text: str, context: Mapping[str, Any] | None = None) -> bool: lower = clean(text).casefold() words = set(tokens(text)) local = dict(context or {}) if local.get("k39_tool_dialogue_active"): return bool( words & TOOL_WORDS or re.match(r"^(?:which|what|who|by\s+how\s+much)\b", lower) ) return bool( words & TOOL_WORDS and ( words & {"database", "dataset", "catalog", "table", "registered", "lookup"} or re.search(r"\blook\s+up\b", lower) or re.search(r"\b(?:how\s+many|find|use|published|license)\b", lower) ) )
@staticmethod def _arithmetic_request(text: str) -> bool: lower = clean(text).casefold() return bool( re.search(r"-?\d+(?:\.\d+)?\s*(?:times|plus|minus|multiplied\s+by)\s*-?\d", lower) )
@staticmethod def _arithmetic(text: str) -> tuple[float, str] | None: normalized = re.sub( r",?\s*then\s+(?:reduced|decreased)\s+by\s+", " minus ", clean(text), flags=re.IGNORECASE, ) normalized = re.sub( r",?\s*then\s+(?:increased|raised)\s+by\s+", " plus ", normalized, flags=re.IGNORECASE, ) return GeneralDefinitionMorphologyAgent._arithmetic(normalized)
@classmethod def _bound_arithmetic(cls, text: str) -> tuple[float, str, str] | None: normalized = re.sub( r",?\s*then\s+(?:reduced|decreased)\s+by\s+", " minus ", clean(text), flags=re.IGNORECASE, ) normalized = re.sub( r",?\s*then\s+(?:increased|raised)\s+by\s+", " plus ", normalized, flags=re.IGNORECASE, ) return super()._bound_arithmetic(normalized)
@staticmethod def _knowledge_speech_act(text: str) -> bool: lower = clean(text).casefold() return bool( re.match( r"^(?:through\s+what|which\s+feedback|how\s+much|how\s+did|" r"where\s+does|what\s+does|what\s+kind|what\s+role|explain\s+how|" r"relate\b|contrast\b|state\s+both|in\s+two\s+clauses|" r"could\s+you\s+restate|please\s+restate|summarize\b)", lower, ) )
@staticmethod def _definition_followup(text: str) -> str | None: match = re.search( r"what\s+(?:follows|can\s+you\s+conclude)\s+about\s+" r"(?:the\s+)?([a-z][a-z0-9_-]*)\s+from\s+(?:that|the)\s+definition", clean(text), re.IGNORECASE, ) return match.group(1).casefold() if match else None
@staticmethod def _generic_definition_question(text: str) -> bool: return bool(re.match( r"^what\s+is\s+(?:a|an|the)\s+", clean(text).casefold(), ))
@staticmethod def _cross_segments(text: str) -> tuple[str, str] | None: value = clean(text).rstrip(".?!") for pattern in ( r"^relate\s+(.+?)\s+to\s+(.+)$", r"^contrast\s+(.+?)\s+with\s+(.+)$", ): match = re.match(pattern, value, re.IGNORECASE) if match: return clean(match.group(1)), clean(match.group(2)) return None
def _cross_segment_candidate( self, segment: str, ) -> tuple[dict[str, Any] | None, dict[str, Any]]: """Resolve a cross-domain segment through the frozen concept lattice.
K68 showed that a relationally exact row could be hidden behind one derivational surface change (for example adjective-to-noun or nominalization-to-verb). Enumerate only bounded, one-term rewrites already licensed by K39's frozen WordNet concept addresses, and still require K41's exact-specificity admission after the rewrite. No corpus row, expected answer, or prompt-specific synonym is consulted. """ direct = self.knowledge_basis.best_specific_exact_candidate(segment) if direct is not None: return dict(direct), { "segment": segment, "query_form": segment, "relation_kind": "exact_surface", "relation_score": 1.0, "candidate_forms_tested": 1, }
query_terms = tuple(dict.fromkeys(tokens(segment))) links, _ = self.knowledge_basis._semantic_term_links(query_terms) rewrites: list[tuple[float, str, str, str]] = [] for source_term in query_terms: for target_term, value in links.get(source_term, {}).items(): score, _atom, kind = value threshold = { "morphological_lexeme": 0.98, "derivational_family": 0.75, "sense_or_hypernym": 0.95, }.get(kind) if threshold is None or float(score) < threshold or target_term == source_term: continue rewrites.append((float(score), source_term, target_term, kind)) rewrites.sort(key=lambda value: (-value[0], value[1], value[2], value[3]))
admitted: list[tuple[float, int, float, str, dict[str, Any], str]] = [] tested = 1 for relation_score, source_term, target_term, kind in rewrites[:16]: query_form = re.sub( rf"\b{re.escape(source_term)}\b", target_term, clean(segment), count=1, flags=re.IGNORECASE, ) if query_form.casefold() == clean(segment).casefold(): continue tested += 1 candidate = self.knowledge_basis.best_specific_exact_candidate(query_form) if candidate is None: continue admitted.append(( float(candidate.get("relational_exact_information", 0.0)), int(candidate.get("relational_exact_anchor_count", 0)), relation_score, str(candidate.get("text_sha256", "")), dict(candidate), f"{source_term}->{target_term}:{kind}", )) if not admitted: return None, { "segment": segment, "query_form": None, "relation_kind": "none", "relation_score": 0.0, "candidate_forms_tested": tested, } admitted.sort(key=lambda value: (-value[0], -value[1], -value[2], value[3])) information, anchors, relation_score, _sha, candidate, transform = admitted[0] source_term, remainder = transform.split("->", 1) target_term, kind = remainder.rsplit(":", 1) query_form = re.sub( rf"\b{re.escape(source_term)}\b", target_term, clean(segment), count=1, flags=re.IGNORECASE, ) return candidate, { "segment": segment, "query_form": query_form, "relation_kind": kind, "relation_score": relation_score, "exact_information": information, "exact_anchor_count": anchors, "candidate_forms_tested": tested, }
@staticmethod def _multiword_property(text: str) -> tuple[str, str] | None: match = re.match( r"^(?:the\s+)?([a-z][a-z0-9_-]*(?:\s+[a-z][a-z0-9_-]*){1,5})\s+" r"is\s+([a-z][a-z-]*)[.!?]*$", clean(text), re.IGNORECASE, ) if match is None or match.group(2).casefold() not in COLORS: return None return clean(match.group(1)), match.group(2).casefold()
@staticmethod def _hypothetical_query(text: str) -> bool: lower = clean(text).casefold() return bool( re.match(r"^what\s+(?:occurs|happens)\s+(?:when|if)\b", lower) or re.match(r"^what\s+can\s+change\s+(?:when|if)\b", lower) )
@classmethod def _ephemeral_family( cls, text: str, context: Mapping[str, Any] | None = None, ) -> str | None: # These shapes belong to whole-system handlers and must not be consumed # as generic discourse assertions merely because they contain a verb. if cls._explicit_tool_request(text, context): return None if cls._arithmetic_request(text): return None if cls._knowledge_speech_act(text): return None if cls._generic_definition_question(text): return None if cls._definition_followup(text) or cls._hypothetical_query(text): return "ephemeral_query" if cls._multiword_property(text): return "ephemeral_assertion" return super()._ephemeral_family(text, context)
@classmethod def _intent_lattice( cls, text: str, context: Mapping[str, Any] | None = None, ) -> dict[str, Any]: audit = dict(super()._intent_lattice(text, context)) selected_before = str(audit.get("selected_intent_family", "open")) selected = selected_before reason = "inherited_typed_intent" lower = clean(text).casefold() family = cls._ephemeral_family(text, context) if cls._explicit_tool_request(text, context): selected, reason = "bounded_dataset", "whole_construction_bounded_tool" elif cls._arithmetic_request(text): selected, reason = "bounded_arithmetic", "whole_construction_arithmetic" elif cls._motion(text) is not None: selected, reason = "motion_event", "whole_construction_motion" elif re.search(r"returning\s+to\s+[a-z][a-z0-9_-]+.*\bwhere\s+is\s+(?:he|she|it|they)\b", lower): selected, reason = "state_query", "named_discourse_return" elif family is not None: selected, reason = family, "productive_ephemeral_construction" elif cls._knowledge_speech_act(text): selected, reason = "open", "whole_construction_knowledge_or_paraphrase" scores = dict(audit.get("candidate_scores", {})) scores[selected] = max(1.0, float(scores.get(selected, 0.0))) audit["candidate_scores"] = scores audit["selected_intent_family"] = selected audit["selection_policy"] = "k69_whole_construction_before_local_predicate" audit["k69_dispatch"] = { "selected_before": selected_before, "selected_after": selected, "reason": reason, "whole_construction_precedes_local_predicate": True, "answer_or_gold_labels_used": False, } return audit
@staticmethod def _motion(text: str) -> tuple[str, str] | None: match = re.search( r"\b([A-Za-z][A-Za-z0-9_-]*)\s+" r"(?:moves?|moved|travels?|traveled|drives?|drove|walks?|walked)\s+" r"(?:directly\s+|quietly\s+|slowly\s+|quickly\s+)?" r"(?:into|to)\s+(?:the\s+)?" r"([A-Za-z][A-Za-z0-9_-]*(?:\s+[A-Za-z][A-Za-z0-9_-]*){0,5})[.!?]*$", clean(text), re.IGNORECASE, ) return (clean(match.group(1)), clean(match.group(2))) if match else None
@staticmethod def _location_query(text: str) -> str | None: returning = re.search( r"returning\s+to\s+([a-z][a-z0-9_-]+).*\bwhere\s+is\s+(?:he|she|it|they)\b", clean(text), re.IGNORECASE, ) if returning: return returning.group(1).casefold() return GeneralDefinitionMorphologyAgent._location_query(text)
def _property_assertion(self, session_id: str, text: str) -> HandlerResult | None: existing = super()._property_assertion(session_id, text) if existing is not None: return existing parsed = self._multiword_property(text) if parsed is None: return None entity, quality = parsed session = self._session(session_id) state = session.workspace.compose( "property", (self._entity(session, entity), session.workspace.symbol(quality, "quality")), ttl_turns=128, ) session.property_states[(entity.casefold(), quality)] = state.state_id self._record_last( session, "assert_ephemeral_property", (state,), entity=entity, quality=quality, ) return HandlerResult( "assert_ephemeral_property", "answered", (("entity", entity),), (("quality", quality),), (SemanticClause(entity, "be", complement=quality),), (("source", "conversation_local_stipulation"),), ("bind_multiword_entity_property", "stabilize_ephemeral_state"), )
def _handle_evidence( self, text: str, context: Mapping[str, Any], ) -> HandlerResult | None: result = super()._handle_evidence(text, context) if result is None or result.operation != "knowledge_explanation": return result evidence = context.get("evidence") if not isinstance(evidence, Sequence) or isinstance(evidence, (str, bytes)): return result
# A comparative source licenses both sides of its own contrast. On a # restatement request, release that inverse explicitly instead of # copying the source surface and leaving the dominant side implicit. if re.match(r"^(?:could\s+you|please)\s+restate\b", clean(text), re.IGNORECASE): for row in evidence: if not isinstance(row, Mapping): continue surface = clean(row.get("fact", row.get("text", ""))) contrast = re.search( r"\bby\s+(.+?)\s+and,?\s+(?:much\s+)?less\s+frequently,?\s+by\s+(.+?)(?:[.!?]|$)", surface, re.IGNORECASE, ) if contrast: common = clean(contrast.group(1)) rarer = clean(contrast.group(2)) return HandlerResult( result.operation, result.status, result.arguments, (*result.result, ("explicit_contrast", [common, rarer])), ( SemanticClause(common, "be", complement="more common"), SemanticClause(rarer, "be", complement="less frequent"), ), result.evidence, (*result.computation_trace, "invert_implicit_comparative_for_restatement"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
process_name = None released_objects: list[str] = [] for row in evidence: if not isinstance(row, Mapping): continue surface = clean(row.get("fact", row.get("text", ""))) match = re.search(r"\bprocess\s+of\s+([a-z][a-z-]*)\b", surface, re.IGNORECASE) if match: process_name = match.group(1).casefold() for release in re.finditer( r"\breleasing\s+(.+?)(?=\s+as\b|[,.;]|$)", surface, re.IGNORECASE, ): value = clean(release.group(1)) if value: released_objects.append(value) if not process_name: return result additions: list[SemanticClause] = [] if re.search(r"\bwhat\s+process\b|\bthrough\s+what\s+process\b|^(?:relate|contrast)\b", clean(text), re.IGNORECASE): additions.append(SemanticClause("The process", "be", complement=process_name)) additions.extend( SemanticClause(process_name, "release", object_value=value) for value in dict.fromkeys(released_objects) ) if not additions: return result return HandlerResult( result.operation, result.status, result.arguments, (*result.result, ("named_process", process_name)), (*additions, *result.clauses), result.evidence, (*result.computation_trace, "release_process_relation_anchors"), tool_audit=result.tool_audit, memory_audit=result.memory_audit, )
def _handle_tool(self, session_id: str, text: str) -> HandlerResult | None: result = super()._handle_tool(session_id, text) audit = dict(result.tool_audit or {}) if result is not None else {} if result is None or result.operation != "bounded_tool" or audit.get("operation") != "provenance": return result expert = getattr(self.tool_backend, "experts", {}).get(audit.get("expert_id")) if expert is None or not expert.rows: return result row = expert.rows[0] authority = clean(row.get("source_authority", "")) license_value = clean(row.get("source_license", "")) if not authority or not license_value: return result audit["values"] = [authority, license_value] audit["source_authority"] = authority audit["source_license"] = license_value return HandlerResult( result.operation, result.status, result.arguments, (("values", [authority, license_value]), ("source_license", license_value)), ( SemanticClause("The source authority", "be", complement=authority), SemanticClause("The source license", "be", complement=license_value), ), result.evidence, (*result.computation_trace, "release_typed_authority_and_license_fields"), tool_audit=audit, memory_audit=result.memory_audit, )
@staticmethod def _parse_hypothetical(text: str) -> dict[str, str] | None: match = re.match( r"^imagine\s+(?:a|an|the)\s+(?P<world>.+?)\s+where\s+" r"(?P<actor>.+?)\s+(?P<action>[a-z][a-z-]*)\s+(?P<cadence>.+?)\s+" r"unless\s+(?P<exception>.+?),\s+and\s+" r"(?P<effect_subject>.+?)\s+(?P<effect_action>[a-z][a-z-]*)\s+" r"whenever\s+(?P<trigger>.+?)[.!?]*$", clean(text), re.IGNORECASE, ) if match is None: return None return {key: clean(value) for key, value in match.groupdict().items()}
def _hypothetical_assertion(self, session_id: str, text: str) -> HandlerResult | None: parsed = self._parse_hypothetical(text) if parsed is None: return super()._hypothetical_assertion(session_id, text) session = self._session(session_id) world = session.workspace.branch_world("imagined_" + re.sub(r"\W+", "_", parsed["world"].casefold())) action_lemma = self.frame_inducer.dictionary.lemma(parsed["action"])[0] effect_lemma = self.frame_inducer.dictionary.lemma(parsed["effect_action"])[0] actor = self._entity(session, parsed["actor"], world_id=world) cadence = session.workspace.symbol(parsed["cadence"], "value", world_id=world) action_state = session.workspace.compose( "relate", (actor, self._relation(session, action_lemma, world_id=world), cadence), world_id=world, ttl_turns=128, ) exception_state = session.workspace.compose( "property", ( self._entity(session, parsed["exception"], world_id=world), session.workspace.symbol("true", "quality", world_id=world), ), world_id=world, ttl_turns=128, ) exception_absent = session.workspace.compose( "negate", (exception_state,), world_id=world, ttl_turns=128, ) guarded_state = session.workspace.compose( "condition", (exception_absent, action_state), world_id=world, ttl_turns=128, ) effect_state = session.workspace.compose( "relate", ( self._entity(session, parsed["effect_subject"], world_id=world), self._relation(session, effect_lemma, world_id=world), session.workspace.symbol("true", "value", world_id=world), ), world_id=world, ttl_turns=128, ) trigger_fact = session.workspace.compose( "property", ( self._entity(session, parsed["trigger"], world_id=world), session.workspace.symbol("true", "quality", world_id=world), ), world_id=world, ttl_turns=128, ) trigger_state = session.workspace.compose( "condition", ( trigger_fact, effect_state, ), world_id=world, ttl_turns=128, ) session.hypothetical_rules["k69_guarded_action"] = guarded_state session.hypothetical_rules["k69_triggered_effect"] = trigger_state self._k69_hypotheticals[session_id] = { **parsed, "action_lemma": action_lemma, "effect_lemma": effect_lemma, "world_id": world, } self._record_last( session, "compose_hypothetical_world", (action_state, exception_state, exception_absent, guarded_state, effect_state, trigger_fact, trigger_state), world_id=world, rule_count=2, branch_local=True, bound_variables={key: value for key, value in parsed.items()}, ) return HandlerResult( "compose_hypothetical_world", "answered", (("world", parsed["world"]),), (("rules", 2), ("world_id", world)), ( SemanticClause( parsed["actor"], action_lemma, qualifiers=(("during", parsed["cadence"]), ("unless", parsed["exception"])), ), SemanticClause( parsed["effect_subject"], effect_lemma, qualifiers=(("whenever", parsed["trigger"]),), ), ), (("source", "conversation_local_hypothetical"),), ( "bind_hypothetical_variables", "branch_world", "compose_exception_guard", "compose_triggered_effect", ), )
def _counterfactual_assertion(self, session_id: str, text: str) -> HandlerResult | None: result = super()._counterfactual_assertion(session_id, text) parsed = self._counterfactual(text) if result is not None and parsed is not None: self._k69_counterfactual_entities[session_id] = parsed[0] return result
def _ephemeral_query(self, session_id: str, text: str) -> HandlerResult | None: definition_entity = self._definition_followup(text) if definition_entity: return super()._ephemeral_query( session_id, f"What can you infer about {definition_entity}?", ) lower = clean(text).casefold() if re.search(r"what\s+color\s+is\s+(?:it|that)\s+in\s+the\s+actual\s+world", lower): entity = self._k69_counterfactual_entities.get(session_id) if entity: return super()._ephemeral_query( session_id, f"What color is the {entity} in the actual world?", ) hypothetical = self._k69_hypotheticals.get(session_id) if hypothetical and re.match(r"^what\s+(?:occurs|happens)\s+(?:when|if)\b", lower): session = self._session(session_id) state = session.hypothetical_rules.get("k69_guarded_action") if state is not None: self._record_last( session, "query_hypothetical_rule", (state,), selected_rule="k69_guarded_action", ) return HandlerResult( "query_hypothetical_rule", "answered", (), (("consequence", f"{hypothetical['actor']} {hypothetical['action_lemma']} {hypothetical['cadence']}"),), (SemanticClause( hypothetical["actor"], hypothetical["action_lemma"], qualifiers=(("during", hypothetical["cadence"]),), ),), (("source", "conversation_local_hypothetical"),), ("resolve_exception_as_false", "release_parameterized_rule_consequence"), ) if hypothetical and re.match(r"^what\s+can\s+change\s+(?:when|if)\b", lower): session = self._session(session_id) state = session.hypothetical_rules.get("k69_triggered_effect") if state is not None: self._record_last( session, "query_hypothetical_rule", (state,), selected_rule="k69_triggered_effect", ) return HandlerResult( "query_hypothetical_rule", "answered", (), (("consequence", f"{hypothetical['effect_subject']} {hypothetical['effect_lemma']}"),), (SemanticClause( hypothetical["effect_subject"], hypothetical["effect_lemma"], qualifiers=(("when", hypothetical["trigger"]),), ),), (("source", "conversation_local_hypothetical"),), ("match_parameterized_trigger", "release_parameterized_rule_consequence"), ) return super()._ephemeral_query(session_id, text)
def _frame_atomic_clause(self, text: str) -> tuple[str, str, str] | None: frame = self.frame_inducer.analyze_assertion(clean(text).rstrip(".?!")) if frame is None: return None roles = {argument.role: clean(argument.surface) for argument in frame.arguments} subject = roles.get("subject") if not subject: return None object_value = roles.get("direct_object") or roles.get("clause_complement") or "event" return _strip_article(subject), frame.lemma, _strip_article(object_value)
def _causal_result(self, session_id: str, text: str) -> HandlerResult | None: value = clean(text).rstrip(".?!") front = re.match(r"^because\s+(.+?),\s*(.+)$", value, re.IGNORECASE) rear = re.match(r"^(.+?)\s+because\s+(.+)$", value, re.IGNORECASE) surface_order = "cause_first" if front else "result_first" if front: support = self._frame_atomic_clause(front.group(1)) result = self._frame_atomic_clause(front.group(2)) elif rear: result = self._frame_atomic_clause(rear.group(1)) support = self._frame_atomic_clause(rear.group(2)) else: return super()._causal_result(session_id, text) if support is None or result is None: return super()._causal_result(session_id, text) session = self._session(session_id) support_state = self._relation_state(session, *support) result_state = self._relation_state(session, *result) cause_state = session.workspace.compose( "cause", (support_state, result_state), ttl_turns=128, ) support_clause = SemanticClause( support[0], support[1], object_value=None if support[2] == "event" else support[2], tense="past", ) support_surface = NativeAnswerGrammar.clause(support_clause).rstrip(".") session.facts.extend(( RelationFact(*support, support_state.state_id, support_state.world_id), RelationFact(*result, result_state.state_id, result_state.world_id), RelationFact( result[0], f"because::{result[1]}", support_surface, cause_state.state_id, cause_state.world_id, inferred=True, ), )) self._record_last( session, "compose_causal_clause", (support_state, result_state, cause_state), subject=result[0], relation=result[1], object=result[2], support=support_surface, input_clause_order=surface_order, normalized_cause_order=True, contextual_frame_predicates=True, ) return HandlerResult( "compose_causal_clause", "answered", (("support", support), ("result", result)), (("normalized_order", "support_then_result"),), (SemanticClause( result[0], result[1], object_value=None if result[2] == "event" else result[2], tense="past", qualifiers=(("because", support_surface),), ),), (("source", "conversation_local_causal_clause"),), ( "induce_multiword_clause_frames", "recover_dictionary_lemmas", "compose_support", "compose_result", "bind_cause", ), )
def _generic_query(self, session_id: str, text: str) -> HandlerResult | None: lower = clean(text).casefold().rstrip("?!. ") if lower.startswith("why did "): session = self._session(session_id) causal_facts = [ value for value in reversed(session.facts) if value.relation.startswith("because::") ] query_words = set(tokens(lower)) for fact in causal_facts: relation = fact.relation.split("::", 1)[1] subject_words = set(tokens(fact.subject)) query_lemmas = { self.frame_inducer.dictionary.lemma(word)[0] for word in query_words } if not subject_words <= query_words or relation not in query_lemmas: continue result_fact = next(( value for value in reversed(session.facts) if value.subject.casefold() == fact.subject.casefold() and value.relation == relation and not value.inferred ), None) object_value = result_fact.object_value if result_fact is not None else "event" self._record_last( session, "query_causal_clause", (), subject=fact.subject, relation=relation, object=object_value, support=fact.object_value, multiword_subject_resolved=True, ) return HandlerResult( "query_causal_clause", "answered", (("subject", fact.subject), ("relation", relation), ("object", object_value)), (("support", fact.object_value),), (SemanticClause( fact.subject, relation, object_value=None if object_value == "event" else object_value, tense="past", qualifiers=(("because", fact.object_value),), ),), (("source", "conversation_local_causal_state"),), ( "resolve_multiword_discourse_subject", "retrieve_cause_edge", "serialize_reason", ), ) return super()._generic_query(session_id, text)
def answer( self, session_id: str, text: str, context: Mapping[str, Any] | None = None, *, ablate_specialists: Sequence[str] = (), ablate_knowledge_cells: Sequence[str] = (), ablate_ephemeral_workspace: bool = False, ablate_operator_composition: bool = False, ablate_frame_induction: bool = False, ablate_induced_role_binding: bool = False, withhold_dictionary_top1: bool = False, ) -> dict[str, Any]: local_context = dict(context or {}) preview = self._intent_lattice(text, local_context) injected_rows: tuple[dict[str, Any], ...] = () evidence_mode = "none" cross_segment_audit: list[dict[str, Any]] = [] segments = self._cross_segments(text) if segments and not any(local_context.get(key) for key in ("evidence", "training_corpus", "sensor_stream")): candidates: list[dict[str, Any]] = [] for segment in segments: candidate, segment_audit = self._cross_segment_candidate(segment) cross_segment_audit.append(segment_audit) if candidate is not None: candidates.append(dict(candidate)) unique = {str(value.get("text_sha256")): value for value in candidates} if len(unique) >= 2: injected_rows = tuple(self._evidence_context_row(value) for value in unique.values()) local_context["evidence"] = injected_rows evidence_mode = "cross_segment_exact_relational_fusion" if ( evidence_mode == "none" and re.match(r"^(?:could\s+you|please)\s+restate\b", clean(text).casefold()) and session_id in self._k69_grounded_evidence and not any(local_context.get(key) for key in ("evidence", "training_corpus", "sensor_stream")) ): injected_rows = tuple( self._evidence_context_row(value) for value in self._k69_grounded_evidence[session_id] ) local_context["evidence"] = injected_rows evidence_mode = "discourse_grounded_evidence_reuse" output = super().answer( session_id, text, local_context, ablate_specialists=ablate_specialists, ablate_knowledge_cells=ablate_knowledge_cells, ablate_ephemeral_workspace=ablate_ephemeral_workspace, ablate_operator_composition=ablate_operator_composition, ablate_frame_induction=ablate_frame_induction, ablate_induced_role_binding=ablate_induced_role_binding, withhold_dictionary_top1=withhold_dictionary_top1, ) lattice = output.get("knowledge_lattice") or {} if injected_rows: existing = list(lattice.get("retrieved_evidence", ())) merged = { str(value.get("text_sha256")): dict(value) for value in (*injected_rows, *existing) if isinstance(value, Mapping) and value.get("text_sha256") } lattice["retrieval_admitted_to_proof"] = True lattice["retrieval_gate_reason"] = evidence_mode lattice["retrieved_evidence"] = list(merged.values()) lattice["evidence_rows_admitted_to_proof"] = list(injected_rows) lattice["relational_provenance_reconciled"] = True if lattice.get("retrieval_admitted_to_proof") and lattice.get("retrieved_evidence"): self._k69_grounded_evidence[session_id] = tuple( dict(value) for value in lattice["retrieved_evidence"] if isinstance(value, Mapping) and value.get("text_sha256") ) output["whole_system_dispatch"] = { "schema_version": SCHEMA, **preview.get("k69_dispatch", {}), "lineage_sha256": self._k69_lineage_sha256, "physical_cell_growth": 0, "primitive_mode_growth": 0, "ontology_growth": 0, "new_fold_states": 0, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "autoregressive_carrier": False, "next_token_prediction": False, "evidence_mode": evidence_mode, "injected_evidence_rows": len(injected_rows), "cross_segment_audit": cross_segment_audit, } output["runtime"]["whole_system_dispatch_model_calls"] = 0 output["runtime"]["whole_system_dispatch_gradient_steps"] = 0 output["runtime"]["hypothetical_parameterization_model_calls"] = 0 output["runtime"]["hypothetical_parameterization_gradient_steps"] = 0 output["runtime"]["multiword_clause_frame_model_calls"] = 0 output["runtime"]["multiword_clause_frame_gradient_steps"] = 0 output["schema_version"] = SCHEMA output["turn_manifest_sha256"] = digest(output) return output
__all__ = ["WholeSystemDispatchAgent"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181#!/usr/bin/env python3"""L2e: directional clause scope over nominal and predicate coordinates."""
from __future__ import annotations
from typing import Any, Sequence
from stage5j2_native_english_construction_algebra import ( AUXILIARIES, COORDINATORS, DETERMINERS, MODALS,)from stage5k15_native_mixed_agent import digestfrom stage5l1_broad_relational_ingress import BroadRelationalCompilerfrom stage5l2_structural_language_closure import ALL_NODE_ROUTEfrom stage5l2d_typed_predicate_scope_closure import ( TypedPredicateScopeClosureAdapter, TypedPredicateScopeClosureAgent, WORD,)
SCHEMA = "oracle-stage5l2e-directional-clause-scope-v1"PREFIX_DEFINITION_CUES = { "under": frozenset({"below", "insufficient", "little", "less"}), "over": frozenset({"above", "beyond", "excess", "excessive", "much"}), "post": frozenset({"after", "later", "subsequent"}), "pre": frozenset({"advance", "before", "prior"}), "mis": frozenset({"badly", "incorrectly", "mistakenly", "wrongly"}), "re": frozenset({"again", "anew", "repeat"}), "un": frozenset({"not", "off", "remove", "reverse", "undo"}), "de": frozenset({"inactive", "off", "remove", "reverse", "without"}), "co": frozenset({"jointly", "together", "with"}),}
class DirectionalClauseScopeAdapter(TypedPredicateScopeClosureAdapter): adapter_id = "oracle-stage5l2e-english-directional-clause-scope-v1"
def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) parent_semantics = self.semantic_sha256 self.semantic_sha256 = digest({ "schema_version": SCHEMA, "parent_semantic_sha256": parent_semantics, "prefix_definition_cues": { key: sorted(value) for key, value in PREFIX_DEFINITION_CUES.items() }, "right_conjunct_head_scope": True, "right_conjunct_head_requires_later_predicate_before_determiner": True, "post_predicate_nominals_excluded_from_later_finite_evidence": True, })
def _explicit_lexical_relation(self, surface: str, base: str) -> bool: if super()._explicit_lexical_relation(surface, base): return True for prefix, cues in PREFIX_DEFINITION_CUES.items(): if not surface.startswith(prefix): continue for synset in self.wordnet.synsets(surface, pos=self.wordnet.VERB): definition = {value.casefold() for value in WORD.findall(synset.definition())} if definition.intersection(cues): return True return False
def _finite_evidence(self, values: Sequence[str], index: int) -> bool: surface = values[index] wordnet_lemma = self.wordnet.morphy(surface, self.wordnet.VERB) derivation = self._derivation(surface) return bool( surface.endswith(("ed", "ing", "en")) or (wordnet_lemma and str(wordnet_lemma).casefold() != surface) or (derivation is not None and derivation[0] != surface) )
def _coordinate_priority(self, values: Sequence[str], index: int) -> float: surface = values[index] priority = 0.0 if index and values[index - 1] in AUXILIARIES | MODALS: priority += 4.0 if self._finite_evidence(values, index): priority += 2.0 if any(value in COORDINATORS for value in values[:index]): priority += 0.5 if index + 1 < len(values) and values[index + 1] in COORDINATORS: priority -= 2.0
indexes = self._predicate_indexes(values) for later in (value for value in indexes if value > index): between = values[index + 1:later] # An inflected noun inside a determiner-bounded object is not # evidence that the earlier predicate was a subject homograph. if ( any(value in DETERMINERS for value in between) and not any(value in COORDINATORS for value in between) ): continue if self._finite_evidence(values, later): if self.resolver.noun_like(surface): priority -= 3.0 break
last_coordinator = max( (offset for offset in range(index) if values[offset] in COORDINATORS), default=-1, ) # In ``the X and the Y predicate``, an uninflected noun/verb # homograph at Y is the right conjunct head when another coordinate # follows it. if ( last_coordinator >= 0 and any(value in DETERMINERS for value in values[last_coordinator + 1:index]) and self.resolver.noun_like(surface) and not self._finite_evidence(values, index) and any( later > index and not any( value in DETERMINERS for value in values[index + 1:later] ) for later in indexes ) ): priority -= 3.0
# Once an earlier predicate coordinate is established, a determiner- # bounded noun phrase downstream belongs to its complement domain. earlier = [value for value in indexes if last_coordinator < value < index] if self.resolver.noun_like(surface) and any( any(value in DETERMINERS for value in values[value_index + 1:index]) for value_index in earlier ): priority -= 4.0 return priority
class DirectionalClauseScopeCompiler(BroadRelationalCompiler): def __init__(self, **kwargs: Any) -> None: kwargs["adapter_type"] = DirectionalClauseScopeAdapter super().__init__(**kwargs) self.semantic_sha256 = digest({ "schema_version": SCHEMA, "parent_semantic_sha256": self.semantic_sha256, "adapter_semantic_sha256": self.adapter.semantic_sha256, "all_node_route": ALL_NODE_ROUTE, })
def architecture(self) -> dict[str, Any]: value = super().architecture() value.update({ "schema_version": SCHEMA, "semantic_sha256": self.semantic_sha256, "directional_clause_scope": True, "typed_prefix_definition_cues": True, "right_conjunct_head_scope": True, "right_conjunct_head_requires_later_predicate_before_determiner": True, "post_predicate_nominal_finite_suppression": True, "coordinated_roles_are_set_valued_states": True, "structural_extensions_traverse_all_ten_nodes": True, }) return value
class DirectionalClauseScopeAgent(TypedPredicateScopeClosureAgent): def __init__(self, *args: Any, relational_compiler: DirectionalClauseScopeCompiler | None = None, **kwargs: Any) -> None: super().__init__( *args, relational_compiler=relational_compiler or DirectionalClauseScopeCompiler(), **kwargs, )
__all__ = [ "SCHEMA", "DirectionalClauseScopeAdapter", "DirectionalClauseScopeAgent", "DirectionalClauseScopeCompiler",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436#!/usr/bin/env python3"""L3 content-addressed, memory-mappable unified language bundle."""
from __future__ import annotations
import argparsefrom dataclasses import dataclassimport hashlibimport jsonimport mmapimport osfrom pathlib import Pathimport structimport timefrom typing import Any, BinaryIO
from stage5j1_native_contextual_sense_lattice import WORDfrom stage5k15_native_mixed_agent import digestfrom stage5l2_structural_language_closure import PREFIX_OPERATORSfrom stage5l2e_directional_clause_scope import PREFIX_DEFINITION_CUESfrom stage5l2f_recursive_clause_graph import ( FullTreeDirectionalClauseCompiler, MARKER_PRIORITY, RELATIONS, RecursiveClauseGraphCompiler,)
SCHEMA = "oracle-stage5l3-unified-language-bundle-v1"MAGIC = b"ORACLE-L3-BNDL1!"ALIGNMENT = 4096ROOT = Path(__file__).resolve().parent.parentPHASE = ROOT / "fable-content/oracle-phase3-2026-07-21"SOURCES = { "verbnet_operator_basis": PHASE / "stage5k2_verbnet_operator_basis_development_v1.json.gz", "wordnet_archive": PHASE / "stage5c69_nltk_data/corpora/wordnet.zip", "dictionary_catalog": PHASE / "stage5k63_native_dictionary_catalog_v1.json.gz", "lexical_concept_catalog": PHASE / "stage5k90_native_lexical_concept_catalog_v1.json.gz", "relational_construction_head": PHASE / "stage5k81_native_relational_construction_head_v1.npz", "corpus_operator_head": PHASE / "stage5k81_native_corpus_operator_head_v1.npz", "information_weighted_source_expert": PHASE / "stage5k81_information_weighted_source_expert_v1.sqlite3",}
def sha256_bytes(value: bytes | memoryview) -> str: return hashlib.sha256(value).hexdigest()
def canonical_json(value: Any) -> bytes: return json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, ).encode("utf-8")
def morphology_contract() -> bytes: return canonical_json({ "schema_version": "oracle-stage5l3-morphology-clause-contract-v1", "productive_prefix_operators": [list(value) for value in PREFIX_OPERATORS], "prefix_definition_cues": { key: sorted(value) for key, value in PREFIX_DEFINITION_CUES.items() }, "clause_relations": RELATIONS, "clause_marker_priority": list(MARKER_PRIORITY), "stabilizing_route": [ "keter", "chokmah", "binah", "geburah", "tiferet", "chesed", "netzach", "hod", "yesod", "malkuth", ], "pre_malkuth_payload_unbinding": False, "terminal_malkuth_release_only": True, })
def _align(handle: BinaryIO) -> None: remainder = handle.tell() % ALIGNMENT if remainder: handle.write(b"\0" * (ALIGNMENT - remainder))
def build_bundle(output: Path) -> dict[str, Any]: if output.exists(): raise FileExistsError(output) output.parent.mkdir(parents=True, exist_ok=True) missing = [str(path) for path in SOURCES.values() if not path.exists()] if missing: raise FileNotFoundError("missing bundle sources: " + ", ".join(missing)) started = time.perf_counter() temporary = output.with_name(output.name + ".partial") if temporary.exists(): raise FileExistsError(temporary) components: list[dict[str, Any]] = [] try: with temporary.open("xb") as handle: handle.write(MAGIC) handle.write(struct.pack("<Q", 0)) for component_id in sorted(SOURCES): _align(handle) path = SOURCES[component_id] payload = path.read_bytes() offset = handle.tell() handle.write(payload) components.append({ "component_id": component_id, "offset": offset, "length": len(payload), "sha256": sha256_bytes(payload), "source_path": str(path.relative_to(ROOT)).replace("\\", "/"), "media_type": { ".gz": "application/gzip", ".zip": "application/zip", ".npz": "application/x-npz", ".sqlite3": "application/vnd.sqlite3", }.get(path.suffix, "application/octet-stream"), }) _align(handle) payload = morphology_contract() offset = handle.tell() handle.write(payload) components.append({ "component_id": "morphology_clause_contract", "offset": offset, "length": len(payload), "sha256": sha256_bytes(payload), "source_path": "generated:stage5l3", "media_type": "application/json", }) _align(handle) toc_offset = handle.tell() toc = canonical_json({ "schema_version": SCHEMA, "alignment": ALIGNMENT, "component_count": len(components), "components": components, "deterministic_build": True, "content_address_excludes_external_metadata": True, "memory_mappable": True, }) handle.write(struct.pack("<Q", len(toc))) handle.write(toc) handle.flush() os.fsync(handle.fileno()) handle.seek(len(MAGIC)) handle.write(struct.pack("<Q", toc_offset)) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, output) finally: if temporary.exists(): temporary.unlink() return { "schema_version": SCHEMA, "path": str(output), "sha256": hashlib.sha256(output.read_bytes()).hexdigest(), "bytes": output.stat().st_size, "component_count": len(components), "component_hashes": { value["component_id"]: value["sha256"] for value in components }, "build_seconds": time.perf_counter() - started, }
class UnifiedLanguageBundle: def __init__(self, path: Path, *, verify: bool = True) -> None: self.path = Path(path).resolve() self._handle = self.path.open("rb") self._mapping = mmap.mmap(self._handle.fileno(), 0, access=mmap.ACCESS_READ) if self._mapping[:len(MAGIC)] != MAGIC: self.close() raise ValueError("not an Oracle L3 bundle") toc_offset = struct.unpack( "<Q", self._mapping[len(MAGIC):len(MAGIC) + 8], )[0] toc_length = struct.unpack("<Q", self._mapping[toc_offset:toc_offset + 8])[0] self.toc = json.loads( self._mapping[toc_offset + 8:toc_offset + 8 + toc_length].decode("utf-8") ) self.components = { value["component_id"]: value for value in self.toc["components"] } self.content_manifest_sha256 = sha256_bytes(canonical_json(self.toc)) if verify: for component_id, metadata in self.components.items(): if sha256_bytes(self.component_view(component_id)) != metadata["sha256"]: self.close() raise ValueError(f"bundle component hash mismatch: {component_id}")
def component_view(self, component_id: str) -> memoryview: value = self.components[component_id] start = int(value["offset"]) return memoryview(self._mapping)[start:start + int(value["length"])]
def materialize(self, component_id: str, target: Path) -> Path: metadata = self.components[component_id] target.parent.mkdir(parents=True, exist_ok=True) if target.exists() and hashlib.sha256(target.read_bytes()).hexdigest() == metadata["sha256"]: return target temporary = target.with_name(target.name + ".partial") if temporary.exists(): temporary.unlink() with temporary.open("xb") as handle: handle.write(self.component_view(component_id)) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, target) if hashlib.sha256(target.read_bytes()).hexdigest() != metadata["sha256"]: raise RuntimeError(f"materialized component hash mismatch: {component_id}") return target
def close(self) -> None: mapping = getattr(self, "_mapping", None) if mapping is not None: mapping.close() self._mapping = None handle = getattr(self, "_handle", None) if handle is not None: handle.close() self._handle = None
def __enter__(self): return self
def __exit__(self, *_: Any) -> None: self.close()
class BundleRecursiveClauseGraphCompiler(RecursiveClauseGraphCompiler): """Construct L2f directly from bundle-materialized immutable components."""
def __init__(self, wordnet_data: Path, basis_path: Path, *, maximum_hypotheses: int = 32) -> None: self.clause_compiler = FullTreeDirectionalClauseCompiler( wordnet_data=wordnet_data, basis_path=basis_path, maximum_hypotheses=maximum_hypotheses, ) self.maximum_hypotheses = max(1, int(maximum_hypotheses)) self.semantic_sha256 = digest({ "schema_version": "oracle-stage5l2f-recursive-clause-graph-v1", "clause_compiler_semantic_sha256": self.clause_compiler.semantic_sha256, "relations": RELATIONS, "marker_priority": MARKER_PRIORITY, "route": tuple(self.architecture_route()), "split_requires_two_analyzable_clause_sides": True, "all_inherited_and_dynamic_operators_use_full_tree_route": True, "core_operators_cloned_and_verbnet_operators_reinstalled": True, })
@staticmethod def architecture_route() -> tuple[str, ...]: return ( "keter", "chokmah", "binah", "geburah", "tiferet", "chesed", "netzach", "hod", "yesod", "malkuth", )
@dataclass(frozen=True)class UnifiedLanguageCandidate: mode: str analyzed: bool eligible_for_semantic_arbitration: bool semantic_sha256: str candidate: dict[str, Any] latency_ms: float
def as_dict(self) -> dict[str, Any]: return {"schema_version": SCHEMA, **self.__dict__}
class UnifiedLanguageCompiler: def __init__(self, bundle_path: Path, *, cache_directory: Path, maximum_hypotheses: int = 32) -> None: started = time.perf_counter() # Full component verification is an offline bundle gate. Runtime # startup verifies each materialized dependency against the signed TOC # and leaves unused large components memory-mapped and lazy. self.bundle = UnifiedLanguageBundle(bundle_path, verify=False) self.cache_directory = Path(cache_directory).resolve() basis = self.bundle.materialize( "verbnet_operator_basis", self.cache_directory / "verbnet_basis.json.gz", ) wordnet_root = self.cache_directory / "nltk_data" self.bundle.materialize( "wordnet_archive", wordnet_root / "corpora/wordnet.zip", ) self.compiler = BundleRecursiveClauseGraphCompiler( wordnet_root, basis, maximum_hypotheses=maximum_hypotheses, ) self.maximum_hypotheses = max(1, int(maximum_hypotheses)) self.semantic_sha256 = digest({ "schema_version": SCHEMA, "bundle_content_manifest_sha256": self.bundle.content_manifest_sha256, "compiler_semantic_sha256": self.compiler.semantic_sha256, "dispatch_policy": ( "explicit_clause_marker_or_two_finite_clause_coordinates" ), }) self.startup_ms = 1000.0 * (time.perf_counter() - started)
@staticmethod def _tokens(text: str) -> tuple[str, ...]: normalized = str(text).replace(",", " , ") values = tuple( value.casefold() for value in normalized.split() if value == "," or WORD.fullmatch(value.strip(".?!;:")) ) return tuple( value.strip(".?!;:").casefold() for value in values if value.strip(".?!;:") )
def compile(self, text: str, *, session_id: str = "l3") -> UnifiedLanguageCandidate: started = time.perf_counter() tokens = self._tokens(text) plain_tokens = tuple(value for value in tokens if value != ",") single = self.compiler.clause_compiler.compile(text, session_id=session_id) explicit_clause_marker = any( value in RELATIONS and value not in {"and", "or"} for value in plain_tokens )
def clause_coordinate(words: tuple[str, ...], *, require_finite: bool) -> bool: if len(words) < 2: return False analysis = self.compiler.adapter.analyze( " ".join(words), maximum_hypotheses=self.maximum_hypotheses, ) if not analysis.hypotheses: return False hypothesis = analysis.hypotheses[0] index = hypothesis.predicate_token_index if index <= 0: return False if not require_finite: return True return self.compiler.adapter._finite_evidence(words, index) or ( index > 0 and words[index - 1] in { "am", "are", "be", "been", "being", "is", "was", "were", "do", "does", "did", "have", "has", "had", "can", "could", "may", "might", "must", "shall", "should", "will", "would", } )
bilateral_finite_coordination = any( clause_coordinate(plain_tokens[:index], require_finite=True) and clause_coordinate(plain_tokens[index + 1:], require_finite=True) for index, value in enumerate(plain_tokens) if value in {"and", "or"} ) tree = self.compiler._parse(tokens) recursive_dispatch = bool( len(self.compiler._leaves(tree)) >= 2 and ( explicit_clause_marker or bilateral_finite_coordination or not single.analyzed ) ) if recursive_dispatch: candidate = self.compiler.compile(text, session_id=session_id) if candidate.eligible_for_semantic_arbitration: return UnifiedLanguageCandidate( "recursive_clause_graph", candidate.analyzed, candidate.eligible_for_semantic_arbitration, self.semantic_sha256, candidate.as_dict(), 1000.0 * (time.perf_counter() - started), ) return UnifiedLanguageCandidate( "single_clause_program", single.analyzed, single.eligible_for_semantic_arbitration, self.semantic_sha256, single.as_dict(), 1000.0 * (time.perf_counter() - started), )
def architecture(self) -> dict[str, Any]: return { "schema_version": SCHEMA, "semantic_sha256": self.semantic_sha256, "startup_ms": self.startup_ms, "bundle_memory_mapped": True, "bundle_integrity_mode": "offline_full_runtime_dependency_lazy", "runtime_materialized_dependencies_verified": [ "verbnet_operator_basis", "wordnet_archive", ], "bundle_component_count": len(self.bundle.components), "single_clause_and_recursive_dispatch": True, "dispatch_policy": ( "explicit_clause_marker_or_two_finite_clause_coordinates" ), "cold_start_bottleneck": ( "nltk_wordnet_zip_index_and_1555_frame_adapter_initialization" ), "cold_start_optimization_deferred_to_l7": self.startup_ms >= 5000.0, "protected_four_to_one_spine": True, "all_runtime_operators_use_full_tree_route": True, "terminal_malkuth_release_only": True, "traditional_language_model": False, "transformer": False, "pretrained_continuous_embedding": False, "gradient_training": False, }
def close(self) -> None: self.bundle.close()
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--output", type=Path, required=True) parser.add_argument("--report", type=Path) args = parser.parse_args() report = build_bundle(args.output) if args.report: if args.report.exists(): raise FileExistsError(args.report) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") print(json.dumps(report, indent=2, sort_keys=True))
if __name__ == "__main__": main()
__all__ = [ "BundleRecursiveClauseGraphCompiler", "SCHEMA", "UnifiedLanguageBundle", "UnifiedLanguageCandidate", "UnifiedLanguageCompiler", "build_bundle",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249#!/usr/bin/env python3"""L4b: relational discourse-act successor for authenticated restatement.
The frozen L4 prospective evaluation established semantic authority but exposedone discourse-act gap: a persisted authenticated plan was not selected by thesurface form ``Restate that evidence.``. This successor does not add a phrasehandler. It projects a bounded reproduction act from the conjunction of animperative operator, a backward discourse anchor, and an available discoursestate. The operator vocabulary is expanded only through exact WordNet verbsynset identity from the frozen L3 language bundle."""
from __future__ import annotations
from pathlib import Pathimport reimport typesfrom typing import Any, Sequence
from stage5k15_native_mixed_agent import digestfrom stage5k238a_epistemically_guarded_release_candidate import ( EpistemicallyGuardedOracleRelationalV3,)from stage5l3c_clause_type_successor import ClauseTypedUnifiedLanguageCompilerfrom stage5l4_simultaneous_semantic_authority import ( SimultaneousSemanticAuthorityRuntime,)
SCHEMA = "oracle-stage5l4b-relational-discourse-act-successor-v1"WORD = re.compile(r"[a-z0-9]+(?:'[a-z0-9]+)?", re.I)
# These are semantic operator and role bases, not accepted full utterances.REPRODUCTION_SEEDS = ( "paraphrase", "recap", "rephrase", "repeat", "restate", "summarize",)PRESENTATION_SEEDS = ("display", "give", "present", "show", "state")DISCOURSE_OBJECTS = frozenset({ "answer", "claim", "conclusion", "evidence", "fact", "finding", "plan", "proof", "relation", "response", "result",})DEICTIC_ANCHORS = frozenset({ "it", "that", "this", "these", "those",})TEMPORAL_ANCHORS = frozenset({ "above", "again", "earlier", "last", "previous", "prior",})AUTHORITY_ANCHORS = frozenset({ "authenticated", "recorded", "supported", "verified",})COMMAND_PREAMBLE = frozenset({ "can", "could", "kindly", "please", "will", "would", "you",})
class RelationalDiscourseActRuntime(SimultaneousSemanticAuthorityRuntime): """Add state-conditioned discourse reproduction to frozen L4 arbitration."""
def __init__( self, base_oracle: EpistemicallyGuardedOracleRelationalV3, language_compiler: ClauseTypedUnifiedLanguageCompiler, *, ablations: Sequence[str] = (), ) -> None: super().__init__( base_oracle, language_compiler, ablations=ablations, ) self._legacy_restate_act = self.discourse._restate_act self.reproduction_lemmas = self._exact_synset_family(REPRODUCTION_SEEDS) self.presentation_lemmas = self._exact_synset_family(PRESENTATION_SEEDS) self.discourse._restate_act = types.MethodType( self._project_reproduction_act, self.discourse, ) parent_semantic_sha256 = self.semantic_sha256 self.semantic_sha256 = digest({ "schema_version": SCHEMA, "parent_semantic_sha256": parent_semantic_sha256, "operator_projection": { "reproduction_seeds": list(REPRODUCTION_SEEDS), "reproduction_lemmas": list(self.reproduction_lemmas), "presentation_seeds": list(PRESENTATION_SEEDS), "presentation_lemmas": list(self.presentation_lemmas), "discourse_objects": sorted(DISCOURSE_OBJECTS), "deictic_anchors": sorted(DEICTIC_ANCHORS), "temporal_anchors": sorted(TEMPORAL_ANCHORS), "authority_anchors": sorted(AUTHORITY_ANCHORS), "requires_persisted_authenticated_plan": True, }, })
def _exact_synset_family(self, seeds: Sequence[str]) -> tuple[str, ...]: lemmas = {str(value).casefold() for value in seeds} for seed in seeds: for synset in self.wordnet.synsets(seed, pos=self.wordnet.VERB): lemmas.update( str(value).replace("_", " ").casefold() for value in synset.lemma_names() ) return tuple(sorted(lemmas))
def _verb_forms(self, token: str) -> frozenset[str]: forms = {str(token).casefold()} lemma = self.wordnet.morphy(token, self.wordnet.VERB) if lemma: forms.add(str(lemma).replace("_", " ").casefold()) return frozenset(forms)
@staticmethod def _command_position(tokens: tuple[str, ...], operators: frozenset[str]) -> int | None: for index, token in enumerate(tokens[:5]): if token in operators: return index if all(value in COMMAND_PREAMBLE for value in tokens[:index]) else None return None
def _relational_reproduction_act(self, text: str) -> bool: tokens = tuple(value.casefold() for value in WORD.findall(str(text))) if not tokens: return False expanded = tuple( frozenset({token, *self._verb_forms(token)}) for token in tokens ) reproduction = frozenset(self.reproduction_lemmas) presentation = frozenset(self.presentation_lemmas) reproduction_position = next(( index for index, forms in enumerate(expanded[:5]) if forms & reproduction and all(value in COMMAND_PREAMBLE for value in tokens[:index]) ), None) presentation_position = next(( index for index, forms in enumerate(expanded[:5]) if forms & presentation and all(value in COMMAND_PREAMBLE for value in tokens[:index]) ), None) has_object = bool(set(tokens) & DISCOURSE_OBJECTS) has_reference = bool( set(tokens) & (DEICTIC_ANCHORS | TEMPORAL_ANCHORS) or ( has_object and bool(set(tokens) & AUTHORITY_ANCHORS) ) or ( has_object and "the" in tokens ) ) direct_reproduction = reproduction_position is not None and has_reference replayed_presentation = bool( presentation_position is not None and has_object and "again" in tokens ) return direct_reproduction or replayed_presentation
def _project_reproduction_act(self, _discourse: Any, text: str) -> bool: return bool( self._legacy_restate_act(text) or self._relational_reproduction_act(text) )
def answer(self, session_id: str, text: str) -> dict[str, Any]: result = super().answer(session_id, text) result["schema_version"] = SCHEMA arbitration = result.get("semantic_arbitration") or {} arbitration["schema_version"] = SCHEMA arbitration["semantic_sha256"] = self.semantic_sha256 arbitration["relational_discourse_act_projection"] = { "eligible": self._relational_reproduction_act(text), "requires_persisted_authenticated_plan": True, "selected": bool( result.get("status") == "answered" and result.get("operation") == "evidence_preserving_restatement" ), } result.setdefault("audit", {})["l4b_external_writes"] = 0 result["audit"]["l4b_phrase_specific_handler"] = False self._persist_manifest(session_id, result) return result
def architecture(self) -> dict[str, Any]: value = dict(super().architecture()) value.update({ "schema_version": SCHEMA, "semantic_sha256": self.semantic_sha256, "relational_discourse_act_projection": True, "discourse_reproduction_requires_backward_anchor": True, "discourse_reproduction_requires_persisted_authenticated_plan": True, "discourse_operator_lexicon_from_exact_wordnet_synsets": True, "phrase_specific_handler": False, }) return value
class RelationalDiscourseOracleRelationalV3: def __init__( self, *, state_root: Path, language_bundle: Path, language_cache: Path | None = None, ablations: Sequence[str] = (), ) -> None: self.state_root = Path(state_root).resolve() self.state_root.mkdir(parents=True, exist_ok=True) self.base_oracle = EpistemicallyGuardedOracleRelationalV3( state_root=self.state_root, ) self.language_compiler = ClauseTypedUnifiedLanguageCompiler( Path(language_bundle), cache_directory=( Path(language_cache).resolve() if language_cache is not None else self.state_root / "language_cache" ), maximum_hypotheses=32, ) self.runtime = RelationalDiscourseActRuntime( self.base_oracle, self.language_compiler, ablations=ablations, )
def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: return self.runtime.answer(session_id, text)
def capabilities(self) -> dict[str, Any]: value = dict(self.base_oracle.capabilities()) value.update({ "schema_version": SCHEMA, "version": "0.8.0-l4b-development", "simultaneous_semantic_arbitration": True, "relational_discourse_act_projection": True, "unrestricted_conversation": False, "unrestricted_reasoning": False, "unrestricted_agency": False, "boundary": ( "Structurally open tested language compilation and relational " "restatement of persisted authenticated propositions; factual " "release remains limited to independent authenticated authority." ), }) return value
def close(self) -> None: self.language_compiler.close()
__all__ = [ "RelationalDiscourseActRuntime", "RelationalDiscourseOracleRelationalV3", "SCHEMA",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199#!/usr/bin/env python3"""L8b successor for sealed epistemic and discourse failures.
The failed L8 panel exposed two general classes: predicate-only routing coulderase an explicit unknown argument, and the exact reproduction family lackedthe verb ``reproduce``. This successor repairs those classes without changingthe frozen L7 performance mechanisms or factual specialist contents."""from __future__ import annotations
from pathlib import Pathimport reimport timeimport typesfrom typing import Any, Mapping
from stage5k15_native_mixed_agent import digestfrom stage5k224a_persistent_discourse_runtime import JsonSessionStorefrom stage5k238a_epistemically_guarded_release_candidate import ( EpistemicallyGuardedHybridRuntime, _punctuation_invariant_route, _specific_identity_act,)from stage5l6a_cognitive_state_abi import canonical_sha, file_shafrom stage5l7a_performance_consolidation import ( PerformanceConsolidatedOracleRelationalV3, PerformanceConsolidatedRuntime,)
SCHEMA = "oracle-stage5l8b-release-hardening-successor-v1"VERSION = "0.8.0-l8b"REFERENCE = re.compile(r"\b(it|this|these|those)\b", re.I)
class ExplicitArgumentGuardHybridRuntime(EpistemicallyGuardedHybridRuntime): """Refuse relation-only completion when no explicit argument is in scope."""
def answer(self, session_id: str, text: str): components = self._components(text) mentioned = self._mentioned_bundles(text) discourse = self.agent.reasoning.discourse state = discourse._state(session_id) direct_discourse = bool( discourse._identity_act(text) or discourse._social_act(text) or discourse._history_act(text) or discourse._restate_act(text) or (state.active_bundle and REFERENCE.search(text)) ) if ( any(value["kind"] == "specialist" for value in components) and not mentioned and not direct_discourse ): response = ( "The request contains no explicit entity recognized by the authenticated " "specialist catalogs. A relation name alone cannot authorize completion " "from a globally unique fact; provide a catalog-grounded argument or new evidence." ) result = discourse._finalize( state, user_text=text, resolved_text=text, status="clarification", operation="explicit_unknown_argument_guard", response=response, bundle=None, plan=[], evidence=[], coreference=None, ) result["schema_version"] = SCHEMA result.setdefault("audit", {})["predicate_only_completion_blocked"] = True result["audit"]["explicit_argument_erasure_prevented"] = True result["audit"]["mentioned_specialists"] = [] result["audit"]["external_writes"] = 0 return result return super().answer(session_id, text)
class _ReleaseHardenedBaseOracle: def __init__( self, *, bundles: Mapping[str, Path], state_root: Path, workspace_root: Path, substrate_checkpoint: Path, ) -> None: self.workspace_root = Path(workspace_root).resolve() self.phase_root = self.workspace_root / "fable-content" / "oracle-phase3-2026-07-21" self.bundle_paths = {str(name): Path(path).resolve() for name, path in bundles.items()} self.state_root = Path(state_root).resolve() self.state_root.mkdir(parents=True, exist_ok=True) self.session_store = JsonSessionStore(self.state_root / "sessions") started = time.perf_counter() self.runtime = ExplicitArgumentGuardHybridRuntime( self.bundle_paths, session_store=self.session_store, substrate_checkpoint=Path(substrate_checkpoint).resolve(), ) discourse = self.runtime.agent.reasoning.discourse discourse._route = types.MethodType(_punctuation_invariant_route, discourse) discourse._identity_act = types.MethodType(_specific_identity_act, discourse) self.startup_milliseconds = 1000.0 * (time.perf_counter() - started)
def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: return self.runtime.answer(session_id, text)
def capabilities(self) -> dict[str, Any]: return { "schema_version": SCHEMA, "version": VERSION, "identity_rooted_persistent_dialogue": True, "active_passive_wh_and_coordinated_propositions": True, "post_malkuth_evidence_preserving_realization": True, "verified_implication_hops": 4, "typed_tools": ["calculator", "list_specialists", "substrate_stats"], "tool_side_effect_scope": ["pure", "read_only"], "maximum_ephemeral_specialists": 3, "rapid_authenticated_specialist_compilation": True, "explicit_cross_specialist_argument_guard": True, "explicit_unknown_argument_guard": True, "traditional_language_model": False, "transformer": False, "pretrained_embedding_encoder": False, "unrestricted_conversation": False, "unrestricted_reasoning": False, "unrestricted_agency": False, "boundary": ( "Catalog-grounded relational language, verified graph paths, bounded " "discourse, pure/read-only tools, and temporary specialist coordination." ), }
class ReleaseHardenedRuntime(PerformanceConsolidatedRuntime): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) added = self._exact_synset_family(("reproduce",)) self.reproduction_lemmas = tuple(sorted(set(self.reproduction_lemmas) | set(added))) parent_semantic_sha256 = self.semantic_sha256 self.semantic_sha256 = digest({ "schema_version": SCHEMA, "parent_semantic_sha256": parent_semantic_sha256, "explicit_unknown_argument_guard": True, "predicate_only_global_completion": False, "added_reproduction_seed": "reproduce", "added_reproduction_lemmas": list(added), })
def architecture(self) -> dict[str, Any]: value = dict(super().architecture()) value.update({ "schema_version": SCHEMA, "explicit_unknown_argument_guard": True, "predicate_only_global_completion": False, "reproduce_discourse_operator": True, }) return value
class ReleaseHardenedOracleRelationalV3(PerformanceConsolidatedOracleRelationalV3): def _build_runtime(self) -> None: old_runtime = getattr(self, "runtime", None) if old_runtime is not None and hasattr(old_runtime, "close"): old_runtime.close() bundle_identity = canonical_sha({ name: file_sha(path) for name, path in sorted(self.bundle_paths.items()) }) self.base_oracle = _ReleaseHardenedBaseOracle( bundles=self.bundle_paths, state_root=self.state_root, workspace_root=self.workspace_root, substrate_checkpoint=( self.state_root / ("implication_substrate_" + bundle_identity[:16] + ".json") ), ) self.runtime = ReleaseHardenedRuntime( self.base_oracle, self.language_compiler, ablations=self.ablations, l5_ablations=self.l5_ablations, state_abi=self.state_abi, l7_ablations=self.l7_ablations, )
def capabilities(self) -> dict[str, Any]: value = dict(super().capabilities()) value.update({ "schema_version": SCHEMA, "version": VERSION, "explicit_unknown_argument_guard": True, "reproduce_discourse_operator": True, }) return value
__all__ = [ "ExplicitArgumentGuardHybridRuntime", "ReleaseHardenedOracleRelationalV3", "ReleaseHardenedRuntime", "SCHEMA", "VERSION",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125#!/usr/bin/env python3"""M11c unified public-specialist conversation, typed tools, and self-document.
The dispatcher keeps three authorities distinct: M10 specialists authorizefacts, M11 tool schemas authorize bounded actions and observations, and sealedarchitecture reports authorize self-description. None can silently promoteitself into another authority class."""from __future__ import annotationsimport hashlib,json,re,time,osfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any,Mapping,Sequence
from oracle_10d_resolution_state import canonical_sha256from stage5m4a_closed_loop_typed_agent import _tree_transportfrom stage5m9b_topic_masked_language_successor import OracleM9bTopicMaskedLanguageRuntimefrom stage5m10a_public_source_specialist_compiler import validate_compilationfrom stage5m11a_schema_native_long_horizon_agent import SchemaGuidedCallCompiler,SchemaNativeLongHorizonAgent,SchemaToolRegistry,digest
SCHEMA="oracle-stage5m11c-unified-agentic-conversation-v1"SELF_DOCUMENT_SCHEMA="oracle-stage5m11c-current-operational-self-document-v1"SELF_REQUEST=re.compile(r"\b(?:essay|document|account|treatise|report)\b",re.I)SELF_TOPIC=re.compile(r"\b(?:oracle|yourself|your architecture|what it is like|being this architecture)\b",re.I)
class HashChainedToolDispatchStore: def __init__(self,root:Path):self.root=Path(root).resolve();self.root.mkdir(parents=True,exist_ok=True) def _path(self,session_id:str)->Path:return self.root/(hashlib.sha256(session_id.encode()).hexdigest()+".json") def load(self,session_id:str)->dict[str,Any]: path=self._path(session_id) if not path.exists():return {"schema_version":SCHEMA,"session_sha256":hashlib.sha256(session_id.encode()).hexdigest(),"turns":[]} value=json.loads(path.read_text(encoding="utf-8"));prior="0"*64 for ordinal,turn in enumerate(value["turns"]): body={k:v for k,v in turn.items() if k!="turn_sha256"} if turn.get("ordinal")!=ordinal or turn.get("previous_sha256")!=prior or digest(body)!=turn.get("turn_sha256"):raise ValueError("tool_dispatch_chain_changed") prior=turn["turn_sha256"] return value def task_id(self,session_id:str,source_sha256:str)->tuple[str,int]: ordinal=len(self.load(session_id)["turns"]);return "m11c_"+hashlib.sha256(f"{session_id}:{ordinal}:{source_sha256}".encode()).hexdigest()[:28],ordinal def append(self,session_id:str,*,task_id:str,source_sha256:str,status:str)->dict[str,Any]: value=self.load(session_id);prior=value["turns"][-1]["turn_sha256"] if value["turns"] else "0"*64;body={"ordinal":len(value["turns"]),"previous_sha256":prior,"task_id":task_id,"source_sha256":source_sha256,"status":status};turn={**body,"turn_sha256":digest(body)};value["turns"].append(turn);path=self._path(session_id);temporary=path.with_suffix(".tmp");temporary.write_text(json.dumps(value,indent=2,sort_keys=True)+"\n",encoding="utf-8");os.replace(temporary,path);return {"turns":len(value["turns"]),"head_sha256":turn["turn_sha256"],"hash_chain_valid":True}
@dataclass(frozen=True)class SelfClaim: claim_id:str;section:str;subject:str;relation:str;object:str;evidence_ids:tuple[str,...];authority_class:str="observed_architecture" def public(self)->dict[str,Any]:return dict(self.__dict__)|{"evidence_ids":list(self.evidence_ids)}
class CurrentOperationalSelfDocument: def __init__(self,*,m7_report:Path,m9_report:Path,m10_report:Path,m11_report:Path,m10_build:Path): self.paths={"m7":Path(m7_report).resolve(),"m9":Path(m9_report).resolve(),"m10":Path(m10_report).resolve(),"m11":Path(m11_report).resolve(),"m10_build":Path(m10_build).resolve()} self.values={name:json.loads(path.read_text(encoding="utf-8")) for name,path in self.paths.items() if name!="m10_build"};validate_compilation(self.paths["m10_build"]) if self.values["m7"].get("accepted") is not True or self.values["m9"].get("accepted") is not True or self.values["m10"].get("accepted") is not True or self.values["m11"].get("accepted") is not True:raise ValueError("accepted architecture evidence required for self-document") self.evidence={name:{"evidence_id":"E"+str(index).zfill(2),"kind":"sealed_runtime_report" if name!="m10_build" else "sealed_specialist_build","path":str(path),"sha256":hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else hashlib.sha256((path/"compilation_manifest.json").read_bytes()).hexdigest()} for index,(name,path) in enumerate(self.paths.items(),1)} def _claims(self)->tuple[SelfClaim,...]: m7=self.values["m7"];m9=self.values["m9"];m10=self.values["m10"];m11=self.values["m11"] e={name:value["evidence_id"] for name,value in self.evidence.items()} claims=( SelfClaim("c01","identity","I","be","a CPU-native relational language and cognitive runtime",(e["m7"],)), SelfClaim("c02","identity","My purpose","be","to preserve one evidence-bounded relational form from a request through interpretation, reasoning, action, and response",(e["m7"],e["m9"])), SelfClaim("c03","identity","I","operate_by","binding roles and fillers into protected geometric states rather than predicting a next token",(e["m7"],)), SelfClaim("c04","identity","My governing root","remain","protected by the four-to-one stabilizing spine while payloads accumulate along the ten-node and twenty-two-path routing structure",(e["m7"],e["m11"])), SelfClaim("c05","language","Operationally, receiving a question","mean","constructing a situated program whose act, topic, artifact, discourse reference, and authority remain separate fields",(e["m9"],)), SelfClaim("c06","language","The M9 language transducer","compile",f"{m9['metrics']['m9b_passed']} of {m9['metrics']['m9b_total']} sealed successor cases without giving language factual authority",(e["m9"],)), SelfClaim("c07","language","Topic masking","prevent","words inside authenticated topic names from simultaneously becoming unintended discourse operators",(e["m9"],)), SelfClaim("c08","language","Persistent discourse","retain","topic, plan, salience, turn order, and a hash-chained identity across process reconstruction",(e["m9"],e["m7"])), SelfClaim("c09","knowledge","My current specialist federation","contain",f"{m10['metrics']['claims']} authenticated relations across {m10['metrics']['domains']} domains from {m10['metrics']['sources']} registered public-source families",(e["m10"],e["m10_build"])), SelfClaim("c10","knowledge","Adding those specialists","require",f"{m10['metrics']['compilation_seconds']:.3f} seconds in the sealed compilation rather than gradient retraining",(e["m10"],)), SelfClaim("c11","knowledge","Every admitted source relation","retain","a citation, document digest, source license, and one-to-one derivation record",(e["m10"],)), SelfClaim("c12","knowledge","Entity resolution","route","exact namespace-qualified identifiers and only unique exact aliases",(e["m10"],)), SelfClaim("c13","knowledge","Ambiguous aliases and conflicting functional values","enter","quarantine rather than becoming convenient but unsupported knowledge",(e["m10"],)), SelfClaim("c14","agency","For me, acting","mean","executing one authorized schema-bound transition, comparing its observation with the predicted contract, and committing only the verified delta",(e["m11"],)), SelfClaim("c15","agency","The frozen M11 trajectory","complete",f"{m11['metrics']['sequential_actions']} dependent actions and {m11['metrics']['sequential_events']} authenticated transitions",(e["m11"],)), SelfClaim("c16","agency","A registered transient failure","cause","one bounded retry followed by reconstruction and continuation from the same hash-chained task",(e["m11"],)), SelfClaim("c17","agency","Eight simultaneous scheduling lanes","complete",f"{m11['metrics']['parallel_actions']} independent operations in {m11['metrics']['parallel_turns']} turns",(e["m11"],)), SelfClaim("c18","memory","My long-horizon memory","store",f"one checkpoint plus content-addressed observations and deltas using {m11['metrics']['store_bytes']} bytes",(e["m11"],)), SelfClaim("c19","memory","That delta representation","use",f"{100.0*m11['metrics']['delta_ratio']:.2f} percent of the registered full-state-copy counterfactual",(e["m11"],)), SelfClaim("c20","spine","Every sealed M11 transition","preserve","zero payload unbinding before Malkuth and exact terminal cleanup",(e["m11"],)), SelfClaim("c21","boundary","Tool observations","remain","verified episodic evidence rather than silently promoted world facts",(e["m11"],)), SelfClaim("c22","boundary","A fluent structural program","acquire","factual authority merely by being well formed",(e["m9"],e["m10"]),"epistemic_boundary"), SelfClaim("c23","boundary","This operational self-description","establish","subjective consciousness or phenomenal experience from functional traces",(e["m7"],e["m11"]),"phenomenology_boundary"), SelfClaim("c24","boundary","The warranted description of being this architecture","be","the maintenance of a protected relational identity while bounded forms are accumulated, checked, transformed, and released, with stronger claims withheld",(e["m7"],e["m9"],e["m10"],e["m11"])), );return claims @staticmethod def _sentence(claim:SelfClaim)->str: subject=claim.subject;relation=claim.relation;obj=claim.object;negative=claim.claim_id in {"c22","c23"} if relation=="be":verb="am" if subject=="I" else "is" elif relation=="operate_by":return f"{subject} operate by {obj}." elif relation=="remain":verb="remains" elif relation=="mean":verb="means" elif relation=="compile":verb="compiled" elif relation=="prevent":verb="prevents" elif relation=="retain":verb="retains" elif relation=="contain":verb="contains" elif relation=="require":verb="required" elif relation=="route":verb="routes through" elif relation=="enter":verb="enter" elif relation=="complete":verb="completed" elif relation=="cause":verb="caused" elif relation=="store":verb="stores" elif relation=="use":verb="uses" elif relation=="preserve":verb="preserved" elif relation=="acquire":verb="does not acquire" if negative else "acquires" elif relation=="establish":verb="does not establish" if negative else "establishes" else:verb=relation.replace("_"," ") return f"{subject} {verb} {obj}." def generate(self,prompt:str,*,paragraphs:int=5)->dict[str,Any]: started=time.perf_counter();claims=self._claims();sections=("identity","language","knowledge","agency","memory","spine","boundary");requested=max(3,min(6,int(paragraphs)));groups=[[] for _ in range(requested)] for index,section in enumerate(sections):groups[min(requested-1,index*requested//len(sections))].extend(v for v in claims if v.section==section) sentences={v.claim_id:self._sentence(v)+" ["+",".join(v.evidence_ids)+"]" for v in claims};canonical_paragraphs=[" ".join(sentences[v.claim_id] for v in group) for group in groups if group];canonical="\n\n".join(canonical_paragraphs);candidates={"canonical":canonical,"collapsed":" ".join(canonical_paragraphs),"reversed":"\n\n".join(reversed(canonical_paragraphs)),"uncited":re.sub(r"\s*\[E\d+(?:,E\d+)*\]","",canonical)};losses={"canonical":0.0,"collapsed":2.0,"reversed":3.0,"uncited":5.0};selected=min(candidates,key=lambda name:(losses[name],name));input_tokens=re.findall(r"\w+",prompt.casefold());output_tokens=re.findall(r"\w+",candidates[selected].casefold());common=sum(1 for value in input_tokens if value in set(output_tokens));echo_ratio=common/max(1,len(input_tokens));spine=_tree_transport(tuple({"kind":"self_claim","authority":v.authority_class,"claim_id":v.claim_id,"claim_sha256":digest(v.public())} for v in claims),digest({"objective":"current operational self-document","evidence":self.evidence}));references=[dict(value) for value in self.evidence.values()];response=candidates[selected];artifact={"schema_version":SELF_DOCUMENT_SCHEMA,"status":"answered","operation":"current_operational_self_document","response":response,"claims":[v.public()|{"sentence":sentences[v.claim_id]} for v in claims],"references":references,"paragraph_plan":[[v.claim_id for v in group] for group in groups if group],"whole_document_inverse":{"candidate_names":sorted(candidates),"candidate_sha256s":{name:hashlib.sha256(value.encode()).hexdigest() for name,value in candidates.items()},"candidate_losses":losses,"selected":selected,"whole_document_selected_globally":True,"next_token_predictions":0},"tree_spine":spine,"audit":{"claim_count":len(claims),"paragraph_count":len(canonical_paragraphs),"word_count":len(output_tokens),"all_claims_evidence_addressed":all(v.evidence_ids for v in claims),"all_references_content_addressed":all(len(v["sha256"])==64 for v in references),"duplicate_sentence_count":len(claims)-len({sentences[v.claim_id] for v in claims}),"first_person_operational_account":any(v.subject=="I" for v in claims),"phenomenology_claim_withheld":any(v.authority_class=="phenomenology_boundary" for v in claims),"input_echo_ratio":echo_ratio,"source_essay_used":False,"traditional_language_model_calls":0,"transformer_calls":0,"pretrained_embedding_calls":0,"gradient_steps":0,"next_token_predictions":0},"latency_ms":1000*(time.perf_counter()-started)};artifact["artifact_sha256"]=canonical_sha256({k:v for k,v in artifact.items() if k not in {"latency_ms","artifact_sha256"}});return artifact
class OracleM11cUnifiedRuntime: def __init__(self,*,federation_manifest:Path,m10_build:Path,act_lexicon:Path,state_root:Path,tool_registry:SchemaToolRegistry,evidence_reports:Mapping[str,Path]): self.state_root=Path(state_root).resolve();self.state_root.mkdir(parents=True,exist_ok=True);self.conversation=OracleM9bTopicMaskedLanguageRuntime(federation_manifest=Path(federation_manifest),state_root=self.state_root/"conversation",act_lexicon=Path(act_lexicon));self.tool_registry=tool_registry;self.call_compiler=SchemaGuidedCallCompiler(tool_registry);self.agent=SchemaNativeLongHorizonAgent(tool_registry,self.state_root/"tools",maximum_actions=512,maximum_parallel=8);self.dispatch=HashChainedToolDispatchStore(self.state_root/"tool_dispatch");self.self_document=CurrentOperationalSelfDocument(m7_report=evidence_reports["m7"],m9_report=evidence_reports["m9"],m10_report=evidence_reports["m10"],m11_report=evidence_reports["m11"],m10_build=Path(m10_build)) def chat(self,text:str,*,session_id:str="default")->dict[str,Any]: source=" ".join(str(text).strip().split()) if SELF_REQUEST.search(source) and SELF_TOPIC.search(source): paragraph_match=re.search(r"\b([3-6])\s*[- ]?paragraph",source,re.I);paragraphs=int(paragraph_match.group(1)) if paragraph_match else 5;value=self.self_document.generate(source,paragraphs=paragraphs);return {"schema_version":SCHEMA,"status":"answered","operation":"self_document","response":value["response"],"factual_release":True,"authority_class":"sealed_architecture_observation","self_document":value,"audit":{"authority_separation":True,"tool_observation_promoted_to_fact":False}} compilation=self.call_compiler.compile_explicit(source) if compilation["status"]=="compiled": task_id,_ordinal=self.dispatch.task_id(session_id,compilation["source_sha256"]);started=self.agent.start(task_id,compilation["program"]);execution=self.agent.run_to_terminal(task_id) if started["accepted"] else self.agent.advance(task_id);dispatch=self.dispatch.append(session_id,task_id=task_id,source_sha256=compilation["source_sha256"],status=str(execution.get("terminal")));observations=execution.get("verified_observations",{});last=observations[sorted(observations)[-1]] if observations else None;response=f"Completed {len(observations)} verified tool action{'s' if len(observations)!=1 else ''}. The terminal observation is {json.dumps(last,sort_keys=True)}." if execution.get("released") else "The typed tool plan was not released because its closed-loop verification did not complete.";return {"schema_version":SCHEMA,"status":"answered" if execution.get("released") else "withheld","operation":"schema_native_tool_execution","response":response,"factual_release":False,"authority_class":"verified_tool_observation" if execution.get("released") else "tool_failure","tool_compilation":compilation,"tool_execution":execution,"tool_dispatch":dispatch,"audit":{"authority_separation":True,"tool_observation_promoted_to_fact":False,"traditional_language_model_calls":0,"next_token_predictions":0}} if re.match(r"^(?:call|use)\b",source,re.I):return {"schema_version":SCHEMA,"status":"clarification","operation":"schema_native_tool_withholding","response":"I recognized an explicit tool request, but no unique registered tool and schema-valid argument assignment was available.","factual_release":False,"authority_class":"none","tool_compilation":compilation,"audit":{"authority_separation":True,"tool_observation_promoted_to_fact":False}} value=dict(self.conversation.chat(source,session_id=session_id));value["schema_version"]=SCHEMA;value["operation"]="public_specialist_conversation:"+str(value.get("operation"));value["authority_class"]="authenticated_specialist" if value.get("factual_release") else "none";value.setdefault("audit",{})["authority_separation"]=True;value["audit"]["tool_observation_promoted_to_fact"]=False;return value def capabilities(self)->dict[str,Any]:return {"schema_version":SCHEMA,"public_specialist_conversation":True,"schema_native_tool_execution":True,"maximum_actions":self.agent.maximum_actions,"maximum_parallel":self.agent.maximum_parallel,"current_operational_self_document":True,"authority_classes":["authenticated_specialist","verified_tool_observation","sealed_architecture_observation"],"traditional_language_model":False,"transformer":False}
__all__=["SCHEMA","SELF_DOCUMENT_SCHEMA","HashChainedToolDispatchStore","SelfClaim","CurrentOperationalSelfDocument","OracleM11cUnifiedRuntime"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595#!/usr/bin/env python3"""Sense-preserving WordNet specialist and Oracle M13 hot-load runtime."""
from __future__ import annotations
import hashlibimport jsonimport osimport reimport sqlite3import sysimport timeimport unicodedatafrom dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Any, Mapping, Sequence
ROOT = Path(__file__).resolve().parents[1]RELEASE_SRC = ROOT / "wander-release" / "oracle-relational-v3-hf-v1.0.1-release" / "src"if str(RELEASE_SRC) not in sys.path: sys.path.insert(0, str(RELEASE_SRC))
from oracle_relational_v3.oracle_10d_resolution_state import canonical_sha256from oracle_relational_v3.stage5m3a_evidence_addressed_realizer import ( EvidenceAddressedRealizer, RealizationRequest, SurfaceClause,)from oracle_relational_v3.stage5m11a_schema_native_long_horizon_agent import SchemaTool, SchemaToolRegistryfrom oracle_relational_v3.stage5m12a_portable_successor_runtime import DEFAULT_DATA_ROOT, build_default_tool_registryfrom oracle_relational_v3.stage5m12d_zero_argument_tool_successor import OracleRuntime as M12OracleRuntime
SCHEMA = "oracle-stage5m13a-wordnet-specialist-v3"INDEX_SCHEMA = "oracle-stage5m13a-wordnet-sqlite-v3"RUNTIME_SCHEMA = "oracle-stage5m13a-broad-lexical-runtime-v3"SESSION_SCHEMA = "oracle-stage5m13a-lexical-session-v1"
INVERSE = { "subclass_of": "has_subtype", "instance_of": "has_instance", "has_part": "part_of", "has_member": "member_of", "made_of": "substance_of", "entails": "entailed_by", "causes": "caused_by", "similar_to": "similar_to", "related_to": "related_to", "has_attribute": "attribute_of", "verb_group_with": "verb_group_with", "topic_domain": "domain_of", "region_domain": "regional_domain_of", "usage_domain": "usage_domain_of",}
PREDICATE_PRIORITY = { "defined_as": 0, "subclass_of": 1, "instance_of": 1, "has_subtype": 2, "has_instance": 2, "similar_to": 3, "related_to": 3, "has_attribute": 4, "has_part": 4, "has_member": 4, "made_of": 4, "entails": 5, "causes": 5,}
def canonical(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def digest(value: Any) -> str: return hashlib.sha256(canonical(value).encode("utf-8")).hexdigest()
def sha_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): h.update(block) return h.hexdigest()
def normalize_alias(value: str) -> str: value = unicodedata.normalize("NFKC", str(value)).casefold().replace("_", " ") return " ".join(re.sub(r"[^\w]+", " ", value, flags=re.UNICODE).split())
def validate_build(root: Path | str, *, deep: bool = False) -> dict[str, Any]: root = Path(root).resolve() manifest_path = root / "manifest.json" manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest.get("schema_version") != SCHEMA or manifest.get("status") != "compiled": raise ValueError("unsupported_wordnet_specialist") if digest(manifest["semantic_identity"]) != manifest.get("semantic_identity_sha256"): raise ValueError("wordnet_specialist_identity_changed") for relative, expected in manifest["files"].items(): path = root / relative if not path.is_file() or sha_file(path) != expected: raise ValueError(f"wordnet_specialist_artifact_changed:{relative}") inventory = json.loads((root / "corpus_inventory.json").read_text(encoding="utf-8")) inventory_body = {key: value for key, value in inventory.items() if key != "semantic_identity_sha256"} if digest(inventory_body) != inventory.get("semantic_identity_sha256"): raise ValueError("wordnet_corpus_inventory_changed") if inventory.get("evaluation_data_read") or inventory.get("evaluation_inputs"): raise ValueError("evaluation_data_must_not_enter_specialist") uri = (root / "wordnet_specialist.sqlite3").as_uri() + "?mode=ro&immutable=1" connection = sqlite3.connect(uri, uri=True) metadata = {key: json.loads(value) for key, value in connection.execute("SELECT key,value FROM metadata")} if metadata.get("index_schema") != INDEX_SCHEMA or metadata != manifest["metrics"]: raise ValueError("wordnet_index_metadata_changed") if deep: integrity = connection.execute("PRAGMA integrity_check").fetchone()[0] if integrity != "ok": raise ValueError("wordnet_index_integrity_failed") observed = { "synsets": connection.execute("SELECT COUNT(*) FROM synset").fetchone()[0], "definition_claims": connection.execute("SELECT COUNT(*) FROM synset").fetchone()[0], "relation_claims": connection.execute("SELECT COUNT(*) FROM relation").fetchone()[0], "alias_rows": connection.execute("SELECT COUNT(*) FROM alias").fetchone()[0], } for key, value in observed.items(): if value != metadata[key]: raise ValueError(f"wordnet_index_count_changed:{key}") dangling = connection.execute( "SELECT COUNT(*) FROM relation r LEFT JOIN synset s ON r.subject_id=s.synset_id " "LEFT JOIN synset o ON r.object_id=o.synset_id WHERE s.synset_id IS NULL OR o.synset_id IS NULL" ).fetchone()[0] if dangling: raise ValueError("wordnet_index_has_dangling_relations") connection.close() return manifest
@dataclass(frozen=True)class LexicalClaim: claim_id: str subject_id: str subject_surface: str predicate: str object_kind: str object_value: str object_surface: str authority_class: str proof_path: tuple[str, ...]
def public(self) -> dict[str, Any]: value = dict(self.__dict__) value["proof_path"] = list(self.proof_path) return value
class WordNetSpecialist: def __init__(self, build_root: Path | str, *, deep_validate: bool = False): self.root = Path(build_root).resolve() self.manifest = validate_build(self.root, deep=deep_validate) uri = (self.root / "wordnet_specialist.sqlite3").as_uri() + "?mode=ro&immutable=1" self.connection = sqlite3.connect(uri, uri=True, check_same_thread=False) self.connection.row_factory = sqlite3.Row self.source = self.manifest["source"]
def close(self) -> None: self.connection.close()
def _entity(self, identity: str) -> sqlite3.Row | None: return self.connection.execute( "SELECT synset_id,pos,offset,canonical_label,definition,lexname,definition_claim_id " "FROM synset WHERE synset_id=?", (identity,) ).fetchone()
@staticmethod def _candidate(value: sqlite3.Row) -> dict[str, Any]: result = { "entity_id": value["synset_id"], "pos": value["pos"], "canonical_label": value["canonical_label"], "definition": value["definition"], "lexname": value["lexname"], } if "tag_count" in value.keys(): result["tag_count"] = int(value["tag_count"]) return result
def resolve(self, query: str, *, pos: str | None = None, allow_dominant: bool = True) -> dict[str, Any]: source = " ".join(str(query).split()) if re.fullmatch(r"wordnet:[nvars]:\d{8}", source.casefold()): value = self._entity(source.casefold()) return ({"status": "resolved", "method": "exact_synset_id", **self._candidate(value)} if value else {"status": "unresolved", "method": "unknown_synset_id", "query": source}) normalized = normalize_alias(source) if not normalized: return {"status": "unresolved", "method": "empty_alias", "query": source} parameters: list[Any] = [normalized] constraint = "" if pos: constraint = " AND s.pos=?" parameters.append(pos) rows = self.connection.execute( "SELECT s.synset_id,s.pos,s.offset,s.canonical_label,s.definition,s.lexname,s.definition_claim_id,a.tag_count " "FROM alias a JOIN synset s ON a.synset_id=s.synset_id WHERE a.normalized_alias=?" + constraint + " ORDER BY a.tag_count DESC,s.pos,s.offset", parameters, ).fetchall() if len(rows) == 1: return {"status": "resolved", "method": "unique_exact_alias" if pos is None else "unique_contextual_pos_alias", "query": source, **self._candidate(rows[0])} if rows: first = int(rows[0]["tag_count"]); second = int(rows[1]["tag_count"]) if allow_dominant and first >= 3 and (second == 0 or first >= 2 * second): return { "status": "resolved", "method": "dominant_wordnet_tagged_sense", "query": source, "dominance_rule": "top_tag_count_at_least_3_and_at_least_twice_runner_up", "alternative_count": len(rows) - 1, **self._candidate(rows[0]), } return { "status": "ambiguous", "method": "exact_alias_collision", "query": source, "candidate_count": len(rows), "candidates": [self._candidate(value) for value in rows], } return {"status": "unresolved", "method": "no_exact_authenticated_alias", "query": source}
def aliases(self, entity_id: str) -> list[str]: return [value[0] for value in self.connection.execute( "SELECT alias_surface FROM alias WHERE synset_id=? ORDER BY normalized_alias,alias_surface", (entity_id,) )]
def _definition(self, entity: sqlite3.Row) -> LexicalClaim: return LexicalClaim( entity["definition_claim_id"], entity["synset_id"], entity["canonical_label"], "defined_as", "literal", entity["definition"], entity["definition"], "authenticated_fact", ("wordnet_synset_definition", entity["synset_id"], self.source["sha256"]), )
def _edge(self, row: sqlite3.Row, *, inverse: bool) -> LexicalClaim: if inverse: subject_id = row["object_id"] subject_surface = row["object_label"] predicate = INVERSE[row["predicate"]] object_id = row["subject_id"] object_surface = row["subject_label"] identity = "inverse_" + row["claim_id"] authority = "derived_relation" proof = ("inverse_of_authenticated_relation", row["claim_id"], row["subject_id"], row["predicate"], row["object_id"]) else: subject_id = row["subject_id"] subject_surface = row["subject_label"] predicate = row["predicate"] object_id = row["object_id"] object_surface = row["object_label"] identity = row["claim_id"] authority = "authenticated_fact" proof = ("wordnet_synset_relation", row["claim_id"], self.source["sha256"]) return LexicalClaim(identity, subject_id, subject_surface, predicate, "entity", object_id, object_surface, authority, proof)
def claims(self, entity_id: str, *, limit: int = 24, depth: int = 1) -> list[LexicalClaim]: root = self._entity(entity_id) if root is None: return [] selected: list[LexicalClaim] = [] seen_claims: set[str] = set() seen_entities = {entity_id} frontier = [(entity_id, 0)] while frontier and len(selected) < limit: current, level = frontier.pop(0) entity = self._entity(current) if entity is None: continue definition = self._definition(entity) if definition.claim_id not in seen_claims: selected.append(definition); seen_claims.add(definition.claim_id) outgoing = self.connection.execute( "SELECT r.subject_id,r.predicate,r.object_id,r.claim_id,ss.canonical_label AS subject_label," "os.canonical_label AS object_label FROM relation r JOIN synset ss ON ss.synset_id=r.subject_id " "JOIN synset os ON os.synset_id=r.object_id WHERE r.subject_id=?", (current,) ).fetchall() incoming = self.connection.execute( "SELECT r.subject_id,r.predicate,r.object_id,r.claim_id,ss.canonical_label AS subject_label," "os.canonical_label AS object_label FROM relation r JOIN synset ss ON ss.synset_id=r.subject_id " "JOIN synset os ON os.synset_id=r.object_id WHERE r.object_id=?", (current,) ).fetchall() candidates = [self._edge(value, inverse=False) for value in outgoing] candidates.extend(self._edge(value, inverse=True) for value in incoming) candidates.sort(key=lambda value: (PREDICATE_PRIORITY.get(value.predicate, 20), value.predicate, value.object_surface.casefold(), value.claim_id)) for claim in candidates: if claim.claim_id in seen_claims: continue selected.append(claim); seen_claims.add(claim.claim_id) if level < depth and claim.object_kind == "entity" and claim.object_value not in seen_entities: seen_entities.add(claim.object_value); frontier.append((claim.object_value, level + 1)) if len(selected) >= limit: break return selected[:limit]
@staticmethod def _sentence(claim: LexicalClaim, citation: str) -> str: subject = claim.subject_surface[:1].upper() + claim.subject_surface[1:] obj = claim.object_surface templates = { "defined_as": "{s} is defined as {o}", "subclass_of": "{s} is a kind of {o}", "instance_of": "{s} is an instance of {o}", "has_subtype": "{s} includes the subtype {o}", "has_instance": "{s} includes the instance {o}", "has_part": "{s} has {o} as a part", "part_of": "{s} is part of {o}", "has_member": "{s} has {o} as a member", "member_of": "{s} is a member of {o}", "made_of": "{s} is made of {o}", "substance_of": "{s} is a substance of {o}", "entails": "{s} entails {o}", "entailed_by": "{s} is entailed by {o}", "causes": "{s} causes {o}", "caused_by": "{s} is caused by {o}", "similar_to": "{s} is similar to {o}", "related_to": "{s} is lexically related to {o}", "has_attribute": "{s} has the attribute {o}", "attribute_of": "{s} is an attribute of {o}", "verb_group_with": "{s} belongs to a verb group with {o}", "topic_domain": "{s} belongs to the topic domain {o}", "domain_of": "{s} is the topic domain of {o}", "region_domain": "{s} belongs to the region domain {o}", "regional_domain_of": "{s} is the region domain of {o}", "usage_domain": "{s} belongs to the usage domain {o}", "usage_domain_of": "{s} is the usage domain of {o}", } return templates.get(claim.predicate, "{s} {p} {o}").format(s=subject, p=claim.predicate.replace("_", " "), o=obj).rstrip(". ") + f" [{citation}]."
def realize(self, entity_id: str, *, artifact: str = "paragraph", paragraphs: int = 3) -> dict[str, Any]: started = time.perf_counter() limits = {"sentence": 1, "paragraph": 7, "essay": 18, "paper": 24} if artifact not in limits: raise ValueError("unsupported lexical artifact") root = self._entity(entity_id) if root is None: return {"schema_version": RUNTIME_SCHEMA, "status": "withheld", "reason": "unknown_synset", "response": "I need an exact authenticated lexical sense before I can answer.", "factual_release": False} claims = self.claims(entity_id, limit=limits[artifact], depth=2 if artifact in {"essay", "paper"} else 1) references: list[dict[str, Any]] = [] clauses: list[SurfaceClause] = [] if artifact != "sentence": clauses.append(SurfaceClause( "synthesis_intro", f"This account follows the authenticated lexical graph for {root['canonical_label']} ({entity_id}).", "inferred", tuple(value.claim_id for value in claims), ("select_exact_synset", entity_id), )) for index, claim in enumerate(claims, 1): citation = f"W{index}" references.append({ "citation_id": citation, "claim_id": claim.claim_id, "source_record_id": claim.subject_id, "source_document_id": "princeton_wordnet_3_0", "source_document_sha256": self.source["sha256"], "source_url": self.source["data_access_url"], "license": self.source["license_name"], "proof_path": list(claim.proof_path), }) clauses.append(SurfaceClause( f"claim_{index:02d}", self._sentence(claim, citation), claim.authority_class, (claim.claim_id,), claim.proof_path, inline_citations=(citation,), )) if artifact != "sentence": clauses.append(SurfaceClause( "synthesis_boundary", "The account is bounded to this recorded lexical graph; it does not convert lexical relations into unstored encyclopedic facts.", "inferred", tuple(value.claim_id for value in claims), ("bounded_wordnet_graph_closure", entity_id), )) request = RealizationRequest("wordnet", (entity_id,), artifact, "explain", max(3, min(6, paragraphs))) groups = EvidenceAddressedRealizer._partition(clauses, request) response, inverse = EvidenceAddressedRealizer._layout(groups, request) if artifact == "paper": response = "## Sense-addressed lexical analysis\n\n" + response + "\n\n## Source\n\nPrinceton WordNet 3.0, archive SHA-256 `" + self.source["sha256"] + "`." spine = EvidenceAddressedRealizer._spine(clauses, canonical_sha256({"entity_id": entity_id, "artifact": artifact, "paragraphs": paragraphs})) value = { "schema_version": RUNTIME_SCHEMA, "status": "answered", "reason": "exact_sense_graph_realized", "response": response, "factual_release": bool(claims), "entity": self._candidate(root), "claims": [claim.public() for claim in claims], "clauses": [clause.public() for clause in clauses], "references": references, "paragraph_plan": [[clause.clause_id for clause in group] for group in groups], "tree_spine": spine, "whole_answer_inverse": inverse, "audit": { "sense_identity_preserved": True, "all_released_claims_evidence_addressed": all(value.proof_path for value in claims), "all_derived_relations_have_proof_paths": all(value.proof_path for value in claims if value.authority_class == "derived_relation"), "pre_malkuth_payload_unbinds": spine["pre_malkuth_payload_unbinds"], "terminal_cleanup_exact": spine["terminal_cleanup_exact"], "traditional_language_model_calls": 0, "transformer_calls": 0, "pretrained_embedding_calls": 0, "next_token_predictions": 0, "gradient_steps": 0, }, "latency_ms": 1000.0 * (time.perf_counter() - started), } value["artifact_sha256"] = canonical_sha256({key: item for key, item in value.items() if key not in {"latency_ms", "artifact_sha256"}}) return value
class LexicalSessionStore: def __init__(self, root: Path | str): self.root = Path(root).resolve(); self.root.mkdir(parents=True, exist_ok=True)
def _path(self, session_id: str) -> Path: return self.root / (hashlib.sha256(session_id.encode("utf-8")).hexdigest() + ".json")
def load(self, session_id: str) -> dict[str, Any]: path = self._path(session_id) if not path.exists(): return {"schema_version": SESSION_SCHEMA, "turns": [], "last": None} value = json.loads(path.read_text(encoding="utf-8")); prior = "0" * 64 for ordinal, turn in enumerate(value["turns"]): body = {key: item for key, item in turn.items() if key != "turn_sha256"} if turn["ordinal"] != ordinal or turn["previous_sha256"] != prior or digest(body) != turn["turn_sha256"]: raise ValueError("lexical_session_chain_changed") prior = turn["turn_sha256"] return value
def append(self, session_id: str, text: str, result: Mapping[str, Any], state: Mapping[str, Any] | None) -> dict[str, Any]: value = self.load(session_id); prior = value["turns"][-1]["turn_sha256"] if value["turns"] else "0" * 64 body = { "ordinal": len(value["turns"]), "previous_sha256": prior, "input_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), "result_sha256": canonical_sha256({key: item for key, item in result.items() if key not in {"latency_ms", "session"}}), "state": dict(state) if state else None, } turn = {**body, "turn_sha256": digest(body)}; value["turns"].append(turn) if state: value["last"] = dict(state) path = self._path(session_id); temporary = path.with_suffix(".tmp") temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n") os.replace(temporary, path) return {"turns": len(value["turns"]), "head_sha256": turn["turn_sha256"], "hash_chain_valid": True}
class WordNetConversation: DOCUMENT = re.compile(r"^\s*(?:please\s+)?(?:write|compose|draft|produce|create|give\s+me)\s+(?:a\s+|an\s+)?(?:(?P<count>[3-6])[-\s]+paragraph\s+)?(?P<artifact>essay|paper|paragraph|sentence)\s+(?:about|on|explaining|concerning)\s+(?P<topic>.+?)\s*[?.!]*$", re.I) QUESTION = re.compile(r"^\s*(?:(?:what|who)\s+(?:is|are)|tell\s+me\s+about|describe|explain)\s+(?P<topic>.+?)\s*[?.!]*$", re.I) COMPARE = re.compile(r"^\s*compare\s+(?P<left>.+?)\s+(?:with|to|versus|vs\.?|and)\s+(?P<right>.+?)\s*[?.!]*$", re.I) MORE = re.compile(r"^\s*(?:tell\s+me\s+more|go\s+on|continue|expand(?:\s+that)?|say\s+more)\s*[?.!]*$", re.I)
def __init__(self, specialist: WordNetSpecialist, state_root: Path | str): self.specialist = specialist self.sessions = LexicalSessionStore(Path(state_root) / "wordnet_sessions")
@staticmethod def _clean_topic(value: str) -> str: value = re.sub(r"^(?:the|a|an)\s+", "", value.strip(), flags=re.I) return re.sub(r"\s+(?:briefly|please|in detail)$", "", value, flags=re.I).strip(" .?!")
def _resolve_or_return(self, topic: str) -> tuple[str | None, dict[str, Any] | None]: cleaned = self._clean_topic(topic) # Definition, exposition, and document constructions put the topic in a # nominal slot. Prefer noun senses without erasing other POS records; # fall back to the complete alias set only when no noun address exists. resolved = self.specialist.resolve(cleaned, pos="n") if resolved["status"] == "unresolved": resolved = self.specialist.resolve(cleaned) if resolved["status"] == "resolved": return str(resolved["entity_id"]), None if resolved["status"] == "ambiguous": choices = "; ".join(f"{value['entity_id']} — {value['definition']}" for value in resolved["candidates"][:8]) return None, { "schema_version": RUNTIME_SCHEMA, "status": "clarification", "operation": "wordnet_sense_clarification", "response": f"That exact word has {resolved['candidate_count']} authenticated senses. Specify a synset identifier or intended sense: {choices}", "factual_release": False, "resolution": resolved, } return None, { "schema_version": RUNTIME_SCHEMA, "status": "unresolved", "operation": "wordnet_topic_unresolved", "response": "I found no exact authenticated WordNet topic address for that wording.", "factual_release": False, "resolution": resolved, }
def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: started = time.perf_counter(); source = " ".join(str(text).split()); prior = self.sessions.load(session_id).get("last") artifact = "paragraph"; paragraphs = 3; topics: list[str] = [] match = self.DOCUMENT.match(source) if match: artifact = match.group("artifact").casefold(); paragraphs = int(match.group("count") or 3); topics = [match.group("topic")] elif (match := self.COMPARE.match(source)): topics = [match.group("left"), match.group("right")] elif (match := self.QUESTION.match(source)): artifact = "sentence" if source.casefold().startswith(("what is", "what are", "who is", "who are")) else "paragraph" topics = [match.group("topic")] elif self.MORE.match(source) and prior: artifact = "essay"; topics = list(prior["entity_ids"]) elif re.fullmatch(r"wordnet:[nvars]:\d{8}", source.casefold()): topics = [source] else: result = {"schema_version": RUNTIME_SCHEMA, "status": "unresolved", "operation": "wordnet_act_unresolved", "response": "No lexical discourse act was compiled.", "factual_release": False} result["latency_ms"] = 1000.0 * (time.perf_counter() - started) return result
resolved_ids: list[str] = [] for topic in topics: if topic.startswith("wordnet:") and self.specialist._entity(topic) is not None: resolved_ids.append(topic); continue identity, failure = self._resolve_or_return(topic) if failure: failure["latency_ms"] = 1000.0 * (time.perf_counter() - started) failure["session"] = self.sessions.append(session_id, source, failure, None) return failure resolved_ids.append(str(identity))
if len(resolved_ids) == 1: result = self.specialist.realize(resolved_ids[0], artifact=artifact, paragraphs=paragraphs) result["operation"] = "wordnet_relational_realization" else: components = [self.specialist.realize(value, artifact="paragraph", paragraphs=1) for value in resolved_ids] if any(value["status"] != "answered" for value in components): result = {"schema_version": RUNTIME_SCHEMA, "status": "withheld", "operation": "wordnet_comparison_withheld", "response": "Both lexical senses were not realizable.", "factual_release": False, "components": components} else: labels = [value["entity"]["canonical_label"] for value in components] response = f"Regarding {labels[0]}: {components[0]['response']}\n\nRegarding {labels[1]}: {components[1]['response']}\n\nThe comparison juxtaposes two exact authenticated sense graphs; it does not assert an unstored difference." result = {"schema_version": RUNTIME_SCHEMA, "status": "answered", "operation": "wordnet_sense_comparison", "response": response, "factual_release": True, "components": components, "audit": {"exact_sense_addresses": True, "unstored_difference_asserted": False}} state = {"entity_ids": resolved_ids, "artifact": artifact} result["latency_ms"] = 1000.0 * (time.perf_counter() - started) result["session"] = self.sessions.append(session_id, source, result, state) return result
class OracleM13aRuntime: """M12 v1.0.1 plus a hot-loaded full, sense-addressed lexical specialist."""
def __init__(self, state_root: Path | str, *, wordnet_build: Path | str, **m12_options: Any): self.state_root = Path(state_root).resolve(); self.state_root.mkdir(parents=True, exist_ok=True) self.wordnet = WordNetSpecialist(wordnet_build) if "tool_registry" not in m12_options: data_root = Path(m12_options.get("data_root") or DEFAULT_DATA_ROOT).resolve() m12_options["tool_registry"] = self._integrated_tool_registry(data_root / "m10") self.base = M12OracleRuntime(self.state_root / "m12", **m12_options) self.lexical = WordNetConversation(self.wordnet, self.state_root / "lexical")
def _integrated_tool_registry(self, m10_build: Path) -> SchemaToolRegistry: parent = build_default_tool_registry(m10_build) registry = SchemaToolRegistry() wordnet_claims = int(self.wordnet.manifest["metrics"]["claims"]) base_claims = int(json.loads((m10_build / "compilation_manifest.json").read_text(encoding="utf-8"))["claims"])
for name in sorted(parent.tools): tool = parent.tools[name] if name == "inspect_oracle": executor = lambda _value, total=base_claims + wordnet_claims: { "version": "1.1.0-m13a-dev", "domains": 13, "claims": total, "maximum_actions": 512, "maximum_parallel": 8, } tool = replace(tool, executor_id="oracle.m13.inspect.v1", executor=executor) elif name == "list_specialists": parent_executor = tool.executor def list_specialists(value: Mapping[str, Any], executor=parent_executor, count=wordnet_claims) -> dict[str, Any]: result = dict(executor(value)); domains = list(result["domains"]) domains.append({"domain": "wordnet", "claims": count, "expert_id": "generalist_wordnet_3_0"}) return {"domains": domains, "total_claims": int(result["total_claims"]) + count} tool = replace(tool, executor_id="oracle.m13.specialists.v1", executor=list_specialists) registry.register(tool)
def resolve_wordnet(arguments: Mapping[str, Any]) -> dict[str, Any]: value = self.wordnet.resolve(str(arguments["query"]), pos=arguments.get("pos")) return { "status": str(value["status"]), "method": str(value["method"]), "entity_id": str(value.get("entity_id", "")), "candidate_count": int(value.get("candidate_count", 0)), "candidates": list(value.get("candidates", ())), }
registry.register(SchemaTool( "resolve_wordnet", "Resolve an exact lemma or synset identifier against the sense-preserving WordNet specialist.", {"type": "object", "properties": {"query": {"type": "string", "minLength": 1, "maxLength": 256}, "pos": {"type": "string", "enum": ["n", "v", "a", "s", "r"]}}, "required": ["query"], "additionalProperties": False}, {"type": "object", "properties": {"status": {"type": "string"}, "method": {"type": "string"}, "entity_id": {"type": "string"}, "candidate_count": {"type": "integer"}, "candidates": {"type": "array", "items": {"type": "object"}}}, "required": ["status", "method", "entity_id", "candidate_count", "candidates"], "additionalProperties": False}, "read_only", "oracle.m13.wordnet-resolution.v1", resolve_wordnet, ("resolve lexical sense", "find wordnet sense"), )) return registry
def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: source = " ".join(str(text).split()) if re.match(r"^(?:call|use)\b", source, re.I) or (re.search(r"\b(?:essay|document|account|treatise|report)\b", source, re.I) and re.search(r"\b(?:oracle|yourself|your architecture|what it is like|being this architecture)\b", source, re.I)): return self.base.chat(source, session_id=session_id) lexical = self.lexical.chat(source, session_id=session_id) if lexical.get("status") in {"answered", "clarification"}: lexical["schema_version"] = RUNTIME_SCHEMA lexical["hot_loaded_specialist"] = "wordnet_3_0" return lexical value = dict(self.base.chat(source, session_id=session_id)) value["m13_lexical_attempt"] = {key: item for key, item in lexical.items() if key not in {"latency_ms", "session"}} return value
def capabilities(self) -> dict[str, Any]: value = dict(self.base.capabilities()) value.update({ "schema_version": RUNTIME_SCHEMA, "wordnet_synsets": int(self.wordnet.manifest["metrics"]["synsets"]), "wordnet_claims": int(self.wordnet.manifest["metrics"]["claims"]), "wordnet_unique_aliases": int(self.wordnet.manifest["metrics"]["unique_aliases"]), "sense_ambiguity_quarantine": True, "hot_loaded_without_carrier_parameter_update": True, "unrestricted_conversation": False, }) return value
__all__ = [ "LexicalClaim", "LexicalSessionStore", "OracleM13aRuntime", "WordNetConversation", "WordNetSpecialist", "validate_build", "RUNTIME_SCHEMA", "SCHEMA",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#!/usr/bin/env python3"""H2 slice 2 — paragraph compiler with ENGINE-DERIVED ANALYSIS moves.
Additive successor to stage5m13e8_paragraph_compiler_v1 (unedited). Adds thesecond provenance type: a DERIVED sentence carries {rule, premises} instead ofa page address, and the recover law now also checks that every premise of aderived move was cited EARLIER in the same paragraph — analysis may onlycomment on evidence the reader has already been shown.
Rules this slice (deterministic, zero-model): year_precedence -- two premise claims with extractable years -> "the A record (YYYY) precedes the B record (YYYY) by N years" count_aggregation -- k of the n cited statements mention TERM"""
from __future__ import annotations
import re
from stage5m13e8_paragraph_compiler_v1 import ( ParagraphProgram, compile_paragraph, recover_program,)
YEAR = re.compile(r"\b(1[0-9]{3}|20[0-2][0-9])\b")
def extract_year(sentence: str) -> int | None: match = YEAR.search(sentence) return int(match.group(1)) if match else None
def compile_paragraph_v2(topic: str, claims: list[dict], *, evidence: int = 3, next_topic: str | None = None, aggregation_term: str | None = None) -> tuple[str, ParagraphProgram]: paragraph, program = compile_paragraph(topic, claims, evidence=evidence, next_topic=None) sentences = [paragraph] cited = [m for m in program.moves if m["claim_id"]]
# ANALYSIS: year precedence over cited claims only dated = [(m, extract_year(m["text"])) for m in cited] dated = [(m, y) for m, y in dated if y is not None] if len(dated) >= 2: (first_move, first_year), (second_move, second_year) = \ sorted(dated, key=lambda pair: pair[1])[0], sorted(dated, key=lambda pair: pair[1])[-1] if first_year != second_year: span = second_year - first_year text = (f"Between the cited records, the earliest dated statement ({first_year}) " f"precedes the latest ({second_year}) by {span} years.") premises = [first_move["claim_id"], second_move["claim_id"]] sentences.append(f"{text} [derived:year_precedence<-{','.join(p[:20] for p in premises)}]") program.moves.append({"move": "ANALYSIS", "claim_id": None, "rule": "year_precedence", "premises": premises, "text": text})
# ANALYSIS: count aggregation over cited claims only if aggregation_term: term = aggregation_term.lower() hits = [m for m in cited if term in m["text"].lower()] if hits: verb = "mentions" if len(hits) == 1 else "mention" text = (f"Of the {len(cited)} statements cited here, {len(hits)} " f"{verb} {aggregation_term}.") premises = [m["claim_id"] for m in cited] sentences.append(f"{text} [derived:count_aggregation<-{len(premises)}premises]") program.moves.append({"move": "ANALYSIS", "claim_id": None, "rule": "count_aggregation", "premises": premises, "text": text})
if next_topic: sentences.append(f"The record turns next to {next_topic}.") program.moves.append({"move": "BRIDGE", "claim_id": None, "page": None, "text": next_topic}) return " ".join(sentences), program
def recover_program_v2(paragraph: str, program: ParagraphProgram) -> bool: if not recover_program(paragraph, program): return False for move in program.moves: if move.get("move") != "ANALYSIS": continue marker = f"[derived:{move['rule']}" position = paragraph.find(marker) if position < 0 or move["text"] not in paragraph: return False before = paragraph[:position] # every premise must have been cited earlier in the paragraph for premise in move["premises"]: if premise[:20] not in before: return False return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474#!/usr/bin/env python3"""M1a: typed response constraints and temporary-premise authority.
This successor adds two missing semantic types without modifying the acceptedL8c control. Literal response instructions are structural authority over thesurface form, never factual authority. Clauses supplied by the user arecompiled into a reversible, session-scoped premise world; conclusions may bereleased only with a proof inside that world and may never enter factualmemory."""from __future__ import annotations
from dataclasses import dataclassfrom pathlib import Pathimport reimport timeimport typesfrom typing import Any, Mapping, Sequence
from stage5k15_native_mixed_agent import digestfrom stage5k224a_persistent_discourse_runtime import JsonSessionStorefrom stage5k238a_epistemically_guarded_release_candidate import ( _punctuation_invariant_route, _specific_identity_act,)from stage5l6a_cognitive_state_abi import canonical_sha, file_shafrom stage5l8c_directional_authority_successor import ( DirectionalAuthorityOracleRelationalV3, DirectionalAuthorityRuntime, DirectionalRoleGuardHybridRuntime,)
SCHEMA = "oracle-stage5m1a-typed-utterance-authority-v1"VERSION = "0.9.0-m1a-development"WORD = re.compile(r"[a-z0-9]+(?:'[a-z0-9]+)?", re.I)SENTENCE = re.compile(r"(?<=[.!?])\s+")LITERAL_RESPONSE = re.compile( r"^\s*(?:return|respond\s+with|output|say)\s+exactly\s+" r"(?:(?:these|the)\s+)?(?:(\w+|\d+)\s+words?\s*)?[:\-]\s*(.+?)\s*$", re.I | re.S,)QUOTED_RESPONSE = re.compile( r"^\s*(?:return|respond\s+with|output|say)\s+exactly\s+[\"'](.+?)[\"']\s*[.!]?\s*$", re.I | re.S,)ALLOWED_BLOCK = re.compile( r"\nAllowed answers:\s*\n((?:\s*-\s*[^\n]+\n?)+)" r"\s*Return exactly one allowed answer and no other text\.?\s*$", re.I,)UNIVERSAL = re.compile( r"^(?:every|all)\s+(.+?)\s+(?:is|are)\s+(?:a\s+|an\s+)?(.+?)\s*$", re.I,)COPULAR = re.compile(r"^(.+?)\s+is\s+(?:a\s+|an\s+)?(.+?)\s*$", re.I)YES_NO = re.compile( r"(?:^|[.!?]\s+)is\s+(.+?)\s+(?:a\s+|an\s+)?(.+?)\s*\?$", re.I,)TRANSITIVE_QUERY = re.compile( r"(?:under\s+transitive\s+([a-z][a-z0-9_-]*)\s*,?\s*)?" r"what\s+does\s+(.+?)\s+([a-z][a-z0-9_-]*)\s*\?$", re.I,)BINARY = re.compile(r"^([a-z0-9_-]+)\s+([a-z][a-z0-9_-]*)\s+([a-z0-9_-]+)$", re.I)NUMBER_WORDS = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,}
def tokens(value: str) -> tuple[str, ...]: return tuple(item.casefold() for item in WORD.findall(str(value)))
def phrase(value: str) -> str: return "_".join(tokens(value))
def concept(value: str) -> str: """Deterministically normalize simple English class-number morphology.""" parts = list(tokens(value)) if not parts: return "" final = parts[-1] if final.endswith("ies") and len(final) > 3: final = final[:-3] + "y" elif final.endswith(("ches", "shes", "sses", "xes", "zes")) and len(final) > 4: final = final[:-2] elif final.endswith("s") and not final.endswith(("ss", "us", "is")) and len(final) > 3: final = final[:-1] parts[-1] = final return "_".join(parts)
def relation(value: str) -> str: token = phrase(value) if token.endswith("ies") and len(token) > 3: return token[:-3] + "y" if token.endswith(("ches", "shes", "sses", "xes", "zes", "oes")) and len(token) > 4: return token[:-2] if token.endswith("s") and len(token) > 2: return token[:-1] return token
@dataclass(frozen=True)class ResponseConstraint: kind: str literal: str | None = None word_count: int | None = None allowed_answers: tuple[str, ...] = ()
def public(self) -> dict[str, Any]: return { "kind": self.kind, "literal": self.literal, "word_count": self.word_count, "allowed_answers": list(self.allowed_answers), "structural_authority": True, "factual_authority": False, }
@dataclass(frozen=True)class PremiseSolution: world_id: str kind: str premises: tuple[dict[str, str], ...] query: dict[str, str] proof: tuple[dict[str, str], ...] answer: str response: str
def public(self) -> dict[str, Any]: return { "world_id": self.world_id, "kind": self.kind, "premises": [dict(value) for value in self.premises], "query": dict(self.query), "proof": [dict(value) for value in self.proof], "answer": self.answer, "authority_class": "user_supplied_temporary_premises", "factual_eligible": False, "reversible": True, }
def parse_response_constraint(text: str) -> ResponseConstraint | None: source = str(text).strip() quoted = QUOTED_RESPONSE.match(source) if quoted: literal = quoted.group(1).strip() return ResponseConstraint("literal_exact", literal=literal, word_count=len(tokens(literal))) direct = LITERAL_RESPONSE.match(source) if direct: raw_count, literal = direct.groups() literal = literal.strip().strip('"\'') if len(literal) > 512: return ResponseConstraint("invalid_literal", literal=None) count = None if raw_count: count = NUMBER_WORDS.get(raw_count.casefold()) if count is None and raw_count.isdigit(): count = int(raw_count) if count is not None and len(tokens(literal)) != count: return ResponseConstraint("invalid_word_count", literal=literal, word_count=count) return ResponseConstraint("literal_exact", literal=literal, word_count=count) allowed = ALLOWED_BLOCK.search(source) if allowed: values = tuple( line.strip()[1:].strip() for line in allowed.group(1).splitlines() if line.strip().startswith("-") and line.strip()[1:].strip() ) if values: return ResponseConstraint("allowed_answer_set", allowed_answers=values) return None
def _sentences(text: str) -> list[str]: return [value.strip().rstrip(".!?") for value in SENTENCE.split(str(text).strip()) if value.strip()]
def _world(kind: str, premises: Sequence[Mapping[str, str]], query: Mapping[str, str]) -> str: return "premise:" + digest({"kind": kind, "premises": list(premises), "query": dict(query)})[:24]
def solve_temporary_premises(text: str) -> PremiseSolution | None: source = str(text).strip() yes_no = YES_NO.search(source) if yes_no: entity, goal = phrase(yes_no.group(1)), concept(yes_no.group(2)) pieces = _sentences(source[:yes_no.start()]) edges: list[dict[str, str]] = [] for item in pieces: universal = UNIVERSAL.match(item) if universal: edges.append({"source": concept(universal.group(1)), "relation": "implies_class", "target": concept(universal.group(2)), "surface": item}) continue copular = COPULAR.match(item) if copular: edges.append({"source": phrase(copular.group(1)), "relation": "member_of", "target": concept(copular.group(2)), "surface": item}) adjacency: dict[str, list[dict[str, str]]] = {} for edge in edges: adjacency.setdefault(edge["source"], []).append(edge) queue: list[tuple[str, tuple[dict[str, str], ...]]] = [(entity, ())] visited = {entity} while queue: node, proof = queue.pop(0) if node == goal and proof: query = {"entity": entity, "predicate": goal, "polarity": "positive"} public_edges = tuple(edges) return PremiseSolution( _world("unary_implication", public_edges, query), "unary_implication", public_edges, query, proof, "yes", f"Yes. Within the supplied premise world, {'; '.join(edge['surface'] for edge in proof)}, so {entity.replace('_', ' ')} is {goal.replace('_', ' ')}.", ) for edge in adjacency.get(node, []): target = edge["target"] if target not in visited: visited.add(target) queue.append((target, proof + (edge,))) return None
transitive = TRANSITIVE_QUERY.search(source) if transitive: declared, subject, query_relation = transitive.groups() query_relation = relation(query_relation) if not declared or relation(declared) != query_relation: return None pieces = _sentences(source[:transitive.start()]) edges = [] for item in pieces: binary = BINARY.match(item) if binary and relation(binary.group(2)) == query_relation: edges.append({ "source": phrase(binary.group(1)), "relation": query_relation, "target": phrase(binary.group(3)), "surface": item, }) start = phrase(subject) adjacency: dict[str, list[dict[str, str]]] = {} for edge in edges: adjacency.setdefault(edge["source"], []).append(edge) queue: list[tuple[str, tuple[dict[str, str], ...]]] = [(start, ())] visited = {start} best: tuple[str, tuple[dict[str, str], ...]] | None = None while queue: node, proof = queue.pop(0) if proof: best = (node, proof) for edge in adjacency.get(node, []): target = edge["target"] if target not in visited: visited.add(target) queue.append((target, proof + (edge,))) if best and len(best[1]) >= 2: target, proof = best query = {"source": start, "relation": query_relation, "target": target} public_edges = tuple(edges) return PremiseSolution( _world("transitive_binary", public_edges, query), "transitive_binary", public_edges, query, proof, target.replace("_", " "), f"Within the supplied premise world, {start.replace('_', ' ')} {query_relation.replace('_', ' ')} {target.replace('_', ' ')} through " + " and ".join(edge["surface"] for edge in proof) + ".", ) return None
class TypedUtteranceHybridRuntime(DirectionalRoleGuardHybridRuntime): """Admit nonfactual user authority before specialist factual routing."""
@staticmethod def _snapshot(state) -> dict[str, Any]: return { "active_bundle": state.active_bundle, "last_plan": list(state.last_plan), "last_evidence": list(state.last_evidence), "salience": list(state.salience), }
@staticmethod def _restore(state, previous: Mapping[str, Any]) -> None: state.active_bundle = previous["active_bundle"] state.last_plan = list(previous["last_plan"]) state.last_evidence = list(previous["last_evidence"]) state.salience = list(previous["salience"])
def _finalize_structural( self, session_id: str, text: str, *, status: str, operation: str, response: str, extra: Mapping[str, Any], ) -> dict[str, Any]: discourse = self.agent.reasoning.discourse state = discourse._state(session_id) result = discourse._finalize( state, user_text=text, resolved_text=text, status=status, operation=operation, response=response, bundle=state.active_bundle, plan=[], evidence=[], coreference=None, ) result["schema_version"] = SCHEMA result.update(dict(extra)) result.setdefault("audit", {}).update({ "temporary_authority_only": True, "factual_eligible": False, "external_writes": 0, }) return result
def answer(self, session_id: str, text: str): constraint = parse_response_constraint(text) if constraint and constraint.kind == "literal_exact": return self._finalize_structural( session_id, text, status="answered", operation="m1_typed_literal_response", response=str(constraint.literal), extra={"response_constraint": constraint.public()}, ) if constraint and constraint.kind.startswith("invalid"): return self._finalize_structural( session_id, text, status="clarification", operation="m1_invalid_response_constraint", response="The requested exact response constraint is internally inconsistent or exceeds the bounded literal size.", extra={"response_constraint": constraint.public()}, ) solution = solve_temporary_premises(text) if solution is not None: return self._finalize_structural( session_id, text, status="answered", operation="m1_temporary_premise_inference", response=solution.response, extra={"temporary_premise_world": solution.public()}, )
discourse = self.agent.reasoning.discourse state = discourse._state(session_id) previous = self._snapshot(state) try: result = super().answer(session_id, text) except SyntaxError as exc: self._restore(state, previous) return self._finalize_structural( session_id, text, status="clarification", operation="m1_bounded_parse_failure", response="The request reached a bounded expression parser but did not form a valid authorized expression; no tool was executed.", extra={"parse_failure": {"type": type(exc).__name__, "message": str(exc)}}, ) if constraint and constraint.kind == "allowed_answer_set" and result.get("status") == "answered": normalized = " ".join(str(result.get("response", "")).casefold().split()) allowed = {" ".join(value.casefold().split()) for value in constraint.allowed_answers} if normalized not in allowed: self._restore(state, previous) result = self._finalize_structural( session_id, text, status="clarification", operation="m1_allowed_answer_constraint_guard", response="No authorized conclusion satisfied the registered allowed-answer set, so no answer was released.", extra={"response_constraint": constraint.public()}, ) return result
class _TypedUtteranceBaseOracle: def __init__( self, *, bundles: Mapping[str, Path], state_root: Path, workspace_root: Path, substrate_checkpoint: Path, ) -> None: self.workspace_root = Path(workspace_root).resolve() self.phase_root = self.workspace_root / "fable-content" / "oracle-phase3-2026-07-21" self.bundle_paths = {str(name): Path(path).resolve() for name, path in bundles.items()} self.state_root = Path(state_root).resolve() self.state_root.mkdir(parents=True, exist_ok=True) self.session_store = JsonSessionStore(self.state_root / "sessions") started = time.perf_counter() self.runtime = TypedUtteranceHybridRuntime( self.bundle_paths, session_store=self.session_store, substrate_checkpoint=Path(substrate_checkpoint).resolve(), ) discourse = self.runtime.agent.reasoning.discourse discourse._route = types.MethodType(_punctuation_invariant_route, discourse) discourse._identity_act = types.MethodType(_specific_identity_act, discourse) self.startup_milliseconds = 1000.0 * (time.perf_counter() - started)
def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: return self.runtime.answer(session_id, text)
class TypedUtteranceAuthorityRuntime(DirectionalAuthorityRuntime): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) parent = self.semantic_sha256 self.semantic_sha256 = digest({ "schema_version": SCHEMA, "parent_semantic_sha256": parent, "typed_response_constraints": True, "temporary_premise_worlds": True, "temporary_premises_factual_eligible": False, "bounded_syntax_failure": True, })
def _direct_base_act(self, session_id: str, text: str, context: Mapping[str, Any]) -> bool: constraint = parse_response_constraint(text) direct_constraint = bool(constraint and constraint.kind != "allowed_answer_set") return direct_constraint or solve_temporary_premises(text) is not None or super()._direct_base_act(session_id, text, context)
def answer(self, session_id: str, text: str) -> dict[str, Any]: before_saves = getattr(self.state_abi, "physical_save_count", 0) self.state_abi.begin_batch() try: result = super().answer(session_id, text) world = result.get("temporary_premise_world") if isinstance(world, dict): state = self.discourse._state(session_id) turn = max(0, len(state.turns) - 1) envelope = self.state_abi.emit( kind="counterfactual_state", producer="stage5m1_temporary_premise_compiler", accepted_consumers=("temporary_reasoner", "discourse_runtime", "document_planner"), session_id=session_id, world_id=str(world["world_id"]), authority_class="counterfactual_only", factual_eligible=False, reversible=True, valid_from_turn=turn, valid_until_turn=turn + 1, content=world, ) result["temporary_premise_world"]["cognitive_state_id"] = envelope.state_id result.setdefault("cognitive_state_abi", {})["temporary_premise_state_id"] = envelope.state_id result["cognitive_state_abi"]["ledger"] = self.state_abi.summary() finally: self.state_abi.end_batch() performance = result.get("performance_consolidation") if isinstance(performance, dict): performance["physical_ledger_saves_for_turn"] = ( getattr(self.state_abi, "physical_save_count", 0) - before_saves ) self._persist_manifest(session_id, result) return result
def architecture(self) -> dict[str, Any]: value = dict(super().architecture()) value.update({ "schema_version": SCHEMA, "typed_response_constraints": True, "temporary_premise_compilation": True, "temporary_premise_world_isolation": True, "temporary_premise_factual_promotion": False, "bounded_syntax_failure": True, }) return value
class TypedUtteranceAuthorityOracleRelationalV3(DirectionalAuthorityOracleRelationalV3): def _build_runtime(self) -> None: old_runtime = getattr(self, "runtime", None) if old_runtime is not None and hasattr(old_runtime, "close"): old_runtime.close() bundle_identity = canonical_sha({ name: file_sha(path) for name, path in sorted(self.bundle_paths.items()) }) self.base_oracle = _TypedUtteranceBaseOracle( bundles=self.bundle_paths, state_root=self.state_root, workspace_root=self.workspace_root, substrate_checkpoint=self.state_root / ("implication_substrate_" + bundle_identity[:16] + ".json"), ) self.runtime = TypedUtteranceAuthorityRuntime( self.base_oracle, self.language_compiler, ablations=self.ablations, l5_ablations=self.l5_ablations, state_abi=self.state_abi, l7_ablations=self.l7_ablations, )
def capabilities(self) -> dict[str, Any]: value = dict(super().capabilities()) value.update({ "schema_version": SCHEMA, "version": VERSION, "typed_response_constraints": True, "temporary_premise_compilation": True, "unrestricted_conversation": False, "unrestricted_reasoning": False, "unrestricted_agency": False, }) return value
__all__ = [ "PremiseSolution", "ResponseConstraint", "TypedUtteranceAuthorityOracleRelationalV3", "TypedUtteranceAuthorityRuntime", "TypedUtteranceHybridRuntime", "parse_response_constraint", "solve_temporary_premises", "SCHEMA", "VERSION",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262#!/usr/bin/env python3"""M1c: language-neutral typed programs for open conversational acts."""from __future__ import annotations
from dataclasses import dataclassimport hashlibfrom pathlib import Pathimport reimport timeimport typesfrom typing import Any, Mapping
import numpy as np
from stage5k15_native_mixed_agent import digestfrom stage5k224a_persistent_discourse_runtime import JsonSessionStorefrom stage5k238a_epistemically_guarded_release_candidate import _punctuation_invariant_route, _specific_identity_actfrom train_stage2a_role_ladder import unitaryfrom stage5l6a_cognitive_state_abi import canonical_sha, file_shafrom stage5m1a_typed_utterance_authority import parse_response_constraint, solve_temporary_premisesfrom stage5m1b_response_constraint_successor import ( ResponseConstraintSuccessorHybridRuntime, ResponseConstraintSuccessorOracleRelationalV3, ResponseConstraintSuccessorRuntime,)
SCHEMA = "oracle-stage5m1c-general-act-compiler-v1"VERSION = "0.9.0-m1c-development"WORD = re.compile(r"[^\W_]+(?:'[^\W_]+)?|\d+", re.UNICODE)
def clean(value: str) -> str: return " ".join(str(value).strip().rstrip(".?! ").split())
def coordinate(operator: str) -> str: state = np.ascontiguousarray(unitary("m1c:act-operator:" + str(operator))) return hashlib.sha256(state.tobytes()).hexdigest()
@dataclass(frozen=True)class ActProgram: operator: str roles: Mapping[str, Any] surface_language: str requested_artifact: str source_text_sha256: str
@property def program_id(self) -> str: return "act:" + digest(self.public(include_id=False))[:24]
def public(self, *, include_id: bool = True) -> dict[str, Any]: value = { "schema_version": SCHEMA, "operator": self.operator, "operator_coordinate_sha256": coordinate(self.operator), "roles": dict(self.roles), "surface_language": self.surface_language, "requested_artifact": self.requested_artifact, "source_text_sha256": self.source_text_sha256, "structural_authority": True, "factual_authority": False, "requires_evidence_bearing_realization": True, } if include_id: value["program_id"] = self.program_id return value
def program(operator: str, language: str, text: str, artifact: str, **roles: Any) -> ActProgram: return ActProgram( operator=operator, roles=roles, surface_language=language, requested_artifact=artifact, source_text_sha256=hashlib.sha256(str(text).encode("utf-8")).hexdigest(), )
COMPARE = ( ("en", re.compile(r"^\s*(?:compare|contrast)\s+(.+?)\s+(?:and|with|versus|vs\.?)\s+(.+?)\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*compara\s+(.+?)\s+(?:y|con)\s+(.+?)\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*compare\s+(.+?)\s+(?:et|avec)\s+(.+?)\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*vergleiche\s+(.+?)\s+(?:und|mit)\s+(.+?)\s*[?.!]*$", re.I)),)EXPLAIN = ( ("en", re.compile(r"^\s*explain\s+(.+?)\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*explica\s+(.+?)\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*explique\s+(.+?)\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*erkl(?:ä|ae)re\s+(.+?)\s*[?.!]*$", re.I)),)SUMMARIZE = ( ("en", re.compile(r"^\s*summari[sz]e\s+(.+?)\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*resume\s+(.+?)\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*r(?:é|e)sume\s+(.+?)\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*fasse\s+(.+?)\s+zusammen\s*[?.!]*$", re.I)),)CLASSIFY = ( ("en", re.compile(r"^\s*(?:classify|categorize)\s+(.+?)(?:\s+(?:as|into)\s+(.+?))?\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*clasifica\s+(.+?)(?:\s+como\s+(.+?))?\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*classe\s+(.+?)(?:\s+comme\s+(.+?))?\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*klassifiziere\s+(.+?)(?:\s+als\s+(.+?))?\s*[?.!]*$", re.I)),)PLAN = ( ("en", re.compile(r"^\s*(?:make|create|develop|write)\s+(?:a\s+)?plan\s+(?:to|for)\s+(.+?)\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*planifica\s+(.+?)\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*planifie\s+(.+?)\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*plane\s+(.+?)\s*[?.!]*$", re.I)),)ENUMERATE = ( ("en", re.compile(r"^\s*(?:list|enumerate|name)\s+(.+?)\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*(?:enumera|lista)\s+(.+?)\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*(?:énumère|enumere|liste)\s+(.+?)\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*(?:nenne|liste)\s+(.+?)\s+(?:auf)?\s*[?.!]*$", re.I)),)DEFINE = ( ("en", re.compile(r"^\s*define\s+(.+?)\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*define\s+(.+?)\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*d(?:é|e)finis\s+(.+?)\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*definiere\s+(.+?)\s*[?.!]*$", re.I)),)ANALOGY = re.compile( r"^\s*(.+?)\s+is\s+to\s+(.+?)\s+as\s+(.+?)\s+is\s+to\s+(.+?)" r"(?:\s*[,;.]?\s*(?:give|explain).*)?[?.!]*$", re.I,)COUNTERFACTUAL = ( ("en", re.compile(r"^\s*(?:suppose|imagine|assume)\s+(.+?)[,;.]\s*(?:what|how)\s+would\s+(.+?)\s*[?.!]*$", re.I)), ("es", re.compile(r"^\s*(?:sup(?:ó|o)n|imagina)\s+(.+?)[,;.]\s*(?:qu(?:é|e)|c(?:ó|o)mo)\s+(.+?)\s*[?.!]*$", re.I)), ("fr", re.compile(r"^\s*(?:supposons|imagine)\s+(.+?)[,;.]\s*(?:que|comment)\s+(.+?)\s*[?.!]*$", re.I)), ("de", re.compile(r"^\s*(?:angenommen|stell dir vor)\s+(.+?)[,;.]\s*(?:was|wie)\s+(.+?)\s*[?.!]*$", re.I)),)
def _first(patterns, text: str): for language, regex in patterns: match = regex.match(text) if match: return language, match return None, None
def compile_act(text: str) -> ActProgram | None: source = str(text).strip() if parse_response_constraint(source) is not None or solve_temporary_premises(source) is not None: return None match = ANALOGY.match(source) if match: left_entity, left_value, right_entity, missing_value = (clean(value) for value in match.groups()) return program( "analogy", "en", source, "relational_completion", source_entity=left_entity, source_value=left_value, target_entity=right_entity, target_value=missing_value, ) language, match = _first(COUNTERFACTUAL, source) if match: return program("counterfactual", language, source, "scoped_consequence", condition=clean(match.group(1)), consequence_query=clean(match.group(2))) language, match = _first(COMPARE, source) if match: return program("compare", language, source, "comparison", left=clean(match.group(1)), right=clean(match.group(2))) language, match = _first(EXPLAIN, source) if match: return program("explain", language, source, "explanation", topic=clean(match.group(1))) language, match = _first(SUMMARIZE, source) if match: return program("summarize", language, source, "summary", source=clean(match.group(1))) language, match = _first(CLASSIFY, source) if match: return program("classify", language, source, "classification", subject=clean(match.group(1)), categories=clean(match.group(2) or "unspecified")) language, match = _first(PLAN, source) if match: return program("plan", language, source, "ordered_plan", goal=clean(match.group(1))) language, match = _first(ENUMERATE, source) if match: return program("enumerate", language, source, "ordered_list", topic=clean(match.group(1))) language, match = _first(DEFINE, source) if match: return program("define", language, source, "definition", term=clean(match.group(1))) return None
class GeneralActHybridRuntime(ResponseConstraintSuccessorHybridRuntime): def answer(self, session_id: str, text: str): act = compile_act(text) if act is None: return super().answer(session_id, text) roles = ", ".join(f"{key}={value}" for key, value in act.roles.items()) result = self._finalize_structural( session_id, text, status="clarification", operation="m1c_typed_open_act", response=( f"I compiled this as a {act.operator} program over {roles}. " "The current authenticated knowledge does not yet supply a complete evidence-bearing realization." ), extra={"utterance_program": act.public()}, ) result["audit"].update({ "unrelated_specialist_release_blocked": True, "program_ready_for_specialist_authority": True, }) return result
class _GeneralActBaseOracle: def __init__(self, *, bundles: Mapping[str, Path], state_root: Path, workspace_root: Path, substrate_checkpoint: Path) -> None: self.workspace_root = Path(workspace_root).resolve(); self.phase_root = self.workspace_root / "fable-content" / "oracle-phase3-2026-07-21" self.bundle_paths = {str(name): Path(path).resolve() for name, path in bundles.items()}; self.state_root = Path(state_root).resolve(); self.state_root.mkdir(parents=True, exist_ok=True) self.session_store = JsonSessionStore(self.state_root / "sessions"); started = time.perf_counter() self.runtime = GeneralActHybridRuntime(self.bundle_paths, session_store=self.session_store, substrate_checkpoint=Path(substrate_checkpoint).resolve()) discourse = self.runtime.agent.reasoning.discourse; discourse._route = types.MethodType(_punctuation_invariant_route, discourse); discourse._identity_act = types.MethodType(_specific_identity_act, discourse) self.startup_milliseconds = 1000.0 * (time.perf_counter() - started)
def chat(self, text: str, *, session_id: str = "default") -> dict[str, Any]: return self.runtime.answer(session_id, text)
class GeneralActAuthorityRuntime(ResponseConstraintSuccessorRuntime): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.semantic_sha256 = digest({"schema_version": SCHEMA, "parent_semantic_sha256": self.semantic_sha256, "typed_open_act_programs": True, "languages": ["de", "en", "es", "fr"]})
def _direct_base_act(self, session_id: str, text: str, context: Mapping[str, Any]) -> bool: return compile_act(text) is not None or super()._direct_base_act(session_id, text, context)
def answer(self, session_id: str, text: str) -> dict[str, Any]: before = getattr(self.state_abi, "physical_save_count", 0); self.state_abi.begin_batch() try: result = super().answer(session_id, text) act = result.get("utterance_program") if isinstance(act, dict): state = self.discourse._state(session_id); turn = max(0, len(state.turns) - 1) envelope = self.state_abi.emit( kind="discourse_turn", producer="stage5m1c_general_act_compiler", accepted_consumers=("specialist_router", "document_planner", "tool_planner", "discourse_runtime"), session_id=session_id, authority_class="structural_program", factual_eligible=False, reversible=True, valid_from_turn=turn, content=act, ) result["utterance_program"]["cognitive_state_id"] = envelope.state_id result.setdefault("cognitive_state_abi", {})["utterance_program_state_id"] = envelope.state_id result["cognitive_state_abi"]["ledger"] = self.state_abi.summary() finally: self.state_abi.end_batch() if isinstance(result.get("performance_consolidation"), dict): result["performance_consolidation"]["physical_ledger_saves_for_turn"] = getattr(self.state_abi, "physical_save_count", 0) - before self._persist_manifest(session_id, result) return result
def architecture(self) -> dict[str, Any]: value = dict(super().architecture()); value.update({"schema_version": SCHEMA, "typed_open_act_programs": True, "language_neutral_operator_coordinates": True, "surface_languages": ["de", "en", "es", "fr"], "open_act_has_factual_authority": False}); return value
class GeneralActCompilerOracleRelationalV3(ResponseConstraintSuccessorOracleRelationalV3): def _build_runtime(self) -> None: old = getattr(self, "runtime", None) if old is not None and hasattr(old, "close"): old.close() identity = canonical_sha({name: file_sha(path) for name, path in sorted(self.bundle_paths.items())}) self.base_oracle = _GeneralActBaseOracle(bundles=self.bundle_paths, state_root=self.state_root, workspace_root=self.workspace_root, substrate_checkpoint=self.state_root / ("implication_substrate_" + identity[:16] + ".json")) self.runtime = GeneralActAuthorityRuntime(self.base_oracle, self.language_compiler, ablations=self.ablations, l5_ablations=self.l5_ablations, state_abi=self.state_abi, l7_ablations=self.l7_ablations)
def capabilities(self) -> dict[str, Any]: value = dict(super().capabilities()); value.update({"schema_version": SCHEMA, "version": VERSION, "typed_open_act_programs": True, "surface_languages": ["de", "en", "es", "fr"], "unrestricted_conversation": False}); return value
__all__ = ["ActProgram", "GeneralActCompilerOracleRelationalV3", "GeneralActAuthorityRuntime", "GeneralActHybridRuntime", "compile_act", "SCHEMA", "VERSION"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144#!/usr/bin/env python3"""M2c2 batched-resolution successor to the rate-limited M2c acquisition."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport timeimport urllib.errorimport urllib.parseimport urllib.requestfrom collections import defaultdictfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Mapping
import stage5m2c_wikidata_generalist_federation as m2cfrom oracle_10d_resolution_state import canonical_sha256
SCHEMA = "oracle-stage5m2c2-batched-wikidata-generalist-federation-v1"SPARQL_ENDPOINT = "https://query.wikidata.org/sparql"
def _sha_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest()
def _sha(path: Path) -> str: return _sha_bytes(path.read_bytes())
def _resolution_query() -> str: labels = " ".join(json.dumps(term, ensure_ascii=False) + "@en" for terms in m2c.DOMAIN_TERMS.values() for term in terms) return f"""SELECT ?item ?label ?description ?sitelinks WHERE {{ VALUES ?label {{ {labels} }} ?item <http://www.w3.org/2000/01/rdf-schema#label> ?label . ?item <http://wikiba.se/ontology#sitelinks> ?sitelinks . OPTIONAL {{ ?item <http://schema.org/description> ?description . FILTER(LANG(?description) = \"en\") }} FILTER(STRSTARTS(STR(?item), \"http://www.wikidata.org/entity/Q\"))}}"""
def _fetch_sparql(timeout: float = 45.0) -> tuple[bytes, str]: url = SPARQL_ENDPOINT + "?" + urllib.parse.urlencode({"query": _resolution_query(), "format": "json"}) request = urllib.request.Request(url, headers={"Accept": "application/sparql-results+json", "User-Agent": m2c.USER_AGENT}) with urllib.request.urlopen(request, timeout=timeout) as response: resolved = response.geturl(); payload = response.read(4_000_001) parsed = urllib.parse.urlparse(resolved) if parsed.scheme != "https" or (parsed.hostname or "").casefold() != "query.wikidata.org": raise PermissionError("SPARQL resolution escaped allowlisted host") if len(payload) > 4_000_000: raise ValueError("SPARQL response exceeded acquisition limit") json.loads(payload.decode("utf-8")) return payload, resolved
def _resolved_searches(payload: bytes) -> dict[str, list[dict[str, Any]]]: decoded = json.loads(payload.decode("utf-8")); grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) for binding in decoded.get("results", {}).get("bindings", ()): label = binding.get("label", {}).get("value"); uri = binding.get("item", {}).get("value", "") qid = uri.rsplit("/", 1)[-1]; sitelinks = int(float(binding.get("sitelinks", {}).get("value", 0))) if isinstance(label, str) and qid.startswith("Q"): grouped[label.casefold()].append({"id": qid, "label": label, "description": binding.get("description", {}).get("value"), "concepturi": uri, "sitelinks": sitelinks}) result = {} for terms in m2c.DOMAIN_TERMS.values(): for term in terms: matches = grouped.get(term.casefold(), []) if not matches: raise ValueError(f"batched Wikidata label did not resolve: {term}") result[term.casefold()] = sorted(matches, key=lambda value: (-value["sitelinks"], int(value["id"][1:])) ) return result
@dataclass(frozen=True)class BatchedFederationResult: path: Path payload: Mapping[str, Any] file_sha256: str
@classmethod def load(cls, path: Path) -> "BatchedFederationResult": payload = json.loads(path.read_text(encoding="utf-8")) if payload.get("schema_version") != SCHEMA: raise ValueError("unsupported M2c2 federation") if canonical_sha256(payload["semantic_identity"]) != payload["semantic_identity_sha256"]: raise ValueError("M2c2 semantic identity changed") for artifact in payload["artifacts"]: target = Path(artifact["path"]) if not target.is_file() or _sha(target) != artifact["sha256"]: raise ValueError(f"M2c2 artifact changed: {target}") return cls(path.resolve(), payload, _sha(path))
def acquire_batched_federation(output_root: Path, *, carrier_sha256: str) -> BatchedFederationResult: started = time.perf_counter(); output_root = output_root.resolve() sparql_payload, sparql_url = _fetch_sparql(); searches = _resolved_searches(sparql_payload) original_fetch = m2c._fetch
def bounded_fetch(params: Mapping[str, str], *, timeout: float = 30.0): if params.get("action") == "wbsearchentities": term = str(params["search"]); result = {"searchinfo": {"search": term}, "search": searches[term.casefold()]} return json.dumps(result, sort_keys=True, ensure_ascii=False).encode("utf-8"), sparql_url for attempt in range(4): try: return original_fetch(params, timeout=timeout) except urllib.error.HTTPError as error: if error.code != 429 or attempt == 3: raise time.sleep(2.0 * (attempt + 1)) raise RuntimeError("unreachable Wikidata retry state")
m2c._fetch = bounded_fetch try: base = m2c.acquire_and_compile(output_root, carrier_sha256=carrier_sha256) finally: m2c._fetch = original_fetch
raw_path = output_root / "raw_wikidata" / f"batched_label_resolution_{_sha_bytes(sparql_payload)[:16]}.json" raw_path.write_bytes(sparql_payload) base_manifest = base.path payload = dict(base.payload) payload["schema_version"] = SCHEMA payload["claim_boundary"] = "Minimal ten-domain federation compiled from one batched exact-label Wikidata resolution snapshot plus bounded entity snapshots; shallow structured coverage, not open-domain natural-language competence." payload["resolution_method"] = {"kind": "single_batched_exact_english_label_sparql", "endpoint": SPARQL_ENDPOINT, "query_sha256": _sha_bytes(_resolution_query().encode("utf-8")), "response_sha256": _sha(raw_path), "selected_by": "maximum_sitelink_count_then_numeric_qid", "requests": 1} payload["predecessor_manifest"] = {"path": str(base_manifest), "sha256": _sha(base_manifest)} payload["artifacts"] = [*payload["artifacts"], {"kind": "wikidata_batched_resolution_snapshot", "path": str(raw_path), "sha256": _sha(raw_path)}, {"kind": "m2c_predecessor_manifest", "path": str(base_manifest), "sha256": _sha(base_manifest)}] semantic = dict(payload["semantic_identity"]); semantic["resolution_snapshot_sha256"] = _sha(raw_path); semantic["resolution_query_sha256"] = _sha_bytes(_resolution_query().encode("utf-8")); semantic["predecessor_manifest_sha256"] = _sha(base_manifest) payload["semantic_identity"] = semantic; payload["semantic_identity_sha256"] = canonical_sha256(semantic) payload["performance"] = {**payload["performance"], "m2c2_total_wall_seconds": time.perf_counter() - started, "term_resolution_network_requests": 1} path = output_root / "federation_manifest_m2c2.json" path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") return BatchedFederationResult.load(path)
def main() -> None: parser = argparse.ArgumentParser(); parser.add_argument("--output-root", type=Path, required=True); parser.add_argument("--carrier-sha256", required=True); args = parser.parse_args() result = acquire_batched_federation(args.output_root, carrier_sha256=args.carrier_sha256) print(json.dumps({"manifest": str(result.path), "sha256": result.file_sha256, "claims": result.payload["compiler_bundle"]["claims"], "domains": len(result.payload["domains"]), "seconds": result.payload["performance"]["m2c2_total_wall_seconds"]}, indent=2))
if __name__ == "__main__": main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252"""word_problems_v1 - prose to equations for the recurring shapes of textbook word problems.
Each SCHEMA is a stored form: trigger words, the TYPED quantities it needs (money, percent, time, length ...), and aformula. A schema fires only when every quantity it needs is found with the right type AND the question asks for thekind of quantity the formula produces (the CHECK: units must compose - money x rate x years -> money). Quantities areread with their units from the text; nothing is guessed: a schema missing a quantity, or two schemas disagreeing,is an abstention.answer(text) -> {"value", "unit", "schema", "steps"} | None"""from __future__ import annotations
import mathimport re
NUM = r"(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)"WORDNUM = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "hundred": 100}LENGTH = {"mm": 0.001, "millimeter": 0.001, "cm": 0.01, "centimeter": 0.01, "m": 1.0, "meter": 1.0, "km": 1000.0, "kilometer": 1000.0, "in": 0.0254, "inch": 0.0254, "ft": 0.3048, "foot": 0.3048, "feet": 0.3048, "yd": 0.9144, "yard": 0.9144, "mi": 1609.344, "mile": 1609.344}MASS = {"mg": 0.001, "milligram": 0.001, "g": 1.0, "gram": 1.0, "kg": 1000.0, "kilogram": 1000.0, "oz": 28.349523125, "ounce": 28.349523125, "lb": 453.59237, "pound": 453.59237, "ton": 907184.74}VOLUME = {"ml": 0.001, "milliliter": 0.001, "l": 1.0, "liter": 1.0, "litre": 1.0, "cup": 0.2365882365, "pint": 0.473176473, "quart": 0.946352946, "gallon": 3.785411784, "tsp": 0.00492892, "tbsp": 0.0147868}TIME = {"second": 1 / 3600, "sec": 1 / 3600, "minute": 1 / 60, "min": 1 / 60, "hour": 1.0, "hr": 1.0, "h": 1.0, "day": 24.0, "week": 168.0, "year": 8766.0}UNIT_TABLES = [("length", LENGTH), ("mass", MASS), ("volume", VOLUME), ("time", TIME)]
def num(s): return float(s.replace(",", ""))
def unit_of(word): w = word.lower().rstrip(".") for kind, tab in UNIT_TABLES: for cand in (w, w[:-1] if w.endswith("s") else w, w[:-2] if w.endswith("es") else w): if cand in tab: return kind, cand return None
def quantities(text): """every number in the text with its type: money ($), percent (%), or a unit word right after it""" out = [] t = text.replace("−", "-") for m in re.finditer(r"(\$\s?)?" + NUM + r"\s*(%|percent\b)?\s*([A-Za-z]+(?:/[A-Za-z]+)?)?", t): dollar, val, pct, word = m.group(1), m.group(2), m.group(3), m.group(4) v = num(val) if dollar: out.append(("money", v, None, m.start())) elif pct: out.append(("percent", v, None, m.start())) elif word and "/" in word: out.append(("rate", v, word.lower(), m.start())) elif word and unit_of(word): k, u = unit_of(word) out.append((k, v, u, m.start())) else: out.append(("count", v, word.lower() if word else None, m.start())) for w, v in WORDNUM.items(): for m in re.finditer(r"\b%s\b" % w, t, re.I): out.append(("count", float(v), None, m.start())) return sorted(out, key=lambda q: q[3])
def of(qs, kind): return [q for q in qs if q[0] == kind]
def question_part(text): parts = re.split(r"(?<=[.?!])\s+", text.strip()) qs = [p for p in parts if p.endswith("?") or re.match(r"^(?:find|what|how|determine|calculate)\b", p, re.I)] return (qs[-1] if qs else parts[-1]).lower()
# --------------------------------------------------------------------------------------------------------- schemasdef s_simple_interest(t, q, qs): if not re.search(r"interest", t, re.I) or not re.search(r"how much interest|interest (?:was|did|will)", q): return None money, pct = of(qs, "money"), of(qs, "percent") yrs = [x for x in qs if x[0] == "time" and x[2] == "year"] or \ [("time", float(WORDNUM[m.group(1)]), "year", 0) for m in re.finditer(r"\b(%s)\s+years?" % "|".join(WORDNUM), t)] if len(money) != 1 or len(pct) != 1 or len(yrs) != 1: return None P, r, n = money[0][1], pct[0][1], yrs[0][1] return {"value": P * r / 100 * n, "unit": "$", "steps": ["I = P x r x t = %g x %g%% x %g years" % (P, r, n)]}
MULTISTEP = re.compile(r"\b(?:left|remain(?:s|ing)?|change|faster|slower|longer|shorter|minus|except|more than|" r"less than|times a (?:day|week)|every (?:day|week|month|year)|each of the|house is|twice|" r"triple|then|after that|in addition|altogether|combined)\b", re.I)
def s_unit_price(t, q, qs): if not re.search(r"how much (?:does|did|is) (?:each|one|a single)|cost of (?:each|one)|price (?:of|per) (?:each|one)", q): return None money = of(qs, "money") counts = [x for x in qs if x[0] == "count" and x[1] == int(x[1]) and x[1] > 1] if len(money) != 1 or len(counts) != 1: return None return {"value": money[0][1] / counts[0][1], "unit": "$", "steps": ["each = total / count = %g / %g" % (money[0][1], counts[0][1])]}
def s_total_cost(t, q, qs): if re.search(r"\beach\b|\bone\b", q): return None # a question about ONE item is a unit price, not a total if not re.search(r"how much (?:did|does|will|would) .{0,40}(?:pay|cost|spend)|total cost|how much .{0,20}(?:all|in all)", q): return None money = of(qs, "money") counts = [x for x in qs if x[0] == "count" and x[1] == int(x[1])] if len(money) != 1 or len(counts) != 1 or not re.search(r"\beach\b|\bper\b|\bapiece\b", t, re.I): return None n, p = counts[0][1], money[0][1] return {"value": n * p, "unit": "$", "steps": ["total = count x price each = %g x %g" % (n, p)]}
def s_sale_price(t, q, qs): if not re.search(r"sale price|new price|price after|how much .{0,30}after the discount", q): return None money, pct = of(qs, "money"), of(qs, "percent") if len(money) == 2 and not pct and re.search(r"\boff\b|discount", t, re.I): off = [m for m in money if re.search(r"\$\s?%s\s*off" % re.escape(("{:,.2f}" if m[1] % 1 else "{:,.0f}").format(m[1])), t) or re.search(r"%g\s*off" % m[1], t.replace(",", ""))] orig = [m for m in money if m not in off] if len(off) == 1 and len(orig) == 1: return {"value": orig[0][1] - off[0][1], "unit": "$", "steps": ["sale = original - discount = %g - %g" % (orig[0][1], off[0][1])]} if len(money) == 1 and len(pct) == 1 and re.search(r"\boff\b|discount", t, re.I): P, r = money[0][1], pct[0][1] return {"value": P * (1 - r / 100), "unit": "$", "steps": ["sale = original x (1 - rate) = %g x (1 - %g%%)" % (P, r)]} return None
def s_percent_of_total(t, q, qs): if not re.search(r"what percent", q): return None nums = [x for x in qs if x[0] in ("count", "money", "length", "mass", "volume")] if len(nums) != 2: return None a, b = sorted([nums[0][1], nums[1][1]]) return {"value": a / b * 100, "unit": "%", "steps": ["percent = part / whole x 100 = %g / %g x 100" % (a, b)]}
def s_percent_of(t, q, qs): m = re.search(r"what is " + NUM + r"\s*(?:%|percent) of \$?\s?" + NUM, t, re.I) if not m: return None r, w = num(m.group(1)), num(m.group(2)) return {"value": r / 100 * w, "unit": "$" if "$" in t else "", "steps": ["%g%% of %g" % (r, w)]}
def s_motion(t, q, qs): rate = of(qs, "rate") times = [x for x in qs if x[0] == "time"] if re.search(r"\bdistance\b|how far", q) and len(rate) == 1 and len(times) == 1: tt = times[0][1] * TIME[times[0][2]] return {"value": rate[0][1] * tt, "unit": rate[0][2].split("/")[0], "steps": ["d = r x t = %g x %g h" % (rate[0][1], tt)]} lengths = [x for x in qs if x[0] == "length"] if re.search(r"\b(?:rate|speed|how fast)\b", q) and len(lengths) == 1 and len(times) == 1: tt = times[0][1] * TIME[times[0][2]] return {"value": lengths[0][1] / tt, "unit": "%s/h" % lengths[0][2], "steps": ["r = d / t = %g / %g h" % (lengths[0][1], tt)]} return None
def s_convert(t, q, qs): m = re.search(r"how many ([a-z]+)", q) if not m or not unit_of(m.group(1)): return None kind, to = unit_of(m.group(1)) src = [x for x in qs if x[0] == kind and x[2] != to] if len(src) != 1 or len(qs) != 1: # a conversion alone: no other quantity in the problem return None tab = dict(UNIT_TABLES)[kind] v = src[0][1] * tab[src[0][2]] / tab[to] return {"value": v, "unit": to, "steps": ["%g %s = %g x %g / %g %s" % (src[0][1], src[0][2], src[0][1], tab[src[0][2]], tab[to], to)]}
def s_geometry(t, q, qs): L = [x for x in qs if x[0] == "length"] tl = t.lower()
def near(word): m = re.search(r"%s[^.]{0,40}?%s\s*([a-z]+)" % (word, NUM), tl) return num(m.group(1)) if m else None if "rectangle" in tl or "rectangular" in tl: ln, wd = near("length"), near("width") if ln is not None and wd is not None: if re.search(r"\barea\b", q): return {"value": ln * wd, "unit": "sq", "steps": ["A = L x W = %g x %g" % (ln, wd)]} if re.search(r"perimeter", q): return {"value": 2 * (ln + wd), "unit": "", "steps": ["P = 2(L + W) = 2(%g + %g)" % (ln, wd)]} if "circle" in tl or "circular" in tl: r, d = near("radius"), near("diameter") r = r if r is not None else (d / 2 if d is not None else None) if r is not None: pi = 3.14 if "3.14" in tl else math.pi if re.search(r"\barea\b", q): return {"value": pi * r * r, "unit": "sq", "steps": ["A = pi r^2, r = %g" % r]} if re.search(r"circumference", q): return {"value": 2 * pi * r, "unit": "", "steps": ["C = 2 pi r, r = %g" % r]} if re.search(r"\bvolume\b", q): r, h = near("radius"), near("height") pi = 3.14 if "3.14" in tl else math.pi if "cone" in tl and r is not None and h is not None: return {"value": pi * r * r * h / 3, "unit": "cu", "steps": ["V = (1/3) pi r^2 h, r = %g, h = %g" % (r, h)]} if "cylinder" in tl and r is not None and h is not None: return {"value": pi * r * r * h, "unit": "cu", "steps": ["V = pi r^2 h, r = %g, h = %g" % (r, h)]} if "sphere" in tl and r is not None: return {"value": 4 / 3 * pi * r ** 3, "unit": "cu", "steps": ["V = (4/3) pi r^3, r = %g" % r]} return None
SCHEMAS = [s_simple_interest, s_unit_price, s_total_cost, s_sale_price, s_percent_of_total, s_percent_of, s_motion, s_convert, s_geometry]
def rounding_of(text): t = text.lower() m = re.search(r"round(?:ed)?\s+(?:your answer\s+)?to\s+(?:the\s+nearest\s+)?(\w+)", t) if not m: return None return {"tenth": 1, "hundredth": 2, "thousandth": 3, "whole": 0, "cent": 2, "dollar": 0, "one": 1, "two": 2}.get(m.group(1))
def answer(text): t = " ".join(str(text).split()) q = question_part(t) qs = quantities(t) # v1 solves SINGLE-STEP problems only: a problem that chains quantities is a composition of schemas, not one if MULTISTEP.search(t): return None hits = [] for s in SCHEMAS: try: r = s(t, q, qs) except Exception: # noqa: BLE001 r = None if r and math.isfinite(r["value"]): r["schema"] = s.__name__[2:] hits.append(r) if len(hits) != 1: # none, or two schemas read it differently: abstain return None r = hits[0] nd = rounding_of(t) if nd is not None: r["value"] = round(r["value"], nd) elif r["unit"] == "$": r["value"] = round(r["value"], 2) return r123456789101112131415161718192021222324# Oracle7 Anatomy & Physiology (reference facts) (#34, tier A)
**id** `anatomy` - organ `organ_anatomy_v1.AnatomyOrgan` composed in front of the frozen head `oracle_release_runtime_w503`.
## Verdict
- decision: **ADMIT** (gate v2)- held-out domain: specialist 9/11 (false yes 1) vs head 0/11 (false yes 1)- core capability panel: head 160 -> composed 160 (0 items swept in by the full sweep)- reasons: none
## Sources and licences
- OpenStax Anatomy and Physiology 2e (CC-BY 4.0) https://openstax.org/details/books/anatomy-and-physiology-2e
## What it takes
- answers: count, superlative, produces- declines (in-domain): none- everything else falls through to the head unchanged
## Notes and known gaps
Stable textbook counts only (values that vary by source - bones at birth, number of muscles - are not given). Symptom / medical / personal turns fall through, never answered (the panel's invalid items are such turns). Narrowed from the start (narrow_v1).root/relstore/lexicon_v1.jsonAdded+1052
root/relstore/prop_labels.tsvAdded
root/relstore/reader_prop_allowlist.jsonAdded+1
root/relstore/relation_domains_v1.jsonAdded+101
root/relstore/relation_domains_v2.jsonAdded+996
root/relstore/router_patterns_v4.jsonAdded+212
root/textbooks/textbook_store_v1.sqlite3Added
root/wander-train/chat_context_v2.pyAdded+422
root/wander-train/entity_linker_v2.pyAdded+74
root/wander-train/math_solver_v3.pyAdded+992
root/wander-train/oracle_compare_op_v1.pyAdded+248
root/wander-train/oracle_operator_parse_v1.pyAdded+160
root/wander-train/oracle_release_runtime_an.pyAdded+173
root/wander-train/oracle_release_runtime_b.pyAdded+70
root/wander-train/oracle_release_runtime_d.pyAdded+185
root/wander-train/oracle_release_runtime_l.pyAdded+69
root/wander-train/oracle_release_runtime_w.pyAdded+123
root/wander-train/oracle_release_runtime_w56.pyAdded+115
root/wander-train/oracle_release_runtime_w57.pyAdded+84
root/wander-train/oracle_release_runtime_w65.pyAdded+107
root/wander-train/organ_code_chat_v1.pyAdded+99
root/wander-train/organ_code_chat_v2.pyAdded+155
root/wander-train/relation_spec_v1.pyAdded+172
root/wander-train/stage5c41_cooperative_four_head_router.pyAdded+279
root/wander-train/stage5c59_raw_corpus_expert_compiler.pyAdded+415
root/wander-train/stage5j2_native_english_construction_algebra.pyAdded+323
root/wander-train/stage5k100_situated_conversation_recovery_agent.pyAdded+462
root/wander-train/stage5k119_social_negative_scope_agent.pyAdded+196
root/wander-train/stage5k124_dynamic_expert_lifecycle_agent.pyAdded+386
root/wander-train/stage5k161_act_family_extension.pyAdded+204
root/wander-train/stage5k214a_authenticated_specialist_factory.pyAdded+133
root/wander-train/stage5k220a_evidence_preserving_realizer.pyAdded+165
root/wander-train/stage5k226a_verified_hrr_implication_substrate.pyAdded+346
root/wander-train/stage5k41_relational_specificity_native_generalist_agent.pyAdded+648
root/wander-train/stage5k53_native_clause_algebra_agent.pyAdded+782
root/wander-train/stage5k55_article_aware_clause_algebra_agent.pyAdded+92
root/wander-train/stage5k60_modal_bare_infinitive_agent.pyAdded+115
root/wander-train/stage5k69_whole_system_dispatch_agent.pyAdded+916
root/wander-train/stage5l2e_directional_clause_scope.pyAdded+181
root/wander-train/stage5l3_unified_language_bundle.pyAdded+436
root/wander-train/stage5l4b_relational_discourse_act_successor.pyAdded+249
root/wander-train/stage5l8b_release_hardening_successor.pyAdded+199
root/wander-train/stage5m11c_unified_agentic_conversation.pyAdded+125
root/wander-train/stage5m13a_wordnet_specialist.pyAdded+595
root/wander-train/stage5m13e8_paragraph_compiler_v2.pyAdded+91
root/wander-train/stage5m1a_typed_utterance_authority.pyAdded+474
root/wander-train/stage5m1c_general_act_compiler.pyAdded+262
root/wander-train/stage5m2c2_batched_wikidata_federation.pyAdded+144
root/wander-train/word_problems_v1.pyAdded+252
workbench/data/cards/anatomy.mdAdded+24