File size: 17,318 Bytes
7a838c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AutoCode product-study: create, source-link and gate a product blueprint.

Standard library only (Python 3.8+). Works on <root>/<slug>/blueprint.md next
to the sources.json that fetch_public.py produced.

Usage:
  blueprint.py init <slug> --product NAME [--site URL] [--goal TEXT] [--root DIR] [--force]
      Copy references/blueprint-template.md into place with the header filled in,
      then append the Sources section from sources.json.
  blueprint.py sources <slug> [--root DIR]
      Regenerate the "## Sources" section from sources.json (run after fetching more).
  blueprint.py check <slug> [--root DIR]
      Gate: every claim carries a source and a confidence tag, sources exist, no
      placeholders, no copied sentences, no asset links or long code blocks, MVP
      cut within size. Exit 0 = pass, 1 = fail. Prints one line per check.
  blueprint.py mvp <slug> [--root DIR]
      Extract the MVP cut (sections 9 and 10 + header) into mvp.md: the hand-off
      to the build phase. Refuses while section 9 still has TODO.
"""
import argparse
import datetime
import json
import os
import re
import sys

DEFAULT_ROOT = os.path.join(".autocode", "study")
HERE = os.path.dirname(os.path.abspath(__file__))
TEMPLATE = os.path.join(HERE, "..", "references", "blueprint-template.md")

CONF_WORDS = {"high": "high", "medium": "medium", "guess": "guess", "高": "high", "中": "medium", "推测": "guess"}
CONF_RE = re.compile(r"\{(high|medium|guess|高|中|推测)\}")
REF_BRACKET_RE = re.compile(r"\[((?:\s*S\d+\s*[,,;;]?\s*)+)\]")
REF_CELL_RE = re.compile(r"^(?:\s*S\d+\s*[,,;;]?\s*)+$")
S_RE = re.compile(r"S(\d+)")
IMAGE_RE = re.compile(r"https?://\S+\.(png|jpe?g|gif|svg|webp|ico)(\?\S*)?", re.I)
LOGO_RE = re.compile(r"https?://\S*logo\S*", re.I)
CJK_RE = re.compile(r"[぀-ヿ㐀-䶿一-鿿가-힯]")
CLAIM_SECTIONS = set(range(1, 9))
MAX_OBJECTS, MAX_SCREENS, MAX_CODE_LINES = 5, 7, 15


def paths(slug, root):
    d = os.path.join(root, slug)
    return d, os.path.join(d, "blueprint.md"), os.path.join(d, "sources.json"), os.path.join(d, "mvp.md")


def load_sources(index_path):
    if not os.path.exists(index_path):
        return None
    with open(index_path, encoding="utf-8") as f:
        return json.load(f)


def sources_section(index, study_dir):
    lines = ["## Sources", "", "<!-- Generated by `blueprint.py sources <slug>` from sources.json. Do not edit by hand. -->", ""]
    if not index or not index.get("sources"):
        lines.append("- (no sources collected yet: run fetch_public.py first)")
    for s in (index or {}).get("sources", []):
        day = (s.get("fetched_at") or "")[:10]
        extra = " · license %s" % s["license"] if s.get("license") else ""
        lines.append("- [%s] %s — %s (fetched %s, sha256 %s%s)" % (s["id"], s.get("title") or "", s.get("url"), day, (s.get("sha256") or "")[:12], extra))
    skipped = (index or {}).get("skipped", [])
    if skipped:
        lines += ["", "Refused or skipped (out of scope by policy, not used):", ""]
        for s in skipped:
            lines.append("- %s — %s" % (s.get("url"), s.get("reason")))
    lines.append("")
    return "\n".join(lines)


def replace_sources(text, section):
    m = re.search(r"^## Sources\b.*", text, re.M | re.S)
    body = text[: m.start()] if m else text.rstrip() + "\n\n"
    return body.rstrip() + "\n\n" + section


def cmd_init(args):
    study_dir, bp, idx, _ = paths(args.slug, args.root)
    os.makedirs(study_dir, exist_ok=True)
    if os.path.exists(bp) and not args.force:
        print("%s exists; use --force to overwrite" % bp)
        return 1
    if not os.path.exists(TEMPLATE):
        print("template missing: %s" % TEMPLATE)
        return 1
    with open(TEMPLATE, encoding="utf-8") as f:
        text = f.read()
    today = datetime.datetime.now(datetime.timezone.utc).date().isoformat()  # UTC, same clock as fetch stamps
    text = text.replace("# Product blueprint: TODO product name", "# Product blueprint: %s" % args.product, 1)
    header = "Product: %s · Official site: %s · Studied on: %s · Goal: %s" % (
        args.product, args.site or "TODO url", today, args.goal or "TODO one sentence on what the user wants to build and for whom")
    text = re.sub(r"^Product: TODO name .*$", lambda m: header, text, count=1, flags=re.M)
    text = replace_sources(text, sources_section(load_sources(idx), study_dir))
    with open(bp, "w", encoding="utf-8") as f:
        f.write(text)
    print("created %s" % bp)
    return 0


def cmd_sources(args):
    study_dir, bp, idx, _ = paths(args.slug, args.root)
    if not os.path.exists(bp):
        print("no blueprint yet: run init first")
        return 1
    with open(bp, encoding="utf-8") as f:
        text = f.read()
    text = replace_sources(text, sources_section(load_sources(idx), study_dir))
    with open(bp, "w", encoding="utf-8") as f:
        f.write(text)
    print("sources section refreshed in %s" % bp)
    return 0


# ---------------------------------------------------------------- check

def strip_comments(text):
    return re.sub(r"<!--.*?-->", "", text, flags=re.S)


def split_sections(text):
    """Return list of (section_key, [lines]); key is int for numbered, 'sources', or 'head'."""
    sections, key, buf = [], "head", []
    for line in text.splitlines():
        m = re.match(r"^## (\d+)\.", line)
        if m:
            sections.append((key, buf))
            key, buf = int(m.group(1)), []
            continue
        if re.match(r"^## Sources\b", line):
            sections.append((key, buf))
            key, buf = "sources", []
            continue
        buf.append(line)
    sections.append((key, buf))
    return sections


def claim_lines(lines):
    """Bullets and table body rows. Yields (line_no, line, is_table_row)."""
    out = []
    for i, line in enumerate(lines):
        s = line.strip()
        if re.match(r"^[-*] ", s):
            out.append((i, s, False))
        elif s.startswith("|"):
            if re.match(r"^\|\s*:?-{2,}", s):
                continue  # separator
            nxt = lines[i + 1].strip() if i + 1 < len(lines) else ""
            if re.match(r"^\|\s*:?-{2,}", nxt):
                continue  # header row
            out.append((i, s, True))
    return out


def normalize(s):
    s = re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s)
    s = re.sub(r"\{[^}]*\}|\[[^\]]*\]", " ", s)
    s = re.sub(r"[|*_`>#]", " ", s)
    return " ".join(s.lower().split())


def copied_from(body, src_norm):
    """True when a long enough run of the claim appears verbatim in the sources.
    Latin text: any 12-word window; CJK-heavy text: any 25-character window."""
    if not src_norm:
        return False
    cjk = len(CJK_RE.findall(body)) > 0.3 * max(1, len(body))
    if cjk:
        compact = body.replace(" ", "")
        src = src_norm.replace(" ", "")
        if len(compact) < 25:
            return False
        return any(compact[i:i + 25] in src for i in range(0, len(compact) - 24, 5))
    words = body.split()
    if len(words) < 12:
        return False
    return any(" ".join(words[i:i + 12]) in src_norm for i in range(0, len(words) - 11))


def parse_claim(line, is_table):
    conf, refs = None, set()
    m = CONF_RE.search(line)
    if m:
        conf = CONF_WORDS[m.group(1)]
    if is_table:
        cells = [c.strip() for c in line.strip("|").split("|")]
        for c in cells:
            bare = c.strip("{}").strip()
            if bare in CONF_WORDS and conf is None:
                conf = CONF_WORDS[bare]
            if REF_CELL_RE.match(c):
                refs.update("S" + n for n in S_RE.findall(c))
    for grp in REF_BRACKET_RE.findall(line):
        refs.update("S" + n for n in S_RE.findall(grp))
    return conf, refs


def cmd_check(args):
    study_dir, bp, idx, _ = paths(args.slug, args.root)
    fails, oks = [], []

    def check(name, cond, detail=""):
        (oks if cond else fails).append(name + ("" if cond else "  " + str(detail)[:300]))
        print(("ok   " if cond else "FAIL ") + name + ("" if cond else "  " + str(detail)[:300]))

    if not os.path.exists(bp):
        print("FAIL blueprint missing: %s" % bp)
        return 1
    with open(bp, encoding="utf-8") as f:
        raw = f.read()
    index = load_sources(idx)
    known = {s["id"] for s in (index or {}).get("sources", [])}
    check("sources.json present with at least one source", bool(known), "run fetch_public.py first")
    text = strip_comments(raw)
    sections = split_sections(text)
    keys = [k for k, _ in sections]
    for n in range(0, 11):
        check("section %d present" % n, n in keys)
    check("Sources section present", "sources" in keys)

    todo_lines = [i + 1 for i, l in enumerate(text.splitlines()) if re.search(r"\bTODO\b", l)]
    check("no TODO placeholders left", not todo_lines, "lines %s" % todo_lines[:10])

    # fenced code blocks: structure only, never copied code
    longest, inblock, count = 0, False, 0
    for l in text.splitlines():
        if l.strip().startswith("```"):
            if inblock:
                longest = max(longest, count)
            inblock, count = not inblock, 0
        elif inblock:
            count += 1
    check("no code block longer than %d lines" % MAX_CODE_LINES, longest <= MAX_CODE_LINES, "longest %d" % longest)
    bad_assets = [l.strip()[:80] for l in text.splitlines() if IMAGE_RE.search(l) or LOGO_RE.search(l)]
    check("no image/logo links (describe, do not embed)", not bad_assets, bad_assets[:3])

    # claims
    src_norm = ""
    if index:
        parts = []
        for s in index.get("sources", []):
            p = os.path.join(study_dir, s.get("file", ""))
            if os.path.exists(p):
                with open(p, encoding="utf-8") as f:
                    parts.append(normalize(f.read()))
        src_norm = "\n".join(parts)
    n_claims, untagged, unsourced, unknown, copied = 0, [], [], [], []
    for key, lines in sections:
        if key not in CLAIM_SECTIONS:
            continue
        for i, line, is_table in claim_lines(lines):
            n_claims += 1
            conf, refs = parse_claim(line, is_table)
            where = "§%s: %s" % (key, line[:60])
            if conf is None:
                untagged.append(where)
                continue
            if conf in ("high", "medium") and not refs:
                unsourced.append(where)
            missing = sorted(r for r in refs if r not in known)
            if missing:
                unknown.append("%s -> %s" % (where, ",".join(missing)))
            if copied_from(normalize(line), src_norm):
                copied.append(where)
    cited = set()
    for key, lines in sections:
        if key in CLAIM_SECTIONS or key == 0:
            for l in lines:
                cited.update("S" + n for grp in REF_BRACKET_RE.findall(l) for n in S_RE.findall(grp))
                if l.strip().startswith("|"):
                    for c in l.strip("|").split("|"):
                        if REF_CELL_RE.match(c):
                            cited.update("S" + n for n in S_RE.findall(c))
    unused = sorted(known - cited, key=lambda x: int(x[1:]))
    if unused:
        print("note unused sources (fetched but never cited; thin pages? drop or cite): %s" % ", ".join(unused))
    claim_text = " ".join(l for key, lines in sections if key in CLAIM_SECTIONS for l in lines)
    bp_cjk = len(CJK_RE.findall(claim_text)) > 0.3 * max(1, len(claim_text))
    src_cjk = len(CJK_RE.findall(src_norm)) > 0.3 * max(1, len(src_norm)) if src_norm else bp_cjk
    if bp_cjk != src_cjk:
        print("note blueprint and sources are in different languages: the verbatim check cannot bite; a translated sentence is still a copy, keep saying it in your own words")
    check("claims found in sections 1-8", n_claims > 0)
    check("every claim has a confidence tag {high}/{medium}/{guess}", not untagged, untagged[:4])
    check("every high/medium claim cites a source [Sn]", not unsourced, unsourced[:4])
    check("every cited source exists in sources.json", not unknown, unknown[:4])
    check("no claim is a verbatim sentence from a source (say it in your own words)", not copied, copied[:4])

    # MVP cut
    mvp = dict(sections).get(9, [])
    mtxt = "\n".join(mvp)

    def count_items(label):
        m = re.search(r"\*\*%s[^*]*\*\*\s*(.+)" % label, mtxt)
        if not m:
            return None
        raw_items = re.sub(r"[((][^))]*[))]", "", m.group(1))  # commas inside parentheses do not split an item
        items = [x for x in re.split(r"[,,、;;\n]|\s\|\s", raw_items) if x.strip() and not re.match(r"^\s*(none|无|-)\s*$", x, re.I)]
        return len(items)

    n_obj, n_scr = count_items("Objects"), count_items("Screens")
    check("MVP objects listed and <= %d" % MAX_OBJECTS, n_obj is not None and 1 <= n_obj <= MAX_OBJECTS, "found %s" % n_obj)
    check("MVP screens listed and <= %d" % MAX_SCREENS, n_scr is not None and 1 <= n_scr <= MAX_SCREENS, "found %s" % n_scr)
    bo = mtxt.split("**Build order", 1)[1] if "**Build order" in mtxt else ""
    bo = re.split(r"\n\*\*", bo, maxsplit=1)[0]  # the numbered steps between the Build order label and the next bold label
    steps = re.findall(r"^\s*\d+\.\s+\S", bo, re.M)
    check("MVP build order has >= 3 steps", len(steps) >= 3, "found %d" % len(steps))
    acc = mtxt.split("**Acceptance", 1)[1] if "**Acceptance" in mtxt else ""
    acc = acc.split("**Learned", 1)[0]
    acc_lines = re.findall(r"^\s*(?:[-*]|\d+\.)\s+(\S.*)$", acc, re.M)
    check("MVP acceptance has 3-5 checks", 3 <= len(acc_lines) <= 5, "found %d" % len(acc_lines))
    # each check = what the user does -> what they should see -> what a machine can verify (the third part may say "manual")
    three = [l for l in acc_lines if len(re.split(r"\s(?:->|→|⇒)\s", l)) >= 3]
    check("every acceptance check has three parts (user does -> should see -> machine checks)", acc_lines and len(three) == len(acc_lines), "%d of %d" % (len(three), len(acc_lines)))
    lvo = re.search(r"\*\*Learned[^*]*\*\*\s*(.+)", mtxt, re.S)
    lvo_txt = lvo.group(1) if lvo else ""
    lvo_lines = [l for l in lvo_txt.splitlines() if l.strip()]
    says_own = bool(re.search(r"\bown\b|自己", lvo_txt, re.I))
    check("MVP says which rules were learned from the target and which are our own", bool(lvo) and lvo_lines and says_own, "found %d lines%s" % (len(lvo_lines), "" if says_own else ", no 'own' part"))
    check("'what we will not copy' section has its four lines", len(claim_lines(dict(sections).get(10, []))) >= 4)

    print("%d ok, %d fail" % (len(oks), len(fails)))
    return 0 if not fails else 1


def cmd_mvp(args):
    study_dir, bp, idx, mvp_path = paths(args.slug, args.root)
    if not os.path.exists(bp):
        print("no blueprint yet")
        return 1
    with open(bp, encoding="utf-8") as f:
        text = strip_comments(f.read())
    sections = dict(split_sections(text))
    head = [l for l in sections.get("head", []) if l.startswith("Product:")]
    sec9, sec10 = sections.get(9, []), sections.get(10, [])
    if not sec9 or any("TODO" in l for l in sec9):
        print("section 9 (MVP cut) is not finished; fill it, run check, then mvp")
        return 1
    out = ["# MVP hand-off", ""] + head + ["", "Source blueprint: blueprint.md (same folder). Build only what is below; the rest of the blueprint is context, not scope.", "",
                                           "## MVP cut"] + sec9 + ["", "## What we will not copy"] + sec10 + ["",
                                           "## Verify", "",
                                           "Keep the rules (numbers, formulas, state changes) in one block the acceptance runner can load without a browser; tag the learned ones [learned].",
                                           "Ship a checks file next to the build (acceptance.js or acceptance.py) that prints one JSON row per machine check; run it with",
                                           "`python3 <product-study>/scripts/acceptance_run.py <site_dir>` before go-live and again with `--url <live url>` after. The table it prints is what the user sees.",
                                           "The remaining checks are actions the user performs; list them as actions, never as 'tests passed'."]
    with open(mvp_path, "w", encoding="utf-8") as f:
        f.write("\n".join(l.rstrip() for l in out).strip() + "\n")
    print("wrote %s" % mvp_path)
    return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd")
    i = sub.add_parser("init"); i.add_argument("slug"); i.add_argument("--product", required=True)
    i.add_argument("--site"); i.add_argument("--goal"); i.add_argument("--root", default=DEFAULT_ROOT); i.add_argument("--force", action="store_true")
    for name in ("sources", "check", "mvp"):
        p = sub.add_parser(name); p.add_argument("slug"); p.add_argument("--root", default=DEFAULT_ROOT)
    args = ap.parse_args(argv)
    if not args.cmd:
        ap.print_help()
        return 1
    return {"init": cmd_init, "sources": cmd_sources, "check": cmd_check, "mvp": cmd_mvp}[args.cmd](args)


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