diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 9944242b..5c48ca6a 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -196,6 +196,18 @@ never the *authority*. A shift brief written with `review-at:` is that act in writing (2026-11-03): the human dispatches by writing it, and its scope is the whole grant (`AUTONOMY.md`, "Shift briefs and unattended `glance`"). +`batch brief --new --review-at ` composes that writing: +a skeleton brief whose `goals:` are `PyAutoMind/goals.md`'s, in order, with +`backlog: scoped` to their `epics:`/`tags:` (else `fill-idle`) and +`merge-cap: 0`. It prints to stdout (`--out FILE` writes it) and never writes a +record into `batches/` — saving it there is the human's dispatch. +A goal whose line was last written by a `Via: mind-dashboard` commit (git +blame) is web-page text, so it is emitted commented out — "from dashboard, +last edited " — and never reaches a worker unless the human adopts it; +`--new` also prints on stderr how the goals changed since the newest brief. +`brief --check` warns when `goals.md`'s goal 1 is missing from a brief, unless +goal 1 came from the dashboard (PyAutoMind#565; readers in `_steer.py`). + ## The watcher (phases 3a–3d) `bin/orchestrator_watch.py --brief --mind ` runs **one diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index bac38479..e3227081 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -55,6 +55,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from _status import PENDING_RE, RULING_WORDS, freeze_line # noqa: E402 import _brief # noqa: E402 +# The human's goals (goals.md, PyAutoMind#565): `brief --new` copies them. +from _steer import read_goals # noqa: E402,F401 — re-exported beside read_queue # The close-out guard's reader (intake `looks-shipped`): the live flags minus # human dismissals. Loaded by path — a plain `import _shipped` would also work # once intake's directory is on sys.path, but this keeps the batch planner from @@ -2920,6 +2922,10 @@ def main(argv=None) -> int: ap.add_argument("--check", default="", metavar="FILE", help="brief: validate this shift brief against " "PyAutoMind/batches/AGENTS.md") + ap.add_argument("--new", default="", metavar="SLOT", + help="brief: print a skeleton shift brief for SLOT (e.g. " + "2026-11-14-am) whose goals: come from goals.md; " + "needs --review-at; --out FILE writes it instead") ap.add_argument("--brief", default="", metavar="FILE", help="plan: compose inside this shift brief (named tasks " "first, then its backlog policy)") @@ -3170,13 +3176,243 @@ def _main_watch(a) -> int: interval=a.interval, once=a.once) +#: A brief's slot names its record, `batches/.md`. +SLOT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}-(am|pm)$") +#: Defaults `brief --new` writes for the keys the human usually leaves alone. +#: `merge-cap: 0` is the safe one: nothing merges unattended until raised. +NEW_BRIEF_DEFAULTS = {"review-minutes": str(DEFAULT_REVIEW_BUDGET), + "lanes": "any", "merge-cap": "0", + "token-budget": "2000000"} + + +#: The trailer every dashboard write carries (PyAutoMind `dashboard_input.py`). +DASHBOARD_TRAILER_RE = re.compile(r"^Via: mind-dashboard\s*$", re.M) + + +def goal_provenance(mind: Path) -> list[dict] | None: + """Per goal, in order: `{"dashboard": bool, "date": "YYYY-MM-DD"}` — whether + the goal's line was last written by a `Via: mind-dashboard` commit, and when. + + A goal from the dashboard is free text from a web page, written through a + browser token (PyAutoMind#565): `brief --new` never hands it to workers as + the human's word. A line not yet committed is the human's local edit. + None when provenance cannot be read (no git checkout, an uncommitted + file, or a blame that does not line up with the goals): callers then + treat EVERY goal as untrusted (`resolve_provenance`).""" + try: + out = subprocess.run(["git", "-C", str(mind), "blame", "--line-porcelain", + "--", "goals.md"], capture_output=True, text=True, + timeout=30) + except (OSError, subprocess.TimeoutExpired): + return None + if out.returncode != 0: + return None + lines, cur = [], {} + for line in out.stdout.split("\n"): + if line.startswith("\t"): + lines.append((cur.get("sha", ""), cur.get("time", 0), line[1:])) + continue + m = re.match(r"^([0-9a-f]{40}) \d+ \d+", line) + if m: + cur = {"sha": m.group(1)} + elif line.startswith("author-time "): + cur["time"] = int(line.split()[1]) + heads, fenced = [], False + for sha, when, text in lines: + if text.lstrip().startswith("```"): + fenced = not fenced + elif not fenced and re.match(r"^##\s+\d+\.\s+\S", text): + heads.append((sha, when)) + if len(heads) != len(read_goals(mind)): + return None + verdict: dict[str, bool] = {} + out_list = [] + for sha, when in heads: + if sha not in verdict: + body = "" + if sha and set(sha) != {"0"}: + body = subprocess.run(["git", "-C", str(mind), "show", "-s", + "--format=%B", sha], capture_output=True, + text=True).stdout + verdict[sha] = bool(DASHBOARD_TRAILER_RE.search(body)) + date = (_dt.datetime.fromtimestamp(when, _dt.timezone.utc).date().isoformat() + if when else "") + out_list.append({"dashboard": verdict[sha], "date": date}) + return out_list + + +def resolve_provenance(mind: Path, prov: list[dict] | None) -> list[dict]: + """Per-goal provenance that fails closed: unknown means untrusted.""" + goals = read_goals(mind) + if prov is None or len(prov) != len(goals): + return [{"dashboard": True, "date": "", "unknown": True} for _ in goals] + return prov + + +def _last_brief_goals(mind: Path) -> tuple[str, list[str]] | None: + """(record name, goal texts) of the newest batch record with a brief.""" + records = sorted(f for f in (mind / "batches").glob("*.md") if f.name != "AGENTS.md") + for f in reversed(records): + try: + brief = _brief.parse(f.read_text(encoding="utf-8", errors="replace"))["brief"] + except (OSError, _brief.BriefError): + continue + if brief and brief.get("goals"): + return f.name, [re.sub(r"^\d+\.\s*", "", c["text"]) + for c in brief["goals"]["children"]] + return None + + +def goals_report(mind: Path, prov: list[dict] | None) -> list[str]: + """What `brief --new` tells the human on stderr: provenance, then how the + goals changed since the newest brief.""" + goals = [g["text"] for g in read_goals(mind)] + L = [] + if prov is None and goals: + L.append("goals: provenance unknown (no git history lines up with goals.md) — " + "every goal is left commented out; adopt them by hand") + for g, p in zip(goals, prov or []): + if p["dashboard"]: + L.append(f"goals: \"{g}\" is from the dashboard (last edited " + f"{p['date']}) — left commented out; adopt it by hand") + last = _last_brief_goals(mind) + if last is None: + L.append("goals: no earlier brief to compare with") + return L + name, before = last + added = [g for g in goals if g not in before] + dropped = [g for g in before if g not in goals] + moved = [(g, before.index(g) + 1, goals.index(g) + 1) for g in goals + if g in before and before.index(g) != goals.index(g)] + if not (added or dropped or moved): + L.append(f"goals: unchanged since {name}") + return L + L.append(f"goals since {name}:") + L += [f" + {g}" for g in added] + [f" - {g}" for g in dropped] + L += [f" ~ {g} ({a} → {b})" for g, a, b in moved] + return L + + +_UNSET = object() + + +def new_brief(mind: Path, slot: str, review_at: str, now=None, + prov=_UNSET) -> str: + """A skeleton shift brief whose `goals:` are `goals.md`'s, in order. + + A goal last written from the dashboard is emitted commented out, marked + with its date: workers never see it until the human adopts it by hand. + So is every goal when provenance cannot be read ("provenance unknown"). + `backlog: scoped` covers the union of the hand-written goals' + `epics:`/`tags:`; with none named, `fill-idle`. Every other required key + gets a default the human edits. Writing the record (with its `review-at:`) + is the dispatch, so this only composes the text (batches/AGENTS.md + "Shift brief").""" + goals = read_goals(mind) + prov = resolve_provenance(mind, goal_provenance(mind) if prov is _UNSET else prov) + now = now or _dt.datetime.now(_dt.timezone.utc) + epics: list[str] = [] + tags: list[str] = [] + for g, p in zip(goals, prov): + if p["dashboard"]: + continue + epics += [e for e in g["epics"] if e not in epics] + tags += [t for t in g["tags"] if t not in tags] + shift = {"am": "morning", "pm": "afternoon"}.get(slot.rsplit("-", 1)[-1], slot) + L = [f"# Batch {slot.rsplit('-', 1)[0]} {slot.rsplit('-', 1)[-1]}", + f"- dispatched: {now.strftime('%Y-%m-%dT%H:%MZ')}", + f"- review-at: {review_at}", + f"- shift: {shift}", + "- brief:", + " - goals: # from goals.md, in order"] + for g, p in zip(goals, prov): + # A goal is one line of plain text (goals.md's own check); ` # ` would + # read as a trailing comment here, so it is spelled out. + text = f"{g['n']}. " + re.sub(r"\s#\s", " no. ", g["text"]) + if p.get("unknown"): + L.append(f" # - {text} <- provenance unknown: not adopted; " + "delete the '# ' to adopt") + elif p["dashboard"]: + L.append(f" # - {text} <- from dashboard, last edited {p['date']}: " + "not adopted; delete the '# ' to adopt") + else: + L.append(f" - {text}") + if epics or tags: + L += [" - backlog: scoped # the goals' epics and tags", + " - scoped:"] + if epics: + L.append(f" - epics: {', '.join(epics)}") + if tags: + L.append(f" - tags: {', '.join(tags)}") + else: + L.append(" - backlog: fill-idle # no goal names an epic or tag") + L += [f" - review-minutes: {NEW_BRIEF_DEFAULTS['review-minutes']}", + f" - lanes: {NEW_BRIEF_DEFAULTS['lanes']}", + f" - merge-cap: {NEW_BRIEF_DEFAULTS['merge-cap']}" + " # unattended glance merges: raise deliberately", + f" - token-budget: {NEW_BRIEF_DEFAULTS['token-budget']}"] + return "\n".join(L) + "\n" + + +def goal_one_warning(path: Path, mind: Path) -> str: + """A warning when `goals.md`'s goal 1 is missing from the brief at `path` + — never for a dashboard-sourced goal 1, which the human adopts or not.""" + goals = read_goals(mind) + if not goals: + return "" + prov = resolve_provenance(mind, goal_provenance(mind)) + if prov[0]["dashboard"]: + return "" + try: + brief = _brief.parse(path.read_text(encoding="utf-8", errors="replace"))["brief"] + except (OSError, _brief.BriefError): + return "" + node = (brief or {}).get("goals") + have = " ".join(c["text"] for c in node["children"]) if node else "" + if goals[0]["text"].lower() in have.lower(): + return "" + return (f"brief.goals: goal 1 of goals.md (\"{goals[0]['text']}\") is not " + "in this brief — `batch brief --new` copies the current list") + + def _main_brief(mind: Path, a) -> int: - """`batch brief --check ` — read-only; exit 0 valid, 1 refused.""" + """`batch brief --check ` — read-only; exit 0 valid, 1 refused. + `batch brief --new --review-at ` — print (or `--out`) a + skeleton brief whose goals come from goals.md.""" + if a.new: + if a.check: + print("batch brief: --new and --check are separate runs", file=sys.stderr) + return RC_USAGE + if not SLOT_RE.match(a.new): + print(f"batch brief --new: slot {a.new!r} is not YYYY-MM-DD-am|pm", + file=sys.stderr) + return RC_USAGE + if not a.review_at or _brief._iso(a.review_at) is None: + print("batch brief --new: --review-at is required — the " + "grant expires there, and it is yours to declare", file=sys.stderr) + return RC_USAGE + prov = goal_provenance(mind) + text = new_brief(mind, a.new, a.review_at, prov=prov) + for line in goals_report(mind, prov): + print(line, file=sys.stderr) + if a.out: + Path(a.out).write_text(text, encoding="utf-8") + print(f"batch brief --new: wrote {a.out} " + f"({len(read_goals(mind))} goal(s) from goals.md)") + else: + sys.stdout.write(text) + if not read_goals(mind): + print("batch brief --new: goals.md has no goals — `brief --check` " + "refuses a brief without one", file=sys.stderr) + return RC_OK if not a.check: - print("batch brief: --check is the only brief verb " + print("batch brief: --check or --new " "(the digest is `batch digest --record `)", file=sys.stderr) return RC_USAGE res = _brief.check(Path(a.check), mind) + warn = goal_one_warning(Path(a.check), mind) + if warn: + res["warnings"].append(warn) # The premise leg: a named task whose premise is gone on main is flagged # here, before the shift pays a worker to discover it. A warning, not a # refusal — the check is mechanical, and the human reads the evidence. diff --git a/agents/conductors/batch/_steer.py b/agents/conductors/batch/_steer.py new file mode 100644 index 00000000..21e309c7 --- /dev/null +++ b/agents/conductors/batch/_steer.py @@ -0,0 +1,92 @@ +"""The human's two steering files in the Mind: `queue.md` and `goals.md`. + +Readers only. `queue.md` is the ordered list of prompts the human wants done +(the planner's statement of importance); `goals.md` is the ordered list of +goals a shift brief copies into `goals:` (PyAutoMind#565). Both are written by +hand or by the Mind's `dashboard_input.yml` (the ★ and Goals box on the +published dashboard), and validated by the Mind's `lifecycle.py check`. + +The grammar is the one `lifecycle.py` and `_batch.read_queue` read: a fenced +block is the schema's own example, any heading ends the entry above it, and +only a numbered `## . ` heading starts one. The dashboard's client +(`intake/dashboard_edit.js`) parses the same way; a test holds them together. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +ENTRY_RE = re.compile(r"^##\s+\d+\.\s+(.+?)\s*$") +QUEUE_FIELD_RE = re.compile(r"^-\s+(kind|ref|note):\s*(.+?)\s*$") +GOAL_FIELD_RE = re.compile(r"^-\s+(epics|tags|note):\s*(.*?)\s*$") + + +def _read(path: Path) -> str: + try: + return path.read_text(encoding="utf-8", errors="replace") + except OSError: + return "" + + +def _entries(text: str, field_re: re.Pattern) -> list[dict]: + out: list[dict] = [] + cur, fenced = None, False + for line in text.split("\n"): + if line.lstrip().startswith("```"): + fenced = not fenced + continue + if fenced: + continue + if line.startswith("#"): + m = ENTRY_RE.match(line) + cur = {"text": m.group(1), "fields": {}} if m else None + if cur is not None: + out.append(cur) + continue + m = field_re.match(line) if cur is not None else None + if m and m.group(1) not in cur["fields"]: + cur["fields"][m.group(1)] = m.group(2) + return out + + +def read_queue_entries(mind: Path) -> list[dict]: + """The live `queue.md` entries, top first: `{pos, label, kind, ref, note}`. + + Every numbered entry is listed (its position is its place in the file); + only `kind: prompt` entries carry a `ref` the planner reads. An absent + file is an empty list.""" + out = [] + for n, e in enumerate(_entries(_read(mind / "queue.md"), QUEUE_FIELD_RE), 1): + f = e["fields"] + out.append({"pos": n, "label": e["text"], + "kind": f.get("kind", "").split("#")[0].strip(), + "ref": f.get("ref", "").split("#")[0].strip(), + "note": f.get("note", "")}) + return out + + +def queued_names(entries: list[dict]) -> dict[str, int]: + """{prompt basename: queue position} — how the lifecycle matches an entry + (a `draft/` ref keeps its place once the prompt moves to `active/`).""" + out: dict[str, int] = {} + for e in entries: + if e["kind"] == "prompt" and e["ref"]: + out.setdefault(Path(e["ref"]).name, e["pos"]) + return out + + +def _csv(value: str) -> list[str]: + return [v for v in re.split(r"[,\s]+", value.split(" #")[0].strip()) if v] + + +def read_goals(mind: Path) -> list[dict]: + """`goals.md`'s goals, top first: `{n, text, epics, tags, note}`. An + absent file is an empty list.""" + out = [] + for n, e in enumerate(_entries(_read(mind / "goals.md"), GOAL_FIELD_RE), 1): + f = e["fields"] + out.append({"n": n, "text": e["text"], "epics": _csv(f.get("epics", "")), + "tags": _csv(f.get("tags", "")), + "note": f.get("note", "").split(" #")[0].strip()}) + return out diff --git a/agents/conductors/intake/AGENTS.md b/agents/conductors/intake/AGENTS.md index 180767e9..57ffe925 100644 --- a/agents/conductors/intake/AGENTS.md +++ b/agents/conductors/intake/AGENTS.md @@ -124,7 +124,7 @@ with or without it. Unknown keywords are counted in the page's Hygiene section. | **classify** | `intake ""` / `intake classify --file P [--lane L]` | classify one raw input; `--apply` writes the prompt — and **refuses** (exit 6) when no lane is decided: no `--lane`, no `Lane:` header in the text, no resource signal (M2.3, `AUTONOMY.md` "M2 rulings — 2026-11-12") | | **ideas** | `intake ideas [--lane L]` | scan `ideas.md`, propose one prompt per bullet; `--apply` writes them, refusing (and not marking) any bullet with no decided lane | | **census** | `intake census` | inventory every filed prompt (work-type/target/difficulty/status + hygiene flags); always read-only | -| **dashboard** | `intake dashboard` | render the census as the Mind **task** page — picks, in flight, pending release, planned, backlog (including human review), recent, epics; `--apply` writes `PyAutoMind/dashboard.md` + `dashboard.html` + `state.json` (the organ-cockpit feed, `board/_state.py` v1: red when a task awaits input/is blocked or prompts drift, yellow when work waits on a merge/release/review or picks exist; items carry the page's own copy payloads), `--check` exits 1 on drift (ignoring the page date and the feed's `updated`) | +| **dashboard** | `intake dashboard` | render the census as the Mind **task** page — picks, in flight, pending release, planned, backlog (including human review), recent, epics; `--apply` writes `PyAutoMind/dashboard.md` + `dashboard.html` + `state.json` (the organ-cockpit feed, `board/_state.py` v1: red when a task awaits input/is blocked or prompts drift, yellow when work waits on a merge/release/review or picks exist; items carry the page's own copy payloads), `--check` exits 1 on drift (ignoring the page date and the feed's `updated`). The HTML page is also the Mind's write door (PyAutoMind#565): a ★ per prompt row and a Goals box, rendered from `queue.md`/`goals.md` and edited through `dashboard_edit.js`, which opens one labelled `dashboard-input` issue per edit with an Issues-only token for the Mind's `dashboard_input.yml` to apply and close; one inline script, pinned by a CSP hash, `connect-src` the GitHub API only | | **formalise** | `intake formalise [prefix]` | retroactively header the prompts census flags — derive the missing fields, insert in place, prose untouched; `--apply` writes | | **reconcile** | `intake reconcile [prefix]` | rank backlog prompts that look already-shipped (vs the `complete/` records / `active/`), and pair live prompts that look like the same work filed twice; always read-only — retiring stays human | | **looks-shipped** | `intake looks-shipped [prefix] [--root DIR] [--pr-cache F]` | the **close-out guard**: flag open drafts with *strong* evidence their work already shipped (see "Close-out guard" below); `--apply` writes `PyAutoMind/looks_shipped.json` only — never anything under `draft/` | diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 7ce8b9fa..7c6b59ab 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -83,6 +83,9 @@ dev_status, pick_slot, read_record, render_html as _status_box_html, render_md as _status_box_md, ) +# The human's steering files (queue.md, goals.md): readers shared with the +# batch planner and `batch brief --new` (PyAutoMind#565). +from _steer import queued_names, read_goals, read_queue_entries # noqa: E402 # The close-out guard (strong-evidence `looks-shipped` flags): the detector and # the one reader the dashboard and the batch planner share. @@ -1751,6 +1754,10 @@ def _count(key): # Strong-evidence close-out flags (`intake looks-shipped`), minus what # a human dismissed or already closed — the "Looks shipped" section. "looks_shipped": _looks_shipped_rows(mind, records), + # The human's steering (PyAutoMind#565): the ★ state of every row and + # the Goals box at the top of the page. + "queue": read_queue_entries(mind), + "goals": read_goals(mind), } c["recent"] = recent_events(c) # Needs `in_flight` in place, so it is derived after the dict is built. @@ -2338,6 +2345,7 @@ def render_dashboard(c: dict) -> str: L += [""] if c["batch"] is not None: L += [_status_box_md(c["batch"]), ""] + L += _steer_md(c) L += ["## Start here", ""] # Epic members never appear in the pick lists or the work-type sections — @@ -2590,13 +2598,195 @@ def _attr(value: str) -> str: .replace("<", "<").replace(">", ">")) -def _html_task(text_html: str, payload: str) -> str: - """One task row on the HTML page: a real copy button, then the text.""" - return (f'

{text_html}

') +def _star_button(path: str, title: str, queued: dict) -> str: + """The ★ toggle for a prompt row (PyAutoMind#565). + + Rendered pressed, with its queue position, when `queue.md` queues the + prompt (matched by basename, as the lifecycle matches). Disabled until the + page's script finds a token: with JS off, or without a token, the star is + a read-only view of the queue.""" + pos = queued.get(Path(path).name) + on = pos is not None + return (f'') + + +def _repo_slug(home: str) -> str: + m = re.match(r"https://github\.com/([A-Za-z0-9-]+/[A-Za-z0-9._-]+)$", home) + return m.group(1) if m else "" + + +def _steer_md(c: dict) -> list: + """The markdown page's read-only Goals and Queue (the HTML twin edits).""" + goals, queue = c.get("goals") or [], [ + e for e in c.get("queue") or [] if e["kind"] == "prompt" and e["ref"]] + L = ["## Goals", ""] + L += [f"{g['n']}. {_md_inline_escape(g['text'])}" for g in goals] or [ + "_(no goals — write them in [`goals.md`](goals.md))_"] + L += ["", "## Queue", ""] + L += [f"{e['pos']}. [{_md_inline_escape(e['label'])}]({e['ref']})" for e in queue] or [ + "_(nothing queued — [`queue.md`](queue.md) is empty)_"] + return L + [""] + + +def _md_inline_escape(text: str) -> str: + return str(text).replace("<", "<").replace(">", ">").replace("[", "\\[").replace("]", "\\]") + + +_STEER_CSS = """\ +.steer{margin:0 0 1.2rem;padding:.75rem .9rem;border:1px solid var(--edge); + border-radius:11px;background:var(--tint)} +.steer h2{margin:.1rem 0 .4rem;font-size:1.05rem} +.steer h3{margin:.7rem 0 .2rem} +.steer ol{margin:.2rem 0;padding-left:1.4rem} +.steer ol.steer-queue{list-style:none;padding-left:0} +.steer-row{display:flex;gap:.5rem;align-items:center;flex-wrap:wrap} +.steer textarea{box-sizing:border-box;width:100%;min-height:9rem;font:inherit; + font-size:16px;color:var(--fg);background:var(--bg);border:1px solid var(--line); + border-radius:8px;padding:.5rem} +.steer details{margin-top:.6rem} +.steer input[type=password]{box-sizing:border-box;width:100%;min-height:44px; + font-size:16px;color:var(--fg);background:var(--bg);border:1px solid var(--line); + border-radius:8px;padding:.4rem .6rem} +.steer button.act{min-height:44px;min-width:44px;font:inherit;font-weight:650; + border:1px solid var(--edge);border-radius:9px;background:var(--btn);color:var(--accent); + padding:0 .9rem;cursor:pointer} +.steer .pending{opacity:.6} +button.star{flex:0 0 auto;min-width:2.75rem;height:2.75rem;font-size:1.15rem; + border:1px solid var(--edge);border-radius:9px;background:transparent;cursor:pointer; + color:var(--muted);opacity:.55;position:relative;padding:0} +button.star[aria-pressed="true"]{color:#d4a017;opacity:1;background:var(--tint)} +button.star:disabled{cursor:default} +button.star.pending{animation:starpulse 1s ease-in-out infinite} +@keyframes starpulse{50%{opacity:.35}} +button.star .qpos{position:absolute;right:2px;bottom:1px;font-size:.62rem; + font-weight:700;color:var(--fg)} +.steer-toast{position:fixed;left:50%;bottom:1rem;transform:translateX(-50%); + max-width:calc(100vw - 2rem);box-sizing:border-box;padding:.6rem .9rem; + border-radius:10px;background:var(--fg);color:var(--bg);z-index:10; + box-shadow:0 4px 16px #0004} +.steer-toast a{color:inherit;text-decoration:underline} +""" + + +def _token_url(repo: str) -> str: + """GitHub's new fine-grained token page, prefilled where it accepts it.""" + owner = repo.split("/")[0] + return ("https://github.com/settings/personal-access-tokens/new?" + "name=Mind%20dashboard&description=Mind%20dashboard%20%E2%98%85%20and%20goals" + f"&target_name={owner}&expires_in=90&issues=write") + + +def _steer_html(c: dict, link) -> list: + """The steering box at the top of the page: Goals, Queue, and the token. + + Server-rendered from the census so the page reads right with JS off; + the script (`dashboard_edit.js`) takes over when a token is present.""" + repo = _repo_slug(c.get("home", "")) + queued = queued_names(c.get("queue") or []) + goals = c.get("goals") or [] + queue = [e for e in c.get("queue") or [] if e["kind"] == "prompt" and e["ref"]] + H = [f'", + ''] + return H + + +#: The page's write client (PyAutoMind#565), inlined after the theme script. +_EDIT_JS_PATH = Path(__file__).resolve().parent / "dashboard_edit.js" + + +def _edit_js() -> str: + return _EDIT_JS_PATH.read_text(encoding="utf-8") + + +def _steer_first(page: str) -> str: + """Lift the Goals and queue box above the section cards. + + The shared layout moves the orchestration panel above the navigation + cards; the steering box belongs straight after it, at the top of the + first screen, not below seven count cards.""" + start = page.find('", start) + len("") + box = page[start:end] + page = page[:start] + page[end:] + return page[:nav] + box + "\n" + page[nav:] + + +def _with_csp(page: str) -> str: + """Pin the page's one inline script by hash and allow connections to the + GitHub API only. A meta CSP because Pages cannot set headers; the hash is + computed here, so `--check` stays deterministic.""" + import base64 + import hashlib + scripts = re.findall(r"", page, re.S) + if len(scripts) != 1: + raise ValueError(f"dashboard.html must carry exactly one inline script, " + f"found {len(scripts)}") + digest = base64.b64encode(hashlib.sha256(scripts[0].encode("utf-8")).digest()).decode() + csp = ("default-src 'none'; " + f"script-src 'sha256-{digest}'; " + "style-src 'unsafe-inline'; " + "connect-src https://api.github.com; " + "img-src data:; base-uri 'none'; form-action 'none'") + meta = (f'\n' + '') + return page.replace('', '\n' + meta, 1) + + def render_dashboard_html(c: dict) -> str: """Render the census as `dashboard.html` — the one-tap-copy twin. @@ -2617,12 +2807,18 @@ def render_dashboard_html(c: dict) -> str: def link(path, text_html): return f'{text_html}' + queued = queued_names(c.get("queue") or []) + + def star(path, title): + return _star_button(path, title, queued) + def record_row(r): text = link(r["path"], _summary_label(r["title"])) + pills( *(_summary_label(x) for x in (r["target"], r["difficulty"], r["autonomy"], r["priority"])), work_type=r["work_type"]) - return _html_task(text, f"Use the start-dev skill. {r['path']}") + return _html_task(text, f"Use the start-dev skill. {r['path']}", + star(r["path"], r["title"])) H = [ "", @@ -2633,7 +2829,7 @@ def record_row(r): "PyAutoMind Dashboard", f"", - f"", + f"", "", "", hero(THEME_ORGAN, "Dashboard", navigation=_dashboard_navigation(c), @@ -2678,6 +2874,7 @@ def record_row(r): work_links=[{"label": "Open Mind repository", "href": home}] if home else [], organ="mind", refreshed_at=c.get("refreshed_at"), refresh_url=home + "/actions/workflows/dashboard_refresh.yml" if home else None)) + H += _steer_html(c, link) if c.get("drift"): H += ['

⚠️ Needs lifecycle reconciliation — draft prompts ' "whose body records a fix PR (done, never advanced):

", "
    "] @@ -2779,7 +2976,8 @@ def h2(title, src): text += (f' — ' f'{_summary_label(_clip(r["status"]))}') text += _pr_column(r) - H.append(_html_task(text, f"Use the start-dev skill. {r['path']}")) + H.append(_html_task(text, f"Use the start-dev skill. {r['path']}", + star(r["path"], r["title"]))) if not c["in_flight"]: H.append('

    (nothing in flight)

    ') @@ -2816,7 +3014,7 @@ def h2(title, src): work_type=HUMAN_REVIEW) if r.get("date"): text += f'{_dated(r)}' - H.append(_html_task(text, _review_payload(r))) + H.append(_html_task(text, _review_payload(r), star(r["path"], r["title"]))) if not reviews: H.append('

    (nothing awaiting review)

    ') @@ -2874,8 +3072,8 @@ def h2(title, src): footer = boards_footer(dict(_board_links(home)), THEME_ORGAN) if footer: H.append(footer) - H += [f"", "", ""] - return section_layout("\n".join(H) + "\n") + H += [f"", "", ""] + return _with_csp(_steer_first(section_layout("\n".join(H) + "\n"))) def _dashboard_body(page: str) -> str: diff --git a/agents/conductors/intake/dashboard_edit.js b/agents/conductors/intake/dashboard_edit.js new file mode 100644 index 00000000..76f53edb --- /dev/null +++ b/agents/conductors/intake/dashboard_edit.js @@ -0,0 +1,532 @@ +// The write side of the Mind dashboard (PyAutoMind#565, design C). +// +// A ★ on a task row, or an edit in the Goals box, opens ONE small issue in the +// Mind repo, whose body is a fixed key: value form, then adds the +// `dashboard-input` label to it. The Mind's `dashboard_input.yml` (always the +// default branch's copy, run by the `issues: labeled` event) validates it, +// commits queue.md / goals.md, and closes and locks the issue with a one-line +// result comment. The page holds only a fine-grained token of a dedicated +// machine account (never the human's) with Issues permission on the Mind repo. +// +// The UI is optimistic: a tap flips at once, shows "pending", and turns into +// "confirmed" when the issue closes as applied (about 20-40 s), or reverts +// with the workflow's own reason. One issue is in flight at a time; taps made +// meanwhile are coalesced behind it (the latest state per task wins, a tap +// and its undo cancel out), so one device never makes the workflow drop a run. +// +// Inlined by `render_dashboard_html` into the page's one ", page, re.S) + assert len(scripts) == 1 and "