File size: 60,473 Bytes
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c1c64
 
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94ac135
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94ac135
 
 
 
 
 
 
 
 
81c1c64
94ac135
 
 
81c1c64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94ac135
 
 
 
 
 
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c1c64
 
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94ac135
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c1c64
 
 
 
 
 
 
 
 
 
 
04e89f2
94ac135
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c1c64
 
 
04e89f2
 
 
 
 
 
 
 
81c1c64
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94ac135
 
 
 
 
 
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
"""converse.session - the Converse organ: ComposeRouterV9 built from the pack's own parts, with the head first.

Built the way the measured loop built it (release115/meta_loop_r10.py), so the chat path and the measurement are the same
program. The head's reply is taken as given (one head call per turn): where the head answered with an answer, that stands;
where it declined, or answered with a lecture / help text / a word list, the turn loop composes."""
import json
import os
import re
import threading
import time

import converse  # noqa: F401  (sets the data paths)

LECTURE_WORDS = 90


class Converse:
    def __init__(self, engine, workbench):
        self.eng = engine
        self.wb = workbench
        self.router = None
        self.reader = None
        self.speaker = None
        self.error = None
        self.stage = "starting"
        self.started = time.time()
        self._memo = {}
        self._lock = threading.Lock()
        self._ready_event = threading.Event()
        threading.Thread(target=self._build, daemon=True).start()

    # ---------------- construction (in the background; the head answers meanwhile)
    def _build(self):
        try:
            import server
            import cli as _cli
            import operations102
            from relational_instrument_v1 import act_of, ACTS
            from squircle_reply import human_phi
            from turn_reader import Dict, Speller, Reader, corpus_texts, open_dict
            from compose_reply_v9 import ComposeRouterV9
            from turn_meaning import _ExactWords
            self.stage = "loading_dictionary"
            db = open_dict()
            d = Dict(db)
            # Work does not depend on the facts organ or the scene index. Make
            # the real dictionary/grammar available before waiting for either.
            self.reader = Reader(d, _ExactWords())
            dd = os.environ["ORACLE7_DAILYDIALOG"]
            self.stage = "loading_spelling"
            reader = Reader(d, Speller(d, corpus_texts(converse.TREE, dd, db)))
            self.reader = reader
            self.stage = "waiting_for_head_parts"
            rt = getattr(self.eng, "_rt", None)
            for _ in range(60):
                rt = getattr(self.eng, "_rt", None)
                if rt is not None and ("facts" in rt._organs or "error" in rt._organs):
                    break
                time.sleep(5)
            self.stage = "loading_conversation"
            raw = json.load(open(dd))["validation"]
            phi = human_phi([{"a0": ACTS.get(r["acts"][0]), "a1": ACTS.get(r["acts"][1])} for r in raw if len(r["utterances"]) > 1])
            ops = operations102.catalogue(self.eng)[0]
            router = ComposeRouterV9(self._head, ops, phi, act_of, converse.TREE, rt, self.eng.chat, _cli.__doc__,
                                     specialists_fn=server.specialists_payload, history_fn=server.conv_list, reader=reader)
            with self._lock:
                self.router = router
        except Exception as e:  # noqa: BLE001
            self.error = (self.stage + ": " + type(e).__name__ + ": " + str(e))[:600]
            self.stage = "failed"
            self._ready_event.set()
            return
        try:                                               # 12.0 Amendment 8: open talk planned backward from the turn
            self.stage = "loading_speaker"
            import accord as _accord                       # (accord.py; its forms are inside the tree, a few seconds to load)
            self.speaker = _accord.Speaker(converse.TREE)
            self.stage = "ready"
        except Exception as e:  # noqa: BLE001
            self.error = "speaker: " + repr(e)[:250]
            self.stage = "partial"
        finally:
            self._ready_event.set()

    def ready(self):
        return self.router is not None and getattr(self, "stage", "ready") in ("ready", "partial")

    def wait_ready(self, timeout=120):
        self._ready_event.wait(timeout)
        return self.ready()

    def status(self):
        return {"stage": getattr(self, "stage", "unknown"), "reader": self.reader is not None,
                "conversation": self.router is not None, "speaker": self.speaker is not None,
                "elapsed_s": round(time.time() - getattr(self, "started", time.time()), 1),
                "error": self.error}

    def read_request(self, text, sid):
        """The native clause reading shared by conversation and work; never a rewritten instruction."""
        reader = self.reader or getattr(self.router, "reader", None)
        if reader is None:
            return {"original": text, "available": False, "basis": "turn_reader:loading",
                    "clauses": [], "goals": [], "outcomes": [], "constraints": [], "literals": [],
                    "unresolved": [{"kind": "reader", "text": "the native word reader is still loading"}]}
        from turn_meaning import TurnMeaning, literals
        prior = []
        # Delivered context survives a process restart. Reading it cannot run
        # past actions, and another conversation never supplies a referent.
        from context_record import entries
        frames = []
        for entry in entries(sid):
            frame = dict(reader.read(entry.get("you", "")))
            frame["turn"] = entry.get("you", "")
            frames.append(frame)
        if not frames:
            frames = list(getattr(self.router, "frames", {}).get(sid, ()))[-12:]
        for frame in frames:
            files = [item["text"] for item in literals(frame.get("turn", "")) if item["kind"] == "file"]
            names = []
            if not files and self.router is not None:
                held = self._held_parts()
                if held:
                    names = [held.S.label(qid) for _span, qid, _weight in self.router.link(frame.get("turn", "")) if held.S.label(qid)]
            targets = files or names or ([" ".join(frame.get("topic") or frame.get("object") or [])]
                                if not frame.get("refs") and (frame.get("topic") or frame.get("object")) else [])
            if targets:
                prior.append({"targets": targets, "basis": "conversation:" + frame.get("turn", "")})
        claim_context = None
        try:
            import reflect
            stored = reflect.load(sid)
            ledger = stored.get("ledger") or []
            if ledger and str(ledger[-1].get("path", "")).startswith("converse:claim:"):
                claim_context = next((x.get("graph") for x in reversed(stored.get("thread", [])) if x.get("kind") == "received_claim"), None)
        except (OSError, ValueError):
            pass
        return TurnMeaning(reader).read(text, prior, claim_context=claim_context)

    def restore_context(self, sid):
        """Restore only delivered conversation context, once per ready organ."""
        if self.router is None:
            return
        restored = self.__dict__.setdefault('_restored_context', set())
        if sid in restored:
            return
        restored.add(sid)
        from context_record import entries
        delivered = entries(sid)
        for entry in delivered:
            self.observe(entry.get('you', ''), sid,
                         {'response': entry.get('said', ''), 'path': entry.get('path', ''),
                          'status': entry.get('status'), 'execution': entry.get('ex') or {}})
        return int(delivered[-1]['n']) if delivered else 0

    def writing_reply(self, text, sid, direct_only=False):
        reading = self.read_request(text, sid)
        outcomes = [c for c in reading.get('clauses', []) if c.get('kind') == 'outcome']
        if len(outcomes) > 1:
            return None  # one prose take cannot certify other requested outcomes
        part = self._discussion_part()
        take = part.writing_take(text, sid) if part is not None else None
        if take and (not direct_only or self._direct_take(take)):
            return self._discuss(text, sid)
        return None

    @staticmethod
    def _direct_take(take):
        """12.5 (q50 finding): in an open environment a command is the work receivers' unless the prose outcome is
        asked for outright: the predicate is itself an account verb, a text output or a size is named, or the turn
        continues a writing request already held. A predicate that reaches an account verb only through another of
        its senses (run -> cover -> discuss, handle -> treat -> discuss, read -> interpret -> explain) is not a
        prose request there; the sense choice itself is class 2.A."""
        wr = take.get('writing_reading')
        if wr is None:
            return True                                     # a continuation of the held writing request
        if any(not s.get('default') for s in take.get('sizes') or []):
            return True
        if wr.get('kind') == 'text-output' or wr.get('content'):
            return True
        return len(wr.get('definition_heads') or []) == 1

    def contribution_reply(self, text, sid):
        reader = self.reader or getattr(self.router, 'reader', None)
        if reader is None:
            return None
        from discourse_reasoning import handle
        return handle(text, sid, reader)

    def _page_answer(self, text, sid):
        """A held page can answer the demanded field when the head has no answer."""
        discussion = self._discussion_part()
        if discussion is None:
            return None
        reader = discussion.router.reader
        frame = reader.read(text)
        if frame.get('mood') != 'question':
            return None
        subjects, _origin = discussion.subjects(text, frame, sid)
        import writing_request as WR
        import writing_sources as WS
        request = WR.load(sid).get('request') or {}
        received_title = request.get('title', '')
        if received_title and received_title.casefold() in text.casefold():
            subjects = [request['subject']]
        if len(subjects) != 1:
            return None
        import prosefold.options as PO
        import question_obligation as QO
        title = received_title if request.get('subject') == subjects[0] else discussion.parts.S.label(subjects[0])
        records = PO.page_records(title) + WS.records(sid, subjects[0])
        answer = QO.select_records(text, records, reader, title=title, subjects=[title])
        if answer is None:
            return None
        # Re-read the actual held record before publishing the selected span.
        fresh = next((r for r in PO.page_records(title) + WS.records(sid, subjects[0])
                      if r.get('claim') == answer.get('claim')), None)
        if fresh is None or fresh.get('sentence') != answer.get('sentence'):
            return None
        excerpt = answer['answer_check'].get('source_excerpt')
        wording = ('The source says: ' + excerpt) if excerpt else answer['sentence']
        return {'status': 'answered', 'path': 'converse:page:answer',
                'response': wording + ' [1]\n\n### Sources\n\n1. ' +
                    str(answer.get('title') or title) + ' — ' + str(answer.get('source', 'held page')) +
                    ' (' + str(answer.get('claim')) + ')',
                'subjects': subjects, 'reading': frame,
                'basis': {'source': 'held page', 'record': answer.get('claim'),
                          'answer_check': answer['answer_check'], 'question': answer['question_obligation']},
                'execution': {'state': 'read', 'check': {'ok': True}, 'records': [answer.get('claim')]}}

    def commit_writing(self, sid, reply):
        if not reply.get('writing'):
            return reply
        part = self._discussion_part()
        return part.commit_writing(sid, reply) if part is not None else reply

    _WRITING = __import__("re").compile(
        r"^\s*(?:(?:ok(?:ay)?|now|so|and)[\s,]+)*(?:please\s+|can you\s+|could you\s+|would you\s+)?(?:write|explain|describe|"
        r"tell me (?:more )?about|give me (?:an?\s+)?(?:essay|explanation|account|overview|summary))\b", __import__("re").I)

    def proposition_reply(self, text, sid, allow_statement=True):
        if self._WRITING.match(text or ""):
            return None                                 # 12.0 C29: a request to write or explain is not a claim to discuss
        if __import__("re").match(r"(?i)^\s*(?:i'?m|i am|i feel|i'?ve been|i was)\b", text or ""):
            return None                                 # 12.0.2: the speaker saying how they are is talk, not a claim to examine
        reader = self.reader or getattr(self.router, "reader", None)
        if reader is None:
            return None
        from priority_claims import handle
        if allow_statement:
            result = handle(text, sid, reader)
            if result:
                return result
        from claim_discussion import handle as discuss_claim
        return discuss_claim(text, sid, reader, allow_statement=allow_statement)

    def _held_parts(self):
        held = self.__dict__.get("_parts")
        if held is None:
            import parts
            path = os.path.join(converse.TREE, "workbench", "converse", "data", "parts", "parts.json")
            held = self._parts = parts.Parts(converse.TREE, path) if os.path.isfile(path) else False
        return held

    def _discussion_part(self):
        if self.router is None:
            return None
        held = self._held_parts()
        if not held:
            return None
        if self.__dict__.get("_discussion") is None:
            from held_discussion import HeldDiscussion
            self._discussion = HeldDiscussion(self.router, held)
        return self._discussion

    def _discuss(self, text, sid):
        discussion = self._discussion_part()
        if discussion is None:
            return None
        held = discussion.parts
        result = discussion.reply(text, sid)
        if result and result.get("claims"):
            # Reflection already knows how to join, revisit and challenge held
            # claims. Give it the actual claims said here, so "what follows?"
            # continues this discussion instead of falling back to work rules.
            try:
                import reflect
                record = reflect.load(sid)
                record.setdefault("thread", []).append({"kind": "think", "t": time.time(), "source": "converse:parts",
                                                        "subjects": [[held.S.label(q), q] for q in result["subjects"]],
                                                        "claims": result["claims"], "premises": []})
                record["thread"] = record["thread"][-40:]
                reflect.save(sid, record)
            except Exception as error:
                result["reflection_error"] = repr(error)[:200]
        return self._offer_reading(result, sid) if result else result

    def _head(self, q, s):
        """the head's reply for this turn, already obtained by Workbench.chat (one head call per turn)"""
        r = self._memo.get((s, q))
        if r is None:
            r = self.wb.chat_core(q, s or "probe")
        return r

    # ---------------- the rule: the head stands where it answered with an answer
    # (gate run 1, 2026-11-08: a word-count clause here reclassified one right exclusion of the head as a lecture and lost
    # it; the clause is removed. The head's own path names help, lecture and wordnet; no threshold decides.)
    def asks_nothing(self, text):
        """12.0 open talk: a turn that asks nothing (no question, no request) - the reader's act decides"""
        if text.rstrip().endswith("?"):
            return False
        sp = self.speaker                                   # Amendment 9: the speaker's own reading of the turn's opening
        try:
            if sp is not None and (sp.asks(text) or sp.tells(text)):
                return False
        except Exception:  # noqa: BLE001
            pass
        try:
            from relational_instrument_v1 import act_of
            if act_of(text) not in ("inform", "commissive"):
                return False
        except Exception:  # noqa: BLE001
            return False
        # gate 12.0 run 1: "Is the area less than 50 square versta for Chillicothe" has no question mark, so the act reader
        # (last sentence, punctuation) read it as inform and it lost the head's right "no". The turn reader reads mood from
        # the sentence's shape; a turn it reads as a question asks something (its requests: the act reader already excludes directives). One class, one place.
        r = self.router
        if r is not None and getattr(r, "reader", None) is not None:
            try:
                if r.reader.read(text).get("mood") in ("question", "request"):
                    return False
            except Exception:  # noqa: BLE001
                pass
        return True

    _TELL = __import__("re").compile(r"^\s*(tell me|go on|read it|please do|yes,? ?(please|tell me|read it))\b", __import__("re").I)
    _CAPNOISE = {"capability", "arb", "select", "novel", "act", "resolve", "topic", "simply"}

    def _names_capability(self, hp, text):
        """does the turn name the capability the head used (summarize / summary, explain, list, compare, continue)"""
        rx = __import__("re")
        names = [n for n in rx.findall(r"[a-z]+", hp.lower()) if n not in self._CAPNOISE and len(n) >= 4]
        words = [w for w in rx.findall(r"[a-z]+", text.lower()) if len(w) >= 4]
        return any(n[:5] == w[:5] for n in names for w in words)

    def _lecture_refused(self, head, text):
        """the head's keyword capability or definition, on a turn that did not ask for it (Amendments 9, 10, 15)"""
        hp = str(head.get("path", ""))
        if head.get("status") != "answered" or hp.startswith(("workbench:", "yours:", "tool:")):
            return False
        if hp.startswith(("wordnet", "help", "arb:", "capability:", "resolve:")) and self.router is not None:
            try:
                frame = self.router.reader.read(text)
                if frame["mood"] == "request":
                    textual = self.router.is_text_request(frame)
                    verb = frame.get("verb")
                    discussion = self._discussion_part()
                    if discussion:
                        textual = textual or discussion._verb_class(verb, {"explain", "describe", "understand", "discuss"})
                    glosses = [g for pos, gs in self.router.reader.d.entries(verb) if pos == "verb" for g in gs]
                    comparing = verb in ("compare", "contrast", "distinguish") or any(
                        __import__("re").search(r"\b(?:compare|contrast|comparison)\b", gloss) for gloss in glosses[:8])
                    if textual or comparing:
                        subjects = [qid for _span, qid, _weight in self.router.link(text)]
                        if not subjects and frame.get("refs") and self.__dict__.get("_discussion"):
                            # No sid is supplied to stands; frame references must
                            # be checked in reply(), never borrowed across chats.
                            subjects = []
                        held = self._held_parts() if subjects else None
                        if held:
                            body = str(head.get("response", "")).casefold()
                            if any((held.S.label(qid) or "").casefold() not in body and ("q%d" % qid) not in body for qid in subjects):
                                return True
            except Exception:  # noqa: BLE001
                pass
        if text.rstrip().endswith("?"):
            return False
        sp, asks, tells = self.speaker, False, False
        try:
            asks = bool(sp is not None and sp.asks(text))
            if not asks and self.router is not None:
                asks = self.router.reader.read(text).get("mood") == "question"
            tells = bool(sp is not None and sp.tells(text)) and not asks
        except Exception:  # noqa: BLE001
            pass
        if ("capability:" in hp or hp.startswith(("arb:", "resolve:", "act:"))) and not self._names_capability(hp, text):
            if not asks:
                return True
            try:
                if sp is not None and not sp.about(text, str(head.get("response", ""))):
                    return True
            except Exception:  # noqa: BLE001
                pass
        if tells and ("definitional" in hp or "explain_simply" in hp or hp.startswith(("wordnet", "help"))) and \
                not self._names_capability(hp + " define definition meaning explain", text):
            return True
        return False

    def context_refuses(self, head, text, sid):
        """A generic self-introduction cannot answer a request about held subjects.

        This is session scoped because the request may name them only as 'them'.
        It never calls a second head or substitutes one chat's subjects for another.
        """
        discussion = self.__dict__.get("_discussion")
        if discussion is None or head.get("status") != "answered":
            return False
        path = str(head.get("path", ""))
        if not (path.startswith(("wordnet", "help", "arb:", "capability:", "resolve:")) or path.endswith(">addressed")):
            return False
        frame = self.router.reader.read(text)
        if frame["mood"] != "request":
            return False
        verb = frame.get("verb")
        if not (self.router.is_text_request(frame) or discussion._verb_class(
                verb, {"compare", "contrast", "distinguish", "explain", "describe", "discuss", "continue", "elaborate", "expand"})):
            return False
        subjects, _basis = discussion.subjects(text, frame, sid)
        body = str(head.get("response", "")).casefold()
        return bool(subjects and any((discussion.parts.S.label(qid) or "").casefold() not in body and
                                     ("q%d" % qid) not in body for qid in subjects))

    def _offer_reading(self, reply, sid):
        """12.0.1: a writing request short of what it holds, with no question to answer and sizes that are valid, offers to
        read the topic in Simple English Wikipedia and Wikipedia (writeup.write_up, on go), in plain words, with what it
        does hold below; the request is kept, so the draft can still be continued from another source"""
        w = reply.get("writing") or {}
        ex = reply.get("execution") or {}
        req = w.get("request") or {}
        if str(reply.get("path", "")).endswith(":offer-read"):
            return reply
        if not (reply.get("status") == "hole" and ex.get("cause") == "writing-evidence-or-size" and w.get("need")):
            return reply
        n = (w.get("counts") or {}).get("sentence", 0)
        body = str(w.get("body") or "").strip()
        q = " ".join(str(req.get("question") or "").split()).rstrip(" .?!")
        if q and not w.get("answer_present", True):
            # 12.0.2: it holds the subject but no sentence answering the question: offer to read the question itself
            topic = q
            if len(topic.split()) > 12:
                return reply
            held = "I hold no sentence that answers %s." % topic
        elif not req.get("question") and req.get("title"):
            topic = " ".join(str(req.get("title")).split())
            if not topic or len(topic.split()) > 6:
                return reply
            held = ("I hold nothing I can write about %s." % topic if not n else
                    "I hold %s on %s, not enough for what you asked." % ("one sentence" if n == 1 else "%d sentences" % n, topic))
        else:
            return reply
        self.__dict__.setdefault("_fw", {})[sid] = topic
        lead = held + (" I can read about it in Simple English Wikipedia and Wikipedia and write it up with its sources - "
                       "say go.")
        out = dict(reply, response=lead + (("\n\nWhat I hold now:\n\n" + body) if body else ""),
                   path=str(reply.get("path", "")) + ":offer-read")
        return out

    def stands(self, head, text):
        if self._REPORT.match(text or "") or (self.__dict__.get("_fw") and self._GO.match(text or "")):
            return False                                    # Amendment 11: the report, or "go" after an offer to read and write
        if self.__dict__.get("_about") and self._TELL.match(text or ""):
            return False                                    # Amendment 9: "tell me" after an offer to read a record
        if self._ACCOUNT.match(text or "") and ("capability:" in str(head.get("path", "")) or str(head.get("path", "")).startswith(("arb:", "resolve:"))
                                              or head.get("status") != "answered"):
            return False                                    # an account asked for goes to the paragraph writer first
        am_ = self._ACCOUNT.match(text or "")
        if am_ and not text.rstrip().endswith("?") and self._claims_paragraph(am_.group(1)):
            return False                                    # parts2: claims to write from: the writer first, the head's summary after
        if head.get("status") != "answered":
            return False
        if self._lecture_refused(head, text):
            return False
        # the head's "you have me mixed up with <Name>" reply stands only when what it took for a name is one: a turn's
        # first word that the dictionary holds as an ordinary word ("Hmm", "Earlier", "Honestly") addresses nobody
        mixed = re.match(r"I think you've got me mixed up with ([A-Za-z]+)", str(head.get("response", "")))
        if mixed and self.router is not None:
            try:
                pos = self.router.reader.d.pos(mixed.group(1).lower())
                if pos and "name" not in pos:
                    return False
            except Exception:  # noqa: BLE001
                pass
        hp = str(head.get("path", ""))
        # Amendment 9: a keyword capability on a turn that does not ask stands only where the turn names it. (Ben's own 570
        # turns, 2026-11-10: 100 of them got a lecture - "lets get it built" -> "Can could mean a cylinder shaped object".)
        if ("capability:" in hp or hp.startswith(("arb:", "resolve:", "act:"))) and not text.rstrip().endswith("?"):
            asks = False
            try:
                asks = bool(self.speaker is not None and self.speaker.asks(text))
                if not asks and self.router is not None:
                    asks = self.router.reader.read(text).get("mood") == "question"
            except Exception:  # noqa: BLE001
                pass
            if not self._names_capability(hp, text):
                if not asks:
                    return False
                try:                                        # Amendment 10: it asks, without a question mark: the summary must be
                    if self.speaker is not None and not self.speaker.about(text, str(head.get("response", ""))):
                        return False                        # about something the turn names ("...on 4" was about nothing in it)
                except Exception:  # noqa: BLE001
                    pass
        # 12.0: a turn that asks nothing is talk; the head's reading of it (a definition, a lookup) is not the reply. Its own
        # replies (help, history, your readers, tools) still stand.
        if self.speaker is not None and self.asks_nothing(text) and not hp.startswith(("workbench:", "yours:", "tool:")):
            return False
        # merged release (11-08): on a STATEMENT the head's keyword-arbitrated capabilities (summarize, list, timeline, explain)
        # are not the reply ("The new job starts on Monday and I am nervous" -> a list of things named New); requests and
        # questions are unchanged. The reader's own mood decides statement.
        if hp.startswith("arb:") and not text.rstrip().endswith("?") and self.router is not None:
            try:
                if self.router.reader.read(text).get("mood") in ("inform", "statement", "commissive", "expressive"):
                    return False
            except Exception:  # noqa: BLE001
                pass
        if hp.startswith(("workbench:", "yours:")):
            return True                                                   # help, history, your own readers: theirs
        # gate run 2 (2026-11-08): the head's proved exclusion "No" on a question came through its wordnet path and this clause
        # handed the question to the composer, which could only name a hole. The exclusion is for turns that ask nothing: a
        # statement answered with a definition or help text belongs to the turn loop; a question the head answered stands.
        if (hp.startswith("help") or "lecture" in hp or hp.startswith("wordnet")) and not text.rstrip().endswith("?"):
            return False
        return True

    def observe(self, text, sid, head):
        """Amendment 14 (2): record an exchange the head answered as the composer's context (turns, frames, the reference
        history, what the other speaker said), exactly as reply() records its own turns, without composing anything"""
        r = self.router
        if r is None:
            return
        try:
            import numpy as np
            from compose_reply_v8 import OPENERS, unit
            r.turns[sid].append(text)
            r.reader.sp.observe(text)
            r.receive(r.common[sid], text)
            stripped = OPENERS.sub("", text, count=1).strip() or text
            fr = r.bind(sid, r.reader.read(stripped if len(stripped.split()) >= 2 else text))
            fr["turn"] = text
            r.frames[sid].append(fr)
            wts, _h = r.demand(text, fr)
            words = list(wts)
            q = unit(r.text_vec(words, wts)) if words else np.zeros(r.OK.shape[1], dtype=np.float32) + 1e-6
            r.hist[sid].append((q, [w for w in sorted(wts, key=lambda x: -wts[x])][:6]))
            r.role_turns[sid].append(str(head.get("response", "")))
            discussion = self._discussion_part()
            if discussion is not None:
                discussion.observe(text, sid, head)
        except Exception as e:  # noqa: BLE001
            self.error = "observe: " + repr(e)[:200]

    def _commit(self, sid, r):
        """Amendment 14 (4): the builder's proposal is applied only if its reply is the one delivered; a build runs here,
        once, and its actual receipt replaces the proposal's words"""
        b = getattr(self.router, "builder", None)
        if b is None or not hasattr(b, "commit"):
            return r
        p = getattr(b, "proposal", {}).get(sid)
        if p and p["text"] not in str(r.get("response", "")):
            # the builder's reply realises the operation the turn named; a generic line that only names the operation
            # ("it changes state, so I run it on your go") does not displace it (11-08 build conversation)
            r = dict(r, response=p["text"], path=str(r.get("path", "")) + ">build:proposal",
                     status="answered" if p["kind"] == "build" else "hole")
        try:
            receipt = b.commit(sid, r.get("response", ""))
        except Exception as e:  # noqa: BLE001
            receipt = "The build raised %s [op:build]." % repr(e)[:100]
        if receipt:
            r = dict(r, response=receipt, path=str(r.get("path", "")) + ">build:receipt")
        return r

    def idea_reply(self, text, sid):
        """An idea the speaker is weighing (turn_act "idea"): received as their plan, a supplied premise, never a checked
        claim; the held pages say what its parts are, each sentence cited; the bench's own reading of the thing to be made
        (project_intent.receive, dry) says what building it would take, as holes with the input each one needs; a later
        "build it" carries the kept plan to the work receivers. An opinion asked about the plan is answered by what the
        record holds and what is still open, not by a stance Oracle7 does not hold."""
        import re
        import reflect
        part = self._discussion_part()
        if part is None:
            return None
        st = reflect.load(sid)
        ideas = st.setdefault("ideas", [])
        reader = part.router.reader
        verbs_at = [(m.start(), reader.d.lemma(m.group().lower(), "verb")) for m in re.finditer(r"[A-Za-z]{3,}", text)
                    if "verb" in reader.d.pos(m.group().lower())]
        # the verb of making itself (its lemma), not a verb some definition reaches it through ("do" -> make)
        make_at = next((i for i, v in verbs_at if v in ("build", "make", "create", "design", "develop", "write")), None)
        if make_at is not None:
            clause = re.split(r"(?<=[.!?])\s+", text[make_at:].strip())[0].rstrip(".!?")
            ideas.append({"text": text, "plan": clause, "t": __import__("time").time()})
            reflect.save(sid, st)
        elif ideas:
            clause = ideas[-1]["plan"]
        else:
            try:                                   # the work this conversation keeps is the plan on the table
                import bench
                work = bench.Turn(sid).s.get("work") or {}
                clause = str(work.get("original") or (work.get("build_intent") or {}).get("original") or "").strip()
            except Exception:  # noqa: BLE001
                clause = ""
            if not clause:
                return None
        lines = ['You\'re weighing: "%s". I keep that as your plan, not as a checked claim.' % clause]
        refs, used = [], []
        try:
            import prosefold.options as PO
            # the things the plan makes and works on: nouns after its verb, not the verb itself ("building" is the act)
            frame = reader.read(re.sub(r"(?i)^(?:building|making|creating)\b", "build", clause))
            nouns = [w for w in list(frame.get("object") or []) + list(frame.get("topic") or [])
                     if "noun" in reader.d.pos(w) and len(w) > 2
                     and not (reader.d.pos(w) & {"article", "det", "pron", "prep", "conj"})]
            for w in nouns:
                if len(refs) >= 3:
                    break
                lemma = reader.d.lemma(w, "noun")
                for title in (lemma[:1].upper() + lemma[1:], "mobile " + lemma):
                    recs = PO.page_records(title)
                    if recs:
                        k = len(refs) + 1
                        lines.append("%s [%d]" % (recs[0]["sentence"], k))
                        refs.append("%d. %s - %s (%s)" % (k, recs[0]["title"], recs[0]["source"], recs[0]["claim"]))
                        used.append(recs[0]["claim"])
                        break
        except Exception:  # noqa: BLE001
            pass
        takes = []
        try:
            import project_intent as PI
            intent = PI.receive("build " + re.sub(r"(?i)^(?:building|build|making|make|creating|create)\s+", "", clause))
            takes = [h["text"] for h in PI.holes(intent)]
        except Exception:  # noqa: BLE001
            takes = []
        if takes:
            lines.append("To build it here I would need: " + " ".join(takes))
        lines.append('Whether it is worth doing is yours to weigh; what I can add is what the record holds above. Say "build it" '
                     "with those details and I will start it as work in this conversation.")
        body = "\n\n".join(lines) + ("\n\n### Sources\n\n" + "\n".join(refs) if refs else "")
        return {"status": "offered", "path": "converse:idea", "response": body, "takes": takes or ["build it"],
                "records": used, "basis": {"premise": clause, "kind": "supplied plan", "sourced": used},
                "execution": {"state": "not_run", "cause": "awaiting go", "takes": takes or ["build it"]}}

    BUILD_IT = __import__("re").compile(r"(?i)^\W*(?:ok(?:ay)?|yes|sure|great|alright)?[,.!\s]*(?:let'?s\s+|please\s+|go\s+ahead\s+and\s+)?(?:build|make|start)\s+it\b(.*)$")

    def build_kept_idea(self, text, sid):
        """'build it' after an idea: the kept plan, with whatever the turn adds, as the request the work receivers take"""
        m = self.BUILD_IT.match(text or "")
        if not m:
            return None
        import reflect
        ideas = reflect.load(sid).get("ideas") or []
        extra = m.group(1).strip(" ,.;:")
        if not ideas:
            # work already kept: "build it" adds nothing new, so what the turn adds ("call it books.py") is the fill the
            # kept work receives, said on its own so its receiver reads it as one
            try:
                import bench
                if bench.Turn(sid).s.get("work") and extra:
                    return extra
            except Exception:  # noqa: BLE001
                pass
            return None
        plan = ideas[-1]["plan"]
        plan = __import__("re").sub(r"(?i)^(?:building|making|creating)\b", "build", plan)
        if not __import__("re").match(r"(?i)^(?:build|make|create)\b", plan):
            plan = "build " + plan
        extra = m.group(1).strip(" ,.;:")
        return plan + (". " + extra if extra else "")

    REPAIR = __import__("re").compile(
        r"^\W*(?:(?:sorry|no|nope|oh|wait|actually|well|oops|hmm)[,.!]?\s*)*(?:i\s+meant|i\s+mean|i\s+was\s+(?:asking|talking)\s+about)"
        r"\s+(.+?)(?:,?\s+not\s+(.+?))?[.!?]*\s*$", 2)
    REPAIR_NOT = __import__("re").compile(r"^\W*(?:(?:sorry|no|actually|oops)[,.!]?\s*)*not\s+(.+?),\s*(?:but\s+)?(.+?)[.!?]*\s*$", 2)

    def repair(self, text, sid):
        """Amendment 14 (1), widened 11-17: a correction of the referent ("Sorry, I meant X", "Actually I meant X, not Y",
        "Not Y, X") applies to the open obligation: the previous request of this conversation, whatever its mood (a writing
        request, a question, a command), is asked again with X in place of Y (or of the last thing it named), through
        the whole door. Returns the rewritten request or None."""
        m = self.REPAIR.match(text or "")
        if m:
            new, old = m.group(1).strip(), (m.group(2) or "").strip()
        else:
            m = self.REPAIR_NOT.match(text or "")
            if not m:
                return None
            old, new = m.group(1).strip(), m.group(2).strip()
        prev = None
        RE = __import__("re")
        try:
            from context_record import entries
            asked = [e.get('you', '') for e in reversed(entries(sid)) if e.get('you', '').strip()
                     and not (self.REPAIR.match(e.get('you', '')) or self.REPAIR_NOT.match(e.get('you', '')))]
            # "not Mars" names what is corrected: the latest request that said it, even if a follow-up came between
            prev = (next((t for t in asked if RE.search(r"(?<![A-Za-z])" + RE.escape(old) + r"(?![A-Za-z])", t, RE.I)), None)
                    if old else None) or (asked[0] if asked and not old else None)
        except Exception:  # noqa: BLE001
            prev = None
        r = self.router
        if not prev and r is not None:
            prev = next((t for t in reversed(r.turns[sid]) if t.strip() and t.strip() != (text or "").strip()), None)
        if not prev:
            return None
        if old:
            hit = RE.search(r"(?<![A-Za-z])" + RE.escape(old) + r"(?![A-Za-z])", prev, RE.I)
            return prev[:hit.start()] + new + prev[hit.end():] if hit else None
        spans = [s for s, _e, _x in r.link(prev)] if r is not None else []
        if spans:
            old = spans[-1]
            return prev.replace(old, new.replace("the ", "", 1) if not old.lower().startswith("the ") else new, 1)
        return None

    _ACCOUNT = __import__("re").compile(
        r"^\s*(?:please\s+|can you\s+|could you\s+)?(?:tell me (?:more )?about|explain|describe|write (?:a paragraph |an essay |something )?(?:about|on)|"
        r"what(?:'s| is) the significance of|why does)\s+(?:the |a |an )?(.+?)(?:\s+matter)?[.!?\s]*$", __import__("re").I)

    def _claims_paragraph(self, topic):
        """Amendment 12: a paragraph about one thing written from the claims the store holds, by parts; each sentence is
        read back before it is said. None unless three or more claims have a named part."""
        try:
            P = self._held_parts()
            if not P:
                return None
            t = " ".join(str(topic).split())
            best = None                                     # parts3: every reading of the title; the best held one
            for cand in dict.fromkeys((t, t[:1].upper() + t[1:], t.title(), "The " + t.title(), "The " + t)):
                q = P.S.qid_of_title(cand)
                if q is None:
                    continue
                r = P.about(q, limit=6)
                if r and len(r["claims"]) >= 3 and (best is None or len(r["claims"]) > best[1]):
                    best = (r["text"], len(r["claims"]))
            return best
        except Exception:  # noqa: BLE001
            return None

    def _prose(self, topic, sid):
        """an account of a topic: a paragraph written from the store's claims (parts), then ProseFold's paragraphs from the
        head's own records; None unless one of them has something to say"""
        written = self.writing_reply('Explain ' + str(topic), sid)
        if written:
            return written
        try:
            topic = " ".join(str(topic).split())[:80]
            if not topic or len(topic.split()) > 6:
                return None
            cp = self._claims_paragraph(topic)
            r = None
            try:
                import prosefold.options as PO
                r = PO.write(self.eng.chat, topic, length="short", level="general", depth="standard", style="plain")
            except Exception:  # noqa: BLE001
                r = None
            has_prose = bool(r) and int(r.get("sentences") or 0) >= 2
            if not cp and not has_prose:
                return None
            out, status = [], "answered"
            if cp:
                out.append(cp[0])
                out.append("(%d sentences written from claims I hold; each was read back before it was said)" % cp[1])
            if cp and not has_prose:                        # the head's own cited account of it, after the claims
                try:
                    h_ = self.wb.chat_core("Tell me about %s." % topic, (sid or "x") + "#acct")
                    if h_.get("status") == "answered" and not self._lecture_refused(h_, "tell me about %s?" % topic):
                        out += ["", str(h_.get("response", "")).strip()]
                except Exception:  # noqa: BLE001
                    pass
            if has_prose:
                if cp:
                    out.append("")
                out.append(str(r.get("essay_md", "")).strip())
                out.append("(%d sentences from %d records, %d checked word for word against their sources)" % (
                    r["sentences"], r["records_used"], r["faithful"]))
                if r["faithful"] != r["sentences"]:
                    status = "offered"
            return {"status": status, "response": chr(10).join(out),
                    "path": "converse:%s:%s" % ("parts+prosefold" if (cp and has_prose) else "parts" if cp else "prosefold", topic)}
        except Exception:  # noqa: BLE001
            return None

    _SELF = __import__("re").compile(r"\b(you|your|we|our|oracle ?7|this (?:release|version)|the (?:release|harness|gates?))\b", __import__("re").I)
    # 12.0.2: a topic about the world says "we" too ("why we have day and night"); a topic about Oracle7 names it or "you"
    _SELF_TOPIC = __import__("re").compile(r"\b(you|your|oracle ?7|this (?:release|version)|the (?:release|harness|gates?))\b", __import__("re").I)

    _WORK = __import__("re").compile(r"\b(is it (?:all )?(?:done|finished|ready|working)|been done|what'?s left|how close|"
                                     r"significance|the (?:project|work|build|goal))\b", __import__("re").I)

    _STATUS = __import__("re").compile(r"\b(where are we|where we are|where (?:do )?things stand|how close|what'?s left|what is left|"
                                       r"is it (?:all )?(?:done|finished|ready|working)|what'?s? (?:has )?been done|eta)\b", __import__("re").I)
    _REQUEST = __import__("re").compile(r"^\s*(?:\w+,?\s+){0,3}(?:can|could|will|would|should) (?:we|you|i)\b", __import__("re").I)

    def _own_record(self, text, sid):
        """a turn that asks about Oracle7 itself, answered from the release's own changelogs in their own words"""
        try:
            if not (text.rstrip().endswith("?") or (self.speaker is not None and self.speaker.asks(text))):
                return None
            selfcue = bool(self._SELF.search(text or "") or self._WORK.search(text or ""))
            status = bool(self._STATUS.search(text or ""))
            asks = text.rstrip().endswith("?") or (self.speaker is not None and self.speaker.asks(text))   # a14
            if not status:                                  # a18: a proper name (not Oracle7) makes it a question about the world
                import accord as _acc
                tn = _acc.read_turn(self.speaker.A.W, text)
                if any(k == "NAME" and not t.lower().startswith("oracle") for _i, t, k in tn["content"]):
                    rec0 = self.__dict__.get("_rec")
                    if rec0 is None or not rec0.versions_in(text):
                        return None
            if not status and (self._REQUEST.match(text or "") or (not asks and self.speaker is not None and self.speaker.tells(text))):
                return None                                 # a request is not a question for the record
            rec = self.__dict__.get("_rec")
            if rec is None:
                import ownrecord
                rec = self._rec = ownrecord.OwnRecord(converse.TREE, self.speaker.A.W)
            from context_record import open_requests
            r = rec.answer(text, open_requests(sid), about_self=selfcue, status_ask=status)
            if not r:
                return None
            return {"status": "answered", "response": r["text"], "path": "converse:record:" + ",".join(r["files"])}
        except Exception:  # noqa: BLE001
            return None

    # Amendment 11
    _GO_ONLY = __import__("re").compile(r"^\s*(?:go|go ahead|do it|please do|read it|write it(?: up)?)\b[\s.!]*$", __import__("re").I)
    _GO = __import__("re").compile(r"^\s*(?:yes|yeah|yep|go|go ahead|do it|sure|ok|okay|please do|read it|write it(?: up)?)\b[\s.!]*$", __import__("re").I)
    _REPORT = __import__("re").compile(
        r"^\s*(?:please\s+|can you\s+|could you\s+)?(?:assess|give me (?:an assessment|a report)(?: of| on)?|write (?:up|an assessment of|a report on)|"
        r"report on|sum up|summari[sz]e)\s+(?:the\s+|this\s+)?(?:release|version|oracle ?7|what (?:we|you) (?:did|built|have built)|where we are|\d{1,2}\.\d)(.*)$",
        __import__("re").I)

    def _report(self, text):
        m = self._REPORT.match(text or "")
        if not m:
            return None
        try:
            import ownrecord, writeup
            rec = self.__dict__.get("_rec")
            if rec is None:
                rec = self._rec = ownrecord.OwnRecord(converse.TREE, self.speaker.A.W)
            vs = rec.versions_in(text)
            return writeup.report(rec, vs[0] if vs else None)
        except Exception:  # noqa: BLE001
            return None

    def _about_offer(self, text, sid):
        """the turn's own subject, if the head holds a record on it that it has not offered in this conversation"""
        try:
            subj = self.speaker.subject(text)
            seen = self.__dict__.setdefault("_about_seen", {}).setdefault(sid, set())
            if not subj or subj.lower() in seen:
                return None
            seen.add(subj.lower())
            h = self.wb.chat_core("What is %s?" % subj, sid + "#about")
            if self._claims_paragraph(subj) and not (h.get("status") == "answered" and subj.lower() in str(h.get("response", "")).lower()):
                h = {"status": "answered", "response": "", "path": "converse:parts"}     # parts3: claims to write from
            if h.get("status") == "answered" and (not h.get("response") or subj.lower() in str(h.get("response", "")).lower()):
                self.__dict__.setdefault("_about", {})[sid] = dict(h, _subject=subj)
                return subj
        except Exception:  # noqa: BLE001
            pass
        return None

    def reply(self, text, sid, head):
        # The reader and linker choose held subjects/relations; the existing
        # sentence parts word their claims and read every sentence back. This
        # accepts a dictionary reading, not only _ACCOUNT's sentence openings.
        related = None
        try:
            # The head's standing answer comes first: discussion words a held
            # claim about a subject the turn names, which on a factual question
            # is a true sentence that does not answer it ("Was Michael Cera born
            # after 1932?" -> "Michael Cera was born in Brampton"; gate c17: 22).
            # A lecture the turn did not ask for does not stand.
            head_stands = False
            try:
                head_stands = bool(head and head.get("status") == "answered" and self.stands(head, text)
                                   and not self._lecture_refused(head, text))
            except Exception:  # noqa: BLE001
                head_stands = False
            if not head_stands and self._SELF.search(text or ""):
                # a question put to Oracle7 about itself ("How do you check your answers?") is its own record's before
                # the discussion part reads "check" as a subject page (11-17)
                own = self._own_record(text, sid)
                if own:
                    return own
            page_answer = None if head_stands else self._page_answer(text, sid)
            if page_answer:
                return page_answer
            discussion = None if head_stands else self._discuss(text, sid)
            if discussion and discussion.get("status") == "offered":
                # related held claims, not an answer: the record, the head on a
                # repaired reading and the other parts go first (below)
                related, discussion = discussion, None
            if discussion and discussion.get("status") == "hole" and str(discussion.get("path", "")).endswith(
                    "discussion:unresolved") and __import__("re").match(r"(?i)^\s*(?:please\s+|can you\s+|could you\s+)?(?:tell me|explain|describe|write)\b", text or ""):
                # 12.0.2: an account asked for that the held parts cannot write ("tell me about the Carrington Event": the
                # subject is held, no sentence on it) offers to read it, like any account it holds nothing for
                am0 = self._ACCOUNT.match(text or "")
                topic0 = " ".join(am0.group(1).split()) if am0 else ""
                if topic0 and len(topic0.split()) <= 8 and not self._SELF_TOPIC.search(topic0):
                    self.__dict__.setdefault("_fw", {})[sid] = topic0
                    return {"status": "hole", "path": str(discussion.get("path")) + ":offer-read",
                            "response": "I hold nothing I can write about %s. I can read about it in Simple English Wikipedia "
                                        "and Wikipedia and write it up with its sources - say go." % topic0}
            if discussion:
                discussion = self._offer_reading(discussion, sid)
                self.observe(text, sid, discussion)
                return discussion
        except Exception as e:  # noqa: BLE001
            self.error = "discussion: " + repr(e)[:200]
        ab = self.__dict__.get("_about") or {}
        if sid in ab and self._TELL.match(text or ""):
            h = ab.pop(sid)                                 # the head's own checked reading, asked for now
            pr = self._prose(h.get("_subject", ""), sid)
            return pr or dict(h, path="about>" + str(h.get("path", "")))
        ab.pop(sid, None)
        fw = self.__dict__.setdefault("_fw", {})
        if sid in fw and self._GO.match(text or ""):         # Amendment 11: read the verified sources and write it up
            topic = fw.pop(sid)
            try:
                import writeup
                keep = __import__("os").path.join(__import__("os").environ.get("ORACLE7_STATE") or __import__("os").path.join(converse.TREE, "workbench", "local"), "read_pages")
                return writeup.write_up(topic, keep_dir=keep)
            except Exception as e:  # noqa: BLE001
                return {"status": "hole", "response": "The reading did not complete: %s" % repr(e)[:160], "path": "writeup:error"}
        fw.pop(sid, None)
        rp = self._report(text)
        if rp:
            return rp
        am = self._ACCOUNT.match(text or "")
        # A field question must never be converted into a fresh prose request:
        # doing that also replaces the saved draft it was asking about.
        if am:
            reader = self.reader or getattr(self.router, 'reader', None)
            if reader is not None and reader.read(text).get('mood') == 'question' and not __import__("re").match(
                    r"(?i)^\s*(?:please\s+|can you\s+|could you\s+)?(?:tell me|explain|describe|write)\b", text or ""):
                am = None                                   # 12.0.2: "Explain why we have day and night" is a request
        if am:
            pr = self._prose(am.group(1), sid)
            if pr:
                return pr
            own = self._own_record(text if (text.rstrip().endswith("?") or self.speaker.asks(text)) else text.rstrip(" .!") + "?", sid)
            if own:
                return own                                  # the record speaks to it: no need to read elsewhere
            topic = " ".join(am.group(1).split())
            if topic and len(topic.split()) <= 8 and not self._SELF_TOPIC.search(topic) and not self._WORK.search(text or ""):
                fw[sid] = topic
                return {"status": "hole", "path": "tool:writeup:offer",
                        "response": "I hold nothing I can write about %s. I can read about it in Simple English Wikipedia and "
                                    "Wikipedia and write it up with its sources - say go." % topic}
        if head.get("status") != "answered" or not self.stands(head, text):
            own = self._own_record(text, sid)               # Amendment 10
            if own:
                return own
        q2 = self.repair(text, sid)
        if q2 and q2 != text:
            h2 = self.wb.chat_core(q2, sid)
            if h2.get("status") == "answered" and self.stands(h2, q2):
                self.observe(q2, sid, h2)
                return dict(h2, path="repair>" + str(h2.get("path", "")), repaired=q2)
            text, head = q2, h2
        if related is not None and head.get("status") != "answered":
            self.observe(text, sid, related)
            return related
        if self._GO_ONLY.match(text or ""):
            # 12.0.1: a go with nothing waiting for it in this conversation is said so; it is not talk to answer ("go" after
            # no offer was met with "( five minutes later ) Now, what are you having?")
            return {"status": "hole", "path": "converse:go:nothing-waiting",
                    "response": "Nothing in this conversation is waiting for a go. Say what you want done or written, and I will "
                                "say what I would do and wait for your go."}
        if self.speaker is not None and self.asks_nothing(text):
            try:
                said, _brought, how = self.speaker.solve(text)
            except Exception as e:  # noqa: BLE001
                said, how = None, repr(e)[:120]
            if said:
                said = __import__("re").sub(r"\b(\w+) (s|re|m|ll|ve|d|t)\b", lambda m: m.group(1) + "'" + m.group(2), said)
                said = __import__("re").sub(r"\bi\b", "I", said)
                said = said[:1].upper() + said[1:]
                subj = self._about_offer(text, sid)
                if subj:
                    said += " I hold something on %s: say \"tell me\" and I read it." % subj
                self.observe(text, sid, {"response": said})
                # the law: talk composed by the speaker is offered, never recorded as an answer
                return {"status": "offered", "response": said, "path": "converse:speaker:" + str(how),
                        "head": {"status": head.get("status"), "path": head.get("path")}}
        self._memo[(sid, text)] = head
        try:
            r = self.router.reply(text, sid)
        except Exception as e:  # noqa: BLE001
            return dict(head, converse_error=repr(e)[:200])
        finally:
            self._memo.pop((sid, text), None)
        r = self._commit(sid, r)
        try:                                                # Amendment 10: no scene move and no essay on a word of the turn
            rp, sp = str(r.get("path", "")), self.speaker   # for a turn that asks or tells; the gap, named
            refused_head = rp.endswith(":head") and self._lecture_refused(head, text)     # a16: not by the router's hand either
            if sp is not None and (refused_head or (("c8:play" in rp or rp.endswith(":essay")) and (sp.tells(text) or sp.asks(text)))):
                if sp.tells(text) and not sp.asks(text):
                    said = ("I can't carry that out: no part of mine does it yet. I have kept it as an open request - ask me "
                            "where things stand and I list it. What I can do here: index, find, read, write, run, fetch, make, "
                            "change and want; answer what I can check; explain what I hold records on.")
                else:
                    said = "I can't answer that from anything I can check."
                r = {"status": "hole", "act": "hole", "response": said, "path": "compose8:gap"}
        except Exception:  # noqa: BLE001
            pass
        try:                                                # Amendment 10: told to do something, and no part of mine did it
            if r.get("status") != "answered" and self.speaker is not None and self.speaker.tells(text):
                r['_open_request'] = text
        except Exception:  # noqa: BLE001
            pass
        # a store read carries its record's citation [wd:Q.. P..]; delivered that way, the question did not go past the checks
        if r.get("status") in ("answered", "offered") and head.get("status") != "answered" and "[wd:Q" in str(r.get("response", "")):
            try:                                                       # Amendment 14 (3): the self organ follows the delivery
                ego = getattr(getattr(self.eng, "_rt", None), "_ego", None)
                if ego is not None and hasattr(ego.mood, "deliver"):
                    ego.mood.deliver("wb-" + sid, "answered", r.get("path"))
            except Exception:  # noqa: BLE001
                pass
        if r.get("status") != "answered":
            return head if (head.get("status") == "answered" and not self._lecture_refused(head, text)) else r
        r = dict(r)
        r["path"] = "converse:" + str(r.get("path", ""))
        r["head"] = {"status": head.get("status"), "path": head.get("path")}
        # the law: reach is not answer. Where the head declined, a composed reply that is not verified against the store is
        # offered, marked as held back (constitution, article 1), never recorded as an answer. (Gate run 1: 325 declined
        # reference questions came back as answers: 158 store readings of an entity in the question, 105 scene moves,
        # 62 holes; all three are reach. One class, one place.)
        if head.get("status") != "answered" and "verified" not in str(r.get("path", "")):
            r["status"] = "offered"
        if str(r.get("path", "")).endswith(":hole") or r.get("act") == "hole":
            r["status"] = "hole"                                           # a hole is a hole, never an answer (gate run 2)
        return r