File size: 6,258 Bytes
9542666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""The end-of-wave checklist as ONE command (analyze-paper, Close the loop).

The checklist is mechanical, so it lives here rather than as prose an agent has
to replay in the right order. One run:

  1. regenerates every derived file (GENERATORS, in order);
  2. runs every health check, scoped to the wave where the check supports it;
  3. prints the wave metrics (edge mix, against-share vs the vault's) and a
     random sample of the wave's stance edges for the extraction spot-audit.

It decides nothing: the report ends with the judgment calls left to the session
(integrity errors, dupe/chronology adjudication, retro-edge reading list,
spot-audit). After acting on them, rerun with --generate so the derived files
match the final notes, then commit.

    python3 _scripts/end_of_wave.py                         # wave = new notes vs git HEAD
    python3 _scripts/end_of_wave.py --papers a,b --ideas x  # explicit wave
    python3 _scripts/end_of_wave.py --generate              # step 1 only
    python3 _scripts/end_of_wave.py --strict                # exit 1 on integrity ERRORs

The default wave is read from git: notes under papers/ influences/ ideas/ that
are untracked or added since HEAD (i.e. the uncommitted wave).
"""
import os
import random
import re
import subprocess
import sys
from collections import Counter

VAULT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
S = os.path.join(VAULT, "_scripts")
GENERATORS = ["make_ideas_index", "make_methods_index", "make_bib", "make_authors",
              "make_toread", "make_similarity", "make_families", "make_status"]
STANCE_RE = re.compile(r"^(first-mention|argues-for|argues-against|nuances|tests)::\s*(.*)$", re.M)
SAMPLE = 10


def run(script, *args):
    r = subprocess.run([sys.executable, os.path.join(S, script + ".py"), *args],
                       cwd=VAULT, capture_output=True, text=True)
    return r.returncode, (r.stdout + r.stderr).rstrip()


def wave_from_git():
    out = subprocess.run(["git", "status", "--porcelain", "--untracked-files=all",
                          "papers", "influences", "ideas"],
                         cwd=VAULT, capture_output=True, text=True).stdout
    papers, ideas = [], []
    for ln in out.splitlines():
        code, path = ln[:2], ln[3:].strip().strip('"')
        if not path.endswith(".md") or not ("?" in code or "A" in code):
            continue
        slug = os.path.basename(path)[:-3]
        (ideas if path.startswith("ideas/") else papers).append(slug)
    return sorted(papers), sorted(ideas)


def opt(args, name):
    if name in args:
        return [s.strip() for s in args[args.index(name) + 1].split(",") if s.strip()]
    return None


def section(title):
    print(f"\n{'=' * 8} {title} {'=' * max(0, 60 - len(title))}")


def edges_of(slug):
    for d in ("papers", "influences"):
        p = os.path.join(VAULT, d, slug + ".md")
        if os.path.exists(p):
            return STANCE_RE.findall(open(p, encoding="utf-8").read())
    return []


def main():
    args = sys.argv[1:]
    section("1. regenerate derived files")
    for g in GENERATORS:
        code, out = run(g)
        last = out.splitlines()[-1] if out else ""
        print(f"  {'OK ' if code == 0 else 'ERR'} {g}: {last[:110]}")
        if code:
            print(out)
    if "--generate" in args:
        return 0

    papers, ideas = wave_from_git()
    papers = opt(args, "--papers") or papers
    ideas = opt(args, "--ideas") or ideas
    print(f"\n  wave: {len(papers)} papers {papers}\n        {len(ideas)} new ideas {ideas}")

    section("2a. integrity (whole vault)")
    code, out = run("check_integrity")
    errs = 0
    for ln in out.splitlines():
        if ln.startswith("===") or ln.startswith("summary") or \
                any(f"] {p}" in ln or f"[[{p}]]" in ln or f" {p}:" in ln for p in papers + ideas):
            print(ln)
        m = re.match(r"summary: (\d+) errors", ln)
        errs = int(m.group(1)) if m else errs
    print("  (warnings above are filtered to the wave; run check_integrity.py for all)")

    section("2b. slug dupes / year drift")
    _, out = run("check_slug_dupes")
    keep = [ln for ln in out.splitlines() if "CANDIDATE" not in ln and "same-author" not in ln]
    print("\n".join(keep))

    if ideas:
        section("2c. idea near-duplicates (new ideas only)")
        print(run("check_idea_dupes", "--new", ",".join(ideas))[1])
        section("2d. retro-edge reading list (new ideas)")
        print(run("suggest_retro_edges", "--new", ",".join(ideas))[1])
    if papers:
        section("2e. first-mention chronology (wave papers)")
        print(run("check_chronology", *papers)[1])

    section("3. wave metrics")
    wave = Counter(k for p in papers for k, _ in edges_of(p))
    vault = Counter()
    for d in ("papers", "influences"):
        for f in os.listdir(os.path.join(VAULT, d)):
            if f.endswith(".md"):
                vault.update(k for k, _ in edges_of(f[:-3]))

    def share(c):
        votes = c["argues-for"] + c["first-mention"] + c["argues-against"]
        return f"{100 * c['argues-against'] / votes:.1f}%" if votes else "n/a"
    print("  edge mix (wave): " + ", ".join(f"{k} {v}" for k, v in wave.most_common()))
    print(f"  against-share of stance votes: wave {share(wave)} | vault {share(vault)}"
          "  (low = the related-work disagreement pass may be thin)")

    section(f"4. spot-audit sample ({SAMPLE} stance edges; verify vs pdf/<slug>.txt)")
    pool = [(p, k, v) for p in papers for k, v in edges_of(p)]
    random.seed(" ".join(papers))
    for p, k, v in random.sample(pool, min(SAMPLE, len(pool))):
        txt = "txt" if os.path.exists(os.path.join(VAULT, "pdf", p + ".txt")) else "NO TXT"
        print(f"  [{txt}] {p}: {k}:: {v[:140]}")

    section("left to you")
    print("  - fix every integrity ERROR; adjudicate 2b-2e; add retro-edges only where the\n"
          "    candidate note already supports them; verify the spot-audit sample and\n"
          "    report its error rate; then: python3 _scripts/end_of_wave.py --generate\n"
          "    and make the single batch commit.")
    return 1 if ("--strict" in args and errs) else 0


if __name__ == "__main__":
    sys.exit(main())