File size: 42,125 Bytes
d9b105f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""reflect - Oracle7 reflects on its own work, and develops an idea about the world, in the same conversation (12.0 dev,
Amendment 14).

What it reflects on is real: a ledger of every delivered turn of this conversation (what was asked, which part of Oracle7
handled it, the execution receipt: started, finished, exit, check, files, the change made, what was tried), its parts as
its own code describes them (each module's own first docstring line, read from the install, not written here), its frozen
identity, and the thread of ideas the conversation is developing (subjects, claims, deductions, interpretations, the
operator's corrections).

Every sentence it says carries what kind of thing it is:
  checked        a receipt of this conversation, or a claim the store holds         (the record shows it)
  deduction      built from checked steps, with the steps shown                    (examine the steps)
  interpretation a reading that goes beyond the steps                              (useful, not established)
  your claim     what the operator said, held as theirs
A sentence of its own is built from those pieces; nothing is said that has no piece under it. No language model.

  "what parts of yourself did you use for that, and what did each contribute"     the task's ledger, part by part
  "what did the failure reveal about how you approached it"                          failures, what followed, what they show
  "how does this connect to what we discussed earlier"                               shared files, functions, operations, things
  "what is an implication of these two ideas" / "what follows from that"            a chain of the store's claims or the
                                                                                     bench's own laws, never stored whole
  "what would make that wrong"                                                       the premises, and counterexamples found
  "I disagree because ..."                                                           the correction weighed against the premises
  "revisit that given the new result"                                                the thread recomputed from the new receipts
  "let's think about X (and Y)" / "how are X and Y related"                          facts, relations, comparison, consequences"""
import json
import os
import re
import time
from pathlib import Path

NL = chr(10)
WB = Path(__file__).resolve().parent
TREE = WB.parent
HOME = Path(os.environ.get("ORACLE7_BENCH_HOME") or (Path(os.environ.get("ORACLE7_STATE") or Path.home() / ".oracle7") / "bench"))

# which part of Oracle7 a delivered path came from: (path prefix, module file under the install, short name)
PARTS = [
    ("bench:repair", "workbench/repair.py", "the change composer (repair.py)"),
    ("bench:compose", "workbench/compose_code.py", "the code composer (compose_code.py, composer_v3 over value shapes)"),
    ("bench:store", "workbench/code_store.py", "the code store on the Tree of Life spine (functions kept after a passing check, lit by a goal's facts)"),
    ("bench:audit", "workbench/findings.py", "the findings reader (findings.py)"),
    ("bench:fix", "workbench/findings.py", "the findings reader (findings.py)"),
    ("bench:run", "workbench/bench.py", "the bench's runner"),
    ("bench:edit", "workbench/bench.py", "the bench's editor"),
    ("bench:write", "workbench/bench.py", "the bench's editor"),
    ("bench:undo", "workbench/bench.py", "the bench's editor"),
    ("bench:log", "workbench/bench.py", "the bench's log reader"),
    ("bench:solved", "workbench/bench.py", "the bench's log reader"),
    ("bench:", "workbench/bench.py", "the bench"),
    ("tool:make", "workbench/make.py", "the program builder (make.py)"),
    ("tool:want", "workbench/planner.py", "the planner (planner.py)"),
    ("tool:", "workbench/tools.py", "the workspace tools (tools.py)"),
    ("converse:parts", "workbench/converse/parts.py", "the parts writer (parts.py)"),
    ("converse:record", "workbench/converse/ownrecord.py", "the record reader (ownrecord.py)"),
    ("converse:report", "workbench/converse/writeup.py", "the report writer (writeup.py)"),
    ("writeup", "workbench/converse/writeup.py", "the write-up reader (writeup.py)"),
    ("converse:accord", "workbench/converse/accord.py", "the talk forms (accord.py)"),
    ("converse:", "workbench/converse/session.py", "the conversation organ (session.py)"),
    ("learn:", "workbench/learn.py", "the lookup (learn.py)"),
    ("reflect:", "workbench/reflect.py", "reflection (reflect.py)"),
]
KIND = {"checked": "checked", "deduction": "deduction", "interpretation": "interpretation", "yours": "your claim"}


def part_of(path):
    p = str(path or "")
    for pre, f, name in PARTS:
        if p.startswith(pre):
            return name, f
    return "the head (chat_core and its specialists)", "oracle7.py"


def own_words(module):
    """the part's own account of itself: the first line of its docstring, as installed"""
    try:
        s = (TREE / module).read_text(encoding="utf-8", errors="ignore")
        m = re.search(r'^\s*(?:#![^\n]*\n)?\s*(?:#[^\n]*\n)*\s*"""(.*?)(?:\n|""")', s, re.S)
        return " ".join(m.group(1).split())[:220] if m else None
    except Exception:  # noqa: BLE001
        return None


# ---------------------------------------------------------------- the ledger and the thread
def _f(sid):
    HOME.mkdir(parents=True, exist_ok=True)
    return HOME / ("reflect_%s.json" % re.sub(r"[^A-Za-z0-9_-]", "", str(sid))[:60])


def load(sid):
    try:
        return json.load(open(_f(sid)))
    except Exception:  # noqa: BLE001
        return {"ledger": [], "thread": []}


def save(sid, st):
    p = _f(sid)
    tmp = p.with_suffix(".tmp%d" % os.getpid())
    json.dump(st, open(tmp, "w"), indent=1)
    os.replace(tmp, p)


def record(text, sid, r):
    """every delivered turn, once, with its receipt"""
    try:
        st = load(sid)
        ex = r.get("execution") or {}
        # C11: the turn's number is the conversation's own sequence, kept with it; never the length of the recall window
        # (which stops at 400 and gave every later turn the number 401). Turns leaving the window go to the archive, whole.
        seq = int(st.get("seq") or (st["ledger"][-1]["n"] if st["ledger"] else 0)) + 1
        st["seq"] = seq
        st["ledger"].append({"n": seq, "eid": "%s:%d" % (sid, seq), "t": time.time(), "you": str(text), "path": str(r.get("path", "")),
                             "status": r.get("status"), "ex": ex, "said": str(r.get("response", ""))[:600]})
        if len(st["ledger"]) > 400:
            with open(_f(sid).with_suffix(".archive.jsonl"), "a", encoding="utf-8") as fh:
                for e in st["ledger"][:-400]:
                    fh.write(json.dumps(e, default=str) + "\n")
            st["ledger"] = st["ledger"][-400:]
        save(sid, st)
    except Exception:  # noqa: BLE001
        pass


def _say(kind, text, basis=None):
    return {"kind": kind, "text": text, "basis": basis or []}


def _render(lines, head=None):
    out = [head] if head else []
    for ln in lines:
        b = (" [%s]" % "; ".join(str(x) for x in ln["basis"][:4])) if ln["basis"] else ""
        out.append("- (%s) %s%s" % (KIND.get(ln["kind"], ln["kind"]), ln["text"], b))
    return NL.join(out)


def _reply(sid, st, lines, head, path, thread=None):
    if thread:
        thread["t"] = time.time()
        st["thread"].append(thread)
        st["thread"] = st["thread"][-40:]
        save(sid, st)
    return {"status": "answered" if lines else "hole", "path": "reflect:" + path, "response": _render(lines, head),
            "execution": {"state": "read", "kinds": sorted({ln["kind"] for ln in lines})}}


def _task(st):
    """the entries of the current task: back to the last turn that opened an environment or set a new goal"""
    L = [e for e in st["ledger"] if not e["path"].startswith("reflect:")]
    start = 0
    for i, e in enumerate(L):
        if e["path"].startswith("bench:open"):
            start = i
    return L[start:]


# ---------------------------------------------------------------- reflection on its own work
def contribution(e):
    """what this turn's part did, from its receipt"""
    ex, path, said = e.get("ex") or {}, e["path"], e.get("said", "")
    first = said.strip().splitlines()[0] if said.strip() else ""
    st = ex.get("state")
    if path.startswith("bench:repair"):
        if st == "changed-checked":
            return "found %s and made the change \"%s\"; the check passed after it (%s candidate%s tried)" % (
                ex.get("function", "the function"), ex.get("what", "?"), ex.get("tried", "?"), "" if ex.get("tried") == 1 else "s")
        if st == "changed-untested":
            return "made the change \"%s\" in %s; no check tested it" % (ex.get("what", "?"), ex.get("function", "?"))
        if st == "waiting":
            return "stopped to ask for one detail: " + first[:160]
        return "could not compose the change: " + first[:200]
    if path.startswith("bench:run"):
        if st in ("running", "queued"):
            return "started job %s" % ex.get("job")
        if st == "interrupted":
            return "job %s stopped without an exit status: interrupted, outcome not known" % ex.get("job")
        return "ran it: exit %s, %s" % (ex.get("exit"), "passed" if st == "passed" else "failed")
    if path.startswith(("bench:fix", "bench:audit")):
        return first[:200]
    if path.startswith("bench:edit") or path.startswith("bench:write"):
        return "made edit %s to %s as given" % (ex.get("edit"), ", ".join(ex.get("files") or []))
    if path.startswith("bench:open"):
        return first[:200]
    if path.startswith("bench:log"):
        return "read the log of job %s" % ex.get("job")
    return "%s (%s)" % (first[:160], e.get("status"))


def parts_used(sid, st):
    T = _task(st)
    if not T:
        return None
    by = {}
    for e in T:
        name, mod = part_of(e["path"])
        by.setdefault(name, {"mod": mod, "turns": []})["turns"].append(e)
    lines = []
    for name, v in by.items():
        own = own_words(v["mod"])
        lines.append(_say("checked", "%s%s" % (name, (": by its own account, \"%s\"" % own) if own else ""), [v["mod"]]))
        for e in v["turns"][-4:]:
            lines.append(_say("checked", "  turn %d, \"%s\": %s" % (e["n"], e["you"][:70], contribution(e)), ["receipt of turn %d" % e["n"]]))
    states = [(e.get("ex") or {}).get("state") for e in T]
    if "changed-checked" in states or "passed" in states:
        lines.append(_say("deduction", "what made the result stand was the check, not the part that proposed it: a change was kept "
                          "only after a check passed", ["turns %s" % ", ".join(str(e["n"]) for e in T if (e.get("ex") or {}).get("state") in ("changed-checked", "passed"))]))
    return _reply(sid, st, lines, "For this task (since turn %d):" % T[0]["n"], "parts",
                  {"kind": "parts", "subject": "the task", "turns": [e["n"] for e in T]})


SOURCE = {  # where in its own code each kind of failure is decided: (module, a line that only that place carries)
    "bench:repair:locate": ("workbench/repair.py", '"missing": "locate"'),
    "bench:repair:change": ("workbench/repair.py", 'none made the check pass, and each was put back'),
    "bench:repair:check": ("workbench/repair.py", '"missing": "check"'),
    "bench:repair:value": ("workbench/repair.py", '"missing": "value"'),
    "bench:edit:match": ("workbench/bench.py", "it must occur exactly once"),
    "bench:run:interrupted": ("workbench/bench.py", 'j["state"], j["t_end"] = "interrupted"'),
    "bench:run": ("workbench/bench.py", 'j["passed"] = j["exit"] == 0'),
    "bench:fix:authority": ("workbench/bench.py", "Prepared, not applied"),
    "tool:make": ("workbench/tools.py", "it did not run cleanly"),
    "bench:newfn:gap": ("workbench/bench.py", "I could not compose every step of"),
}


def src_line(path):
    """the file and line of its own code that decided an outcome of this kind, read from the install as it is"""
    for pre, (mod, needle) in SOURCE.items():
        if path.startswith(pre):
            try:
                for i, ln in enumerate((TREE / mod).read_text(encoding="utf-8").splitlines(), 1):
                    if needle in ln:
                        return "%s:%d" % (mod, i), ln.strip()[:140]
            except Exception:  # noqa: BLE001
                return None
    return None


REVEAL = [  # (path prefix of the failure, what it shows about the approach)
    ("bench:run:interrupted", "a run stopped without an exit status; I do not assume it finished or that it did nothing, and "
                              "before repeating it I look at what changed"),
    ("bench:newfn:gap", "the program builder composes from the moves it has; a step none of them does is named, not guessed"),
    ("bench:repair:locate", "I find the code by the words of the request and by the frames of a failing run; this request "
                            "named nothing I could match and no run had failed yet, so there was nothing to hold on to"),
    ("bench:repair:change", "the changes I compose are single moves (an operator, a comparison, a term, a constant, a guard); "
                            "none passed the check, so what is needed is more than one move, or a move of another kind"),
    ("bench:repair:check", "with no check in the project I cannot tell a right change from a wrong one unless the request names "
                           "both what the code does and what it should do"),
    ("bench:repair:value", "the request left one thing open (what to give in the empty case) and no test says it, so I asked "
                           "rather than choose"),
    ("bench:edit:match", "an exact edit needs its text to occur once; I do not guess which occurrence was meant"),
    ("bench:run", "the run itself failed: the receipt says so, and the next step reads its log, not my expectation"),
    ("bench:fix:authority", "I prepared the correction but did not apply it: this conversation could only read"),
    ("tool:make", "the program builder put the steps together but one step failed when run, and its repair loop could not mend it"),
]


def _job_now(sid, L):
    """a turn that started a job reported it running; what became of the job is read now, from the bench (a job interrupted
    or failed after its turn is a failure of that turn: acceptance I3, run 2)"""
    try:
        import bench as _b
        env = _b.Turn(sid).env
        if env is None:
            return L
        jobs = {j["id"]: j for j in _b._jobs(env)}
    except Exception:  # noqa: BLE001
        return L
    out = []
    for e in L:
        ex = e.get("ex") or {}
        j = jobs.get(ex.get("job")) if ex.get("job") else None
        if j and ex.get("state") in ("running", "queued") and j["state"] in ("interrupted", "finished"):
            st = "interrupted" if j["state"] == "interrupted" else ("passed" if j.get("passed") else "failed")
            e = dict(e, ex=dict(ex, state=st, exit=j.get("exit")), path="bench:run:interrupted" if st == "interrupted" else e["path"],
                     said=(j.get("result") or e.get("said", "")))
        out.append(e)
    return out


def failures(sid, st):
    L = _job_now(sid, [e for e in st["ledger"] if not e["path"].startswith("reflect:")])
    bad = [e for e in L if (e.get("ex") or {}).get("state") in ("failed", "missing", "blocked", "refused", "interrupted") or
           (e["status"] == "hole" and e["path"].startswith(("bench:", "tool:")))]
    if not bad:
        return _reply(sid, st, [_say("checked", "nothing failed in this conversation's work so far", ["%d turns" % len(L)])],
                      None, "failure")
    lines = []
    for e in bad[-4:]:
        lines.append(_say("checked", "turn %d (\"%s\") did not succeed: %s" % (e["n"], e["you"][:70], contribution(e)),
                          ["receipt of turn %d" % e["n"]]))
        why = next((w for pre, w in REVEAL if e["path"].startswith(pre)), None)
        if why:
            lines.append(_say("deduction", "it shows that " + why, ["path %s" % e["path"]]))
        sl = src_line(e["path"])
        if sl:
            lines.append(_say("checked", "the place in my code that decided it: %s  `%s`" % sl, [sl[0]]))
        caps = (e.get("ex") or {}).get("caps") or {}
        if caps:
            lines.append(_say("checked", "the search reached its own limit%s: %s" % ("s" if len(caps) > 1 else "", ", ".join(
                "%s = %s" % kv for kv in sorted(caps.items()))), ["receipt of turn %d" % e["n"]]))
        after = [x for x in L if x["n"] > e["n"] and (x.get("ex") or {}).get("state") in ("changed-checked", "passed")]
        if after:
            x = after[0]
            lines.append(_say("checked", "what changed the outcome: turn %d (\"%s\"): %s" % (x["n"], x["you"][:60], contribution(x)),
                              ["receipt of turn %d" % x["n"]]))
            if x["path"].startswith("bench:repair") and e["path"].startswith("bench:run"):
                lines.append(_say("interpretation", "the failure was useful to me: its frames and its assertion told me where to "
                                  "look, and the same test then judged the change", ["turns %d, %d" % (e["n"], x["n"])]))
        else:
            lines.append(_say("checked", "nothing after it has passed yet: it is still open", []))
    return _reply(sid, st, lines, None, "failure", {"kind": "failure", "turns": [e["n"] for e in bad]})


# ---------------------------------------------------------------- the world: things, relations, implications
_ST = {}


def store():
    if "p" not in _ST:
        import sys
        sys.path[:0] = [str(WB / "converse")]
        import parts as P
        _ST["p"] = P.Parts(str(TREE), str(WB / "converse" / "data" / "parts" / "parts.json"))
    return _ST["p"]


def qid(name):
    P = store()
    t = " ".join(name.strip(" .?!,'\"").split())
    best = None
    for c in dict.fromkeys((t, t[:1].upper() + t[1:], t.title(), "The " + t.title(), t.lower())):
        q = P.S.qid_of_title(c)
        if q is not None:
            n = len(P.S.facts(q))
            if best is None or n > best[1]:
                best = (q, n)
    return best[0] if best else None


def plabel(p):
    P = store()
    lab = (P.S.props.get(p) or ("", ""))[1]
    if not lab or re.fullmatch(r"P\d+", str(lab)):
        al = [a for a in P.S.alias.get(p, []) if a]
        lab = al[0] if al else "P%d" % p
    return str(lab)


SKIP_P = {5008, 1889, 910, 1343, 373, 935, 8402, 2184, 1151, 1424}   # the store's housekeeping: lists, "not to be confused with", categories


def claim_text(s, p, o):
    P = store()
    t = P.say(s, p, o)
    return t or "%s - %s - %s" % (P.S.label(s), plabel(p), P.S.label(o))


TRANSITIVE = {131: "located in", 361: "part of", 279: "subclass of", 17: "country", 276: "location"}


def relate(a, b):
    """how two things are related in the store: direct claims, shared objects, chains of two"""
    P = store()
    fa = [x for x in P.S.facts(a)[:600] if x[0] not in SKIP_P]
    fb = [x for x in P.S.facts(b)[:600] if x[0] not in SKIP_P]
    direct = [(a, p, o) for p, o in fa if o == b] + [(b, p, o) for p, o in fb if o == a]
    oa, ob = {}, {}
    for p, o in fa:
        oa.setdefault(o, []).append(p)
    for p, o in fb:
        ob.setdefault(o, []).append(p)
    shared = [(o, oa[o][0], ob[o][0]) for o in oa if o in ob and o not in (a, b)]
    shared.sort(key=lambda x: -P.S.links(x[0]))
    return direct, shared[:6]


def think(sid, st, names):
    P = store()
    qs = [(n, qid(n)) for n in names]
    missing = [n for n, q in qs if q is None]
    if missing:
        return {"status": "hole", "path": "reflect:think:missing", "execution": {"state": "missing"},
                "response": "I hold no record that I can match to %s, so I have nothing checked to think with about %s. "
                            "Give me another name for it, or say go and I'll read about it." % (", ".join(missing), " and ".join(missing))}
    lines = []
    for n, q in qs:
        r = P.about(q, limit=5)
        if r:
            for (s, p, o) in r["claims"]:
                if p in SKIP_P:
                    continue
                lines.append(_say("checked", claim_text(s, p, o), ["wd:Q%d P%d" % (s, p)]))
    thread = {"kind": "think", "subjects": [[n, q] for n, q in qs], "claims": [], "premises": []}
    if len(qs) >= 2:
        (na, a), (nb, b) = qs[0], qs[1]
        direct, shared = relate(a, b)
        for s, p, o in direct[:3]:
            lines.append(_say("checked", claim_text(s, p, o), ["wd:Q%d P%d" % (s, p)]))
            thread["claims"].append([s, p, o])
        for o, pa, pb in shared[:3]:
            lines.append(_say("checked", "%s and %s both have %s as %s / %s" % (P.S.label(a), P.S.label(b), P.S.label(o),
                                                                              plabel(pa), plabel(pb)),
                              ["wd:Q%d P%d Q%d" % (a, pa, o), "wd:Q%d P%d Q%d" % (b, pb, o)]))
            thread["claims"] += [[a, pa, o], [b, pb, o]]
        if not direct and not shared:
            lines.append(_say("checked", "the store holds no claim joining %s and %s directly or through one shared thing" % (
                P.S.label(a), P.S.label(b)), []))
    return _reply(sid, st, lines, "What I hold on %s:" % " and ".join(P.S.label(q) for _n, q in qs), "think", thread)


def _last(st, kinds):
    for th in reversed(st["thread"]):
        if th["kind"] in kinds:
            return th
    return None


LAWS = [  # the bench's own laws as conditionals (read in bench.py / repair.py docstrings); id, if, then
    ("L1", "a change is kept", "a check passed after it"),
    ("L2", "a check passed before a change and after it", "the check does not test the change"),
    ("L3", "the check does not test the change", "the change is reported as changed, not yet tested"),
    ("L4", "a run fails", "its receipt says failed and its status is never answered"),
    ("L5", "a fix needs more moves than one", "no fix is found"),
    ("L6", "no fix is found", "the task stays open and the missing step is named"),
    ("L7", "a conversation may only read", "a prepared correction waits for allow changes and go"),
]


def law_instances(ledger):
    """the turns of this conversation that are cases of each law: what the receipts show the rules doing"""
    out = {}
    for e in ledger:
        ex, path = e.get("ex") or {}, e["path"]
        st = ex.get("state")
        if st == "changed-checked":
            out.setdefault("L1", []).append(e["n"])
        if st == "changed-untested" and ex.get("check") == "not testing this":
            out.setdefault("L2", []).append(e["n"])
        if st == "changed-untested":
            out.setdefault("L3", []).append(e["n"])
        if st == "failed" and path.startswith("bench:run"):
            out.setdefault("L4", []).append(e["n"])
        if path.startswith("bench:repair:change"):
            out.setdefault("L5", []).append(e["n"])
        if st in ("missing", "waiting") and path.startswith(("bench:repair", "bench:newfn")):
            out.setdefault("L6", []).append(e["n"])
        if path.startswith("bench:fix:authority"):
            out.setdefault("L7", []).append(e["n"])
    return out


def chain_laws(seed=None):
    """two laws whose then is the other's if: a conditional no file states whole"""
    out = []
    for i1, if1, th1 in LAWS:
        for i2, if2, th2 in LAWS:
            if i1 != i2 and th1 == if2:
                out.append((i1, i2, if1, th2, th1))
    if seed:
        out.sort(key=lambda c: -len(set(seed.lower().split()) & set((c[2] + " " + c[3]).lower().split())))
    return out


def _idea(st):
    """the idea under discussion: the last thread that carries one (things with claims, or rules), not a connect or a question
    about it; a correction or a falsification carries its idea forward"""
    for th in reversed(st["thread"]):
        if th.get("subjects") or th.get("laws") or [x for x in th.get("premises", []) if len(x) == 3]:
            return th
    return None


def implication(sid, st):
    th = _idea(st) or _last(st, ("parts", "failure"))
    if th and th["kind"] in ("think", "implication") and len(th.get("subjects", [])) >= 2:
        P = store()
        (na, a), (nb, b) = th["subjects"][:2]
        lines, prem = [], []
        for x, nx in ((a, na), (b, nb)):
            for p, o in P.S.facts(x)[:400]:
                if p not in TRANSITIVE:
                    continue
                for p2, o2 in P.S.facts(o)[:200]:
                    if p2 == p and o2 not in (a, b) and not P.S.holds(x, p, o2):
                        lines.append(_say("deduction", "%s is %s %s, which is %s %s; so %s is %s %s - a claim the store does not "
                                          "hold in one piece" % (P.S.label(x), TRANSITIVE[p], P.S.label(o), TRANSITIVE[p],
                                                                 P.S.label(o2), P.S.label(x), TRANSITIVE[p], P.S.label(o2)),
                                          ["wd:Q%d P%d Q%d" % (x, p, o), "wd:Q%d P%d Q%d" % (o, p, o2)]))
                        prem += [[x, p, o], [o, p, o2]]
                        break
                if len(lines) >= 2:
                    break
        direct, shared = relate(a, b)
        if shared:
            o, pa, pb = shared[0]
            if pa == pb:
                lines.append(_say("interpretation", "since %s and %s share %s as %s, what is true of %s through that %s may bear on "
                                  "both; that is a reading of the link, not a claim the store makes" % (
                                      P.S.label(a), P.S.label(b), P.S.label(o), plabel(pa), P.S.label(o), plabel(pa)),
                                  ["wd:Q%d P%d Q%d" % (a, pa, o), "wd:Q%d P%d Q%d" % (b, pb, o)]))
                prem += [[a, pa, o], [b, pb, o]]
        if not lines:
            return _reply(sid, st, [_say("checked", "from what I hold on %s and %s I can build no step the store does not already "
                                         "hold; I won't offer one with nothing under it" % (P.S.label(a), P.S.label(b)), [])],
                          None, "implication")
        return _reply(sid, st, lines, "Built from claims I hold, not stored as such:", "implication",
                      {"kind": "implication", "subjects": th["subjects"], "premises": prem, "lines": [l["text"] for l in lines]})
    seed = " ".join(e["you"] for e in st["ledger"][-6:])
    ch = chain_laws(seed)
    if not ch:
        return None
    i1, i2, if1, th2, mid = ch[0]
    lines = [_say("checked", "%s: if %s, then %s" % (i1, LAWS[[l[0] for l in LAWS].index(i1)][1], mid), ["bench.py / repair.py"]),
             _say("checked", "%s: if %s, then %s" % (i2, mid, th2), ["bench.py / repair.py"]),
             _say("deduction", "so: if %s, then %s" % (if1, th2), [i1, i2])]
    rec = [e for e in st["ledger"] if (e.get("ex") or {}).get("state") == "changed-untested"]
    if rec and "check" in if1:
        lines.append(_say("interpretation", "that is what happened at turn %d: a passing check was not evidence for the change" % rec[-1]["n"],
                          ["receipt of turn %d" % rec[-1]["n"]]))
    return _reply(sid, st, lines, "An implication of two of my own rules, not written anywhere as one:", "implication",
                  {"kind": "implication", "laws": [i1, i2], "premises": [[i1], [i2]], "lines": [l["text"] for l in lines]})


def falsify(sid, st):
    th = _idea(st) or _last(st, ("failure", "parts"))
    if not th:
        return None
    lines = []
    if th.get("laws"):
        for lid in th["laws"]:
            l = next(x for x in LAWS if x[0] == lid)
            lines.append(_say("deduction", "it is wrong if %s does not hold: if %s and yet not %s" % (lid, l[1], l[2]), [lid]))
        lines.append(_say("checked", "a test of that: a run where a change was kept with no check passing after it would break %s; "
                          "no receipt in this conversation shows one" % th["laws"][0], ["%d turns" % len(st["ledger"])]))
    for s, p, o in [tuple(x) for x in th.get("premises", []) if len(x) == 3][:4]:
        P = store()
        lines.append(_say("deduction", "it rests on \"%s\"; if that claim is wrong, what was built on it falls" % claim_text(s, p, o),
                          ["wd:Q%d P%d" % (s, p)]))
    if th["kind"] == "implication" and any("interpretation" in t for t in th.get("lines", [])) or th.get("subjects"):
        lines.append(_say("interpretation", "a shared link is not a shared property: two things in one place need not share what "
                          "that place has; one counterexample of that kind defeats the reading", []))
    if th.get("yours"):
        lines.append(_say("yours", "and your point stands against it: " + th["yours"][-1], []))
    return _reply(sid, st, lines, "What would make that wrong:", "falsify",
                  dict(th, kind="falsify", of=th["kind"]))          # the idea is carried forward, laws and premises with it


NEG = re.compile(r"(?i)\b(?:not|isn't|is not|aren't|doesn't|does not|never|no longer|wasn't|false|wrong|untrue)\b")


def disagree(sid, st, text):
    th = _idea(st) or _last(st, ("failure", "parts"))
    why = re.sub(r"(?i)^\s*(?:i\s+)?(?:disagree|don't agree|do not agree|that's not right|that is not right|no)[,:]?\s*(?:because|since|as)?\s*", "", text).strip()
    if not th:
        return None
    words = {w.lower() for w in re.findall(r"[A-Za-z]{4,}", why)}
    hit = []
    for lid in th.get("laws", []):
        l = next(x for x in LAWS if x[0] == lid)
        if words & set((l[1] + " " + l[2]).lower().split()):
            hit.append(("law", lid, l))
    P = None
    prem = [x for x in th.get("premises", []) if len(x) == 3]
    pm = re.match(r"(?i)^(.+?)\s+(?:is|are|was|were)\s+not\s+(?:(?:located|situated)\s+in|part of|in|on|a|an|the)?\s*(.+?)\s*[.!]?$", why)
    if pm and prem:                                  # "X is not (in) Y": the step whose two ends are X and Y, exactly
        P = store()
        xs, ys = pm.group(1).strip().lower(), pm.group(2).strip().lower()
        exact = [x for x in prem if str(P.S.label(x[0]) or "").lower() == xs and str(P.S.label(x[2]) or "").lower() == ys]
        for x in exact:
            hit.append(("claim", x, None))
    if not hit:
        for x in prem:
            P = P or store()
            lab = " ".join(str(P.S.label(q) or "") for q in (x[0], x[2])).lower()
            if words & set(lab.split()):
                hit.append(("claim", x, None))
    lines = [_say("yours", why or text, [])]
    negates = bool(NEG.search(why))
    if hit and negates:
        for kind, what, l in hit[:2]:
            if kind == "law":
                lines.append(_say("checked", "that disputes %s (if %s, then %s), which the conclusion rested on" % (what, l[1], l[2]), [what]))
            else:
                lines.append(_say("checked", "that disputes \"%s\", a step it rested on" % claim_text(*what), ["wd:Q%d P%d" % (what[0], what[1])]))
        lines.append(_say("deduction", "so the conclusion no longer follows; I withdraw it until the disputed step is settled", []))
        rec = [e for e in st["ledger"] if (e.get("ex") or {}).get("state")]
        if any(kind == "law" for kind, _w, _l in hit):
            lines.append(_say("checked", "what the record can settle: %d receipts in this conversation; ask me to check them against "
                              "your point (\"revisit that\")" % len(rec), []))
        status = "withdrawn"
    elif hit:
        lines.append(_say("deduction", "it touches %s without denying it; I keep the conclusion with your point as a condition on it" % (
            ", ".join(h[1] if h[0] == "law" else claim_text(*h[1]) for h in hit[:2])), []))
        status = "conditioned"
    else:
        lines.append(_say("deduction", "it does not meet any step the conclusion rested on (%s), so the conclusion stands; your "
                          "point is held as yours alongside it" % ", ".join(th.get("laws") or [claim_text(*x) for x in th.get("premises", []) if len(x) == 3][:2] or ["its steps"]), []))
        status = "unaffected"
    new = dict(th, kind="revised", status=status, yours=(th.get("yours") or []) + [why or text])
    return _reply(sid, st, lines, None, "disagree", new)


def revisit(sid, st):
    th = _idea(st) or _last(st, ("failure", "parts"))
    if not th:
        return None
    L = [e for e in st["ledger"] if not e["path"].startswith("reflect:")]
    since = [e for e in L if e["t"] > th.get("t", 0)]
    lines = [_say("checked", "since that (%d turn%s of work): %s" % (len(since), "" if len(since) == 1 else "s",
                                                                    "; ".join("turn %d %s" % (e["n"], contribution(e)[:90]) for e in since[-3:]) or "nothing"),
                  ["receipts"])]
    if th.get("laws"):
        broke = [e for e in since if (e.get("ex") or {}).get("state") == "changed-checked" and "passed" not in contribution(e)]
        held = [e for e in since if (e.get("ex") or {}).get("state") in ("changed-checked", "changed-untested", "passed", "failed")]
        if broke:
            lines.append(_say("deduction", "turn %d is a counterexample to %s: the conclusion falls" % (broke[0]["n"], th["laws"][0]), []))
        elif held:
            lines.append(_say("deduction", "the new receipts agree with %s: %s" % (" and ".join(th["laws"]), "; ".join(
                "turn %d %s" % (e["n"], (e.get("ex") or {}).get("state")) for e in held[-3:])), ["receipts"]))
        if th.get("status") == "withdrawn" and held and not broke:
            lines.append(_say("deduction", "your objection disputed one of those rules; the new receipts show it holding in %d more "
                              "case%s, so I'd restore the conclusion, with your objection still on record" % (len(held), "" if len(held) == 1 else "s"),
                              ["receipts"]))
    if th["kind"] in ("failure", "parts"):
        return failures(sid, st) if th["kind"] == "failure" else parts_used(sid, st)
    if th.get("subjects") and not th.get("laws"):
        lines.append(_say("checked", "the work since does not touch %s; what I said about it stands as it was" % " and ".join(
            n for n, _q in th["subjects"]), []))
    return _reply(sid, st, lines, "Revisiting what I said:", "revisit", dict(th, kind=th["kind"], t=time.time()))


def connect(sid, st):
    L = [e for e in st["ledger"] if not e["path"].startswith("reflect:")]
    if len(L) < 2:
        return None
    cur = L[-1]
    cw = _keys(cur)
    best = []
    for e in L[:-1]:
        sh = cw & _keys(e)
        if sh:
            best.append((len(sh), e, sh))
    th_subj = [th for th in st["thread"] if th.get("subjects")]
    lines = []
    for n, e, sh in sorted(best, key=lambda x: -x[0])[:3]:
        lines.append(_say("checked", "turn %d (\"%s\") and the last turn share %s" % (e["n"], e["you"][:60], ", ".join(sorted(sh)[:5])),
                          ["turns %d, %d" % (e["n"], cur["n"])]))
    # the work through its rules: which turns are cases of which of the bench's laws, and which laws chain
    inst = law_instances(L)
    for lid, turns in sorted(inst.items()):
        l = next(x for x in LAWS if x[0] == lid)
        lines.append(_say("checked", "turn%s %s %s a case of %s (if %s, then %s)" % ("s" if len(turns) > 1 else "", ", ".join(map(str, turns[-4:])),
                                                                                   "are" if len(turns) > 1 else "is", lid, l[1], l[2]),
                          ["receipts of turns %s" % ", ".join(map(str, turns[-4:]))]))
    for i1, i2, if1, th2, mid in chain_laws():
        if i1 in inst and i2 in inst:
            lines.append(_say("deduction", "%s and %s chain through those turns: if %s, then %s" % (i1, i2, if1, th2), [i1, i2]))
    # ideas through the store: an earlier thing and a later thing, joined by a claim or a shared thing
    if len(th_subj) >= 2:
        a_s, b_s = th_subj[-2]["subjects"], th_subj[-1]["subjects"]
        for na, qa in a_s[:2]:
            for nb, qb in b_s[:2]:
                if qa == qb:
                    continue
                direct, shared = relate(qa, qb)
                for s, p, o in direct[:1]:
                    lines.append(_say("checked", claim_text(s, p, o), ["wd:Q%d P%d" % (s, p)]))
                for o, pa, pb in shared[:1]:
                    lines.append(_say("checked", "%s (earlier) and %s (now) both have %s as %s" % (na, nb, store().S.label(o), plabel(pa)),
                                      ["wd:Q%d P%d Q%d" % (qa, pa, o), "wd:Q%d P%d Q%d" % (qb, pb, o)]))
    if th_subj and inst:
        s = th_subj[-1]["subjects"]
        lines.append(_say("interpretation", "the thread on %s and the work share a method, not a subject: what I said about %s stands on "
                          "claims I can cite, and each result of the work stands on a receipt; no claim I hold joins the two subjects" % (
                              " and ".join(x[0] for x in s), s[0][0]), []))
    if not lines:
        lines.append(_say("checked", "the last turn shares no file, function, operation or named thing with anything earlier here", []))
    return _reply(sid, st, lines, None, "connect", {"kind": "connect", "turns": [e["n"] for _n, e, _s in best[:3]]})


_STOPK = set("what that this with from have your about there their them they then than were when will would could should "
             "into just like make made does done again also only very more most some such".split())


def _keys(e):
    ex = e.get("ex") or {}
    ks = {w.lower() for w in re.findall(r"[A-Za-z_][A-Za-z0-9_]{3,}", e["you"] + " " + " ".join(ex.get("files") or []) + " " +
                                         str(ex.get("function") or ""))}
    return {k for k in ks if k not in _STOPK}


# ---------------------------------------------------------------- the door
_PARTS = re.compile(r"(?i)\b(?:what|which) (?:parts?|pieces?) (?:of (?:yourself|you)\s+)?(?:did you use|were used|did you draw on)|"
                    r"\bwhat did each (?:part )?contribute\b|\bhow did you do (?:that|it)\b")
_FAIL = re.compile(r"(?i)\bwhat did (?:the |that |those )?(?:failures?|mistakes?|errors?) (?:reveal|show|teach|tell)|"
                   r"\bwhat (?:did you learn|does it reveal) from (?:the |that )?(?:failure|mistake)|\bwhy did (?:you|it) fail at first\b")
_CONNECT = re.compile(r"(?i)\bhow does (?:this|that|it) (?:connect|relate|tie) (?:to|with|back)|\bconnect (?:this|that) to (?:what|our|the earlier)")
_IMPL = re.compile(r"(?i)\b(?:an?|the|what(?:'s| is)(?: an?| the)?) implications?\b|\bwhat follows from\b|\bwhat does that imply\b|"
                   r"\bconsequences? of (?:these|those|the) two\b")
_FALS = re.compile(r"(?i)\bwhat would (?:make|prove|show) (?:that|this|it)(?: \w+){0,2} (?:wrong|false|fail|mistaken)|"
                   r"\bhow could (?:that|this)(?: \w+)? be wrong|\bcounter-?examples?\b|\bwhat would (?:falsify|refute|undermine)\b")
_DIS = re.compile(r"(?i)^\s*(?:i\s+)?(?:disagree|don't agree|do not agree|that's not right|that is not right)\b")
_REV = re.compile(r"(?i)\brevisit\b|\b(?:given|with|in light of) (?:the|this|that) new result\b|\bdoes (?:the|this|that) (?:new )?result change\b")
_THINK = re.compile(r"(?i)^\s*(?:let'?s think about|think about|what do you make of|reflect on|how (?:are|is) (.+?) (?:and|related to) (.+?) related)\s*(.*?)\s*\??$")
_REL = re.compile(r"(?i)^\s*(?:how (?:are|is)|what(?:'s| is) the (?:relationship|connection|link) between)\s+(.+?)\s+(?:and|to)\s+(.+?)(?:\s+related| connected)?\s*\??$")


def claims(text, sid):
    """this turn is reflection's (so the bench does not read it as a change to make): asked about its own work or the thread"""
    t = (text or "").strip()
    st = load(sid)
    if not (st["ledger"] or st["thread"]):
        return False
    return bool(_PARTS.search(t) or _FAIL.search(t) or _FALS.search(t) or (_DIS.match(t) and st["thread"]) or
                (_REV.search(t) and st["thread"]) or _IMPL.search(t) or _CONNECT.search(t))


def after_head(text, sid, head):
    """things to think about, asked as a question the head may answer: only where the head did not answer"""
    t = (text or "").strip()
    if head.get("status") == "answered":
        return None
    m = _REL.match(t)
    if not m:
        return None
    st = load(sid)
    try:
        return think(sid, st, [m.group(1), m.group(2)])
    except Exception:  # noqa: BLE001
        return None


def handle(text, sid="default"):
    t = (text or "").strip()
    if not t:
        return None
    st = load(sid)
    work = any(e["path"].startswith(("bench:", "tool:")) for e in st["ledger"]) or bool(st["thread"])
    try:
        m = re.match(r"(?i)^\s*(?:let'?s think about|think about|what do you make of|reflect on)\s+(.+?)\s*\??$", t)
        if m:
            names = re.split(r"\s+and\s+", m.group(1), maxsplit=1)
            return think(sid, st, names)
        if not work:
            return None                                  # nothing done here yet to reflect on: the chat is unchanged
        if _PARTS.search(t) and st["ledger"]:
            return parts_used(sid, st)
        if _FAIL.search(t) and st["ledger"]:
            return failures(sid, st)
        if _FALS.search(t) and st["thread"]:
            return falsify(sid, st)
        if _DIS.match(t) and st["thread"]:
            return disagree(sid, st, t)
        if _REV.search(t) and st["thread"]:
            return revisit(sid, st)
        if _IMPL.search(t) and (st["thread"] or st["ledger"]):
            return implication(sid, st)
        if _CONNECT.search(t) and st["ledger"]:
            return connect(sid, st)
    except Exception as e:  # noqa: BLE001
        return {"status": "hole", "path": "reflect:error", "response": "Reflection did not complete: %s" % repr(e)[:240],
                "execution": {"state": "failed"}}
    return None