Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ CI failures retain their existing bug route. No new blocker severity is added.
`fix_plan`, `penalties`, `vantage`, `devbox_observed` and section entries are
additive; existing `stale_plan` and `performance` consumers need no migration.

`fix_plan.prompt` is a bounded summary (under 45,000 characters), suitable for
copying into an assistant. It preserves workflow constraints and references the
full `board.json` evidence. `fix_plan.evidence` holds the uncapped source
observations that used to be embedded in that prompt; consumers needing the
complete checklist must read it together with blockers and sections. Large
slices and omitted summary lines are explicitly identified. The shared browser
clipboard ceiling is 50,000 characters; larger requests are offered as complete
text downloads for attachment, never silently truncated.

Published dev-box entries use the existing path scrub on the complete entry,
including its evidence and prompt. Entries containing private local paths stay
local. Fresh observations retain their timestamp; expired observations remain
Expand Down
57 changes: 44 additions & 13 deletions heart/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -1121,11 +1121,10 @@ def build_board(

def build_fix_plan(board: Board, snapshot: dict | None = None, *,
devbox: dict | None = None) -> dict:
"""Complete, read-only repair context, independent of display row limits.
"""Bounded repair prompt; complete source observations remain in evidence.

V0 deliberately forwards existing remedies rather than inventing new ones.
Raw drift/CI/timing observations fill the gaps left by capped Section details.
They are evidence to diagnose, not instructions to execute blindly.
Keep below the family's 50,000-character clipboard ceiling without making
non-HTML Heart consumers depend on a Brain checkout.
"""
lines = [
"Use the health skill. Work through this Heart dashboard systematically in this chat.",
Expand Down Expand Up @@ -1172,24 +1171,55 @@ def build_fix_plan(board: Board, snapshot: dict | None = None, *,
lines.append(f" evidence: {link.get('url', '')}")
if link.get("prompt"):
lines.append(f" existing prompt: {link['prompt']}")
# Include uncapped source observations behind capped lists. Exclude unrelated
# history/log bodies, while retaining every finding and its existing remedy.
# Keep the raw observations in the machine surface, not the clipboard.
# Small slices remain useful inline; large slices get explicit references.
source = snapshot or {}
evidence = {}
for key in ("repos", "worktree_drift", "script_timing", "import_time",
"unit_test_timing", "unit_timings", "ci_timing", "smoke_timings",
"test_run", "validation_report", "verify_install", "url_check",
"version_skew", "profiling_drift", "manifest_drift",
"required_workflow_drift", "no_run_census"):
if source.get(key):
lines += ["", f"Source observations: {key}",
json.dumps(source[key], ensure_ascii=False, sort_keys=True)]
evidence[key] = source[key]
if devbox:
lines += ["", "Published dev-box observations (check timestamp before acting):",
json.dumps(devbox, ensure_ascii=False, sort_keys=True)]
evidence["devbox"] = devbox
if board.performance:
lines += ["", "Performance context and existing remedies:",
json.dumps(board.performance, ensure_ascii=False, sort_keys=True)]
return {"prompt": "\n".join(lines)}
evidence["performance"] = board.performance
for key, value in evidence.items():
detail = json.dumps(value, ensure_ascii=False, sort_keys=True)
if len(detail) > 8_000:
count = len(value) if isinstance(value, (dict, list)) else 1
detail = (f"{count} top-level records; full observations in "
f"fix_plan.evidence.{key} (omitted from this prompt).")
lines += ["", f"Source observations: {key} (check timestamp before acting)", detail]

evidence_note = (
"\n\nFull evidence: read the published Heart board.json at "
f"{PAGES_URL}board.json, including blockers, sections, performance and "
"fix_plan.evidence. For local evidence use pyauto-heart dashboard --json "
"and the state.json/release_ready.json files in HEART_STATE_DIR "
"(default ~/.pyauto-heart). Reconcile timestamps before acting. "
"This prompt is a summary, not the complete checklist; read the full "
"evidence before deciding scope. If unavailable, report the missing "
"evidence rather than assuming the omitted findings are resolved."
)
# Whole lines only: never cut a command, safety instruction or Unicode
# character mid-way. The fixed instructions always fit; oversized dynamic
# fields and exhausted summaries are explicitly accounted for below.
kept = []
remaining = 45_000 - len(evidence_note) - 150
omitted = 0
for line in lines:
if len(line) + 1 <= remaining:
kept.append(line)
remaining -= len(line) + 1
else:
omitted += 1
if omitted:
kept.append(f"\n{omitted} summary lines omitted to fit the prompt budget; "
"read the full evidence below.")
return {"prompt": "\n".join(kept) + evidence_note, "evidence": evidence}


def _record_lines(record: Any) -> tuple[str, str]:
Expand Down Expand Up @@ -2064,6 +2094,7 @@ def _html_reason(item: dict) -> str:
_COPY_JS = """
async function copyCmd(b){
const cmd=b.dataset.cmd, status=document.getElementById('copy-status');
if(!guardPrompt(cmd,b))return;
let copied=false;
try{await navigator.clipboard.writeText(cmd);copied=true;}
catch(e){
Expand Down
15 changes: 11 additions & 4 deletions tests/test_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,17 @@ def test_html_is_self_contained():
assert "fetch(" not in out and "XMLHttpRequest" not in out
lowered = out.lower()
assert '<script src' not in lowered and "import(" not in out
# every http(s) URL sits in an anchor href, never in a loadable attribute
for m in re.finditer(r"(?:http|https)://", out):
before = out[max(0, m.start() - 30):m.start()]
assert 'href="' in before or "href='" in before, f"non-href URL at {m.start()}"
# Evidence URLs may also occur in prompt text/data-cmd. Those are inert;
# check actual attributes rather than treating all text as asset loads.
from html.parser import HTMLParser

class Attributes(HTMLParser):
def handle_starttag(self, tag, attrs):
for name, value in attrs:
if value and re.search(r"https?://", value):
assert name in {"href", "data-cmd"}, (tag, name)

Attributes().feed(out)


# --- the unify invariant -----------------------------------------------------
Expand Down
29 changes: 29 additions & 0 deletions tests/test_fix.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,35 @@ def test_no_cache_never_claims_green(monkeypatch, capsys):
assert "no cache" in capsys.readouterr().err


def test_huge_observations_are_recoverable_without_a_huge_clipboard_prompt():
snapshot, verdict = inputs()
snapshot["validation_report"] = {"log": "🌌" * 1_350_000}
board = dashboard.build_board(snapshot, verdict)
plan = board.fix_plan
assert len(plan["prompt"]) < 50_000
assert "Repo11: CI failure" in plan["prompt"]
assert "fix_plan.evidence.validation_report" in plan["prompt"]
assert f"{dashboard.PAGES_URL}board.json" in plan["prompt"]
assert plan["evidence"]["validation_report"] == snapshot["validation_report"]
# Complete evidence survives the published machine surface; HTML and the
# CLI use the same bounded prompt without embedding the raw observation.
assert dashboard.to_dict(board)["fix_plan"] == plan
assert snapshot["validation_report"]["log"] not in dashboard._render_html(board)


def test_summary_overflow_preserves_authority_and_explains_omissions():
snapshot, verdict = inputs()
verdict["red_reasons"] += [f"finding-{i}: " + "x" * 10_000 for i in range(100)]
board = dashboard.build_board(snapshot, verdict)
prompt = board.fix_plan["prompt"]
assert len(prompt) < 50_000
assert "summary lines omitted" in prompt
assert "not approval to merge, delete work or release" in prompt
assert "Dirty worktrees are not disposable" in prompt
assert "read the full evidence" in prompt
assert len(board.blockers) == 114


def test_html_all_tiers_complete_disclosure_and_safe_fallback():
snapshot, verdict = inputs()
html = dashboard.render(snapshot, verdict, fmt="html")
Expand Down
Loading