File size: 34,529 Bytes
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
"""continuation - the receive-and-continue specialist (12.0 C11). It takes part in every project turn of the bench: it receives

the turn against the project of the environment that is open (never another's), decides whether going again can bring

anything new, keeps the attempts and what each one showed, chooses a materially different next step when an attempt

showed nothing new, runs a long turn as a job that stays observable and stoppable and survives a restart, and makes a

checked capability of Oracle7's own discoverable, invokable and usable as a part of later projects.



  WHAT IT TAKES IN     the turn's words, the project kept for the open environment, the attempt record, the turn jobs,

                       Oracle7's code store and its registry of adopted capabilities

  WHERE IT GOES        the project's own record (.oracle7/project.json: attempts, the step chosen, the project id), the

                       bench's state (turn_jobs.json, capabilities.json), the reply's receipt (execution.continuation)



THE ENVIRONMENT      a project belongs to the environment it was received in (env key + a project id kept in its record);

                     opening another environment puts the project away under its own environment and brings back the one

                     kept for the new one. A project from another environment is never revised by this one's words.

AN ATTEMPT           every project turn is an attempt: its input fingerprint (the project's words, meanings, drops and

                     examples; the files it reads; the store and the registry) and its outcome signature (the state, the

                     holes, each requirement's status, what the judge saw). A retry whose inputs are the inputs of an

                     attempt that did not finish would show the same thing again: it is not run. A retry whose inputs

                     changed is run (a useful retry). A job whose log grows is progressing; one whose log is still is not.

THE NEXT STEP        when going again would show nothing new (or did), the next step is chosen from what the record shows,

                     never the step already taken for that same outcome: a part that fills the hole (a kept function, an

                     adopted capability that makes the missing file), a discriminating check (the command run and what it

                     printed against what the requirement wants), a changed hypothesis (a word read as the column it is

                     nearest to), a candidate repair (the traceback's line), and last a focused question naming the one hole.

DONE                 is the judge's, requirement by requirement on what the program did; this module never says done.

No language model."""
import hashlib
import json
import os
import re
import shlex
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path

NL = chr(10)
WB = Path(__file__).resolve().parent


def _home():
    import bench
    return bench.HOME


def _sha(obj):
    return hashlib.sha256(json.dumps(obj, sort_keys=True, default=str).encode()).hexdigest()[:16]


def _load(p, default):
    try:
        return json.loads(Path(p).read_text(encoding="utf-8"))
    except Exception:  # noqa: BLE001
        return default


def _save(p, obj):
    p = Path(p)
    p.parent.mkdir(parents=True, exist_ok=True)
    tmp = p.with_name(p.name + ".tmp%d.%d" % (os.getpid(), threading.get_ident()))
    try:
        tmp.write_text(json.dumps(obj, indent=1, default=str), encoding="utf-8")
        # Windows can briefly deny replacement while a reader/scanner has the
        # target open. Retry the same complete bytes, never a partial write.
        for delay in (0, .01, .02, .04, .08, .16, .32, .64):
            if delay:
                time.sleep(delay)
            try:
                os.replace(tmp, p)
                break
            except PermissionError:
                if os.name != "nt" or delay == .64:
                    raise
    finally:
        if tmp.exists():
            try:
                tmp.unlink()
            except OSError:
                pass


# ---------------------------------------------------------------- the environment's project
def switch(turn, new_env_d):
    """called as an environment is opened: the project of the old environment is put away under it, the one kept for the

    new environment (in this conversation) comes back; candidates of Oracle7 itself are not an environment's"""
    import bench
    old = turn.s.get("env")
    projs = turn.s.setdefault("projects", {})
    works = turn.s.setdefault("works", {})
    focuses = turn.s.setdefault("environment_focus", {})
    cur = turn.s.get("project")
    if old:
        old_key = bench.Env(old).key
        if cur is not None:
            projs[old_key] = cur
        work = turn.s.get("work")
        if work is not None and work.get("env") == old_key:
            works[old_key] = work
        if turn.s.get("focus") in ("project", "work"):
            focuses[old_key] = turn.s["focus"]
    key = bench.Env(new_env_d).key
    turn.s["project"] = projs.get(key)
    turn.s["work"] = works.get(key)
    turn.s["focus"] = focuses.get(key) or ("project" if projs.get(key) else "work" if works.get(key) else None)
    return turn.s["project"]


def bind(turn, env):
    """the project kept for this environment, or None; a project received in another environment is put away under it"""
    cur = turn.s.get("project")
    if cur is not None and cur.get("env") not in (None, env.key):
        turn.s.setdefault("projects", {})[cur["env"]] = cur
        turn.s["project"] = turn.s["projects"].get(env.key)
        cur = turn.s["project"]
    return cur


def stamp(shape, env):
    """the project's identity: its id (kept for its life) and the environment it belongs to"""
    shape.setdefault("pid", uuid.uuid4().hex[:12])
    shape["env"] = env.key
    shape["env_root"] = env.root
    return shape


# ---------------------------------------------------------------- attempts
def _files_of(shape, root):
    names = set()
    import project as PJ
    for c in shape.get("clauses") or []:
        names.update(PJ.DATA.findall(c))
    if shape.get("module"):
        names.add(shape["module"])
    out = {}
    for n in sorted(names):
        p = Path(root) / n
        try:
            st = p.stat()
            digest = hashlib.sha256()
            with p.open("rb") as stream:
                for chunk in iter(lambda: stream.read(1024 * 1024), b""):
                    digest.update(chunk)
            out[n] = [st.st_size, st.st_mtime_ns, digest.hexdigest()]
        except OSError:
            out[n] = None
    return out


def _store_mark():
    try:
        import code_store as CS
        p = CS.store_path()
        st = p.stat()
        return [st.st_size, int(st.st_mtime)]
    except Exception:  # noqa: BLE001
        return None


def fingerprint(shape, root, authority=None):
    """what an attempt depends on: the project's words and fills, the files it reads, the store, the registry, and the

    authority it ran under (12.0 C31: which hosts it may reach, whether it may change files). A grant changes what the

    same words can do, so it reopens the obligation; an unchanged retry still matches and is not run again."""
    keep = {k: shape.get(k) for k in ("clauses", "dropped", "meanings", "examples", "use", "module", "entries",
                                    "source_fills", "scope_fills")}
    return _sha([keep, _files_of(shape, root), _store_mark(), _load(_reg_path(), []), authority or {}])


def outcome_sig(reply, shape):
    ex = reply.get("execution") or {}
    holes = sorted(h.get("text", "")[:200] for h in (shape.get("holes_kept") or []))
    reqs = sorted((r.get("id"), r.get("status")) for r in ex.get("requirements") or [])
    judged = [ln for ln in (reply.get("response") or "").splitlines() if ln.startswith("  - ")][:20]
    return _sha([ex.get("state"), holes, reqs, judged])


def record(shape, text, reply, fp, cont=None):
    """one attempt kept in the project's record, numbered by the project's own sequence (never by a window's length)"""
    shape["seq"] = int(shape.get("seq") or 0) + 1
    a = {"seq": shape["seq"], "t": time.time(), "text": text, "state": (reply.get("execution") or {}).get("state"),
         "fp": fp, "sig": outcome_sig(reply, shape), "cont": cont}
    shape.setdefault("attempts", []).append(a)
    if len(shape["attempts"]) > 300:                  # the record keeps its first and its latest; the sequence goes on
        shape["attempts"] = shape["attempts"][:20] + shape["attempts"][-280:]
    return a


UNFINISHED = ("missing", "failed", "interrupted", "blocked", "refused")


def unchanged_retry(shape, root, text, authority=None):
    """the attempt whose inputs this turn would repeat exactly, when that attempt did not finish; else None"""
    import project as PJ
    if not PJ.CONTINUE.match(text.strip()):
        return None
    att = shape.get("attempts") or []
    if not att or att[-1].get("state") not in UNFINISHED:
        return None
    return att[-1] if att[-1].get("fp") == fingerprint(shape, root, authority) else None


def same_outcome_run(shape):
    """how many attempts in a row ended with the same outcome (1 = the latest is new)"""
    att = shape.get("attempts") or []
    n = 0
    for a in reversed(att):
        if att and a.get("sig") == att[-1].get("sig"):
            n += 1
        else:
            break
    return n


# ---------------------------------------------------------------- the next step
def _words(s):
    return [w for w in re.findall(r"[a-z][a-z0-9_]+", (s or "").lower()) if len(w) > 2]


def _near(word, options):
    """the option nearest a word by shared letters in order (a column a word may have meant)"""
    import difflib
    m = difflib.get_close_matches(word.lower(), [o.lower() for o in options], n=1, cutoff=0.72)
    if not m:
        return None
    return next(o for o in options if o.lower() == m[0])


def _parts_for(hole, shape):
    """a kept part that fills this hole: an adopted capability that makes the missing file, or a kept function whose words

    meet the hole's words. -> (kind, record) or None"""
    if hole.get("kind") == "world" and hole.get("file"):
        for c in capabilities():
            if hole["file"] in (c.get("outputs") or []):
                return "capability", c
    ws = set(hole.get("words") or []) | set(_words(hole.get("name", ""))) | set(_words(hole.get("col", "")))
    if not ws:
        return None
    try:
        import code_store as CS
        best = None
        for e in CS.load():
            ew = set(_words(e.get("name", ""))) | {w.lower() for w in (e.get("words") or [])}
            hit = len(ws & ew)
            if hit and (best is None or hit > best[0]):
                best = (hit, e)
        if best:
            return "function", best[1]
    except Exception:  # noqa: BLE001
        pass
    return None


def _columns(shape, root):
    import project as PJ
    cols = []
    for c in shape.get("clauses") or []:
        for f in PJ.DATA.findall(c):
            try:
                t = PJ.read_table(root, f)
                cols += list((t or {}).get("columns") or [])
            except Exception:  # noqa: BLE001
                continue
    return list(dict.fromkeys(cols))


def _run_entry(shape, root, runenv=None):
    """the project's first command run once, its exit and last lines: the discriminating check"""
    ents = shape.get("entries") or {}
    name = next((n for n, e in ents.items() if "PORT" not in e.get("args", [])), None)
    if not name or not shape.get("module") or not (Path(root) / shape["module"]).is_file():
        return None
    cmd = [sys.executable, shape["module"], name] + list(ents[name].get("args") or [])
    try:
        r = subprocess.run(cmd, cwd=root, capture_output=True, text=True, timeout=60, env=runenv)
        return {"cmd": " ".join(shlex.quote(x) for x in ["python3"] + cmd[1:]), "exit": r.returncode,
                "out": (r.stdout + r.stderr).strip().splitlines()[-12:]}
    except subprocess.TimeoutExpired:
        return {"cmd": " ".join(cmd[1:]), "exit": None, "out": ["ran past 60 s and was stopped"]}


def choose(turn, shape, root, reply, used=(), runenv=None):
    """the next step when an attempt showed nothing new: the first kind the record supports that was not already taken for

    this outcome. -> {"kind", "text", "do"?: what was done}"""
    holes = list(shape.get("holes_kept") or [])
    resp = reply.get("response") or ""
    tried = set(used)
    # 1. a part that fills a hole
    if "part" not in tried:
        for h in holes:
            got = _parts_for(h, shape)
            if not got:
                continue
            kind, rec = got
            if kind == "capability" and turn is not None and turn.env is not None and turn.s.get("authority") == "change":
                ran = invoke(rec, turn.env.root, why="the project's missing %s" % h["file"])
                if ran["ok"]:
                    return {"kind": "part", "rerun": True,
                            "text": "%s was missing; my adopted capability %s makes it (sha %s, judged when it was adopted), so I "
                                    "ran it here: %s, exit 0. Going on with the project." % (
                                        h["file"], rec["name"], rec["sha256"][:12], ran["cmd"])}
                return {"kind": "part", "text": "%s is missing; my capability %s makes it, but running it here failed (exit %s): %s" % (
                    h["file"], rec["name"], ran["exit"], " / ".join(ran["out"][-3:]))}
            if kind == "function":
                return {"kind": "part", "text": "For %s, my store keeps %s (sha %s, from %s), whose words meet this one's. If it is "
                                                "what you mean, say \"%s means %s\" or give two examples." % (
                                                    h.get("req") or h.get("file") or "the hole", rec["name"], rec["sha256"][:12],
                                                    rec.get("project") or "earlier work",
                                                    (h.get("words") or [rec["name"]])[0], rec["name"].replace("_", " "))}
    # 2. a discriminating check: the command run once, against what the judge wanted
    if "check" not in tried and (reply.get("execution") or {}).get("state") == "failed":
        r = _run_entry(shape, root, runenv)
        if r:
            want = [ln.strip() for ln in resp.splitlines() if ln.startswith("  - ")][:3]
            return {"kind": "check", "text": "I ran `%s` once more to see what it does, not to retry: exit %s; it printed: %s. What the "
                                             "requirements wanted and did not get: %s." % (
                                                 r["cmd"], r["exit"], " | ".join(r["out"][-6:]) or "nothing",
                                                 "; ".join(w.lstrip("- ") for w in want) or "see the judge lines above")}
    # 3. a changed hypothesis: an unread word read as the column it is nearest to
    if "hypothesis" not in tried:
        cols = _columns(shape, root)
        for h in holes:
            for w in h.get("words") or []:
                c = _near(w, cols)
                if c and c.lower() != w.lower():
                    return {"kind": "hypothesis", "text": "A different reading: '%s' may be the column '%s' of the table (the "
                                                          "nearest by its letters). If so, say \"%s means %s\"; if not, say what "
                                                          "it means." % (w, c, w, c)}
    # 4. a candidate repair: the traceback's own line
    if "repair" not in tried:
        tb = re.findall(r'File "([^"]+)", line (\d+)', resp)
        if tb:
            f, ln = tb[-1]
            return {"kind": "repair", "text": "The program stopped at %s line %s. Say \"fix %s\" and I compose a repair for that line "
                                              "against the failing requirement." % (os.path.basename(f), ln, os.path.basename(f))}
    # 5. a focused question: the one hole first in line, and the forms an answer can take
    if holes:
        h = holes[0]
        forms = {"unread": "\"%s means ...\" (rows, a column, an operation), or \"drop %s\"" % (
                    (h.get("words") or ["it"])[0], (h.get("req") or "R?")[1:]),
                 "world": "add %s to the folder and say \"it's there now\"" % (h.get("file") or "the table"),
                 "derive": "two or three examples (\"3 -> 9\")",
                 "compose": "examples of other kinds of value (a zero, a negative, a word)",
                 "outcome": "the file to write instead, or \"drop\" with its number"}.get(h.get("kind"), "what it means, or drop it")
        return {"kind": "ask", "text": "One thing stands in the way: %s It can be answered as %s." % (
            h.get("text", "").rstrip(".") + ".", forms)}
    return {"kind": "ask", "text": "The project did not change and I have no new step to take; tell me what to look at."}


def used_for(shape, sig):
    """the steps already taken after attempts that ended with this outcome"""
    return {a.get("cont") for a in shape.get("attempts") or [] if a.get("sig") == sig and a.get("cont")}


# ---------------------------------------------------------------- turn jobs: long work observable, stoppable, kept
_TJ = threading.RLock()
_LIVE = {}            # job id -> {"thread", "stop": Event, "result"}
_LOCAL = threading.local()


class Stopped(BaseException):
    """a stop asked for (not an error: the routes' own error handling must not turn it into a reply)"""


def _tj_path():
    return _home() / "turn_jobs.json"


def _tj_all():
    with _TJ:
        # An unreadable existing ledger is not an empty ledger. Treating it as
        # empty could forget a running request or erase earlier completions.
        for delay in (0, .01, .02, .04, .08, .16, .32, .64):
            if delay:
                time.sleep(delay)
            try:
                jobs = json.loads(_tj_path().read_text(encoding="utf-8"))
                break
            except FileNotFoundError:
                jobs = []
                break
            except PermissionError:
                if os.name != "nt" or delay == .64:
                    raise
        if not isinstance(jobs, list):
            raise ValueError("the turn receipt file is not a job list")
        # A completed worker remains completed if its metadata write failed.
        # Do not let a stale on-disk 'running' record block this process forever.
        return [dict(_LIVE.get(j["id"], {}).get("terminal") or j) for j in jobs]


def _tj_put(j):
    with _TJ:
        live = _LIVE.get(j["id"])
        old = (live or {}).get("terminal")
        if old and old.get("state") != "running" and j.get("state") == "running":
            # A poll/stage snapshot taken before completion may only acknowledge
            # it; it cannot resurrect a finished worker.
            j = dict(old, **{key: j[key] for key in ("shown", "told", "resumed", "stop_asked") if key in j})
        # Publish the known execution outcome before any filesystem operation,
        # including the read needed to merge this receipt into the ledger.
        if live is not None:
            live["record"] = dict(j)
            if j.get("state") != "running":
                live["terminal"] = dict(j)
        try:
            existing = _tj_all()
            old = next((x for x in existing if x["id"] == j["id"]), None)
            if old and old.get("state") != "running" and j.get("state") == "running":
                j = dict(old, **{key: j[key] for key in ("shown", "told", "resumed", "stop_asked") if key in j})
            js = [x for x in existing if x["id"] != j["id"]] + [j]
            js.sort(key=lambda entry: entry.get("t", 0))
            _save(_tj_path(), js[-200:])
            if live is not None:
                live.pop("storage_error", None)
                if isinstance(live.get("terminal"), dict):    # 12.0 C29: a later save that succeeds clears the earlier warning
                    live["terminal"].pop("storage_error", None)
                r = live.get("result")
                if isinstance(r, dict) and (r.get("turn_receipt") or {}).get("saved") is False:
                    r["turn_receipt"] = {"saved": True}
                    r["response"] = str(r.get("response", "")).replace(_RECEIPT_NOTE, "")
        except (OSError, ValueError) as error:
            if live is None or j.get("state") == "running":
                raise
            # The execution outcome is known, but its durability is not. Keep
            # that distinction visible instead of reporting a phantom worker.
            live["storage_error"] = repr(error)
            live["terminal"]["storage_error"] = repr(error)
        return j


_RECEIPT_NOTE = "\n\nThe work returned, but its turn receipt could not be saved. The completion is available in this running session."


def _receipt_note(live):
    r = live.get("result")
    if r is not None and live.get("storage_error"):
        if "turn_receipt" not in r:
            r["response"] = str(r.get("response", "")) + _RECEIPT_NOTE
        r["turn_receipt"] = {"saved": False, "error": live["storage_error"]}


def _tj_mark_interrupted():
    """on load: a turn job left running by an earlier process was interrupted by its end (said so, never 'running' forever)"""
    try:
        js = _tj_all()
    except Exception:  # noqa: BLE001
        return
    ch = False
    for j in js:
        if j.get("state") == "running" and j.get("pid") != os.getpid():
            j["state"], j["t_end"], ch = "interrupted", time.time(), True
    if ch:
        _save(_tj_path(), js)


def stage(name):
    """the stage a turn job is at (shown by status); a stop asked for is honoured here, between stages"""
    jid = getattr(_LOCAL, "jid", None)
    if not jid:
        return
    live = _LIVE.get(jid)
    if live and live["stop"].is_set():
        raise Stopped(name)
    j = next((x for x in _tj_all() if x["id"] == jid), None)
    if j:
        j["stage"], j["t_stage"] = name, time.time()
        j.setdefault("stages", []).append([name, round(time.time() - j["t"], 2)])
        _tj_put(j)


def stop_requested():
    """C14: has a stop been asked of the turn job this thread runs (for work inside a stage, like the composer's child)"""
    live = _LIVE.get(getattr(_LOCAL, "jid", None) or "")
    return bool(live and live["stop"].is_set())


def active(sid):
    """the conversation's newest turn job, if it is running or finished and not yet shown"""
    js = [j for j in _tj_all() if j.get("sid") == sid]
    if not js:
        return None
    j = max(js, key=lambda entry: entry.get("t", 0))
    # C11b: a request cut off or stopped stays one to take up again until it is taken up ("resumed"); being told about it
    # ("told") does not use that up (accept38 H8, first run: a status before "continue" lost the request)
    if j["state"] == "running" or (j["state"] == "finished" and not j.get("shown")) or \
            (j["state"] in ("interrupted", "stopped") and not j.get("resumed")):
        return j
    return None


STATUSQ = re.compile(r"(?i)^\s*(?:ok(?:ay)?[\s,]*)?(?:status|where are we(?: at| now)?|how(?:'s| is) it going|is it done\??|"
                     r"what(?:'s| is) (?:happening|running)|progress)\s*[?.!]*$")
STOPQ = re.compile(r"(?i)^\s*(?:stop|stop it|stop that|cancel(?: it| that| the job)?|abort|halt)\s*[.!]*$")


def _job_text(j):
    st = ", ".join("%s at %.1fs" % (s, t) for s, t in (j.get("stages") or [])[-6:])
    return "job %s (\"%s\"): %s%s, started %ds ago%s" % (
        j["id"], j["text"][:80], j["state"], (" at " + j["stage"]) if j.get("stage") else "", int(time.time() - j["t"]),
        ("; stages: " + st) if st else "")


def intercept(sid, text):
    """before a turn: while this conversation has a turn job running, status and stop are answered from its record and any

    other words wait (so two turns never change one project at once); a finished job's result is given once"""
    j = active(sid)
    if j is None:
        return None
    t = text.strip()
    if j["state"] == "running":
        if STOPQ.match(t):
            live = _LIVE.get(j["id"])
            if live:
                live["stop"].set()
            j["stop_asked"] = time.time()
            _tj_put(j)
            return {"status": "offered", "path": "turn:stop", "response": "Stopping %s at its next stage (it is at %s). What it "
                    "kept so far stays kept; \"continue\" goes on from there." % (j["id"], j.get("stage") or "its start"),
                    "execution": {"state": "running", "job": j["id"], "stop": True}}
        return {"status": "offered", "path": "turn:running", "response": "Still working: %s. Say \"stop\" to stop it at its next "
                "stage; other requests wait until it is done." % _job_text(j),
                "execution": {"state": "running", "job": j["id"], "stage": j.get("stage")}}
    import project as PJ
    if j["state"] in ("interrupted", "stopped") and PJ.CONTINUE.match(t):
        j["shown"] = j["resumed"] = True               # the request that was cut off, taken up again from its own words
        _tj_put(j)
        return {"resume": j}
    if j["state"] == "interrupted" and STATUSQ.match(t):
        j["told"] = True
        _tj_put(j)
        return {"status": "hole", "path": "turn:interrupted", "response": "%s - it was cut off (the harness stopped while it ran), "
                "so what it would have finished is not known. Say \"continue\" and I take that request up again from its "
                "own words." % _job_text(j), "execution": {"state": "interrupted", "job": j["id"]}}
    if j["state"] in ("finished", "stopped") and STATUSQ.match(t) and not j.get("told"):
        j["shown"] = True
        j["told"] = True
        _tj_put(j)
        r = dict(j.get("result") or {"status": "hole", "response": "(no result was kept)", "path": "turn:lost"})
        r["response"] = "%s finished:%s%s" % (_job_text(j), NL, r.get("response", ""))
        return r
    return None


def run_turn(fn, sid, text, deadline):
    """a turn that may run long: started as a job; its reply if it ends within the deadline, else the job's id, and the

    result kept for status"""
    jid = uuid.uuid4().hex[:10]
    j = {"id": jid, "sid": sid, "text": text, "t": time.time(), "state": "running", "pid": os.getpid(), "stage": "received"}
    try:
        _tj_put(j)
    except (OSError, ValueError) as error:
        return {"status": "hole", "path": "turn:storage", "response": "The work did not start because its turn receipt could not be saved: %s" % error,
                "execution": {"state": "failed", "started": False}}
    live = {"stop": threading.Event(), "result": None}
    _LIVE[jid] = live

    def work():
        _LOCAL.jid = jid
        try:
            r = fn()
            state = "finished"
        except Stopped as e:
            r = {"status": "hole", "path": "turn:stopped", "response": "Stopped at %s, as asked. The project is kept as it was "
                 "before that stage; \"continue\" goes on." % e, "execution": {"state": "interrupted", "job": jid}}
            state = "stopped"
        except Exception as e:  # noqa: BLE001
            r = {"status": "hole", "path": "turn:error", "response": "That did not complete: %r" % e, "execution": {"state": "failed"}}
            state = "finished"
        live["result"] = r
        jj = dict(live.get("record") or j)
        jj.update(state=state, t_end=time.time(), result=r)
        _tj_put(jj)
        _receipt_note(live)

    th = threading.Thread(target=work, daemon=True)
    th.start()
    th.join(deadline)
    if not th.is_alive():
        jj = dict(live.get("terminal") or j)
        jj["shown"] = True
        _tj_put(jj)
        _receipt_note(live)
        return live["result"]
    return {"status": "offered", "path": "turn:running", "response": "This is taking longer than %d s, so it goes on as job %s "
            "(now at %s). Say \"status\" to see it or get its result, \"stop\" to stop it at its next stage." % (
                deadline, jid, (next((x for x in _tj_all() if x["id"] == jid), j)).get("stage")),
            "execution": {"state": "running", "job": jid}}


try:
    _tj_mark_interrupted()
except Exception:  # noqa: BLE001
    pass


# ---------------------------------------------------------------- capabilities of Oracle7's own (selfdev adopts, here kept)
def _reg_path():
    return WB / "self" / "capabilities.json"


def capabilities():
    return [c for c in _load(_reg_path(), []) if not c.get("retired")]


def register(cap):
    """a checked capability in the registry the head reads: what it is, how it is called, what it reads and makes, its source

    sha, its dependencies, the checks it passed, and (later) each use"""
    reg = [c for c in _load(_reg_path(), []) if c["name"] != cap["name"]]
    cap.setdefault("uses", [])
    cap["registered"] = time.time()
    reg.append(cap)
    _save(_reg_path(), reg)
    return cap


def _note_use(name, use):
    reg = _load(_reg_path(), [])
    for c in reg:
        if c["name"] == name:
            c.setdefault("uses", []).append(use)
            c["uses"] = c["uses"][-200:]
    _save(_reg_path(), reg)


def invoke(cap, cwd, why=""):
    """run a capability (its own command, in cwd: what it makes lands there); the use is recorded with its outcome"""
    t = time.time()
    try:
        r = subprocess.run([sys.executable, cap["path"]] + cap["argv"], cwd=cwd, capture_output=True, text=True, timeout=300)
        ok, code, out = r.returncode == 0, r.returncode, (r.stdout + r.stderr).strip().splitlines()
    except subprocess.TimeoutExpired:
        ok, code, out = False, None, ["ran past 300 s and was stopped"]
    made = [f for f in cap.get("outputs") or [] if (Path(cwd) / f).is_file() and (Path(cwd) / f).stat().st_mtime >= t - 1]
    _note_use(cap["name"], {"t": t, "cwd": str(cwd), "why": why, "exit": code, "made": made})
    return {"ok": ok and all(f in made for f in cap.get("outputs") or []), "exit": code, "out": out[-40:], "made": made,
            "cmd": "python3 %s %s" % (cap["path"], " ".join(cap["argv"]))}


LISTQ = re.compile(r"(?i)\b(?:what|which)\b.*\b(?:have you (?:added|built|adopted) (?:to|into) yourself|capabilities (?:have )?you "
                   r"(?:built|added|adopted)|did you (?:add|build) (?:to|into) yourself|(?:own|adopted|new) capabilit(?:y|ies))\b")


def capability_for(text, caps=None):
    """the adopted capability this turn calls by its own words, or None; nothing is run (the conversation's ownership

    check asks this before any receiver takes the turn)"""
    caps = capabilities() if caps is None else caps
    t = (text or "").strip()
    import project as PJ
    if PJ.BUILD.search(t) or PJ.ENTRY.search(t) or re.search(r"(?i)\b(?:in)?to\s+(?:yourself|oracle7)\b", t):
        return None                                  # C11c: a turn that builds (or rebuilds) is a project, not a call
    tw = set(_words(t))
    best = None
    for c in caps:
        key = set(c.get("words") or [])
        if not key:
            continue
        hit = len(tw & key) / len(key)
        named = c["name"].lower() in t.lower() or c["entry"].lower() in tw
        if (hit >= 0.6 or (named and hit >= 0.3)) and (best is None or hit > best[0]):
            best = (hit, c)
    return best[1] if best else None


def capability_turn(text, sid):
    """the head's door to Oracle7's adopted capabilities: listed with their records, or one invoked by its own words"""
    caps = capabilities()
    t = text.strip()
    if LISTQ.search(t):
        if not caps:
            return {"status": "answered", "path": "self:capabilities", "response": "I have adopted no capability of my own yet.",
                    "execution": {"state": "read"}}
        lines = ["Capabilities I built into myself and adopted, each judged before it was adopted:"]
        for c in caps:
            lines.append("- %s: %s. Called by `%s %s`; reads %s; makes %s; source sha %s; checks: %s; used %d time%s%s." % (
                c["name"], c["request"][:160], os.path.basename(c["path"]), " ".join(c["argv"]),
                ", ".join(c.get("reads") or []) or "nothing", ", ".join(c.get("outputs") or []) or "printed lines",
                c["sha256"][:12], "; ".join(c.get("checks") or []), len(c.get("uses") or []),
                "" if len(c.get("uses") or []) == 1 else "s",
                (" (last: %s)" % c["uses"][-1].get("why", "")[:80]) if c.get("uses") else ""))
        return {"status": "answered", "path": "self:capabilities", "response": NL.join(lines),
                "execution": {"state": "read", "capabilities": [c["name"] for c in caps]}}
    c = capability_for(t, caps)
    if c is None:
        return None
    import bench
    cwd = bench.Turn(sid).s.get("env") or {}
    cwd = cwd.get("root") if cwd.get("kind") == "folder" and bench.Turn(sid).s.get("authority") == "change" else str(WB / "self" / c["name"])
    ran = invoke(c, cwd, why=t[:200])
    body = NL.join("  " + x for x in ran["out"]) or "  (nothing printed)"
    return {"status": "answered" if ran["ok"] else "hole", "path": "self:capability:" + c["name"],
            "response": "That is my capability %s (adopted, sha %s): `%s` in %s, exit %s.%s%s%s" % (
                c["name"], c["sha256"][:12], ran["cmd"], cwd, ran["exit"], NL, body,
                (NL + "It made: " + ", ".join(ran["made"])) if ran["made"] else ""),
            "execution": {"state": "passed" if ran["ok"] else "failed", "capability": c["name"], "sha256": c["sha256"],
                          "files": ran["made"]}}