Skip to content

Harmix/open-stanley / open-stanley/skills/stanley

stanley

Verified

Your head of content. Use this whenever the user wants help with LinkedIn or X (Twitter) — writing or scheduling a post, finding things to comment on, turning a meeting, voice note, or Slack thread into a post, reviewing why a post did or didn't work, planning the week's content, or asking "what should I post". Also use it for anything that mentions Stanley, ghostwriting, personal brand, founder-led content, building in public, or growing followers, even if the user doesn't say "post". Start here; it routes to the other open-stanley skills and holds the operating rules they all share.

FileKindSize
SKILL.mdskill md14.2 KB
references/capabilities.mdmarkdown3.3 KB
references/platform-access.mdmarkdown4.0 KB
references/recommended-mcps.mdmarkdown5.5 KB
references/recommended.mcp.jsonconfig2.0 KB
references/research-linkedin-2026.mdmarkdown6.7 KB
references/scheduling.mdmarkdown8.6 KB
references/vault-backends.mdmarkdown6.8 KB
references/verify-live.mdmarkdown2.2 KB
references/why-these-rules.mdmarkdown2.1 KB
scripts/stanley-auditexecutablescript24.6 KB
scripts/stanley-briefexecutablescript6.4 KB
scripts/stanley-chartexecutablescript14.5 KB
scripts/stanley-previewexecutablescript5.8 KB
scripts/stanley-statsexecutablescript14.9 KB
scripts/stanley-traceother6.3 KB
scripts/stanley-vaultexecutablescript35.1 KB

scripts/stanley-vault

View on GitHub
#!/usr/bin/env python3
"""stanley-vault: the single entry point for Open Stanley state.

The vault is a folder of markdown + jsonl (see vault-template/). It can live in a
local folder or a git repo (recommended: a private GitHub repo, because remote
scheduled runs can clone it). This script hides which.

Commands
  init [DIR] [--git URL]        create a vault from vault-template (clone URL first if given)
  path                          print the resolved vault path
  sync                          git pull --rebase && push if the vault is a git repo (no-op otherwise)
  run-start JOB                 append a run record; prints the run id
  run-end ID --delivered TEXT [--error TEXT] [--shown N] [--queued N] [--browser yes --tabs-closed N | --browser no]
  surfaced-check URL...         exit 1 and print the ones already surfaced
  surfaced-add URL --author H --platform P [--reason R]
  post-add --platform P --url U --text-file F [--story S ...] [--hook H] [--lane L] [--shape opener:event ...] [--experiment name=variant ...] [--from-meta drafts/X.meta.json] [--via publish|manual|reconciled]
  image-clean FILE... [--out F]  strip content credentials (C2PA), EXIF and XMP from PNG/JPEG before an upload
  drafts-due [--json]           scheduled drafts whose time has passed and that have no ledger row yet
  decision-add --job J --candidates JSON [--chosen S ...] [--rule R]   why a run picked what it picked (ledger/decisions.jsonl)
  verdict-add --kind draft|comment|target|question --ref X --verdict good|bad|edited|held|skipped|posted [--reason R]   the user's reaction (ledger/verdicts.jsonl)
  metrics-add --url U --bucket 1h|24h|7d --impressions N --reactions N --comments N --reposts N [--saves N]
  comment-add --platform P --url U --text-file F --verified SEEN | --skipped --reason R   (a posted comment needs --verified, see references/verify-live.md)
  diff-add --draft-file D --final-file F --platform P [--kind post|comment]
  stories-index                 rebuild stories/index.md from the story files' frontmatter
  queue-add --job J --payload JSON [--expires-hours H]   cloud runs park browser-only work here
  queue-check [--brief]         list pending, unexpired items (exit 1 if any); --brief prints one line for hooks
  queue-done ID [--result TEXT] [--failed]               mark an item done (or failed, kept for the recap)
  milestone-check --impressions-90d N | --mark-done M   exit 2 when a strategy.md milestone is crossed and not done
  is-self URL_OR_HANDLE         exit 0 if this belongs to the user (from my-human.md handles)
  snapshot                      record sha256 of every vault file (call right after mirroring from Drive/Notion)
  changed                       list files added/changed/deleted since the snapshot (what to upload back)

Resolution order for the vault path: --vault, $STANLEY_VAULT, ./stanley-vault, ~/stanley-vault.
"""
import argparse, datetime as dt, json, os, re, subprocess, sys, uuid, shutil
from pathlib import Path

HERE = Path(__file__).resolve().parent            # skills/stanley/scripts
PLUGIN_ROOT = Path(os.environ.get("CLAUDE_PLUGIN_ROOT") or HERE.parent.parent.parent)
TEMPLATE = PLUGIN_ROOT / "vault-template"

def now(): return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")

def resolve(explicit=None):
    here = Path.cwd()
    for c in [explicit, os.environ.get("STANLEY_VAULT"), "./stanley-vault", str(Path.home() / "stanley-vault"),
              str(here) if (here / "my-human.md").exists() else None]:   # a Desktop local task runs with the vault as its working folder
        if c and Path(c).expanduser().exists():
            return Path(c).expanduser().resolve()
    sys.exit("no vault found; run: stanley-vault init [DIR]")

def is_git(v): return (v / ".git").exists()

def git(v, *args, check=True):
    return subprocess.run(["git", "-C", str(v), *args], check=check, capture_output=True, text=True)

def append(v, rel, obj):
    p = v / rel; p.parent.mkdir(parents=True, exist_ok=True)
    with p.open("a", encoding="utf-8") as f: f.write(json.dumps(obj, ensure_ascii=False) + "\n")

def read_jsonl(v, rel):
    p = v / rel
    if not p.exists(): return []
    out = []
    for line in p.read_text(encoding="utf-8").splitlines():
        try: out.append(json.loads(line))
        except Exception: pass
    return out

def norm_url(u):
    u = u.strip().split("?")[0].rstrip("/")
    u = re.sub(r"^https?://(www\.)?", "", u)
    return u.lower()

def handles(v):
    p = v / "my-human.md"
    if not p.exists(): return set()
    t = p.read_text(encoding="utf-8")
    hs = set(h.lower() for h in re.findall(r"(?:linkedin\.com/in/|x\.com/|twitter\.com/|@)([A-Za-z0-9_\-]+)", t))
    return hs

def cmd_init(a):
    target = Path(a.dir or "./stanley-vault").expanduser()
    if a.git:
        subprocess.run(["git", "clone", a.git, str(target)], check=True)
    target.mkdir(parents=True, exist_ok=True)
    for src in TEMPLATE.rglob("*"):
        rel = src.relative_to(TEMPLATE); dst = target / rel
        if src.is_dir(): dst.mkdir(parents=True, exist_ok=True)
        elif not dst.exists(): shutil.copy2(src, dst)
    if not is_git(target) and not a.no_git:
        subprocess.run(["git", "init", "-q", str(target)], check=False)
    print(target.resolve())

def _ensure_identity(v):
    if not git(v, "config", "user.email", check=False).stdout.strip():
        git(v, "config", "user.email", "open-stanley@noreply.invalid", check=False)
        git(v, "config", "user.name", "Open Stanley", check=False)

def _resolve_conflicts(v):
    """jsonl: keep both sides' lines (append-only ledgers). Everything else: take the incoming (newer) side."""
    out = git(v, "diff", "--name-only", "--diff-filter=U", check=False).stdout.split()
    for rel in out:
        p = v / rel
        if rel.endswith(".jsonl"):
            ours = git(v, "show", f":2:{rel}", check=False).stdout.splitlines()
            theirs = git(v, "show", f":3:{rel}", check=False).stdout.splitlines()
            seen, merged = set(), []
            for line in ours + theirs:
                if line and line not in seen: seen.add(line); merged.append(line)
            p.write_text("\n".join(merged) + "\n", encoding="utf-8")
        else:
            git(v, "checkout", "--theirs", "--", rel, check=False)
        git(v, "add", "--", rel, check=False)
    return out

def cmd_sync(a):
    v = resolve(a.vault)
    if not is_git(v): print("not a git vault; nothing to sync"); return
    _ensure_identity(v)
    git(v, "add", "-A", check=False)
    git(v, "commit", "-qm", f"stanley sync {now()}", check=False)
    r = git(v, "remote", check=False)
    if not r.stdout.strip(): print("synced (no remote)"); return
    merged = []
    for attempt in range(3):
        pr = git(v, "pull", "--rebase", "-q", check=False)
        if pr.returncode != 0:
            conflicted = _resolve_conflicts(v)
            if conflicted:
                merged += conflicted
                git(v, "-c", "core.editor=true", "rebase", "--continue", check=False)
            else:
                git(v, "rebase", "--abort", check=False); print(f"sync: pull failed: {pr.stderr.strip()[:200]}"); sys.exit(1)
        ps = git(v, "push", "-q", check=False)
        if ps.returncode == 0:
            print("synced" + (f" (merged {', '.join(sorted(set(merged)))})" if merged else "")); return
    print(f"sync: push rejected after 3 attempts; commit kept locally: {ps.stderr.strip()[:200]}"); sys.exit(1)

def cmd_run_start(a):
    v = resolve(a.vault); rid = uuid.uuid4().hex[:8]
    append(v, "ledger/runs.jsonl", {"id": rid, "job": a.job, "started": now(), "promised": a.promised or ""})
    print(rid)

def cmd_run_end(a):
    v = resolve(a.vault)
    row = {"id": a.id, "ended": now(), "delivered": a.delivered, "error": a.error or ""}
    if a.shown is not None: row["shown"] = a.shown            # candidates/drafts/items actually shown to the human
    if a.queued is not None: row["queued"] = a.queued         # items parked for the laptop
    if a.browser is not None: row["browser"] = a.browser      # "yes" if a browser was available this run
    if a.browser == "yes":
        if a.tabs_closed is None:
            sys.exit("refused: a browser run must close the tabs it opened before run-end and pass --tabs-closed N "
                     "(skills/stanley/SKILL.md, browser tabs). Close them with tabs_close_mcp / tabs_close, then run run-end again.")
        row["tabs_closed"] = a.tabs_closed
    append(v, "ledger/runs.jsonl", row)
    print("ok")

def cmd_surfaced_check(a):
    v = resolve(a.vault)
    seen = {norm_url(r["url"]) for r in read_jsonl(v, "ledger/surfaced.jsonl") if "url" in r}
    dup = [u for u in a.urls if norm_url(u) in seen]
    for u in dup: print(u)
    sys.exit(1 if dup else 0)

def cmd_surfaced_add(a):
    v = resolve(a.vault)
    for u in a.urls:
        append(v, "ledger/surfaced.jsonl", {"url": u, "author": a.author or "", "platform": a.platform, "reason": a.reason or "", "at": now()})
    print("ok")

def cmd_post_add(a):
    v = resolve(a.vault)
    if a.via == "publish" and not (a.verified or "").strip():
        sys.exit(VERIFY_MSG.format(what="post"))
    text = Path(a.text_file).read_text(encoding="utf-8")
    shape = dict(kv.split(":", 1) for kv in (a.shape or []) if ":" in kv)
    exp = dict(kv.split("=", 1) for kv in (a.experiment or []) if "=" in kv)
    stories, lane, image = a.story or [], a.lane or "", a.image or ""
    meta = None
    if a.from_meta:   # drafts/<slug>.meta.json written by write/publish: the tags travel with the draft, so a reconciled post keeps them
        mp = Path(a.from_meta); meta = json.loads(mp.read_text(encoding="utf-8"))
        st = meta.get("story") or meta.get("stories") or []
        stories = stories or ([st] if isinstance(st, str) else list(st)); lane = lane or meta.get("lane", "")
        shape = {**(meta.get("shape") or {}), **shape}; exp = {**(meta.get("experiment") or {}), **exp}
        image = image or ("image" if meta.get("image") else "")
    date = now()[:10]
    if meta and meta.get("scheduled_for") and a.via == "reconciled": date = meta["scheduled_for"][:10]
    hook = a.hook or text.split("\n")[0][:140]
    for p in read_jsonl(v, "ledger/posts.jsonl"):   # the same post reached the ledger twice once (publish, then reconcile): refuse the duplicate
        if p.get("url") == a.url or (p.get("platform") == a.platform and p.get("hook", "")[:60].lower() == hook[:60].lower() and p.get("date", "") >= (dt.date.today() - dt.timedelta(days=30)).isoformat()):
            sys.exit(f"already in the ledger: {p.get('url')} ({p.get('date')}). Use metrics-add for numbers; nothing written.")
    append(v, "ledger/posts.jsonl", {"platform": a.platform, "url": a.url, "date": date, "hook": a.hook or text.split("\n")[0][:140],
                                     "stories": stories, "lane": lane, "shape": shape, "experiment": exp, "image": image, "kind": a.kind, "via": a.via, "verified": a.verified or "", "text": text, "metrics": {}})
    if meta is not None:
        meta.update({"status": "published", "url": a.url, "published": date}); mp.write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
    for slug in stories:   # a published story is spent: flip it so the next weekly run does not pick it again
        if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", slug): continue   # a slug is a file name, never a path
        sf = v / "stories" / f"{slug}.md"
        if sf.exists():
            t = sf.read_text(encoding="utf-8")
            t2 = re.sub(r"^status: *(fresh|drafted)\s*$", "status: used", t, count=1, flags=re.M)
            if t2 != t: sf.write_text(t2, encoding="utf-8")
    print("ok")

def cmd_metrics_add(a):
    v = resolve(a.vault); p = v / "ledger/posts.jsonl"
    rows = read_jsonl(v, "ledger/posts.jsonl"); hit = False
    for r in rows:
        if norm_url(r.get("url", "")) == norm_url(a.url):
            m = {"impressions": a.impressions, "reactions": a.reactions, "comments": a.comments, "reposts": a.reposts, "saves": a.saves, "at": now()}
            rt = {k: getattr(a, k) for k in ("like", "celebrate", "support", "love", "insight", "funny") if getattr(a, k)}
            if rt: m["reaction_types"] = rt
            r.setdefault("metrics", {})[a.bucket] = m
            hit = True
    if not hit: sys.exit("no ledger post with that url")
    p.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows), encoding="utf-8"); print("ok")

VERIFY_MSG = ("refused: a posted {what} needs --verified \"<what you saw after reloading the page>\". "
              "Reload the post, find the text outside the comment box under the user's name "
              "(skills/stanley/references/verify-live.md), then pass what you saw. Nothing is posted until that check passes.")

def cmd_comment_add(a):
    v = resolve(a.vault)
    if not a.skipped and not (a.verified or "").strip():
        sys.exit(VERIFY_MSG.format(what="comment"))
    text = Path(a.text_file).read_text(encoding="utf-8")
    append(v, "ledger/comments.jsonl", {"platform": a.platform, "url": a.url, "date": now()[:10], "text": text,
                                        "skipped": bool(a.skipped), "reason": a.reason or "", "reply_to": a.reply_to or "",
                                        "kind": "reply" if a.reply_to else "comment", "verified": a.verified or ""})
    print("ok")

def cmd_diff_add(a):
    v = resolve(a.vault)
    d = Path(a.draft_file).read_text(encoding="utf-8"); f = Path(a.final_file).read_text(encoding="utf-8")
    append(v, "learn/diffs.jsonl", {"at": now(), "platform": a.platform, "kind": a.kind, "draft": d, "final": f,
                                    "draft_words": len(d.split()), "final_words": len(f.split())})
    print("ok")

def cmd_queue_add(a):
    v = resolve(a.vault); qid = uuid.uuid4().hex[:8]
    exp = (dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=a.expires_hours)).isoformat(timespec="seconds")
    append(v, "ledger/local-queue.jsonl", {"id": qid, "job": a.job, "payload": json.loads(a.payload), "created": now(), "expires": exp, "status": "pending"})
    print(qid)

def queue_state(v):
    items = {}
    for r in read_jsonl(v, "ledger/local-queue.jsonl"):
        if "status" in r and r.get("id") in items and "job" not in r:
            items[r["id"]].update(r)
        elif "job" in r:
            items[r["id"]] = r
    n = now()
    pending, expired = [], []
    for it in items.values():
        if it.get("status") != "pending": continue
        (expired if it.get("expires", "9999") <= n else pending).append(it)
    return pending, expired

def cmd_queue_check(a):
    v = resolve(a.vault); pending, expired = queue_state(v)
    for it in expired:
        append(v, "ledger/local-queue.jsonl", {"id": it["id"], "status": "expired", "at": now()})
    if a.brief:
        if pending: print(f"open-stanley: {len(pending)} queued job(s) need this machine's browser (oldest {min(p['created'] for p in pending)[:16]}). Run /open-stanley:drain first." + (f" {len(expired)} expired." if expired else ""))
    else:
        for it in pending: print(json.dumps(it, ensure_ascii=False))
    sys.exit(1 if pending else 0)

def cmd_queue_done(a):
    v = resolve(a.vault)
    append(v, "ledger/local-queue.jsonl", {"id": a.id, "status": "failed" if a.failed else "done", "result": a.result or "", "at": now()})
    print("ok")

def cmd_stories_index(a):
    v = resolve(a.vault); d = v / "stories"
    rows = []
    for f in sorted(d.glob("*.md")):
        if f.name == "index.md" or f.name.startswith("_"): continue
        t = f.read_text(encoding="utf-8")
        fm = re.search(r"^---\n(.*?)\n---", t, re.S)
        meta = {}
        if fm:
            for line in fm.group(1).splitlines():
                if ":" in line:
                    k, val = line.split(":", 1); meta[k.strip()] = val.split("#", 1)[0].strip()
        rows.append((meta.get("topic", "uncategorized"), f.stem, meta.get("lesson", ""), meta.get("status", "fresh"), meta.get("source", "")))
    by_topic = {}
    for topic, slug, lesson, status, source in rows: by_topic.setdefault(topic, []).append((slug, lesson, status, source))
    out = ["# Stories index", "", f"{len(rows)} stories. Status: fresh = unused, used = published (see ledger), needs-material = idea without a receipt.", ""]
    for topic in sorted(by_topic):
        out.append(f"## {topic} ({len(by_topic[topic])})")
        for slug, lesson, status, source in by_topic[topic]:
            out.append(f"- [{slug}]({slug}.md) — {lesson}  `{status}`" + (f"  (source: {source})" if source else ""))
        out.append("")
    (d / "index.md").write_text("\n".join(out), encoding="utf-8")
    print(f"indexed {len(rows)} stories")

def _hashes(v):
    import hashlib
    out = {}
    for f in v.rglob("*"):
        if f.is_file() and ".git" not in f.parts and f.name != ".stanley-snapshot.json":
            out[str(f.relative_to(v))] = hashlib.sha256(f.read_bytes()).hexdigest()
    return out

def cmd_snapshot(a):
    v = resolve(a.vault); h = _hashes(v)
    (v / ".stanley-snapshot.json").write_text(json.dumps({"at": now(), "files": h}, indent=0), encoding="utf-8")
    print(f"snapshot of {len(h)} files")

def cmd_changed(a):
    v = resolve(a.vault); p = v / ".stanley-snapshot.json"
    old = json.loads(p.read_text(encoding="utf-8"))["files"] if p.exists() else {}
    new = _hashes(v)
    rows = [("added", k) for k in new if k not in old] + [("changed", k) for k in new if k in old and old[k] != new[k]] + [("deleted", k) for k in old if k not in new]
    for kind, k in sorted(rows, key=lambda r: r[1]): print(f"{kind:8} {k}")
    if not rows: print("no changes")
    # Always exit 0: the list is the result. (Earlier versions exited 1 when there were changes, which wrappers read as failure.)

def cmd_is_self(a):
    v = resolve(a.vault); hs = handles(v)
    m = re.search(r"(?:linkedin\.com/in/|x\.com/|twitter\.com/|@)([A-Za-z0-9_\-]+)", a.target)
    h = (m.group(1) if m else a.target).lower().lstrip("@")
    sys.exit(0 if h in hs else 1)


# ---- missed runs (anacron for scheduled tasks) ----
_DOW = {"mon":0,"tue":1,"wed":2,"thu":3,"fri":4,"sat":5,"sun":6}

def _human_lines(v):
    p = v / "my-human.md"
    return p.read_text(encoding="utf-8").splitlines() if p.exists() else []

def _tz(v):
    for line in _human_lines(v):
        m = re.search(r"\b([A-Z][A-Za-z_]+/[A-Za-z_]+(?:/[A-Za-z_]+)?)\b", line)
        if m and ("tz" in line.lower() or "time zone" in line.lower() or "timezone" in line.lower()):
            try:
                from zoneinfo import ZoneInfo; return ZoneInfo(m.group(1))
            except Exception: pass
    return dt.timezone.utc

def schedule(v):
    """Parse `- schedule: job=daily HH:MM[,HH:MM]; job=weekly dow HH:MM; job=monthly D HH:MM` and
    `- catch_up: a, b, c<6h` from my-human.md. `job<Nh` = catch up only if fewer than N hours late."""
    sched, catch = {}, {}
    for line in _human_lines(v):
        low = line.strip().lower()
        if low.startswith("- schedule:"):
            for part in line.split(":", 1)[1].split(";"):
                if "=" not in part: continue
                job, spec = [x.strip() for x in part.split("=", 1)]
                toks = spec.split()
                if not toks: continue
                kind = toks[0].lower()
                if kind == "daily" and len(toks) >= 2: sched[job] = ("daily", None, toks[1].split(","))
                elif kind == "weekly" and len(toks) >= 3: sched[job] = ("weekly", _DOW.get(toks[1][:3].lower(), 0), [toks[2]])
                elif kind == "monthly" and len(toks) >= 3: sched[job] = ("monthly", int(toks[1]), [toks[2]])
        elif low.startswith("- catch_up:") or low.startswith("- catch-up:"):
            for x in line.split(":", 1)[1].split("#")[0].split(","):
                x = x.strip()
                if not x: continue
                m = re.match(r"([\w\-]+)\s*<\s*(\d+(?:\.\d+)?)h", x)
                if m: catch[m.group(1)] = float(m.group(2))
                else: catch[x] = None
    return sched, catch

def _last_due(kind, when, times, now_local):
    """Most recent due datetime <= now_local for one job."""
    best = None
    for t in times:
        hh, mm = [int(x) for x in t.split(":")]
        for back in range(0, 40):
            d = now_local.date() - dt.timedelta(days=back)
            if kind == "weekly" and d.weekday() != when: continue
            if kind == "monthly" and d.day != when: continue
            cand = dt.datetime(d.year, d.month, d.day, hh, mm, tzinfo=now_local.tzinfo)
            if cand <= now_local:
                if best is None or cand > best: best = cand
                break
    return best

_PERIOD_H = {"daily": 24, "weekly": 168, "monthly": 720}

def missed(v, grace_min=20, max_age_h=None):
    sched, catch = schedule(v)
    tz = _tz(v); now_local = dt.datetime.now(tz)
    runs = read_jsonl(v, "ledger/runs.jsonl")
    out = []
    for job, (kind, when, times) in sched.items():
        due = _last_due(kind, when, times, now_local)
        if due is None: continue
        age_h = (now_local - due).total_seconds() / 3600
        if age_h * 60 < grace_min: continue                      # may still be starting
        cap = max_age_h if max_age_h is not None else _PERIOD_H[kind]
        if age_h > cap: continue   # superseded: the next occurrence is due, so this is not a catch-up any more
        window = due - dt.timedelta(minutes=90)                  # a UTC cron fires an hour early once DST ends, and that run still counts
        ran = any(r.get("job") == job and r.get("started") and dt.datetime.fromisoformat(r["started"].replace("Z", "+00:00")) >= window for r in runs)
        if not ran:
            limit = catch.get(job, "no")
            worth = limit != "no" and (limit is None or age_h < limit)
            out.append({"job": job, "due": due.isoformat(timespec="minutes"), "hours_ago": round(age_h, 1), "catch_up": worth,
                        "window_h": limit if limit not in ("no", None) else None})
    return out

def cmd_missed(a):
    v = resolve(a.vault)
    rows = missed(v, max_age_h=a.max_age_hours)
    if a.json: print(json.dumps(rows, ensure_ascii=False))
    elif a.brief:
        worth = [r["job"] for r in rows if r["catch_up"]]
        if worth: print(f"open-stanley: missed scheduled run(s) worth catching up: {', '.join(worth)}. Say 'catch up' to run them now.")
    else:
        for r in rows: print(f"MISSED {r['job']} due {r['due']} ({r['hours_ago']}h ago) catch-up:{'yes' if r['catch_up'] else 'no'}")
        if not rows: print("nothing missed")
    sys.exit(1 if any(r["catch_up"] for r in rows) else 0)

# --- images and scheduled drafts -------------------------------------------------------------
_PNG_META = {b"caBX", b"tEXt", b"iTXt", b"zTXt", b"eXIf"}   # caBX = C2PA/JUMBF content credentials ("made by Claude" when rendered in a cloud sandbox)

def image_clean(src, dst=None):
    """Strip provenance/metadata from a PNG or JPEG. Returns the list of removed chunk/segment names."""
    import struct
    src = Path(src); dst = Path(dst) if dst else src
    d = src.read_bytes(); removed = []
    if d[:8] == b"\x89PNG\r\n\x1a\n":
        out = bytearray(d[:8]); i = 8
        while i + 8 <= len(d):
            n = struct.unpack(">I", d[i:i+4])[0]; t = d[i+4:i+8]; chunk = d[i:i+12+n]
            if t in _PNG_META: removed.append(t.decode("latin1"))
            else: out += chunk
            i += 12 + n
        dst.write_bytes(bytes(out))
    elif d[:2] == b"\xff\xd8":
        out = bytearray(d[:2]); i = 2
        while i + 4 <= len(d):
            if d[i] != 0xFF: out += d[i:]; break
            marker = d[i+1]
            if marker == 0xDA: out += d[i:]; break            # start of scan: copy the rest
            n = struct.unpack(">H", d[i+2:i+4])[0]; seg = d[i:i+2+n]
            if marker in (0xE1, 0xEB, 0xED, 0xEE):           # APP1 (Exif/XMP), APP11 (JUMBF/C2PA), APP13 (IPTC), APP14 (Adobe)
                removed.append({0xE1: "APP1", 0xEB: "APP11", 0xED: "APP13", 0xEE: "APP14"}[marker])
            else: out += seg
            i += 2 + n
        dst.write_bytes(bytes(out))
    else:
        sys.exit(f"{src}: not a PNG or JPEG; convert it first")
    return removed

def cmd_image_clean(a):
    for f in a.files:
        removed = image_clean(f, a.out if a.out and len(a.files) == 1 else None)
        print(f"{f}: removed {', '.join(removed) if removed else 'nothing'}" + (" (had content credentials)" if "caBX" in removed or "APP11" in removed else ""))

def cmd_decision_add(a):
    """Why a run chose what it chose. One row per decision; candidates is a JSON list of {slug, score, why} so later stats can ask 'did the picks the user kept score high?'."""
    v = resolve(a.vault)
    try: cands = json.loads(a.candidates)
    except json.JSONDecodeError as e: sys.exit(f"--candidates must be JSON: {e}")
    append(v, "ledger/decisions.jsonl", {"at": now(), "job": a.job, "run": a.run or "", "kind": a.kind, "candidates": cands, "chosen": a.chosen or [], "rule": a.rule or ""})
    print("ok")

def cmd_verdict_add(a):
    """The user's reaction to a draft, comment or pick: good | bad | edited | held | skipped, with their words. The learn skill reads this instead of mining prose notes."""
    v = resolve(a.vault)
    append(v, "ledger/verdicts.jsonl", {"at": now(), "kind": a.kind, "ref": a.ref, "verdict": a.verdict, "reason": a.reason or "", "run": a.run or ""})
    print("ok")

def load_meta(v):
    out = []
    for m in sorted((v / "drafts").glob("*.meta.json")):
        try: j = json.loads(m.read_text(encoding="utf-8"))
        except Exception: continue
        j["_meta"] = m; j["_draft"] = m.with_name(m.name.replace(".meta.json", ".md")); out.append(j)
    return out

def cmd_drafts_due(a):
    """Scheduled drafts whose time has passed and whose hook is not in the ledger: what recap must reconcile, with the tags intact."""
    v = resolve(a.vault)
    hooks = {p.get("hook", "")[:60].lower() for p in read_jsonl(v, "ledger/posts.jsonl")}
    nowl = dt.datetime.now().astimezone()
    due = []
    for j in load_meta(v):
        if j.get("status") != "scheduled" or not j.get("scheduled_for"): continue
        when = j["scheduled_for"].split(" ")[0]
        try: t = dt.datetime.fromisoformat(when)
        except ValueError: continue
        if t.tzinfo is None: t = t.replace(tzinfo=nowl.tzinfo)
        if t > nowl: continue
        hook = j["_draft"].read_text(encoding="utf-8").strip().split("\n")[0] if j["_draft"].exists() else ""
        if hook[:60].lower() in hooks: continue
        due.append({**{k: j.get(k) for k in ("story", "lane", "shape", "experiment", "image", "scheduled_for", "platform")}, "draft": j["_draft"].name, "meta": j["_meta"].name, "hook": hook})
    if a.json: print(json.dumps(due, ensure_ascii=False, default=str)); return
    for d in due:
        print(f"DUE {d['scheduled_for']}  {d['draft']}\n  hook: {d['hook'][:100]}\n  post-add --platform linkedin --url <live url> --text-file drafts/{d['draft']} --from-meta drafts/{d['meta']} --via reconciled")
    if not due: print("no scheduled drafts past their time without a ledger row")

def _milestone_lists(text):
    """Read `- milestones:` and `- milestones_done:` from strategy.md. Only the numbers before any '(' or '#' count,
    so a note such as '(100K crossed on 11-07, one post for it)' never marks 100000 done."""
    def nums(key):
        m = re.search(r"^\s*-?\s*" + key + r"\s*:\s*(.*)$", text, re.M)
        if not m: return []
        val = re.split(r"[#(]", m.group(1))[0]
        out = []
        for t in re.findall(r"\d[\d,_]*\s*[kKmM]?", val):
            t = t.strip().replace(",", "").replace("_", "")
            mult = 1000 if t[-1] in "kK" else 1_000_000 if t[-1] in "mM" else 1
            out.append(int(t.rstrip("kKmM").strip()) * mult)
        return out
    return nums("milestones"), nums("milestones_done")

def cmd_milestone_check(a):
    """Compare the 90-day impressions read from LinkedIn's content analytics with strategy.md's milestones."""
    v = resolve(a.vault); p = v / "strategy.md"
    text = p.read_text(encoding="utf-8") if p.exists() else ""
    todo, done = _milestone_lists(text)
    if a.mark_done is not None:
        m = a.mark_done
        new_done = sorted(set(done) | {m}); new_todo = [x for x in todo if x != m]
        line_done = "- milestones_done: " + ", ".join(str(x) for x in new_done) + f"   # {m} marked done {dt.date.today().isoformat()}"
        if re.search(r"^\s*-?\s*milestones_done\s*:.*$", text, re.M):
            text = re.sub(r"^\s*-?\s*milestones_done\s*:.*$", line_done, text, count=1, flags=re.M)
        else:
            text = text.rstrip("\n") + "\n" + line_done + "\n"
        text = re.sub(r"^(\s*-?\s*milestones\s*:)[^#\n]*", lambda mm: mm.group(1) + " " + ", ".join(str(x) for x in new_todo) + "   ", text, count=1, flags=re.M)
        p.write_text(text, encoding="utf-8"); print(f"marked {m} done"); return
    n = a.impressions_90d
    crossed = [m for m in sorted(set(todo) | set(done)) if n >= m and m not in done]
    if crossed:
        m = max(crossed)
        print(f"CROSSED {m}: 90-day impressions {n:,} >= {m:,} and {m} is not in milestones_done. Draft the milestone post now (recap 4c); one post for the highest number crossed: {', '.join(str(x) for x in crossed)}.")
        sys.exit(2)
    nxt = [m for m in sorted(todo) if m > n and m not in done]
    print(f"no milestone crossed: 90-day impressions {n:,}" + (f"; next {nxt[0]:,} ({n * 100 // nxt[0]}%)" if nxt else "; no milestone left in strategy.md"))

def main():
    ap = argparse.ArgumentParser(); ap.add_argument("--vault")
    sp = ap.add_subparsers(dest="cmd", required=True)
    p = sp.add_parser("init"); p.add_argument("dir", nargs="?"); p.add_argument("--git"); p.add_argument("--no-git", action="store_true"); p.set_defaults(f=cmd_init)
    p = sp.add_parser("path"); p.set_defaults(f=lambda a: print(resolve(a.vault)))
    p = sp.add_parser("sync"); p.set_defaults(f=cmd_sync)
    p = sp.add_parser("run-start"); p.add_argument("job"); p.add_argument("--promised"); p.set_defaults(f=cmd_run_start)
    p = sp.add_parser("run-end"); p.add_argument("id"); p.add_argument("--delivered", required=True); p.add_argument("--error")
    p.add_argument("--shown", type=int); p.add_argument("--queued", type=int); p.add_argument("--browser", choices=["yes", "no"]); p.add_argument("--tabs-closed", type=int, help="browser tabs this run opened and closed (required with --browser yes)"); p.set_defaults(f=cmd_run_end)
    p = sp.add_parser("surfaced-check"); p.add_argument("urls", nargs="+"); p.set_defaults(f=cmd_surfaced_check)
    p = sp.add_parser("surfaced-add"); p.add_argument("urls", nargs="+"); p.add_argument("--author"); p.add_argument("--platform", required=True); p.add_argument("--reason"); p.set_defaults(f=cmd_surfaced_add)
    p = sp.add_parser("post-add"); p.add_argument("--platform", required=True); p.add_argument("--url", required=True); p.add_argument("--text-file", required=True); p.add_argument("--story", action="append"); p.add_argument("--hook"); p.add_argument("--lane"); p.add_argument("--shape", action="append", help="opener:event ending:flat"); p.add_argument("--experiment", action="append", help="name=variant"); p.add_argument("--image", default="", help="image|carousel|video|doc or a URL; empty = text-only"); p.add_argument("--kind", default="post", choices=["post", "repost"]); p.add_argument("--via", default="", help="publish|manual|reconciled"); p.add_argument("--verified", help="what you saw after reloading the live post (required with --via publish)"); p.add_argument("--from-meta", help="drafts/<slug>.meta.json: take story/lane/shape/experiment/image from it and mark it published"); p.set_defaults(f=cmd_post_add)
    p = sp.add_parser("image-clean", help="strip C2PA/EXIF/XMP from a PNG or JPEG in place (or --out)"); p.add_argument("files", nargs="+"); p.add_argument("--out"); p.set_defaults(f=cmd_image_clean)
    p = sp.add_parser("drafts-due", help="scheduled drafts past their time with no ledger row"); p.add_argument("--json", action="store_true"); p.set_defaults(f=cmd_drafts_due)
    p = sp.add_parser("decision-add", help="log a run's ranked candidates and what it chose"); p.add_argument("--job", required=True); p.add_argument("--kind", default="story-pick", help="story-pick|comment-target|slot"); p.add_argument("--candidates", required=True, help='JSON list of {"slug","score","why"}'); p.add_argument("--chosen", action="append"); p.add_argument("--rule", help="the one line that decided it"); p.add_argument("--run"); p.set_defaults(f=cmd_decision_add)
    p = sp.add_parser("verdict-add", help="log the user's verdict on a draft/comment/pick"); p.add_argument("--kind", required=True, choices=["draft", "comment", "target", "question"]); p.add_argument("--ref", required=True, help="drafts/<file>, a URL, or a story slug"); p.add_argument("--verdict", required=True, choices=["good", "bad", "edited", "held", "skipped", "posted"]); p.add_argument("--reason", help="the user's words"); p.add_argument("--run"); p.set_defaults(f=cmd_verdict_add)
    p = sp.add_parser("metrics-add"); p.add_argument("--url", required=True); p.add_argument("--bucket", required=True, choices=["1h", "24h", "7d"]);
    for k in ("impressions", "reactions", "comments", "reposts", "saves"): p.add_argument("--" + k, type=int, default=0)
    for k in ("like", "celebrate", "support", "love", "insight", "funny"): p.add_argument("--" + k, type=int, default=0, help="reaction-type count from the post page")
    p.set_defaults(f=cmd_metrics_add)
    p = sp.add_parser("comment-add"); p.add_argument("--platform", required=True); p.add_argument("--url", required=True); p.add_argument("--text-file", required=True); p.add_argument("--skipped", action="store_true"); p.add_argument("--reason"); p.add_argument("--reply-to", help="URL of the comment/reply this answers (marks it kind=reply)"); p.add_argument("--verified", help="what you saw after reloading the post: the comment under the user's name (required unless --skipped)"); p.set_defaults(f=cmd_comment_add)
    p = sp.add_parser("diff-add"); p.add_argument("--draft-file", required=True); p.add_argument("--final-file", required=True); p.add_argument("--platform", required=True); p.add_argument("--kind", default="post"); p.set_defaults(f=cmd_diff_add)
    p = sp.add_parser("stories-index"); p.set_defaults(f=cmd_stories_index)
    p = sp.add_parser("snapshot"); p.set_defaults(f=cmd_snapshot)
    p = sp.add_parser("changed"); p.set_defaults(f=cmd_changed)
    p = sp.add_parser("queue-add"); p.add_argument("--job", required=True); p.add_argument("--payload", required=True); p.add_argument("--expires-hours", type=float, default=24); p.set_defaults(f=cmd_queue_add)
    p = sp.add_parser("queue-check"); p.add_argument("--brief", action="store_true"); p.set_defaults(f=cmd_queue_check)
    p = sp.add_parser("queue-done"); p.add_argument("id"); p.add_argument("--result"); p.add_argument("--failed", action="store_true"); p.set_defaults(f=cmd_queue_done)
    p = sp.add_parser("missed", help="scheduled runs that did not happen (needs `- schedule:` in my-human.md)"); p.add_argument("--brief", action="store_true"); p.add_argument("--json", action="store_true"); p.add_argument("--max-age-hours", type=float, default=None); p.set_defaults(f=cmd_missed)
    p = sp.add_parser("milestone-check", help="90-day impressions vs strategy.md milestones; exit 2 when one is crossed and not done"); g = p.add_mutually_exclusive_group(required=True); g.add_argument("--impressions-90d", type=lambda x: int(x.replace(",", ""))); g.add_argument("--mark-done", type=int); p.set_defaults(f=cmd_milestone_check)
    p = sp.add_parser("is-self"); p.add_argument("target"); p.set_defaults(f=cmd_is_self)
    a = ap.parse_args(); a.f(a)

if __name__ == "__main__":
    main()
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall