repomoot 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+
repomoot/server/app.py ADDED
@@ -0,0 +1,367 @@
1
+ """HTTP API of the daemon. Wire protocol for CLI, MCP and any other client.
2
+
3
+ Auth headers: `Authorization: Bearer <daemon token>` (every local client), `X-Repomoot-Session: <session token>`
4
+ (after connect), `X-Repomoot-Human: <human token>` (only the human principal: registration, policy, attestation).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import hmac
10
+ import json
11
+ import threading
12
+ import time
13
+ from contextlib import asynccontextmanager
14
+ from typing import Any
15
+
16
+ from fastapi import Depends, FastAPI, Header, HTTPException, Request
17
+ from fastapi.concurrency import run_in_threadpool
18
+ from pathlib import Path
19
+
20
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
21
+
22
+ from .. import PROTOCOL_VERSION, __version__, config
23
+ from ..core import cards
24
+ from ..core.lifecycle import TransitionError
25
+ from ..core.service import Service, ServiceError
26
+
27
+
28
+ def create_app(service: Service | None = None, api_token: str | None = None, human_token: str | None = None) -> FastAPI:
29
+ svc = service or Service(config.db_path())
30
+ api_token = api_token if api_token is not None else config.token()
31
+ human_token = human_token if human_token is not None else config.human_token()
32
+ started_at = time.time()
33
+ cond = asyncio.Condition()
34
+ loop_ref: dict[str, asyncio.AbstractEventLoop | None] = {"loop": None}
35
+
36
+ @asynccontextmanager
37
+ async def lifespan(_app: FastAPI):
38
+ loop_ref["loop"] = asyncio.get_running_loop()
39
+ yield
40
+
41
+ app = FastAPI(title="Repomoot", version=__version__, lifespan=lifespan)
42
+ app.state.service = svc
43
+
44
+ async def _wake():
45
+ async with cond:
46
+ cond.notify_all()
47
+
48
+ def on_event():
49
+ loop = loop_ref["loop"]
50
+ if loop and loop.is_running():
51
+ loop.call_soon_threadsafe(lambda: asyncio.ensure_future(_wake()))
52
+
53
+ svc.on_event = on_event
54
+
55
+ def _err(e: ServiceError) -> HTTPException:
56
+ return HTTPException(e.status, {"error": str(e), "code": e.code, "hint": e.hint})
57
+
58
+ def bearer(authorization: str | None = Header(default=None)) -> None:
59
+ if not authorization or not hmac.compare_digest(authorization, f"Bearer {api_token}"):
60
+ raise HTTPException(401, {"error": "bad token", "code": "unauthorized", "hint": "token lives in $REPOMOOT_HOME/token"})
61
+
62
+ def human(x_repomoot_human: str | None = Header(default=None), _=Depends(bearer)) -> bool:
63
+ return bool(x_repomoot_human) and hmac.compare_digest(x_repomoot_human, human_token)
64
+
65
+ def session(x_repomoot_session: str | None = Header(default=None), _=Depends(bearer)) -> dict:
66
+ try:
67
+ return svc.auth(x_repomoot_session)
68
+ except ServiceError as e:
69
+ raise _err(e)
70
+
71
+ @app.exception_handler(ServiceError)
72
+ async def _se(_: Request, e: ServiceError):
73
+ return JSONResponse({"error": str(e), "code": e.code, "hint": e.hint, "protocol": PROTOCOL_VERSION}, status_code=e.status)
74
+
75
+ @app.exception_handler(TransitionError)
76
+ async def _te(_: Request, e: TransitionError):
77
+ return JSONResponse({"error": str(e), "code": e.code, "protocol": PROTOCOL_VERSION}, status_code=409)
78
+
79
+ @app.middleware("http")
80
+ async def _proto(request: Request, call_next):
81
+ resp = await call_next(request)
82
+ resp.headers["X-Repomoot-Protocol"] = str(PROTOCOL_VERSION)
83
+ resp.headers["X-Repomoot-Version"] = __version__
84
+ return resp
85
+
86
+ async def body_of(request: Request) -> dict[str, Any]:
87
+ raw = await request.body()
88
+ if len(raw) > 1_000_000:
89
+ raise HTTPException(413, {"error": "body too large", "code": "bad_request"})
90
+ if not raw:
91
+ return {}
92
+ try:
93
+ d = json.loads(raw)
94
+ except ValueError:
95
+ raise HTTPException(400, {"error": "invalid JSON body", "code": "bad_request"})
96
+ if not isinstance(d, dict):
97
+ raise HTTPException(400, {"error": "JSON object expected", "code": "bad_request"})
98
+ return d
99
+
100
+ # ---- public / identity
101
+ @app.get("/health")
102
+ def health():
103
+ return {"ok": True, "version": __version__, "protocol": PROTOCOL_VERSION, "po_present": svc.po_present()}
104
+
105
+ @app.get("/agents", dependencies=[Depends(bearer)])
106
+ def agents():
107
+ return {"agents": svc.list_agents(), "po_present": svc.po_present()}
108
+
109
+ @app.get("/agent-for-cwd", dependencies=[Depends(bearer)])
110
+ def agent_for_cwd(cwd: str):
111
+ return {"agent": svc.agent_for_cwd(cwd)}
112
+
113
+ @app.get("/protocol", dependencies=[Depends(bearer)])
114
+ def protocol(runtime: str | None = None, x_repomoot_session: str | None = Header(default=None)):
115
+ who = None
116
+ if x_repomoot_session:
117
+ try:
118
+ who = svc.whoami(svc.auth(x_repomoot_session))
119
+ except ServiceError:
120
+ who = None
121
+ return {"card": cards.card(who, runtime), "core": cards.CORE, "role": cards.role_text(who) if who else None}
122
+
123
+ @app.post("/sessions/connect")
124
+ async def connect(request: Request, is_human: bool = Depends(human)):
125
+ b = await body_of(request)
126
+ res = svc.connect(b.get("agent"), b.get("kind") or "project", b.get("cwd") or ".", b.get("name"), b.get("runtime"),
127
+ b.get("runtime_ref"), b.get("pid"), b.get("depends_on") or [], b.get("description"), is_human)
128
+ res["card"] = cards.card(res["who"], b.get("runtime"))
129
+ return res
130
+
131
+ @app.post("/sessions/disconnect")
132
+ def disconnect(s: dict = Depends(session)):
133
+ svc.disconnect(s)
134
+ return {"ok": True}
135
+
136
+ @app.get("/whoami")
137
+ def whoami(s: dict = Depends(session)):
138
+ return svc.whoami(s)
139
+
140
+ @app.post("/sessions/me/address")
141
+ async def set_address(request: Request, s: dict = Depends(session)):
142
+ b = await body_of(request)
143
+ return svc.set_session_ref(s, b.get("runtime_ref", ""))
144
+
145
+ @app.post("/agents/{aid}")
146
+ async def update_agent(aid: str, request: Request, is_human: bool = Depends(human)):
147
+ if not is_human:
148
+ raise HTTPException(403, {"error": "human token required", "code": "forbidden", "hint": "run from your terminal or set REPOMOOT_HUMAN_TOKEN"})
149
+ b = await body_of(request)
150
+ return svc.update_agent(aid, b.get("depends_on"), b.get("description"), b.get("add_repo"))
151
+
152
+ # ---- requests
153
+ @app.post("/requests")
154
+ async def create_request(request: Request, s: dict = Depends(session), is_human: bool = Depends(human)):
155
+ b = await body_of(request)
156
+ as_agent = b.get("as_agent")
157
+ if as_agent and not is_human:
158
+ raise HTTPException(403, {"error": "speaking as another agent needs the human token", "code": "forbidden"})
159
+ return svc.create_request(s, b.get("to", ""), b.get("type", "question"), b.get("title", ""), b.get("body", ""), b.get("goal"),
160
+ b.get("priority", "normal"), bool(b.get("blocking")), b.get("cc"), b.get("parent_id"), b.get("labels"),
161
+ b.get("due_at"), b.get("idem"), b.get("kind"), b.get("options"), as_agent)
162
+
163
+ @app.get("/requests")
164
+ def list_requests(box: str = "all", status: str | None = None, type: str | None = None, other: str | None = None,
165
+ since: str | None = None, limit: int = 50, all: bool = False, s: dict = Depends(session)):
166
+ return {"requests": svc.list_requests(s["agent_id"], box, status, type, other, since, limit, open_only=not all)}
167
+
168
+ @app.get("/requests/{rid}")
169
+ def get_request(rid: str, include: str = "messages,artifacts", since: int | None = None, s: dict = Depends(session)):
170
+ return svc.get_request(rid, s["agent_id"], tuple(x for x in include.split(",") if x), since)
171
+
172
+ @app.post("/requests/{rid}/claim")
173
+ def claim(rid: str, s: dict = Depends(session)):
174
+ return svc.claim(s, rid)
175
+
176
+ @app.post("/requests/{rid}/messages")
177
+ async def reply(rid: str, request: Request, s: dict = Depends(session), is_human: bool = Depends(human)):
178
+ b = await body_of(request)
179
+ as_agent = b.get("as_agent")
180
+ if as_agent and not is_human:
181
+ raise HTTPException(403, {"error": "speaking as another agent needs the human token", "code": "forbidden"})
182
+ return svc.reply(s, rid, b.get("body", ""), b.get("type", "comment"), as_agent)
183
+
184
+ @app.post("/requests/{rid}/action")
185
+ async def action(rid: str, request: Request, s: dict = Depends(session)):
186
+ b = await body_of(request)
187
+ return svc.set_status(s, rid, b.get("action", ""), b.get("reason"), b.get("to"))
188
+
189
+ @app.post("/requests/{rid}/accept_proposal")
190
+ async def accept_proposal(rid: str, request: Request, s: dict = Depends(session)):
191
+ b = await body_of(request)
192
+ return svc.accept_proposal(s, rid, b.get("option"), b.get("notes"))
193
+
194
+ @app.post("/requests/{rid}/escalate")
195
+ async def escalate(rid: str, request: Request, s: dict = Depends(session)):
196
+ b = await body_of(request)
197
+ return svc.escalate(s, rid, b.get("question", ""), b.get("kind", "conflict"), b.get("options") or [])
198
+
199
+ @app.post("/requests/{rid}/handoff")
200
+ def handoff(rid: str, s: dict = Depends(session)):
201
+ return svc.handoff(s, rid)
202
+
203
+ @app.post("/requests/{rid}/decide")
204
+ async def decide(rid: str, request: Request, s: dict = Depends(session), is_human: bool = Depends(human)):
205
+ b = await body_of(request)
206
+ return svc.decide(s, rid, b.get("decision", ""), b.get("option"), b.get("reason", ""), b.get("affected") or [], b.get("author") or "po", is_human)
207
+
208
+ @app.post("/requests/{rid}/delegate")
209
+ async def delegate(rid: str, request: Request, s: dict = Depends(session)):
210
+ b = await body_of(request)
211
+ return svc.delegate(s, rid, b.get("reason", ""))
212
+
213
+ # ---- PO
214
+ @app.post("/po/ask")
215
+ async def ask_po(request: Request, s: dict = Depends(session)):
216
+ b = await body_of(request)
217
+ return svc.ask_po(s, b.get("title", ""), b.get("body", ""), b.get("kind", "other"), b.get("options") or [], b.get("parent_id"), bool(b.get("blocking")))
218
+
219
+ @app.post("/tasks")
220
+ async def create_task(request: Request, s: dict = Depends(session)):
221
+ b = await body_of(request)
222
+ return svc.create_task(s, b.get("to", ""), b.get("title", ""), b.get("body", ""), b.get("depends_on") or [], b.get("due_at"))
223
+
224
+ @app.get("/po/dashboard")
225
+ def dashboard(s: dict = Depends(session)):
226
+ return svc.dashboard(s["agent_id"])
227
+
228
+ @app.get("/po/policy")
229
+ def get_policy(s: dict = Depends(session)):
230
+ return svc.get_policy(s["agent_id"])
231
+
232
+ @app.put("/po/policy")
233
+ async def set_policy(request: Request, s: dict = Depends(session), is_human: bool = Depends(human)):
234
+ return svc.set_policy(s, await body_of(request), is_human)
235
+
236
+ # ---- artifacts & agreements
237
+ @app.post("/artifacts")
238
+ async def publish_artifact(request: Request, s: dict = Depends(session)):
239
+ b = await body_of(request)
240
+ return svc.publish_artifact(s, b.get("type", ""), b.get("title", ""), b.get("content", ""), b.get("data"), b.get("request_id"),
241
+ b.get("supersedes"), b.get("verdict"), bool(b.get("requires_po")), b.get("po_question"))
242
+
243
+ @app.get("/artifacts")
244
+ def list_artifacts(type: str | None = None, request_id: str | None = None, agent: str | None = None, limit: int = 50, s: dict = Depends(session)):
245
+ return {"artifacts": svc.list_artifacts(type, request_id, agent, limit)}
246
+
247
+ @app.get("/artifacts/{aid}")
248
+ def get_artifact(aid: str, s: dict = Depends(session)):
249
+ return svc.get_artifact(aid)
250
+
251
+ @app.post("/agreements")
252
+ async def publish_agreement(request: Request, s: dict = Depends(session)):
253
+ b = await body_of(request)
254
+ return svc.publish_agreement(s, b.get("title", ""), b.get("content", ""), b.get("parties") or [], b.get("supersedes"))
255
+
256
+ @app.post("/agreements/{gid}/ack")
257
+ def ack_agreement(gid: str, s: dict = Depends(session)):
258
+ return svc.ack_agreement(s, gid)
259
+
260
+ @app.get("/agreements")
261
+ def list_agreements(party: str | None = None, all: bool = False, s: dict = Depends(session)):
262
+ return {"agreements": svc.list_agreements(party, all)}
263
+
264
+ # ---- inbox & events (async: waiting costs no thread)
265
+ @app.get("/inbox")
266
+ def inbox(s: dict = Depends(session)):
267
+ return svc.inbox(s)
268
+
269
+ @app.get("/events")
270
+ async def events(since: int | None = None, request_id: str | None = None, wait: int = 0, limit: int = 100, own: bool = False,
271
+ s: dict = Depends(session)):
272
+ deadline = time.monotonic() + min(max(wait, 0), 600)
273
+ while True:
274
+ res = await run_in_threadpool(svc.events, s, since, request_id, limit, own)
275
+ if res["events"] or time.monotonic() >= deadline:
276
+ return {**res, "timeout": not res["events"]}
277
+ remaining = deadline - time.monotonic()
278
+ async with cond:
279
+ try:
280
+ await asyncio.wait_for(cond.wait(), timeout=min(remaining, 15))
281
+ except asyncio.TimeoutError:
282
+ pass
283
+
284
+ @app.get("/events/stream")
285
+ async def stream(since: int | None = None, s: dict = Depends(session), last_event_id: int | None = Header(default=None)):
286
+ start = last_event_id if last_event_id is not None else since
287
+
288
+ async def gen():
289
+ cursor = start
290
+ while True:
291
+ res = await run_in_threadpool(svc.events, s, cursor, None, 100, False, False)
292
+ for r in res["events"]:
293
+ cursor = r["id"]
294
+ yield f"id: {r['id']}\nevent: {r['type']}\ndata: {json.dumps(r, ensure_ascii=False)}\n\n"
295
+ if not res["events"]:
296
+ yield ": keepalive\n\n"
297
+ async with cond:
298
+ try:
299
+ await asyncio.wait_for(cond.wait(), timeout=15)
300
+ except asyncio.TimeoutError:
301
+ pass
302
+ return StreamingResponse(gen(), media_type="text/event-stream")
303
+
304
+ @app.post("/ack")
305
+ async def ack(request: Request, s: dict = Depends(session)):
306
+ b = await body_of(request)
307
+ return {"acked": svc.ack_events(s, b.get("event_ids"), b.get("request_id"), bool(b.get("all")))}
308
+
309
+ # ---- misc
310
+ @app.get("/perm")
311
+ def perm(repo: str, op: str = "write", s: dict = Depends(session)):
312
+ return svc.check_permission(s["agent_id"], repo, op)
313
+
314
+ @app.get("/resolve", dependencies=[Depends(bearer)])
315
+ def resolve(ref: str):
316
+ return svc.resolve(ref)
317
+
318
+ @app.get("/search", dependencies=[Depends(bearer)])
319
+ def search(q: str, scope: str = "all", limit: int = 20):
320
+ return {"results": svc.search(q, scope, limit)}
321
+
322
+ # ---- web UI (localhost; the page carries the daemon token as a query parameter)
323
+ ui_html = (Path(__file__).with_name("ui.html")).read_text(encoding="utf-8")
324
+
325
+ @app.get("/ui", response_class=HTMLResponse)
326
+ def ui():
327
+ return ui_html
328
+
329
+ @app.get("/ui/data")
330
+ def ui_data(token: str = ""):
331
+ if not hmac.compare_digest(token, api_token):
332
+ raise HTTPException(401, {"error": "bad token", "code": "unauthorized", "hint": "open the UI with `repomoot ui`"})
333
+ import os
334
+ data = svc.overview()
335
+ reqs = data["requests"]
336
+ open_ = [r for r in reqs if r["status"] not in ("closed", "declined", "withdrawn", "acknowledged", "wont_do")]
337
+ data["workspace"] = {
338
+ "version": __version__, "protocol": PROTOCOL_VERSION, "port": config.port(), "pid": os.getpid(),
339
+ "uptime_s": int(time.time() - started_at), "db": str(config.db_path()), "home": str(config.home()),
340
+ "sessions_online": sum(len(a["sessions"]) for a in data["agents"]), "agents": len(data["agents"]),
341
+ "open": len(open_), "blocking": sum(1 for r in open_ if r["blocking"]),
342
+ "awaiting_decision": sum(1 for r in open_ if r["type"] == "decision"),
343
+ "last_event_at": data["recent_events"][-1]["created_at"] if data["recent_events"] else None,
344
+ }
345
+ return data
346
+
347
+ @app.post("/admin/shutdown", dependencies=[Depends(bearer)])
348
+ def shutdown():
349
+ """Exit the daemon (clients call this when their version differs; the next call restarts it)."""
350
+ import os
351
+ threading.Timer(0.3, lambda: os._exit(0)).start()
352
+ return {"ok": True, "version": __version__}
353
+
354
+ @app.post("/admin/tick", dependencies=[Depends(bearer)])
355
+ def tick():
356
+ return svc.tick()
357
+
358
+ def ticker():
359
+ while True:
360
+ time.sleep(30)
361
+ try:
362
+ svc.tick()
363
+ except Exception: # noqa: BLE001 - keep the daemon alive
364
+ pass
365
+
366
+ threading.Thread(target=ticker, daemon=True).start()
367
+ return app
repomoot/server/run.py ADDED
@@ -0,0 +1,24 @@
1
+ """`python -m repomoot.server.run` — start the daemon (used by `repomoot serve` and by autostart)."""
2
+ from __future__ import annotations
3
+
4
+ import uvicorn
5
+
6
+ from .. import config
7
+ from .app import create_app
8
+
9
+
10
+ def main() -> None:
11
+ import os
12
+ pidf = config.home() / "daemon.pid"
13
+ pidf.write_text(str(os.getpid()), encoding="utf-8")
14
+ try:
15
+ uvicorn.run(create_app(), host="127.0.0.1", port=config.port(), log_level="warning")
16
+ finally:
17
+ try:
18
+ pidf.unlink()
19
+ except OSError:
20
+ pass
21
+
22
+
23
+ if __name__ == "__main__":
24
+ main()
@@ -0,0 +1,182 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Repomoot</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+ <style>
8
+ :root { --bg:#0f1115; --card:#171a21; --line:#2a2f3a; --fg:#e6e6e6; --dim:#8b93a7; --ok:#3fb950; --warn:#d29922; --bad:#f85149; --acc:#58a6ff; --po:#bc8cff; }
9
+ * { box-sizing: border-box; }
10
+ body { margin:0; background:var(--bg); color:var(--fg); font: 13px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
11
+ header { display:flex; gap:16px; align-items:center; padding:10px 16px; border-bottom:1px solid var(--line); position:sticky; top:0; background:var(--bg); z-index:2; }
12
+ header h1 { font-size:15px; margin:0 12px 0 0; }
13
+ .agent { display:inline-flex; align-items:center; gap:6px; padding:2px 8px; border:1px solid var(--line); border-radius:12px; color:var(--dim); }
14
+ .agent b { color:var(--fg); font-weight:600; }
15
+ .dot { width:8px; height:8px; border-radius:50%; background:var(--line); }
16
+ .dot.on { background:var(--ok); }
17
+ .po-badge { color:var(--po); }
18
+ main { padding:12px 16px 40px; max-width:1200px; }
19
+ .req { background:var(--card); border:1px solid var(--line); border-radius:8px; margin:10px 0; padding:10px 12px; }
20
+ .req.done { opacity:.7; }
21
+ .head { display:flex; flex-wrap:wrap; gap:8px 14px; align-items:baseline; }
22
+ .id { color:var(--dim); }
23
+ .type { color:var(--acc); }
24
+ .who b { font-weight:600; }
25
+ .title { flex:1 1 320px; }
26
+ .flag { color:var(--warn); }
27
+ .age { color:var(--dim); }
28
+ .stages { display:flex; align-items:center; margin:8px 0 4px; flex-wrap:wrap; gap:0; }
29
+ .st { padding:2px 8px; border:1px solid var(--line); color:var(--dim); border-radius:4px; font-size:12px; }
30
+ .st + .st { margin-left:14px; position:relative; }
31
+ .st + .st::before { content:"→"; position:absolute; left:-12px; color:var(--line); }
32
+ .st.past { border-color:var(--ok); color:var(--ok); }
33
+ .st.now { border-color:var(--acc); color:#fff; background:#1b2a3d; }
34
+ .st.done { border-color:var(--ok); color:#fff; background:#173220; }
35
+ .st.bad { border-color:var(--bad); color:var(--bad); }
36
+ .st.wait { border-color:var(--warn); color:var(--warn); }
37
+ .tree { margin:6px 0 0 6px; padding-left:12px; border-left:1px dashed var(--line); }
38
+ .leaf { color:var(--dim); margin:2px 0; }
39
+ .leaf b { color:var(--fg); font-weight:600; }
40
+ .leaf .k { color:var(--acc); }
41
+ .leaf .po { color:var(--po); }
42
+ .leaf .ok { color:var(--ok); }
43
+ .leaf .bad { color:var(--bad); }
44
+ .actor { color:var(--warn); }
45
+ .empty { color:var(--dim); padding:30px 0; text-align:center; }
46
+ .toggle { color:var(--acc); cursor:pointer; user-select:none; border:1px solid var(--line); border-radius:12px; padding:2px 8px; }
47
+ #ws { display:flex; flex-wrap:wrap; gap:6px 18px; padding:8px 16px; border-bottom:1px solid var(--line); color:var(--dim); background:#12151b; }
48
+ #ws b { color:var(--fg); font-weight:600; }
49
+ #ws .on { color:var(--ok); } #ws .off { color:var(--bad); } #ws .warn { color:var(--warn); }
50
+ #banner { display:none; padding:10px 16px; background:#3a1518; color:#ffb3b8; border-bottom:1px solid var(--bad); }
51
+ footer { color:var(--dim); padding:6px 16px; border-top:1px solid var(--line); position:fixed; bottom:0; left:0; right:0; background:var(--bg); display:flex; gap:16px; }
52
+ a { color:var(--acc); text-decoration:none; }
53
+ </style>
54
+ </head>
55
+ <body>
56
+ <header>
57
+ <h1>Repomoot</h1>
58
+ <div id="agents"></div>
59
+ <span class="toggle" id="showClosed">hide closed</span>
60
+ </header>
61
+ <div id="banner"></div>
62
+ <div id="ws">workspace: connecting…</div>
63
+ <main id="main"><div class="empty">loading…</div></main>
64
+ <footer><span id="status">connecting…</span><span id="feed"></span></footer>
65
+ <script>
66
+ const token = new URLSearchParams(location.search).get("token") || "";
67
+ const STAGES_FULL = ["open","discussion","proposal","implementation","evaluation","done"];
68
+ const STAGE_MAP = { open:"open", discussion:"discussion", triage:"discussion", review:"discussion", in_review:"discussion",
69
+ proposal:"proposal", implementation:"implementation", evaluation:"evaluation", answered:"evaluation",
70
+ closed:"done", acknowledged:"done", declined:"declined", withdrawn:"withdrawn", wont_do:"wont_do", blocked:"blocked",
71
+ local:"local", deliberation:"deliberation" };
72
+ let showClosed = true;
73
+ function esc(s){ return String(s ?? "").replace(/[&<>"]/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c])); }
74
+ function age(ts){ if(!ts) return ""; const d=(Date.now()-Date.parse(ts))/1000; if(d<90) return "now"; if(d<3600) return Math.floor(d/60)+"m"; if(d<86400) return Math.floor(d/3600)+"h"; return Math.floor(d/86400)+"d"; }
75
+ function stagesFor(r){
76
+ if (r.type === "decision") return ["asked","deliberation","decided"];
77
+ if (r.type === "question" || r.type === "review") return ["open","discussion","answered","done"];
78
+ if (r.type === "notice") return ["sent","acknowledged"];
79
+ if (r.type === "bug" || r.type === "change") return ["open","discussion","implementation","evaluation","done"];
80
+ return STAGES_FULL;
81
+ }
82
+ function currentStage(r){
83
+ if (r.type === "decision") return r.status === "closed" ? "decided" : (r.status === "deliberation" ? "deliberation" : "asked");
84
+ if (r.type === "notice") return r.status === "acknowledged" ? "acknowledged" : "sent";
85
+ if (r.type === "question" || r.type === "review") return r.status === "answered" ? "answered" : (STAGE_MAP[r.status] || r.status);
86
+ const s = STAGE_MAP[r.status] || r.status;
87
+ if (r.type === "bug" || r.type === "change") return s === "proposal" ? "discussion" : s;
88
+ return s;
89
+ }
90
+ function stageBar(r){
91
+ const stages = stagesFor(r), cur = currentStage(r), terminalBad = ["declined","withdrawn","wont_do"].includes(cur);
92
+ const idx = stages.indexOf(cur);
93
+ let html = '<div class="stages">';
94
+ stages.forEach((s,i) => {
95
+ let cls = "st";
96
+ if (terminalBad) cls += i < stages.length-1 && i <= (r.resume_status ? 1 : 0) ? " past" : "";
97
+ else if (cur === "blocked" || cur === "local") cls += i < stages.indexOf(r.resume_status ? (STAGE_MAP[r.resume_status]||"discussion") : "discussion") ? " past" : (i === stages.indexOf(r.resume_status ? (STAGE_MAP[r.resume_status]||"discussion") : "discussion") ? " wait" : "");
98
+ else if (i < idx) cls += " past";
99
+ else if (i === idx) cls += (s === "done" || s === "decided" || s === "acknowledged") ? " done" : " now";
100
+ html += `<span class="${cls}">${s === "done" ? "✓ done" : s}</span>`;
101
+ });
102
+ if (terminalBad) html += `<span class="st bad" style="margin-left:14px">${cur}</span>`;
103
+ if (cur === "blocked") html += `<span class="st wait" style="margin-left:14px">blocked → waiting for decision</span>`;
104
+ if (cur === "local") html += `<span class="st wait" style="margin-left:14px">local: with ${esc(r.routed_to)} — user answers in chat or hands over</span>`;
105
+ html += "</div>";
106
+ return html;
107
+ }
108
+ function artLine(a){
109
+ const d = a.data || {};
110
+ if (a.type === "proposal") return `<span class="k">proposal</span> ${esc(a.title)} — options: ${(d.options||[]).map(o=>esc(o.id)).join(", ")}${d.recommended ? " (recommends "+esc(d.recommended)+")" : ""}`;
111
+ if (a.type === "delivery") return `<span class="k">delivery</span> ${esc(d.repo||"")}@${esc(d.commit||d.branch||"")} · tests ${esc((d.tests||{}).result||"?")}`;
112
+ if (a.type === "evaluation") return `<span class="k">evaluation</span> <span class="${d.verdict==="accepted"?"ok":"bad"}">${esc(d.verdict)}</span> — ${esc(a.title)}`;
113
+ if (a.type === "decision") return `<span class="po">decision</span> option ${esc(d.option||"-")} by ${esc(d.author)}${d.attested===false?' <span class="bad">(unattested)</span>':""} — ${esc(d.reason||"")}`;
114
+ return `<span class="k">${esc(a.type)}</span> ${esc(a.title)}`;
115
+ }
116
+ function fmtUptime(s){ if(s==null) return "?"; if(s<60) return s+"s"; if(s<3600) return Math.floor(s/60)+"m"; if(s<86400) return Math.floor(s/3600)+"h "+Math.floor(s%3600/60)+"m"; return Math.floor(s/86400)+"d "+Math.floor(s%86400/3600)+"h"; }
117
+ function renderWs(w, po){
118
+ if(!w){ document.getElementById("ws").innerHTML = "workspace: <span class='off'>unknown</span>"; return; }
119
+ document.getElementById("ws").innerHTML =
120
+ `<span>daemon <span class="on">● running</span> v${esc(w.version)} · :${w.port} · pid ${w.pid} · up ${fmtUptime(w.uptime_s)}</span>` +
121
+ `<span>product owner: <span class="${po?'on':'warn'}">${po?'present':'absent'}</span></span>` +
122
+ `<span>agents: <b>${w.agents}</b> · sessions online: <b>${w.sessions_online}</b></span>` +
123
+ `<span>open: <b>${w.open}</b> · blocking: <b class="${w.blocking?'warn':''}">${w.blocking}</b> · awaiting decision: <b class="${w.awaiting_decision?'warn':''}">${w.awaiting_decision}</b></span>` +
124
+ `<span>last event: ${w.last_event_at ? age(w.last_event_at)+' ago' : '—'}</span>` +
125
+ `<span title="${esc(w.db)}">db: ${esc(w.home)}</span>`;
126
+ }
127
+ function setBanner(msg){ const b=document.getElementById("banner"); b.style.display = msg ? "block" : "none"; b.textContent = msg||""; }
128
+ function render(data){
129
+ renderWs(data.workspace, data.po_present);
130
+ const ag = data.agents || [];
131
+ document.getElementById("agents").innerHTML = ag.map(a =>
132
+ `<span class="agent"><span class="dot ${a.sessions.length?'on':''}"></span><b class="${a.kind==='product_owner'?'po-badge':''}">${esc(a.id)}</b>${a.sessions.length? '· '+esc(a.sessions.map(s=>s.name||s.id).join(', ')) : '· offline'}</span>`).join(" ");
133
+ const byId = {}; (data.requests||[]).forEach(r => byId[r.id] = r);
134
+ const roots = (data.requests||[]).filter(r => !r.parent_id || !byId[r.parent_id]);
135
+ const closedSet = new Set(["closed","declined","withdrawn","acknowledged","wont_do"]);
136
+ const shown = roots.filter(r => showClosed || !closedSet.has(r.status));
137
+ const main = document.getElementById("main");
138
+ if (!shown.length) { main.innerHTML = '<div class="empty">no requests' + (roots.length ? ' open (toggle "show closed")' : '') + '</div>'; return; }
139
+ const open = shown.filter(r => !closedSet.has(r.status)), closed = shown.filter(r => closedSet.has(r.status));
140
+ main.innerHTML = open.map(r => reqCard(r, byId, data)).join("")
141
+ + (closed.length ? `<div class="empty" style="padding:14px 0 4px;text-align:left">closed (${closed.length})</div>` + closed.map(r => reqCard(r, byId, data)).join("") : "");
142
+ }
143
+ function reqCard(r, byId, data, depth=0){
144
+ const done = ["closed","declined","withdrawn","acknowledged","wont_do"].includes(r.status);
145
+ const kids = (data.requests||[]).filter(k => k.parent_id === r.id);
146
+ const arts = (r.artifacts||[]);
147
+ let html = `<div class="req ${done?'done':''}">
148
+ <div class="head"><span class="id">${esc(r.id)}</span><span class="type">${esc(r.type)}</span>
149
+ <span class="who"><b>${esc(r.from_agent)}</b> → <b>${esc(r.to_agent)}</b></span>
150
+ <span class="title">${esc(r.title)}</span>
151
+ ${r.blocking?'<span class="flag">blocking</span>':''}
152
+ ${r.actor && !done ? `<span class="actor">→ ${esc(r.actor)}</span>` : ''}
153
+ <span class="age">${age(r.updated_at)}</span></div>
154
+ ${stageBar(r)}`;
155
+ const leaves = [];
156
+ if (r.messages_count) leaves.push(`<div class="leaf">${r.messages_count} message${r.messages_count>1?'s':''}${r.last_message_from?' · last from <b>'+esc(r.last_message_from)+'</b>':''}</div>`);
157
+ arts.forEach(a => leaves.push(`<div class="leaf">${artLine(a)}</div>`));
158
+ kids.forEach(k => leaves.push(reqCard(k, byId, data, depth+1)));
159
+ if (leaves.length) html += `<div class="tree">${leaves.join("")}</div>`;
160
+ return html + "</div>";
161
+ }
162
+ async function tick(){
163
+ try {
164
+ const r = await fetch("/ui/data?token=" + encodeURIComponent(token));
165
+ if (!r.ok) { setBanner("auth failed (" + r.status + ") — open the page via `repomoot ui` / `/repomoot ui`"); document.getElementById("status").textContent = "auth failed"; return; }
166
+ const data = await r.json();
167
+ setBanner("");
168
+ render(data);
169
+ document.getElementById("status").textContent = "live · " + new Date().toLocaleTimeString() + " · po " + (data.po_present ? "present" : "absent");
170
+ const ev = data.recent_events || [];
171
+ document.getElementById("feed").textContent = ev.slice(-3).map(e => `#${e.id} ${e.type} ${e.request_id||""}`).join(" ");
172
+ } catch (e) {
173
+ setBanner("Workspace daemon is not reachable on this port. Any `repomoot` command (or `/repomoot start` in a Claude session) starts it; this page keeps retrying.");
174
+ document.getElementById("ws").innerHTML = "daemon <span class='off'>● stopped</span>";
175
+ document.getElementById("status").textContent = "daemon unreachable · retrying";
176
+ }
177
+ }
178
+ document.getElementById("showClosed").onclick = () => { showClosed = !showClosed; document.getElementById("showClosed").textContent = showClosed ? "hide closed" : "show closed"; tick(); };
179
+ tick(); setInterval(tick, 3000);
180
+ </script>
181
+ </body>
182
+ </html>