|
| 1 | +"""Page and neighboring-leaf presence readings.""" |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import json |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from .event_log import read_cursor, read_events |
| 8 | +from .files import latest_revision, list_revisions, read_json |
| 9 | +from .host import state_home |
| 10 | +from .server import running_server |
| 11 | +from .service import ( |
| 12 | + claim_is_active, |
| 13 | + claim_records, |
| 14 | + claim_update_sources, |
| 15 | + page_claim, |
| 16 | + unacknowledged, |
| 17 | + wait_is_live, |
| 18 | +) |
| 19 | +from .structure import parse_revision |
| 20 | + |
| 21 | + |
| 22 | +def other_leaves(page_dir: Path) -> list: |
| 23 | + """The machine's other live leaves, for the banner's panel: each page |
| 24 | + whose server is up, as a title, its handover URL, and the same presence |
| 25 | + facts the page ships about itself — so a row there and the banner above it |
| 26 | + are the one judgment reading the one shape. |
| 27 | +
|
| 28 | + Candidates are the conventional pages/ home and every claim record, which |
| 29 | + is what finds a page served from a session's scratch directory. Released |
| 30 | + and dead claims stay useful here as provenance. Liveness is the held |
| 31 | + server.lock lease, the same answer `running_server` gives everything else, |
| 32 | + and the URL is the one in durable service state, key included. The title is the |
| 33 | + active revision's — the document that page's own root URL answers with — |
| 34 | + read the way `transcript` reads it. |
| 35 | +
|
| 36 | + The whole scan runs on every /api/state; what it reads of each neighbour is |
| 37 | + kept per file, so a state read costs the scan and the presence reads rather than a |
| 38 | + parse of every live neighbour's page (`parse_version`).""" |
| 39 | + candidates = [] |
| 40 | + pages = state_home() / "pages" |
| 41 | + if pages.is_dir(): |
| 42 | + candidates += (d for d in pages.iterdir() if d.is_dir()) |
| 43 | + candidates += (Path(claim["page"]) for claim in claim_records()) |
| 44 | + others = [] |
| 45 | + seen = {page_dir.resolve()} |
| 46 | + for candidate in candidates: |
| 47 | + candidate = candidate.resolve() |
| 48 | + if candidate in seen or not candidate.is_dir(): |
| 49 | + continue |
| 50 | + seen.add(candidate) |
| 51 | + # A neighbour's fault stays its own. This is the one read of state some |
| 52 | + # other page owns: a directory deleted mid-scan (stale pages are deleted |
| 53 | + # and made again) or a log a disk fault corrupted would otherwise 500 |
| 54 | + # every open page's state read on the machine, blaming the page that asked. |
| 55 | + try: |
| 56 | + info = running_server(candidate) |
| 57 | + if not info: |
| 58 | + continue |
| 59 | + events = read_events(candidate) |
| 60 | + if not list_revisions(candidate): |
| 61 | + continue |
| 62 | + revision = latest_revision(candidate) |
| 63 | + parser = parse_revision(candidate, revision) |
| 64 | + present = presence(candidate, events) |
| 65 | + except Exception: # noqa: BLE001, S112 - whatever shape its fault takes |
| 66 | + continue |
| 67 | + others.append( |
| 68 | + { |
| 69 | + "title": parser.title.strip() or candidate.name, |
| 70 | + "url": info["url"], |
| 71 | + **present, |
| 72 | + } |
| 73 | + ) |
| 74 | + return sorted(others, key=lambda entry: entry["title"].lower()) |
| 75 | + |
| 76 | + |
| 77 | +def presence(page_dir: Path, events: list) -> dict: |
| 78 | + """What a seat showing this page says about it: the agent's claim, everything |
| 79 | + the directory holds that can answer for it, and where that agent is working. |
| 80 | + One gatherer for every such seat — `full_state` spreads it into the page's own |
| 81 | + state answer, and `other_leaves` attaches it to each entry — so the runtime's one |
| 82 | + claim-against-proof judgment reads the same fields whichever page it judges, |
| 83 | + and the tray's account of a neighbour is the account this page gives of |
| 84 | + itself.""" |
| 85 | + # A file that isn't there stands in as its whole record, so every read below |
| 86 | + # indexes rather than asking twice whether the field arrived. |
| 87 | + stored_status = read_json(page_dir / "status.json") or { |
| 88 | + "state": "idle", |
| 89 | + "detail": "", |
| 90 | + "ts": None, |
| 91 | + } |
| 92 | + status = {key: value for key, value in stored_status.items() if key != "work"} |
| 93 | + claim = page_claim(page_dir) |
| 94 | + active = claim if claim_is_active(claim) else None |
| 95 | + # What the wait owner has acknowledged after the complete batch reached its |
| 96 | + # next durable consumer. An action past this seq has not reached that point, |
| 97 | + # which lets the runtime carry it forward onto versions written without it. |
| 98 | + cursor = read_cursor(page_dir) |
| 99 | + return { |
| 100 | + "status": status, |
| 101 | + "claims": claim_update_sources(stored_status, events), |
| 102 | + "listening": wait_is_live(page_dir, active), |
| 103 | + "cursor": cursor, |
| 104 | + # The reader's number, not the watcher's: their own messages the agent |
| 105 | + # hasn't taken in. Reports ride the same cursor but are the agent's debt, |
| 106 | + # so the banner never tells a reader that a worker's news is waiting on them. |
| 107 | + "pending": sum( |
| 108 | + 1 for e in unacknowledged(events, cursor) if e["author"] == "user" |
| 109 | + ), |
| 110 | + "agent": claim.get("agent", "Claude") if claim else "Claude", |
| 111 | + # The claimant's host program, for behavior that keys on it — the display |
| 112 | + # name above is anyone's to choose, so nothing may dispatch on it. |
| 113 | + "host": claim.get("host") if claim else None, |
| 114 | + # None when nothing claimed the page — interact.py run outside an agent host. |
| 115 | + "session_alive": active is not None if claim else None, |
| 116 | + # Which session the turn-closed evidence belongs to. Thread updates carry |
| 117 | + # their posting session too, so a delegate is not declared abandoned merely |
| 118 | + # because the orchestrator's turn ended under it. |
| 119 | + "claim_session": claim.get("id") if claim else None, |
| 120 | + # When the claiming session's last turn ended, or None while none has. |
| 121 | + # A `working` claim older than this is one that no turn and no delegate |
| 122 | + # renewed across the boundary — the same judgment the runtime's grace |
| 123 | + # makes, available at the moment it becomes true instead of a quarter of |
| 124 | + # an hour after it. Read with .get like the rest of the claim's fields, |
| 125 | + # since a record written before this existed is still a valid claim. |
| 126 | + "turn_closed": claim.get("turn_closed") if claim else None, |
| 127 | + # When a browser last held the page open (the server bumps viewed.json, |
| 128 | + # throttled, while a tab's news stream stands), or None for a page nobody |
| 129 | + # has ever opened — which used to be indistinguishable from one the user |
| 130 | + # studied and left. |
| 131 | + "viewed": (read_json(page_dir / "viewed.json") or {"t": None})["t"], |
| 132 | + # Where the claimant is working (claim_page), for the tray's hover: what |
| 133 | + # tells one leaf from another is the work behind it, and neither the title |
| 134 | + # nor the page directory says which that is. It outlives the session that |
| 135 | + # wrote it, as every other fact in this record does — a page the tray |
| 136 | + # calls unheld came out of somewhere, and that is still where it came from. |
| 137 | + # None for a page nothing ever claimed, which is the honest nothing. |
| 138 | + "session_cwd": claim.get("cwd") if claim else None, |
| 139 | + } |
| 140 | + |
| 141 | + |
| 142 | +def presence_fingerprint(listening: bool, session_alive, others: list) -> str: |
| 143 | + """The half of a reading that file stamps cannot supply, from the facts a state |
| 144 | + already carries: the lease, the claimant's life, and the neighbours as the tray |
| 145 | + shows them. A neighbour's `viewed` is left out, since it moves every half minute |
| 146 | + that tab stays open and changes nothing this page shows.""" |
| 147 | + facts = ( |
| 148 | + listening, |
| 149 | + session_alive, |
| 150 | + [{k: v for k, v in other.items() if k != "viewed"} for other in others], |
| 151 | + ) |
| 152 | + return hashlib.sha256( |
| 153 | + json.dumps(facts, sort_keys=True, default=str).encode() |
| 154 | + ).hexdigest()[:8] |
| 155 | + |
| 156 | + |
| 157 | +def presence_reading(page_dir: Path) -> str: |
| 158 | + """`presence_fingerprint` read fresh, for a stream between states. The three facts |
| 159 | + are read the way `presence` and `full_state` read them, so the stream and the |
| 160 | + state it prompts name the same reading.""" |
| 161 | + claim = page_claim(page_dir) |
| 162 | + active = claim if claim_is_active(claim) else None |
| 163 | + return presence_fingerprint( |
| 164 | + wait_is_live(page_dir, active), |
| 165 | + active is not None if claim else None, |
| 166 | + other_leaves(page_dir), |
| 167 | + ) |
0 commit comments