#!/usr/bin/env python3
"""For you: the words the app shows the user, written for them.

    bin/foryou build            write .summary/for-you.json; print path, size,
                                and how many items still need words
    bin/foryou wanted [kind]    print, as JSON, the items whose words are missing
                                or stale: key, kind, the facts, the files to read
    bin/foryou put              read JSON from stdin ({"key": {fields}, ...}),
                                check each entry, cache it, rebuild
    bin/foryou today            read the Today JSON from stdin, check it (shape,
                                every link exists), write .summary/today.json
    bin/foryou links FILE.md    every markdown link in FILE resolves, or exit 1

Why it exists. Lines Argoni writes for itself ("13 files, uncommitted") are
not lines for a person. Everything addressed to the user must be written for
them: "you", plain words, what it is, why it matters, what to do, no commit
hashes or code names left unexplained.

How the work splits:
    facts   computed here from the files, every run, no model: dates, states,
            status words, project, type, pairs, the report's own For you lead,
            ledger rows, which reports wait for the user's read-back, failed jobs.
    words   written by a model (the `words` skill, run by the app's runner)
            and cached in .summary/for-you/cache.json under
            the item's key with a fingerprint of the files it was written from.
            When the files change, the fingerprint changes and the words are
            stale: shown as null until the skill writes them again. Never a
            fallback to Argoni's own text, never invented here.

.summary/ is gitignored: all of this is a cache, rebuilt from the markdown.
Standard library only.

Exit status: 0 ok; 1 a file could not be parsed; 3 refused (bad input to put
or today; nothing written).
"""
import datetime
import glob
import hashlib
import importlib.machinery
import importlib.util
import json
import os
import re
import sys

BIN = os.path.dirname(os.path.abspath(__file__))
sys.dont_write_bytecode = True  # no __pycache__ beside the engine's scripts (lifecfg, bin/summary)
sys.path.insert(0, BIN)
import lifecfg  # noqa: E402

LIFE = lifecfg.root()
CFG = lifecfg.config(LIFE)
SUMMARY = os.path.join(LIFE, ".summary")
OUT = os.path.join(SUMMARY, "for-you.json")
TODAY_OUT = os.path.join(SUMMARY, "today.json")
CACHE = os.path.join(SUMMARY, "for-you", "cache.json")

_loader = importlib.machinery.SourceFileLoader("argoni_summary", os.path.join(BIN, "summary"))
_spec = importlib.util.spec_from_loader("argoni_summary", _loader)
S = importlib.util.module_from_spec(_spec)
_loader.exec_module(S)
ParseError, frontmatter, section, rel, read = S.ParseError, S.frontmatter, S.section, S.rel, S.read


def refuse(msg):
    print("foryou: REFUSED %s" % msg)
    sys.exit(3)


def sha(*parts):
    h = hashlib.sha1()
    for p in parts:
        h.update((p if isinstance(p, str) else json.dumps(p, sort_keys=True)).encode("utf-8"))
        h.update(b"\0")
    return h.hexdigest()[:12]


def file_text(path):
    try:
        return read(path)
    except OSError:
        return ""


def git_out(repo, *args):
    code, out, _ = lifecfg.git(repo, *args)
    return out.strip() if code == 0 else ""


def first_added(path, text, repo=LIFE):
    """Date of the oldest commit that added `text` to path, or None."""
    out = git_out(repo, "log", "--format=%as", "-S", text, "--", path)
    rows = out.splitlines()
    return rows[-1] if rows else None


_HISTORY = {}


def history(repo, where=None):
    """({path: day it was first added}, {path: day of its last commit}) for one repo, from
    one `git log` (under `where` only, when given), read once per run: one git process per
    file grew with every brief, decision and report (code review S-E13)."""
    key = (os.path.realpath(repo), where)
    if key not in _HISTORY:
        added, last = {}, {}
        day = None
        out = git_out(repo, "-c", "core.quotePath=false", "log", "--no-renames", "--name-status",
                      "--format=\x01%as", "--", where or ".")
        for line in out.splitlines():
            if line.startswith("\x01"):
                day = line[1:]
            elif "\t" in line and day:
                status, _, path = line.partition("\t")
                last.setdefault(path, day)        # newest first: the first seen is the last commit
                if status.startswith("A"):
                    added[path] = day             # oldest last: the last seen is the first add
        _HISTORY[key] = (added, last)
    return _HISTORY[key]


def first_commit_date(path, repo=LIFE, where=None):
    return history(repo, where)[0].get(path)


def last_commit_date(path, repo=LIFE, where=None):
    return history(repo, where)[1].get(path)


def sentences(text, n):
    text = re.sub(r"\s+", " ", re.sub(r"\*\*|__|`", "", text or "")).strip()
    parts = [x.strip() for x in re.findall(r".+?[.!?](?=\s|$)", text)]
    return " ".join(parts[:n]) if parts else (text or None)


# ---------------------------------------------------------------- facts

REPORT_ID = re.compile(r"^(\d{4}[A-Z]?)-")


def doc_id(path):
    """"0033A" for reports/0033A-some-title.md: the number and its part
    letter. Keying by the first four characters alone would make 0033A, B and
    C one item, so only one of them would ever get words."""
    m = REPORT_ID.match(os.path.basename(path))
    return m.group(1) if m else os.path.basename(path)[:4]


def report_for(num):
    found = sorted(glob.glob(os.path.join(LIFE, "reports", num + "-*.md")))
    return found[0] if found else None


def brief_for(num):
    """The brief for report `num`: briefs/0033A-* if there is one, else the
    parent briefs/0033-* (one brief, several reports)."""
    for n in (num, num[:4]):
        found = sorted(glob.glob(os.path.join(LIFE, "briefs", n + "-*.md")))
        if found:
            return found[0]
    return None


def report_facts(path):
    """Lead, read-back and state of one report (argoni reports/NNNN-*.md)."""
    fields, body = frontmatter(path, required=False)
    num = doc_id(path)
    fy = section(body, "For you")
    rb = section(body, "Read-back")
    brief = brief_for(num)
    bstatus = (frontmatter(brief)[0].get("status") or "") if brief else ""
    # A brief can be "done (e4f03b1); read-back pending": the status line, not
    # the word done, says whether the user's read-back is still owed.
    owed = re.search(r"read-?back[^;]*pending|waits for (?:his|her|their|the user's) read-?back", bstatus)
    if rb:
        state = "done" if bstatus.startswith("done") else "read back, waiting for your commit"
    elif bstatus.startswith("done") and not owed:
        state = "done"
    else:
        state = "waiting for your read-back"
    return {"num": num, "for_you_lead": sentences(fy, 2) if fy else None,
            "has_for_you": bool(fy), "readback": bool(rb), "state": state,
            "brief": rel(brief) if brief else None,
            "subject": (frontmatter(brief)[0].get("subject") if brief else None)}


def needs_from_now():
    """now.md's needs heading (config `needs_heading`), Small: group only; the
    waiting group moves to decisions."""
    _, needs = S.now_md()
    out = []
    for item in needs["todo"]:
        text = item["text"]
        fired = re.search(r"\(scheduled remind-[a-z0-9-]+\).*?from log/(\d{4}-\d{2}-\d{2})\.md", text)
        if fired and fired.group(1) < datetime.date.today().isoformat():
            continue
        linked = "".join(file_text(os.path.join(LIFE, l["path"])) for l in item["links"] if not l["repo"])
        out.append({"key": "need:" + sha(text)[:10], "kind": "need", "source": "now.md",
                    "since": first_added("now.md", text) or datetime.date.today().isoformat(),
                    "facts": {"line": text, "project": item["project"], "links": item["links"],
                              "commit_line": item["commit"]},
                    "read": ["now.md"] + [l["path"] for l in item["links"] if not l["repo"]],
                    "fingerprint": sha(text, linked)})
    return out, needs["waiting"]


def needs_generated():
    """Reports waiting for the user's read-back (and the build test before
    it), and failed scheduled jobs. Each report is its own item: bin/check
    refuses a now.md need line that names a report."""
    out = []
    for path in sorted(glob.glob(os.path.join(LIFE, "reports", "[0-9][0-9][0-9][0-9]*-*.md"))):
        f = report_facts(path)
        if f["state"] != "waiting for your read-back":
            continue
        test = not lifecfg.own(f["subject"])
        waits = "your test, then your read-back" if test else "your read-back"
        out.append({"key": "need:report-" + os.path.basename(path)[:-3], "kind": "need", "source": "report",
                    "since": first_commit_date(rel(path)) or datetime.date.today().isoformat(),
                    "facts": {"report": rel(path), "brief": f["brief"], "project": lifecfg.OWN if lifecfg.own(f["subject"]) else f["subject"],
                              "waits_for": waits,
                              "for_you_lead": f["for_you_lead"],
                              "title": soft_frontmatter(path)[2]},
                    "action": {"kind": "open_report", "target": rel(path)},
                    "read": [rel(path)] + ([f["brief"]] if f["brief"] else []),
                    "fingerprint": sha(file_text(path))})
    out += project_reports_waiting()
    out += github_asks()
    runs = os.path.join(SUMMARY, "runs.json")
    try:
        jobs = json.loads(file_text(runs) or "{}").get("jobs", {})
    except ValueError:
        jobs = {}
    # A job marked "needs_you": false in jobs.json (one that fails when a
    # machine is simply off) keeps its failures in runs.json and on the
    # Scheduled page, not here.
    try:
        quiet = {j["name"] for j in json.loads(file_text(JOBS) or "{}").get("jobs", [])
                 if j.get("needs_you") is False}
    except ValueError:
        quiet = set()
    for name, run in sorted(jobs.items()):
        if not isinstance(run, dict) or run.get("exit") in (0, None) or name in quiet:
            continue
        out.append({"key": "need:job-" + name, "kind": "need", "source": "scheduled",
                    "since": (run.get("at") or "")[:10] or None,
                    "facts": {"job": name, "exit": run.get("exit"), "at": run.get("at"),
                              "note": run.get("note")},
                    "action": {"kind": "open_scheduled", "target": name},
                    "read": [rel(JOBS)], "fingerprint": sha(name, run)})
    return out


# The user's scheduled jobs and switches (engine/bin/scheduled; the built-in
# jobs are in engine/jobs.json and none of them is quiet).
JOBS = os.path.join(LIFE, "jobs.json")

# The work hub (config `work_hub`): its reports enter Needs you at ledger level
# only: the title and that it waits, nothing from inside.
WORK_HUB = lifecfg.work_hub(CFG)
WORK_REPOS = {os.path.basename(WORK_HUB.rstrip("/"))} if WORK_HUB else set()


def project_reports_waiting():
    """Other projects' reports waiting for the user's read-back, from every
    repo bin/standings reads that has docs/standing.md. A report waits when it
    has no `## Read-back` and its brief's status is not done: some repos never
    write that section, so the heading alone would list every old report."""
    repos = list(repos_on_mac())
    if WORK_HUB and os.path.isdir(WORK_HUB) and WORK_HUB not in dict(repos).values():
        repos.append((os.path.basename(WORK_HUB.rstrip("/")), WORK_HUB))
    out = []
    for name, repo in repos:
        if not os.path.isfile(os.path.join(repo, "docs", "standing.md")):
            continue
        for path in sorted(glob.glob(os.path.join(repo, "docs", "reports", "[0-9][0-9][0-9][0-9]*-*.md"))):
            text = file_text(path)
            if re.search(r"(?mi)^## Read-back", text):
                continue
            num = os.path.basename(path)[:4]
            brief = sorted(glob.glob(os.path.join(repo, "docs", "briefs", num + "-*.md")))
            # 0477: a dropped, parked or superseded brief's report waits for nobody either.
            if not brief or BRIEF_CLOSED.match(soft_frontmatter(brief[0])[0].get("status", "")):
                continue
            work = name in WORK_REPOS
            title = soft_frontmatter(path)[2]
            target = "~/" + os.path.relpath(path, os.path.expanduser("~"))
            facts = {"report": target, "project": name, "waits_for": "your read-back", "title": title,
                     "work": work, "for_you_lead": None}
            if not work:
                fy = section(soft_frontmatter(path)[1], "For you")
                facts["for_you_lead"] = sentences(fy, 2) if fy else None
            out.append({"key": "need:report-%s-%s" % (name, os.path.basename(path)[:-3]), "kind": "need",
                        "source": "project-report", "since": first_commit_date(os.path.relpath(path, repo), repo, "docs")
                        or datetime.date.today().isoformat(),
                        "facts": facts,
                        "action": {"kind": "open_file", "target": target},
                        # Work: the words come from the title alone; the report is never read.
                        "read": [] if work else [target],
                        "fingerprint": sha(title, os.path.basename(brief[0]),
                                           "" if work else file_text(path))})
    return out


# GitHub asks, written by bin/asks (the one part that uses the network). An
# ask of the user by name, or an issue assigned to them, is its own item;
# asks of a team they are in fold into one item per account. Title, repo,
# who, when and link only, both sides.
ASKS = os.path.join(SUMMARY, "github-asks.json")
TEAM_REVIEWS = "https://github.com/pulls/review-requested"


def github_asks():
    try:
        data = json.loads(file_text(ASKS) or "{}")
    except ValueError:
        return []
    out, team = [], {}
    asks = data.get("asks") if isinstance(data, dict) else None
    need = ("kind", "link", "title", "repo", "who", "since", "account", "side")
    for a in asks if isinstance(asks, list) else []:
        if not isinstance(a, dict) or any(not isinstance(a.get(k), str) for k in need):
            continue  # bin/asks writes every field; anything else is not an ask
        if a.get("kind") == "review" and a.get("via") == "team":
            team.setdefault(a["account"], []).append(a)
            continue
        out.append({"key": "need:gh-" + sha(a["link"])[:10], "kind": "need", "source": "github",
                    "since": a["since"],
                    "facts": {"ask": a["kind"], "title": a["title"], "repo": a["repo"], "who": a["who"],
                              "project": a["project"], "work": a["side"] == "work", "link": a["link"],
                              "checked": data.get("generated_at")},
                    "action": {"kind": "open_url", "target": a["link"]},
                    "read": [], "fingerprint": sha(a["link"], a["title"])})
    for account, asks in sorted(team.items()):
        asks.sort(key=lambda a: a["since"])
        projects = sorted({a["project"] or "" for a in asks})
        out.append({"key": "need:gh-team-" + account, "kind": "need", "source": "github",
                    "since": asks[0]["since"],
                    "facts": {"ask": "team-reviews", "account": account, "count": len(asks),
                              "bots": sum(1 for a in asks if a.get("bot")),
                              "last_7_days": sum(1 for a in asks if a["since"] >= (datetime.date.today()
                                                 - datetime.timedelta(days=7)).isoformat()),
                              "newest": {"who": asks[-1]["who"], "since": asks[-1]["since"], "repo": asks[-1]["repo"]},
                              "project": projects[0] or None if len(projects) == 1 else None,
                              "work": asks[0]["side"] == "work", "checked": data.get("generated_at")},
                    "action": {"kind": "open_url", "target": TEAM_REVIEWS},
                    "read": [], "fingerprint": sha(account, sorted(a["link"] for a in asks))})
    return out


_REPOS = []


BRIEF_CLOSED = re.compile(r"^\W*(done|dropped|parked|superseded|closed|cancell?ed|abandoned|rejected|withdrawn|"
                          r"retired|archived|merged|replaced|reported|complete|completed|finished)\b", re.I)


def repos_on_mac():
    """(name, path) for every repo Argoni sees on this Mac (config `repos_folders` and
    `repos`, lifecfg.repos()), the life folder left out. Found once per run."""
    if not _REPOS:
        _REPOS.append([(os.path.basename(repo.rstrip("/")), repo) for repo in lifecfg.repos(LIFE)[0]])
    return _REPOS[0]


def soft_frontmatter(path):
    """Frontmatter of a file in another repo: those use YAML lists too, so never fail."""
    text = file_text(path)
    m = re.match(r"---\n(.*?)\n---\n", text.replace("\r\n", "\n"), re.S)
    fields = {}
    if m:
        for line in m.group(1).splitlines():
            k, sep, v = line.partition(":")
            if sep and re.match(r"^[a-z_]+$", k):
                fields[k] = v.strip()
    body = text[m.end():] if m else text
    title = next((l[2:].strip() for l in body.splitlines() if l.startswith("# ")), None)
    return fields, body, title


def review_actions(status, days):
    if status == "proposed":
        return ["accept", "reject"]
    if days is not None and days <= 7:
        return ["still_right", "change_it"]
    return []


def decision_items(waiting, today):
    out = []
    for d in S.decisions(today):
        path = sorted(glob.glob(os.path.join(LIFE, "decisions", d["id"] + "-*.md")))[0]
        fields, _ = frontmatter(path)
        out.append({"key": "decision:argoni-" + d["id"], "kind": "decision",
                    "project": lifecfg.OWN, "area": fields.get("subject"), "repo": None,
                    "path": rel(path), "id": d["id"], "status": d["status"],
                    "date": d["date"], "revisit": d["revisit"], "days_to_revisit": d["days_to_revisit"],
                    "actions": review_actions(d["status"], d["days_to_revisit"]),
                    "facts": {"title": d["title"]},
                    "read": [rel(path)], "fingerprint": sha(file_text(path))})
    # Other repos on this Mac: proposed ones only (they move here from Needs you).
    for name, repo in repos_on_mac():
        for path in sorted(glob.glob(os.path.join(repo, "docs", "decisions", "[0-9][0-9][0-9][0-9]-*.md"))):
            fields, body, title = soft_frontmatter(path)
            if fields.get("status") != "proposed":
                continue
            num = doc_id(path)
            out.append({"key": "decision:%s-%s" % (name, num), "kind": "decision",
                        "project": name, "area": None, "repo": name,
                        "path": os.path.relpath(path, repo), "id": num, "status": "proposed",
                        "date": fields.get("date"), "revisit": fields.get("revisit"),
                        "days_to_revisit": None, "actions": [],  # accept/reject happen in that repo
                        "facts": {"title": title},
                        "read": ["%s:%s" % (name, os.path.relpath(path, repo))],
                        "fingerprint": sha(file_text(path))})
    # now.md "Decisions waiting in projects" lines with no record on this Mac
    # (a repo with no decisions folder, or one kept on another machine).
    # A line whose "(from <owner file>; ...)" is a record above is that record, not a second one.
    have = {(o["project"], o["id"]) for o in out}
    records = {r for o in out for r in o["read"]}
    for need in waiting:
        num = re.match(r"^decision (\d{4})", need["what"] or "")
        if need["project"] and num and (need["project"], num.group(1)) in have:
            continue
        source = re.search(r"\(from ([^;()]+);", need["text"] or "")
        if source and source.group(1).strip() in records:
            continue
        out.append({"key": "decision:now-" + sha(need["text"])[:10], "kind": "decision",
                    "project": need["project"], "area": None, "repo": need["project"],
                    "path": None, "id": None, "status": "waiting for your word, record not on this Mac",
                    "date": None, "revisit": None, "days_to_revisit": None, "actions": [],
                    "facts": {"line": need["text"]},
                    "read": ["now.md"] + (["projects/%s.md" % need["project"]] if need["project"] else []),
                    "fingerprint": sha(need["text"])})
    return out


TYPES = [("briefs", "brief"), ("reports", "report"), ("decisions", "decision"),
         ("projects", "project page"), ("log", "log"), ("research", "research"),
         ("domains", "life"), ("me", "about you"), ("work", "ledger"), ("inbox", "inbox")]


def file_items(today):
    out = []
    reports = {}
    for path in sorted(glob.glob(os.path.join(LIFE, "reports", "[0-9][0-9][0-9][0-9]*-*.md"))):
        # 0033A, 0033B, 0033C: the brief 0033 pairs with the last part.
        reports[doc_id(path)] = path
        reports[doc_id(path)[:4]] = path
    paths = []
    for folder, kind in TYPES:
        for p in sorted(glob.glob(os.path.join(LIFE, folder, "**", "*.md"), recursive=True)):
            if os.path.basename(p) != "README.md":
                paths.append((p, kind))
    for p in sorted(glob.glob(os.path.join(LIFE, "ideas", "*", "*.md"))):
        paths.append((p, "idea"))
    for p in ("now.md", "GUIDE.md", "dogfood.md", "conventions.md", "AGENTS.md"):
        if os.path.isfile(os.path.join(LIFE, p)):
            paths.append((os.path.join(LIFE, p), "your file"))
    for path, kind in paths:
        r = rel(path)
        fields, body, title = soft_frontmatter(path)
        project = fields.get("subject")
        if lifecfg.own(project):
            project = lifecfg.OWN
        date = fields.get("updated") or fields.get("date")
        m = S.DATED.match(os.path.basename(path))
        date = date or (m.group(1) if m else None) or last_commit_date(r) or None
        item = {"key": "file:argoni:" + r, "kind": "file", "repo": None, "path": r,
                "project": project, "type": kind, "title": title, "date": date,
                "status_words": None, "pair": None, "read_only": False,
                "read": [r], "fingerprint": sha(file_text(path))}
        num = doc_id(path)
        if kind == "brief":
            status = fields.get("status") or ""
            rp = reports.get(num)
            if status.startswith("done"):
                item["status_words"] = "done"
            elif status.startswith("parked"):
                item["status_words"] = "parked"
            elif rp:
                item["status_words"] = report_facts(rp)["state"]
            elif "running" in status:
                item["status_words"] = "a session is working on it"
            elif status.startswith("ready"):
                item["status_words"] = "ready, not started"
            item["pair"] = rel(rp) if rp else None
        elif kind == "report":
            f = report_facts(path)
            item["status_words"], item["pair"] = f["state"], f["brief"]
            item["for_you_lead"] = f["for_you_lead"]
        elif kind == "decision":
            st = fields.get("status")
            item["status_words"] = {"proposed": "waiting for your word", "accepted": "decided",
                                    "rejected": "rejected"}.get(st, st)
        elif kind == "idea":
            item["status_words"] = fields.get("status")
        out.append(item)
    # Other repos' documents, read only.
    for name, repo in repos_on_mac():
        docs = os.path.join(repo, "docs")
        found = [os.path.join(docs, "standing.md")]
        for d in ("briefs", "reports", "decisions"):
            found += sorted(p for p in glob.glob(os.path.join(docs, d, "*.md")) if os.path.basename(p) != "README.md")
        for path in found:
            if not os.path.isfile(path):
                continue
            r = os.path.relpath(path, repo)
            fields, body, title = soft_frontmatter(path)
            kind = {"briefs": "brief", "reports": "report", "decisions": "decision"}.get(r.split("/")[1], "standing")
            date = fields.get("updated") or fields.get("date") or last_commit_date(r, repo, "docs") or None
            st = fields.get("status")
            out.append({"key": "file:%s:%s" % (name, r), "kind": "file", "repo": name, "path": r,
                        "project": name, "type": kind, "title": title, "date": date,
                        "status_words": (("waiting for your word" if st == "proposed" else st) if kind == "decision" else
                                         # 0477: a brief's own status (dropped, done) was left out, so dropped briefs read as open.
                                         (st or None) if kind == "brief" else None),
                        "pair": None, "read_only": True,
                        "read": ["%s:%s" % (name, r)], "fingerprint": sha(file_text(path))})
    out.sort(key=lambda i: (i["date"] or "", i["path"]), reverse=True)
    return out


def project_items(projects_list):
    out = []
    for p in projects_list:
        page = os.path.join(LIFE, "projects", p["slug"] + ".md")
        out.append({"key": "project:" + p["slug"], "kind": "project", "slug": p["slug"],
                    "title": p["title"], "last_touched": (p["last_touched"] or "")[:10] or None,
                    "facts": {"state": p["state"], "last_touched": p["last_touched"], "next": p["next"]},
                    "read": ["projects/README.md", rel(page)],
                    "fingerprint": sha(p, file_text(page))})
    return out


LIFE_NOTES_SHOWN = 3  # the card shows the newest three; the cap on a domain is bin/check's


def life_note(path):
    """A dated note in domains/<name>/: its date, title, and the user's words,
    copied from the note's `>` lines (never retyped). Words are None when the
    note holds none of their words (an Argoni-derived note)."""
    fields, body, title = soft_frontmatter(path)
    quote = [l[1:].strip() for l in body.splitlines() if l.startswith(">")]
    return {"path": rel(path), "date": fields.get("updated") or os.path.basename(path)[:10],
            "title": title, "confidence": fields.get("confidence"),
            "words": " ".join(q for q in quote if q) or None}


def life_items():
    """One card per domains/<name>/ folder with a README (personal, career,
    learning, people). The README says what belongs there (`belongs:`).
    `stored: personal-accounts` marks a domain kept off this Mac.
    `sources:` names owner files outside domains/ (a project page that belongs
    to personal, say), comma-separated."""
    now = read(os.path.join(LIFE, "now.md"))
    out = []
    for readme in sorted(glob.glob(os.path.join(LIFE, "domains", "*", "README.md"))):
        folder = os.path.dirname(readme)
        domain = os.path.basename(folder)
        fields, body, _ = soft_frontmatter(readme)
        off_mac = fields.get("stored") == "personal-accounts"
        sources = [s.strip() for s in (fields.get("sources") or "").split(",") if s.strip()]
        sources = [s for s in sources if os.path.isfile(os.path.join(LIFE, s))]
        notes = [] if off_mac else sorted(
            (life_note(p) for p in glob.glob(os.path.join(folder, "*.md"))
             if os.path.basename(p) != "README.md"),
            key=lambda n: (n["date"] or "", n["path"]), reverse=True)
        line = next((l[2:] for l in now.splitlines() if l.startswith("- %s:" % domain)), None)
        read_files = ["now.md", rel(readme)] + sources + [n["path"] for n in notes[:LIFE_NOTES_SHOWN]]
        out.append({"key": "life:" + domain, "kind": "life", "domain": domain,
                    "facts": {"line": line, "belongs": fields.get("belongs"),
                              "stored": "your personal Claude and ChatGPT, not this Mac" if off_mac else "this folder",
                              "notes": len(notes), "latest": notes[:LIFE_NOTES_SHOWN]},
                    "read": read_files,
                    "fingerprint": sha(line or "", *[file_text(os.path.join(LIFE, f)) for f in read_files[1:]])})
    return out


LEDGER_ROW = re.compile(r"^(?:(\d{4}-\d{2}-\d{2})\s+)?(.*?)\s+—\s+([\w./-]+#\d+)\s+—\s+(.*)$")
# A PR anywhere in a row ("#355 keep ...", "some_repo#266 ..."); never a
# zero-padded decision id like project#0029.
LEDGER_PR = re.compile(r"(?<![\w#])((?:[A-Za-z][\w.-]*)?#(?!0)\d{1,5})\b")


def ledger_months():
    out = []
    for path in sorted(glob.glob(os.path.join(LIFE, "work", "achievements", "*.md")), reverse=True):
        _, body = frontmatter(path)
        rows, group = [], None
        title = next((l[2:].strip() for l in body.splitlines() if l.startswith("# ")), None)
        for line in body.splitlines():
            if line.startswith("## "):
                group = line[3:].strip()
            elif line.startswith("- "):
                text = line[2:].strip()
                m = LEDGER_ROW.match(text)
                if m:
                    row = {"group": group, "date": m.group(1), "what": m.group(2),
                           "pr": m.group(3), "for": m.group(4)}
                else:
                    pr = LEDGER_PR.search(text)
                    row = {"group": group, "date": None, "what": text,
                           "pr": pr.group(1) if pr else None, "for": None}
                # Keyed by the row's own text, so an edited row is a new item
                # and a moved one keeps its words.
                row["key"] = "ledger:%s:%s" % (os.path.basename(path)[:-3], sha(line)[:10])
                row["line"] = text
                rows.append(row)
        out.append({"month": os.path.basename(path)[:-3], "title": title,
                    "path": rel(path), "rows": rows})
    return out


def ledger_items(months):
    """One item per ledger row: words for the user, from the row and its
    month file only. Ledger level: nothing the row does not say."""
    out = []
    for m in months:
        for r in m["rows"]:
            out.append({"key": r["key"], "kind": "ledger", "month": m["month"],
                        "facts": {"month_title": m["title"], "group": r["group"], "date": r["date"],
                                  "row": r["line"], "pr": r["pr"], "for": r["for"]},
                        "read": [m["path"]], "fingerprint": sha(r["group"] or "", r["line"])})
    return out


def all_items(today):
    needs, waiting = needs_from_now()
    needs += needs_generated()
    projects_list = S.projects()
    groups = {"needs": needs, "decisions": decision_items(waiting, today),
              "files": file_items(today), "projects": project_items(projects_list),
              "life": life_items(), "ledger": ledger_items(ledger_months())}
    # Two items on one key would share one set of words.
    seen = set()
    for group in groups.values():
        for it in group:
            if it["key"] in seen:
                raise ParseError("two items share the key %s" % it["key"])
            seen.add(it["key"])
    return groups


# ---------------------------------------------------------------- words

def load_cache():
    """{key: cached words}; a damaged cache reads as empty (the words are asked for again)."""
    try:
        cache = json.loads(file_text(CACHE) or "{}")
    except ValueError:
        return {}
    return {k: v for k, v in cache.items() if isinstance(v, dict)} if isinstance(cache, dict) else {}


def words_for(item, cache):
    hit = cache.get(item["key"])
    if hit and hit.get("fingerprint") == item["fingerprint"]:
        return hit["words"], hit.get("written")
    return None, None


ACTIONS = {"open_report", "open_scheduled", "open_file", "delete_file",
           "open_decisions", "open_url", "none"}
HEX = re.compile(r"\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b")
CODE = re.compile(r"(?:\b(?:briefs?|reports?|decisions?|ideas?)\s+\d{4}\b|#\d{4}\b)(?!\s*\()")
PATHLIKE = re.compile(r"\b[\w.-]+/[\w./-]+\.(?:md|py|swift|json|yaml|toml)\b")


USER_NAME = re.compile(r"\b%s\b" % re.escape(CFG["user_name"])) if CFG["user_name"] else None


def plain(text, where, limit):
    """Refuse text that is not written for the user."""
    if not isinstance(text, str) or not text.strip():
        refuse("%s: empty" % where)
    if len(text) > limit:
        refuse("%s: %d characters, limit %d" % (where, len(text), limit))
    for rx, why in ((HEX, "a commit hash"), (CODE, "a code name with no explanation in brackets after it"),
                    (PATHLIKE, "a file path"), (re.compile(r"`"), "a backtick"),
                    (USER_NAME, "the user's name (write 'you')")):
        m = rx.search(text) if rx else None
        if m:
            refuse("%s: has %s (%r)" % (where, why, m.group(0)))


def target_path(target):
    """The real path a target names, or None: a path in the life folder, repo:path for a
    repo Argoni sees, or a ~ or absolute path. Only a file that exists, inside the life
    folder or a folder the user chose (after links and `..` are followed), is a target:
    the words are written by a model, so "open" never reaches anything else on the Mac."""
    if not isinstance(target, str) or not target or "\0" in target:
        return None
    repo, sep, path = target.partition(":")
    if target.startswith(("/", "~")):
        full = os.path.expanduser(target)
    elif sep and "/" not in repo:
        d = dict(repos_on_mac()).get(repo)
        if not d:
            return None
        full = os.path.join(d, path)
    else:
        full = os.path.join(LIFE, target)
    real = os.path.realpath(full)
    if not os.path.exists(real):
        return None
    life, product = os.path.realpath(LIFE), os.path.dirname(os.path.realpath(LIFE))
    if os.path.isdir(os.path.join(product, "engine")) and real.startswith(product + os.sep) \
            and not real.startswith(life + os.sep):
        return None  # Argoni's own files beside data/, even inside a chosen repo that holds them
    roots = [LIFE] + [d for _, d in repos_on_mac()] + ([WORK_HUB] if WORK_HUB else [])
    for r in roots:
        top = os.path.realpath(r)
        if real == top or real.startswith(top.rstrip(os.sep) + os.sep):
            # Never a hidden file or folder (.env, .git, .ssh): Argoni does not read them.
            parts = os.path.relpath(real, top).split(os.sep)
            return None if any(p.startswith(".") for p in parts if p != os.curdir) else real
    return None


def exists(target):
    """True when target names a file Argoni may open for the user (target_path)."""
    return target_path(target) is not None


def in_life(target):
    """True when target is inside the life folder itself (what a delete may name)."""
    real = target_path(target)
    top = os.path.realpath(LIFE)
    return bool(real) and real.startswith(top + os.sep)


def check_action(a, where):
    if not isinstance(a, dict) or a.get("kind") not in ACTIONS:
        refuse("%s: action kind must be one of %s" % (where, ", ".join(sorted(ACTIONS))))
    if a["kind"] in ("open_report", "open_file", "delete_file") and not exists(a.get("target")):
        refuse("%s: action target %r is not a file in your folders" % (where, a.get("target")))
    if a["kind"] == "delete_file" and not in_life(a.get("target")):
        refuse("%s: delete_file names only a file inside the life folder, not %r" % (where, a.get("target")))
    if a["kind"] == "open_url" and not str(a.get("target") or "").startswith("https://github.com/"):
        refuse("%s: open_url opens GitHub pages only, not %r" % (where, a.get("target")))


def check_words(item, w):
    k, key = item["kind"], item["key"]
    if not isinstance(w, dict):
        refuse("%s: words must be an object" % key)
    if k == "need":
        items = w.get("items")
        if not isinstance(items, list):
            refuse("%s: needs `items` (a list; empty with `why_none` when it is not a to-do)" % key)
        if not items:
            plain(w.get("why_none"), key + ".why_none", 200)
        for i, it in enumerate(items):
            if not isinstance(it, dict):
                refuse("%s.items[%d]: must be an object" % (key, i))
            plain(it.get("headline"), "%s.items[%d].headline" % (key, i), 70)
            plain(it.get("body"), "%s.items[%d].body" % (key, i), 320)
            if "action" in item:
                it["action"] = item["action"]  # fixed by the facts, not by the model
            check_action(it.get("action"), "%s.items[%d]" % (key, i))
    elif k == "decision":
        plain(w.get("name"), key + ".name", 60)
        fy = w.get("for_you")
        if not isinstance(fy, dict):
            refuse("%s: needs for_you {decided, why, changed, check_again}" % key)
        for f in ("decided", "why", "changed", "check_again"):
            plain(fy.get(f), "%s.for_you.%s" % (key, f), 220)
    elif k == "file":
        plain(w.get("summary"), key + ".summary", 160)
    elif k == "project":
        for f, lim in (("state", 120), ("next", 140), ("whose", 40)):
            plain(w.get(f), "%s.%s" % (key, f), lim)
    elif k == "life":
        plain(w.get("headline"), key + ".headline", 70)
        plain(w.get("body"), key + ".body", 320)
    elif k == "ledger":
        plain(w.get("what"), key + ".what", 200)
        if w.get("for") is not None:  # null when the month file does not say
            plain(w["for"], key + ".for", 220)
        pr = item["facts"]["pr"]
        for f in ("what", "for"):
            if pr and w.get(f) and re.search(r"#%s\b" % re.escape(pr.split("#")[1]), w[f]):
                refuse("%s.%s: the PR number is its link label; leave it out of the text" % (key, f))


# ---------------------------------------------------------------- fallback

def is_plain(text, limit):
    """plain() without the exit: True when the check would pass."""
    try:
        plain(text, "", limit)
    except SystemExit:
        return False
    return True


def shorten(text, limit):
    text = re.sub(r"\s+", " ", text or "").strip()
    if len(text) <= limit:
        return text
    cut = text[:limit - 1].rsplit(" ", 1)[0].rstrip(" ,;:-")
    return cut + "\u2026"


TITLE_PREFIX = re.compile(r"^(?:Report|Brief|Decision)?\s*\d{4}[A-Z]?\s*[.:]\s*")


def title_of(num, repo=None):
    """The title of report/brief `num` in argoni (or decision `num` in `repo`),
    without its number: what a code name stands for, from the file itself."""
    if repo:
        d = dict(repos_on_mac()).get(repo)
        found = sorted(glob.glob(os.path.join(d, "docs", "decisions", num + "-*.md"))) if d else []
    else:
        found = (sorted(glob.glob(os.path.join(LIFE, "reports", num + "-*.md")))
                 or sorted(glob.glob(os.path.join(LIFE, "briefs", num + "-*.md")))
                 or sorted(glob.glob(os.path.join(LIFE, "briefs", num[:4] + "-*.md"))))
    title = soft_frontmatter(found[0])[2] if found else None
    return TITLE_PREFIX.sub("", title).strip() if title else None


def decode(text):
    """Argoni's shorthand made readable without a model: no markdown, no hashes,
    no paths, and each code name replaced by its file's own title (or dropped
    when there is no file on this Mac). Nothing is added that a file does not say."""
    def named(m, repo=None):
        t = title_of(m.group("n"), repo)
        return '"%s%s"' % (t[0].lower(), t[1:]) if t else ""

    t = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text or "")
    t = re.sub(r"\*\*|__|`", "", t)
    t = re.sub(r"\s*\([^()]*\)", "", t)                      # asides in brackets
    t = HEX.sub("", t)
    t = re.sub(r"(?:~|\b[\w.-]+)?/(?:[\w./~-]*[\w~-])?/?", lambda m: os.path.splitext(m.group(0).rstrip("/").split("/")[-1])[0], t)
    t = re.sub(r"\b([\w-]+)#(?P<n>\d{4})\b", lambda m: named(m, m.group(1)), t)
    t = re.sub(r"\b(?P<n>\d{4})-\d{4}\b", "", t)                 # ranges: 0013-0017
    t = re.sub(r"\bdecision (?P<n>\d{4})\b", "decision", t)         # another repo's; not argoni's 0005
    t = re.sub(r"\b(?P<n>\d{4}[A-Z]?)\b(?!-\d)", named, t)        # 0033B (not dates)
    if CFG["user_name"]:
        name = re.escape(CFG["user_name"])
        t = re.sub(r"\b%s's\b" % name, "your", t)
        t = re.sub(r"\b%s\b" % name, "you", t)
    t = re.sub(r"\s+([,;.:])", r"\1", t)
    t = re.sub(r"([,;])\s*(?=[,;.]|$)", "", t)
    t = re.sub(r"\s{2,}", " ", t).strip(" ,;:")
    return t


def fallback(item):
    """Words from the facts alone, for an item the words skill has not reached
    yet. Marked fallback: never cached, still wanted, replaced by
    the skill's words on its next run. None when the facts give nothing plain."""
    k, f = item["kind"], item.get("facts", {})
    if k == "need" and item["source"] in ("report", "project-report"):
        title = re.sub(r"^(?:Report\s+)?\d{4}[A-Z]?\s*[:\u2014-]\s*", "", f.get("title") or "")
        head = shorten("Read back: " + (decode(title) or "a finished report"), 70)
        if not is_plain(head, 70):
            head = "Read back: a finished report"
        body = f.get("for_you_lead")
        out = {"headline": head}
        if body and is_plain(body, 320):
            out["body"] = body
        elif item["source"] == "project-report":
            out["body"] = "The %s report is finished and waits for your read-back there." % f["project"]
        return {"items": [dict(out, action=item["action"])], "fallback": True}
    if k == "need" and item["source"] == "github":
        repo = f.get("repo", "").split("/")[-1]
        if f["ask"] == "team-reviews":
            n = f["count"]
            head = "%d review%s wait%s for your team" % (n, "s" if n > 1 else "", "" if n > 1 else "s")
            body = "Asked of a team you are in, not of you by name. %d came in the last 7 days; the newest is from %s on %s." % (
                f["last_7_days"], f["newest"]["who"], f["newest"]["since"])
            if f["bots"]:
                body += " %d %s from a bot." % (f["bots"], "are" if f["bots"] > 1 else "is")
        else:
            what = "Review" if f["ask"] == "review" else "Issue"
            head = shorten("%s: %s" % (what, f["title"]), 70)
            if not is_plain(head, 70):
                head = "%s waits for you in %s" % ("A review" if f["ask"] == "review" else "An issue", repo)
            body = ("%s asked you to review this in %s on %s." if f["ask"] == "review"
                    else "Assigned to you in %s since %s, opened by %s.") % (
                (f["who"], repo, item["since"]) if f["ask"] == "review" else (repo, item["since"], f["who"]))
        out = {"headline": head, "action": item["action"]}
        if is_plain(body, 320):
            out["body"] = body
        return {"items": [out], "fallback": True}
    if k == "need" and item["source"] == "scheduled":
        at = (f.get("at") or "")[11:16]
        head = "The %s job failed%s" % (f["job"], " at " + at if at else "")
        return {"items": [{"headline": head, "body": "Open Scheduled to see what it said.",
                           "action": item["action"]}], "fallback": True}
    if k == "need":
        line = f.get("line") or ""
        if f.get("project"):  # the app shows the project beside it
            line = re.sub(r"^%s(?:#\d{4})?:?\s*" % re.escape(f["project"]), "", line)
        text = decode(line)
        if not text:
            return None
        text = text[0].upper() + text[1:]
        out = {"headline": shorten(text.partition("; ")[0], 70)}
        if len(text) > len(out["headline"]) and is_plain(text, 320):
            out["body"] = text + ("" if text.endswith((".", "+")) else ".")
        if not is_plain(out["headline"], 70):
            return None
        return {"items": [dict(out, action={"kind": "none", "target": None})], "fallback": True}
    if k == "decision":
        name = decode(TITLE_PREFIX.sub("", f.get("title") or "") or f.get("line") or "")
        if not name or not is_plain(shorten(name, 60), 60):
            return None
        return {"name": shorten(name, 60), "for_you": {"decided": shorten(name, 220)}, "fallback": True}
    return None


def cmd_put():
    try:
        incoming = json.load(sys.stdin)
    except ValueError as e:
        refuse("stdin is not JSON: %s" % e)
    if not isinstance(incoming, dict) or not incoming:
        refuse("stdin must be an object {key: words}")
    items = {i["key"]: i for group in all_items(datetime.date.today()).values() for i in group}
    for key, w in incoming.items():
        if not isinstance(key, str) or key not in items:
            refuse("unknown key %r (run bin/foryou wanted)" % key)
        check_words(items[key], w)
    cache = load_cache()
    stamp = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
    for key, w in incoming.items():
        cache[key] = {"fingerprint": items[key]["fingerprint"], "written": stamp, "words": w}
    os.makedirs(os.path.dirname(CACHE), exist_ok=True)
    lifecfg.write_atomic(CACHE, json.dumps(cache, indent=1, ensure_ascii=False))
    print("foryou: cached %d" % len(incoming))
    return cmd_build()


# ---------------------------------------------------------------- output

def public(item, keep):
    return {k: item[k] for k in keep if k in item}


def cmd_build():
    today = datetime.date.today()
    try:
        groups = all_items(today)
        ledger = ledger_months()
    except (ParseError, OSError, UnicodeDecodeError) as e:
        print("foryou: FAIL, %s" % e, file=sys.stderr)
        return 1
    cache = load_cache()
    stale = 0
    out = {"version": 1, "generated_at": datetime.datetime.now().astimezone().isoformat(timespec="seconds")}

    needs = []
    for it in groups["needs"]:
        w, written = words_for(it, cache)
        stale += w is None
        w = w or fallback(it)
        base = {"key": it["key"], "source": it["source"], "since": it["since"],
                "project": it["facts"].get("project"), "words_written": written,
                "commit_line": it["facts"].get("commit_line"),
                "fallback": bool(w and w.get("fallback"))}
        if w is None:
            needs.append(dict(base, for_you=None, action=it.get("action")))
            continue
        for n, sub in enumerate(w["items"]):
            needs.append(dict(base, key="%s#%d" % (it["key"], n) if len(w["items"]) > 1 else it["key"],
                              for_you={"headline": sub["headline"], "body": sub.get("body")},
                              action=sub["action"]))
    out["needs"] = needs

    decisions = []
    for it in groups["decisions"]:
        w, written = words_for(it, cache)
        stale += w is None
        w = w or fallback(it)
        decisions.append(dict(public(it, ("key", "project", "repo", "path", "id", "status", "date",
                                          "revisit", "days_to_revisit", "actions")),
                              name=(w or {}).get("name"), for_you=(w or {}).get("for_you"),
                              words_written=written, fallback=bool(w and w.get("fallback"))))
    out["decisions"] = decisions

    files = []
    for it in groups["files"]:
        w, written = words_for(it, cache)
        files.append(dict(public(it, ("key", "repo", "path", "project", "type", "title", "date",
                                      "status_words", "pair", "read_only", "for_you_lead")),
                          summary=(w or {}).get("summary"), words_written=written))
    out["files"] = files
    # 0477: each repo's last commit, read now, so the chat never guesses it from old file dates.
    out["repos"] = [{"name": name, "last_commit": (git_out(repo, "log", "-1", "--format=%cs") or "").strip() or None}
                    for name, repo in repos_on_mac()]
    files_stale = sum(1 for f in files if f["summary"] is None)

    projects = []
    for it in groups["projects"]:
        w, written = words_for(it, cache)
        stale += w is None
        projects.append({"key": it["key"], "slug": it["slug"], "title": it["title"],
                         "last_touched": it["last_touched"], "path": "projects/%s.md" % it["slug"],
                         "card": w, "words_written": written})
    out["projects"] = projects

    life = []
    for it in groups["life"]:
        w, written = words_for(it, cache)
        stale += w is None
        # The user's latest notes go out as they are, beside the words.
        life.append({"key": it["key"], "domain": it["domain"], "for_you": w, "words_written": written,
                     "stored": it["facts"]["stored"], "latest": it["facts"]["latest"]})
    out["life"] = life
    # A row with words shows them in `what` and `for` (the app reads those);
    # Argoni's own row stays in `line`. Without words the row is as written.
    by_key = {it["key"]: it for it in groups["ledger"]}
    ledger_stale = 0
    for m in ledger:
        for r in m["rows"]:
            w, written = words_for(by_key[r["key"]], cache)
            ledger_stale += w is None
            r["words_written"] = written
            if w:
                r["what"], r["for"] = w["what"], w.get("for")
    out["ledger"] = ledger
    out["stale"] = {"words": stale, "file_summaries": files_stale, "ledger_rows": ledger_stale}
    # What the words-on-arrival run is for: needs, decisions, project cards and
    # life cards. A card whose page changed goes blank until something asks
    # for its words again, so every one of them is listed here.
    out["wanted"] = [it["key"] for it in groups["needs"] + groups["decisions"] + groups["projects"]
                     + groups["life"] if words_for(it, cache)[0] is None]

    os.makedirs(SUMMARY, exist_ok=True)
    lifecfg.write_atomic(OUT, json.dumps(out, indent=1, ensure_ascii=False) + "\n")
    print("%s (%d bytes); %d items need words, %d file summaries missing, %d ledger rows without words"
          % (rel(OUT), os.path.getsize(OUT), stale, files_stale, ledger_stale))
    return 0


def cmd_wanted(kind=None):
    groups = all_items(datetime.date.today())
    cache = load_cache()
    want = []
    for group in groups.values():
        for it in group:
            if kind and it["kind"] != kind:
                continue
            if words_for(it, cache)[0] is None:
                want.append({k: v for k, v in it.items() if k != "fingerprint"})
    json.dump(want, sys.stdout, indent=1, ensure_ascii=False)
    print()
    return 0


# ---------------------------------------------------------------- today

LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)\)")


def cmd_links(path):
    base = os.path.dirname(os.path.abspath(path))
    bad = []
    for target in LINK.findall(file_text(path)):
        if re.match(r"^[a-z]+:", target) or target.startswith("#"):
            continue
        if not os.path.exists(os.path.normpath(os.path.join(base, target.split("#")[0]))):
            bad.append(target)
    for b in bad:
        print("foryou: missing link %s" % b)
    print("foryou: %s, %d link(s) missing" % (path, len(bad)))
    return 1 if bad else 0


def cmd_today():
    try:
        t = json.load(sys.stdin)
    except ValueError as e:
        refuse("stdin is not JSON: %s" % e)
    if not isinstance(t, dict):
        refuse("today must be an object")

    def links(obj, where):
        ls = obj.get("links") or []
        if not isinstance(ls, list):
            refuse("%s.links must be a list" % where)
        for i, l in enumerate(ls):
            if not exists(l.get("path") if isinstance(l, dict) else None):
                refuse("%s.links[%d]: %r is not a file in your folders" % (where, i, l))
            plain(l.get("label"), "%s.links[%d].label" % (where, i), 40)

    def objects(rows, where):
        for i, r in enumerate(rows):
            if not isinstance(r, dict):
                refuse("%s[%d] must be an object" % (where, i))

    plain(t.get("right_now"), "right_now", 200)
    dl = t.get("day_line")
    if not isinstance(dl, list) or not 1 <= len(dl) <= 4:
        refuse("day_line: 1 to 4 points")
    objects(dl, "day_line")
    for i, p in enumerate(dl):
        if not re.fullmatch(r"\d{2}:\d{2}", str(p.get("time"))):
            refuse("day_line[%d].time must be HH:MM" % i)
        plain(p.get("caption"), "day_line[%d].caption" % i, 60)
    bl = t.get("bullets")
    if not isinstance(bl, list) or not 1 <= len(bl) <= 5:
        refuse("bullets: 1 to 5")
    objects(bl, "bullets")
    for i, b in enumerate(bl):
        if b.get("state") not in ("done", "open", "next"):
            refuse("bullets[%d].state must be done, open or next" % i)
        plain(b.get("text"), "bullets[%d].text" % i, 200)
        links(b, "bullets[%d]" % i)
    fl = t.get("in_flight")
    if not isinstance(fl, list) or len(fl) > 4:
        refuse("in_flight: at most 4")
    objects(fl, "in_flight")
    for i, f in enumerate(fl):
        plain(f.get("name"), "in_flight[%d].name" % i, 60)
        plain(f.get("where"), "in_flight[%d].where" % i, 160)
        plain(f.get("next"), "in_flight[%d].next" % i, 160)
        plain(f.get("whose"), "in_flight[%d].whose" % i, 40)
        links(f, "in_flight[%d]" % i)
    dt = t.get("done_today")
    if not isinstance(dt, list):
        refuse("done_today must be a list")
    objects(dt, "done_today")
    for i, d in enumerate(dt):
        plain(d.get("text"), "done_today[%d].text" % i, 160)
        links(d, "done_today[%d]" % i)
    t["written_at"] = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
    try:
        t["from_summary"] = json.loads(file_text(os.path.join(SUMMARY, "summary.json"))).get("generated_at")
    except (ValueError, AttributeError):
        t["from_summary"] = None
    os.makedirs(SUMMARY, exist_ok=True)
    lifecfg.write_atomic(TODAY_OUT, json.dumps(t, indent=1, ensure_ascii=False) + "\n")
    print("%s (%d bytes)" % (rel(TODAY_OUT), os.path.getsize(TODAY_OUT)))
    return 0


def main(argv):
    cmd = argv[1] if len(argv) > 1 else "build"
    if cmd == "build":
        return cmd_build()
    if cmd == "wanted":
        return cmd_wanted(argv[2] if len(argv) > 2 else None)
    if cmd == "put":
        return cmd_put()
    if cmd == "today":
        return cmd_today()
    if cmd == "links" and len(argv) == 3:
        return cmd_links(argv[2])
    print(__doc__.split("\n\n")[1])
    return 2


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv))
    except OSError as e:  # a write refused (lifecfg.inside) or the disk: one line, no traceback
        print("foryou: FAIL, %s" % e, file=sys.stderr)
        sys.exit(1)
