6 Commits

Author SHA1 Message Date
sb-iam 9870a1c710 docs: add learning and graph specs 2026-06-28 00:34:47 -07:00
sb-iam 5e9929f8da fix(graph): honest graph-consistent metrics + flow narrative on node click
Address review feedback on the live view:

Metrics looked fake because they counted raw DB events (test churn) instead of
the de-noised entities actually drawn — e.g. "Open risk paths: 50" for 2 files,
"Learned owners: 16" with 2 ownership edges, and the caption ("Files with 2+
editors") contradicting the number. Now derived from the final graph:
- Open risk paths = distinct files carrying a surviving collision (50 -> 4 on live).
- Learned owners  = distinct engineers retained as owners via owns/learned_from
  edges (16 -> 1 on live).
- Accept rate     = accepted vs total real outcomes.
demo.ts metrics + loop counts realigned to its own graph (3 owners / 1 risk path
/ 100%) so nothing contradicts the picture; the PREDICT/ADAPT loop stages reuse
the same de-noised counts.

Right pane now explains the flow: clicking a node renders a plain-English walk of
its path (flowNarrative) — "Karti and Yahya are both editing auth.ts before
pushing ... PodMan suggested a sync PR", "PodMan offered a sync PR for the overlap
on auth.ts. The pod accepted it, so PodMan learned Karti owns auth.ts." With no
selection the panel gives a mode-aware explainer of what the lit path means. Edge
legend rounded out with editing/touches.

Verified: lint + -r typecheck + -r build pass; Playwright confirmed the flow text
per node kind and the demo metrics (3/1/100%); the metric formula re-checked
against the real live graph (4 risk files / 1 learned owner).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 23:47:14 -07:00
sb-iam c97863e05e feat(graph): dynamic force-directed Team-memory graph + learning-loop & activity rails
Rebuild the live "Team memory" view so the light/real-data version matches the
dark Bauhaus mock and the graph is genuinely DYNAMIC instead of dead static columns.

Frontend (frontend/src/components/graph/*, composed into GraphView.tsx):
- forceSim.ts: a tiny dependency-free force layout (charge repulsion, link springs,
  centroid recentering + gentle pull, 2-pass collision, bounds clamp, alpha anneal).
  No d3-force dependency added — keeps the shared pnpm-lock untouched so CI's
  frozen-lockfile install and the deploy path are unaffected.
- GraphCanvas.tsx: SVG render driven by the sim — draggable + pinnable nodes
  (double-click to release), curved edges that fan parallel pairs, weight-sized
  geometric node shapes, fade-in on new nodes/edges, animated learned_from dash,
  risk-path lighting with the rest dimmed, label collision-avoidance.
- MetricsRail / LearningLoop / ActivityStream / SelectedNodePanel / encoding.ts:
  the mock's rails + stream + detail panel, light shadcn (ToggleGroup, ScrollArea,
  Badge, Button) on theme tokens; only the SVG is bespoke.
- GraphView polls /api/pods/:id/graph every 5s and diffs (positions preserved across
  refreshes), with a best-effort ws /api/events nudge. A stale selection (node gone
  across a poll) is dropped so the canvas can't dim entirely.

Backend (additive — materializer de-noise untouched):
- live.ts: buildLoop() (observe→store→predict→outcome→adapt counts, deepest-recent
  stage active) and buildActivity() (time-sorted typed feed, same isFilePath /
  ENGINEER_NOISE / signature de-noise) emitted alongside nodes/edges/metrics.
- demo.ts: fallback loop + activity so the panels render on the demo path.
- shared/src/graph.ts: additive optional PodGraph.loop / .activity + LearningStage /
  ActivityEvent types.

Verified: pnpm lint + -r typecheck + -r build pass; Playwright on the dev build
confirmed force layout (distinct positions, ticks on load under StrictMode), drag,
risk-mode dimming (opacity 0.14), selection panel, legend, and no overlaps on both
the clean demo and the 31-node live hairball.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 23:27:54 -07:00
sb-iam 03a8af6da0 docs: add codex team memory redesign brief 2026-06-27 22:39:07 -07:00
sb-iam 62f5d26f83 docs: team-memory redesign brief as claude_team_memory_redesign.md
Renamed to a root-level, easy-to-discover name so a fresh Claude Code session
can pick it up directly. Committed locally only (not pushed).
2026-06-27 22:36:02 -07:00
sb-iam ad73659389 docs: deep redesign brief for the live Team-memory graph
Self-contained handoff for a fresh session: rebuild the light/real-data graph to
the dark Bauhaus mock's quality + structure (metrics rail, learning-loop rail,
activity stream, selected-node panel) and make the graph dynamic (force-directed
+ animated), in light shadcn. Captures architecture, data, the dynamic-layout
options, what to feed the new panels, files, gotchas, and acceptance criteria.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 22:28:01 -07:00
94 changed files with 4278 additions and 8719 deletions
-3
View File
@@ -11,7 +11,6 @@ GEMINI_API_KEY=
# canonical deployment secret name used by DigitalOcean and docs.
GEMINI_VISION_MODEL=gemini-2.0-flash
GEMINI_LIVE_MODEL=gemini-3.1-flash-tts-preview
GEMINI_TTS_VOICE=Charon
GEMINI_EMBEDDING_MODEL=gemini-embedding-001
# --- GitHub (repo state + sync PR artifacts) ---
@@ -33,8 +32,6 @@ NUDGE_COOLDOWN_MS=180000
# --- Frontend (Vite — must be VITE_ prefixed to reach the client) ---
VITE_LIVEKIT_URL=wss://your-project.livekit.cloud
VITE_BACKEND_URL=http://localhost:8787
# Keep off by default so users hear Gemini audio delivered through LiveKit.
VITE_ENABLE_BROWSER_TTS_FALLBACK=false
# --- Deployment verification ---
# Optional override when the deployed SPA and API use different origins.
-2
View File
@@ -35,8 +35,6 @@ Thumbs.db
coverage/
.cache/
.turbo/
__pycache__/
*.py[cod]
# Ramis
.remember/
-1
View File
@@ -1,4 +1,3 @@
link-workspace-packages=true
prefer-workspace-packages=true
auto-install-peers=true
prefix=/home/ramis/.npm-global
-5
View File
@@ -1,12 +1,7 @@
node_modules
.venv
**/.venv
.pytest_cache
**/.pytest_cache
dist
build
pnpm-lock.yaml
.omc
*.log
.agents
examples/livekit-gemini-hacker-starter
+15 -63
View File
@@ -318,31 +318,30 @@ Everything should serve that outcome.
## Documentation-first enforcement — HARD RULE
**Every line of code must trace back to a spec in `docs/`.**
**Every line of code must trace back to a task in `docs/PLAN.md` or a spec in `docs/`.**
This is not a guideline. This is a gate. The canonical specs are
`docs/gemini.md`, `docs/livekit.md`, `docs/mongodb.md`, `docs/cont_learning.md`,
`docs/hermes.md`, and `docs/digitalocean.md`. `docs/demo.md` is the demo script.
This is not a guideline. This is a gate.
### Before writing any code, verify:
1. **Is the approach consistent with the relevant spec?** Check `docs/gemini.md`, `docs/livekit.md`, `docs/mongodb.md`, `docs/cont_learning.md`, `docs/hermes.md`, `docs/digitalocean.md` as applicable.
2. **Do the file names and API shapes match what's documented?** If a spec says `backend/src/memory/store.ts`, do not create `backend/src/database/engineStates.ts` without updating the spec first.
1. **Is this task in `docs/PLAN.md`?** Find the exact task number. If it's not there, stop.
2. **Is the approach consistent with the relevant spec?** Check `docs/gemini.md`, `docs/livekit.md`, `docs/mongodb.md`, `docs/digitalocean.md` as applicable.
3. **Do the file names and API shapes match what's documented?** If the plan says `backend/src/db/states.ts`, do not create `backend/src/database/engineStates.ts` without updating the spec first.
### If a developer asks for something not in the specs:
### If a developer asks for something not in the plan:
**Do not write the code.** Instead:
1. Say explicitly: _"This isn't in the current specs. Let me understand what you're trying to do."_
1. Say explicitly: _"This isn't in the current plan. Let me understand what you're trying to do."_
2. Ask what problem they're solving and whether it's required for the demo path.
3. Evaluate whether it fits within scope or replaces something documented.
4. If it's valid: **update the relevant spec first**, then proceed to code.
5. If it's scope creep: say so directly and recommend the nearest in-spec alternative.
3. Evaluate whether it fits within scope or replaces something planned.
4. If it's valid: **update `docs/PLAN.md` and the relevant spec first**, then proceed to code.
5. If it's scope creep: say so directly and recommend the nearest in-plan alternative.
### Signs a request is off-spec (stop and consult):
### Signs a request is off-plan (stop and consult):
- Introducing a new file or API route not described in any spec
- Changing a documented API signature (`/health`, `POST /api/token`, `POST /api/outcome`, `GET /api/pods/:id/...`)
- Introducing a new file not mentioned in any task's **Files** list
- Changing an API signature documented in a spec (`/ingest`, `/health`, `/pods/:podId/token`, `/pods/:podId/state`)
- Adding a dependency not in the existing `package.json` files without a clear spec reason
- Building a feature in the **Cut immediately** list
- Touching another engineer's ownership area without explicit cross-team coordination
@@ -360,54 +359,7 @@ This repo is actively used by **4 engineers at the same time**. Claude sessions
### What this means for how you help
- **Assume other files are actively being edited.** Never refactor code outside the immediate task scope without explicit coordination from the user.
- **Treat integration points as contracts.** The shared types in `shared/src/` and the API shapes of `POST /api/token`, `POST /api/outcome`, and the `GET /api/pods/:id/*` routes are the interfaces between all teammates — do not change their signatures unilaterally.
- **Treat integration points as contracts.** The shared types in `shared/src/` and the API shapes of `POST /ingest`, `GET /pods/:podId/token`, and `GET /pods/:podId/state` are the interfaces between all teammates — do not change their signatures unilaterally.
- **Flag merge risk explicitly** before editing a shared file (e.g., `backend/src/index.ts`, `frontend/src/App.tsx`). Say so, then proceed only if the user confirms.
- **Prefer additive changes** — new files, new functions — over modifying existing ones. This minimizes merge conflicts in a concurrent team.
- **When proposing new files**, verify they match the file names and paths described in the relevant spec in `docs/`. Do not invent new paths.
---
## Production deployment & ops — READ BEFORE TOUCHING THE SERVER
The live system runs on a DigitalOcean droplet at `165.22.129.249`
(public: `https://165-22-129-249.sslip.io/` and `podman.live`). Repo on box:
`/root/podman`. SSH is `root@165.22.129.249` (password auth; ask the team for
the password — it is **not** stored in the repo).
### HARD RULE: manage processes with systemd, never manual `node`
The backend API and the LiveKit agent run as **systemd services** with
`Restart=always`:
- `podman-platform-api.service``node backend/dist/server.js` (cwd `/root/podman`)
- `podman-platform-agent.service``node dist/agent.js` (cwd `/root/podman/backend`,
`Environment=POD_ROOM=demo-pod`, `EnvironmentFile=/root/podman/backend/.env`)
**Do not start the agent or server by hand** (`node ...`, `nohup`, `setsid`,
`tsx`). The agent joins LiveKit with a fixed identity (`podman-hermes`); a
second instance with the same identity **evicts the first from the room**, and
they flap forever — silently dropping every intervention/voice update. systemd
keeps exactly one of each alive. If you launched a manual process, kill it and
let systemd own the singleton.
### Frontend is static, served by Caddy
The frontend is a Vite build served by **Caddy** from `/var/www/podman`
(`/etc/caddy/Caddyfile`). Caddy reverse-proxies `/api/*` and `/health` to
`127.0.0.1:8787`. The LiveKit URL reaches the browser via the backend
`/api/token` response, **not** `VITE_LIVEKIT_URL` (intentionally empty in
`frontend/.env`).
### Deploy procedure (run on the box)
```bash
cd /root/podman && git pull && pnpm -r build
rm -rf /var/www/podman/* && cp -r frontend/dist/* /var/www/podman/
systemctl restart podman-platform-api podman-platform-agent
systemctl status podman-platform-agent --no-pager # verify it came up
```
`pnpm -r build` order matters: `@podman/shared` builds first, or backend/frontend
typecheck fails with "Cannot find module '@podman/shared'". MongoDB is
**mandatory** — both services ping Mongo at boot and exit loudly if it is
unreachable (intentional; fix the `.env` creds, do not re-add silent fallbacks).
- **When proposing new files**, verify they match the file names listed in the relevant task in `docs/PLAN.md`. Do not invent new paths.
+130 -216
View File
@@ -1,99 +1,32 @@
# PodMan — A Pair Programmer for Engineering Teams
# PodMan - Real-time AI Team Coordination Agent
[LiveKit](https://livekit.io/)
[MongoDB](https://www.mongodb.com/)
[Gemini](https://ai.google.dev/)
[DigitalOcean](https://www.digitalocean.com/)
[![TypeScript](https://img.shields.io/badge/TypeScript-6.x-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![React](https://img.shields.io/badge/React-19-61DAFB?logo=react&logoColor=111)](https://react.dev/)
[![LiveKit](https://img.shields.io/badge/LiveKit-realtime-000000?logo=livekit&logoColor=white)](https://livekit.io/)
[![MongoDB](https://img.shields.io/badge/MongoDB-memory-47A248?logo=mongodb&logoColor=white)](https://www.mongodb.com/)
[![Gemini](https://img.shields.io/badge/Gemini-vision-8E75B2?logo=googlegemini&logoColor=white)](https://ai.google.dev/)
[![DigitalOcean](https://img.shields.io/badge/DigitalOcean-deploy-0080FF?logo=digitalocean&logoColor=white)](https://www.digitalocean.com/)
**2026 AI Engineer World's Fair Hackathon — Theme: Continual Learning**
**2026 AI Engineer World's Fair Hackathon** - Track: **Continual Learning**
## The bottleneck moved
PodMan is a non-intrusive AI teammate for active coding. It watches consented
LiveKit screen-share context, combines it with local git truth and shared team
memory, and coordinates teammates before a problem becomes a GitHub problem.
Models keep getting better, and more people can build software than ever before.
Writing the code is no longer the hard part — engineering ability is not the
ceiling anymore.
> GitHub sees pushed work. PodMan sees work while it is still happening.
What slows teams down now is everything *around* the code: manually checking each
other's work, re-planning when two people drift into the same change, and
constantly asking "what are you working on?" just to stay in sync. People
naturally want to build together — so as more people start coding, there will be
thousands of teams bottlenecked not by skill, but by the **speed of human
coordination.**
**PodMan is a pair programmer for the whole team.** It watches what every member
is doing in real time, learns your team's decisions and working dynamics, and
gives everyone a live picture of where the others are — without anyone having to
stop and ask.
### The five-minute meeting that isn't
> **What people assume:** "Quick question, five minutes."
> **What actually happens:** the interrupted developer loses their place and needs
> 1525 minutes to climb back into deep focus. That five-minute ask quietly costs
> half an hour — for *two* people.
Multiply that by every teammate, every day, and coordination overhead — not
engineering skill — becomes the real ceiling on how fast a team ships.
PodMan removes the reason to interrupt. Because it already knows who is touching
which file, what's still unpushed, and what each person is in the middle of, any
teammate can see another's status instantly — no tap on the shoulder, no standup,
no recovery tax. And it gets better as it goes: every accept or dismiss teaches
it what your team actually cares about, so it nudges less and helps more over
time.
> GitHub sees pushed work. PodMan sees work while it is still happening — and
> remembers what helped.
PodMan is not a dashboard and not a raw screenshot analyzer. Its job is to
notice useful coordination moments, remember what helped before, and route the
least intrusive intervention: a small card first, a Hermes message when teammates
need coordination, and voice only for urgent escalation.
---
## How it learns
The learning loop is the product, not a side feature. It runs with almost no
extra work from anyone — the only human signal is a single accept/dismiss tap on
a card.
```
observe → detect → RECALL prior outcomes → policy gate → act → record outcome
└──────────────────────────── feeds next recall ───────────────────────────┘
```
| Stage | What happens | Code |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| **Observe** | Gemini Vision turns each screen frame into structured work context (file, symbol, activity, unpushed hints) | `backend/src/vision/gemini.ts` |
| **Detect** | Same file touched by 2+ engineers with unpushed work → a coordination event | `backend/src/collision/detector.ts` |
| **Recall (memory)** | Embed the event, query MongoDB Atlas `$vectorSearch` for similar past events, attach their prior intervention + outcome | `backend/src/memory/vectors.ts` |
| **Policy gate (adapt)** | A dismissed false alarm stays silent; a confirmed real catch escalates to critical; a per-pod cooldown prevents nagging | `backend/src/memory/policy.ts` |
| **Act (least intrusive)** | Reuse the action kind that was accepted before; default to a card, escalate to a Hermes message, voice only when urgent | `backend/src/action/hermes.ts` |
| **Record (feedback)** | Accept/dismiss + "was it real?" is written back to memory, closing the loop for next time | `backend/src/memory/store.ts` |
A few things make this real learning rather than a static prompt:
- It adapts from real teammate behavior during a real session, not an offline
dataset.
- It gets more useful as the `outcomes` collection grows — better recall, fewer
false alarms.
- It needs one tap. No labeling, no config, no retraining.
- The mechanism is memory: Atlas vector recall plus an outcome-conditioned
policy, with an exact-signature fallback when vector search isn't available.
In practice: a false alarm gets dismissed once, and the same pattern stays quiet
next time. A real conflict gets accepted once, and when it recurs PodMan recalls
it and escalates straight to a spoken "seen before" cue.
---
## Architecture
A browser PWA, an HTTP API service, LiveKit agent workers, and a
memory/action layer. The screen signal flows through LiveKit, never a manual
screenshot upload.
PodMan is split into a browser PWA, an HTTP API service, a LiveKit agent worker,
and a persistence/action layer. The screen signal flows through LiveKit, not a
manual screenshot upload endpoint.
```mermaid
flowchart LR
@@ -106,19 +39,17 @@ flowchart LR
subgraph Realtime["LiveKit room"]
Room["Pod room"]
Data["Data topic<br/>podman.intervention"]
Audio["Audio tracks<br/>Gemini TTS + Lyria"]
end
subgraph Backend["PodMan backend"]
API["API service<br/>/api/token /api/pods /api/outcome"]
Agent["Vision agent worker<br/>@livekit/rtc-node"]
Convo["Live conversation agent<br/>Gemini Live API (Python)"]
Agent["Agent worker<br/>@livekit/rtc-node"]
Vision["Gemini Vision<br/>structured JSON"]
Detector["Coordination detector<br/>collisions, blockers"]
Detector["Coordination detector<br/>collisions, blockers, dead ends"]
end
subgraph Memory["Memory and actions"]
Mongo["MongoDB Atlas<br/>observations, outcomes, vectors"]
Mongo["MongoDB<br/>observations, outcomes, pods"]
GitHub["GitHub<br/>repo state + sync PR artifact"]
Hermes["Hermes action layer<br/>cards, messages, urgent voice"]
end
@@ -135,36 +66,23 @@ flowchart LR
Detector --> GitHub
Detector --> Hermes
Hermes --> Data
Hermes --> Audio
Convo --> Audio
Convo --> Mongo
Data --> PWA
Audio --> PWA
PWA -->|"POST /api/outcome"| API
API --> Mongo
```
### Runtime shape
| Layer | Runtime | Responsibility |
| ----------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------- |
| Frontend PWA | React + Vite | Join pods, publish screen share, render interventions, play audio |
| Backend API | Express | Mint LiveKit tokens, manage pods, record outcomes, expose memory stats, create sync PRs |
| Vision agent | `@livekit/rtc-node` | Subscribe to screen-share tracks, sample frames, publish intervention data |
| Live conversation agent | LiveKit Agents (Python) + Gemini Live API | Real-time voice Q&A with function tools over repo, git, and memory |
| Perception | Gemini Vision (`gemini-2.0-flash`) | Sampled IDE frames → structured work context |
| Team memory | MongoDB Atlas | Observations, collisions, interventions, outcomes, vector embeddings |
| Git watcher | Node script | Report each laptop's dirty/unpushed state as ground truth |
| Action layer | Hermes | Cards, teammate messages, Gemini TTS urgent voice, Lyria background score |
| Deployment | DigitalOcean | Static frontend, API service, agent workers |
| Layer | Runtime | Responsibility |
| ------------ | ------------------- | --------------------------------------------------------------------------------------------------- |
| Frontend PWA | React + Vite | Join pods, publish screen share, show live room state, render interventions |
| Backend API | Express | Mint LiveKit tokens, manage pods, record outcomes, expose memory stats, create sync PR artifacts |
| Agent worker | `@livekit/rtc-node` | Join the room as PodMan, subscribe to screen-share tracks, sample frames, publish intervention data |
| Vision loop | Gemini | Convert sampled IDE frames into structured work context |
| Team memory | MongoDB | Store observations, collisions, interventions, outcomes, pods, and git watcher state |
| Git watcher | Node script | Poll each laptop's local git state so dirty/unpushed work is not guessed from vision alone |
| Action layer | Hermes concept | Route cards, teammate messages, optional research summaries, and urgent voice escalation |
| Deployment | DigitalOcean | Static site for frontend, HTTP service for API, worker for the LiveKit agent |
### Data flow
@@ -178,150 +96,139 @@ sequenceDiagram
participant Gemini as Gemini Vision
participant Mongo as MongoDB Memory
participant Hermes as Hermes / Action Layer
participant GH as GitHub
Dev->>API: POST /api/token
API-->>Dev: LiveKit URL + JWT
Dev->>LK: Join pod room + publish screen share
Dev->>LK: Join pod room
Dev->>LK: Publish screen-share track
Agent->>LK: Subscribe to screen-share video
Agent->>Gemini: Sampled JPEG frame
Gemini-->>Agent: Structured work context
Agent->>Mongo: Record observation
Agent->>Mongo: Recall prior patterns (vector search)
Mongo-->>Agent: Prior intervention + outcome
Agent->>Hermes: Create intervention (gated by policy)
Hermes->>LK: Publish card / message / Gemini TTS voice
LK-->>Dev: Render intervention
Dev->>API: POST /api/outcome (accept / dismiss)
Agent->>GH: Read public repo state
Agent->>Mongo: Recall prior patterns
Agent->>Hermes: Create intervention
Hermes->>LK: Publish small data packet
LK-->>Dev: Render card / message / urgent voice cue
Dev->>API: POST /api/outcome
API->>Mongo: Store learning signal
```
### Why this architecture matters
- **LiveKit is the realtime spine.** Screens and intervention data move through a
shared room, so PodMan can react before code is pushed.
- **Gemini is the perception layer.** The agent samples frames and asks Gemini
for structured JSON such as current file, symbol, activity, unpushed hints,
and confidence.
- **MongoDB is the learning loop.** Outcomes and repeated patterns make later
interventions quieter and more useful.
- **Local git is the truth source.** The watcher reports dirty files and branch
state directly from each laptop, which avoids relying on vision for facts
GitHub cannot see.
- **Hermes keeps it non-intrusive.** Most events are cards. Team messages and
voice are escalation paths, not the default.
---
## Built with
Everything below maps to code in this repo.
**Gemini** does the perception, the voice, and the memory:
| Use | Model | Where |
| --------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------ |
| Real-time voice agent (talk to PodMan, answered with repo/git/memory tools) | `gemini-3.1-flash-live-preview` | `agents/podman-live-conversation/agent.py` |
| Spoken urgent alerts over LiveKit | `gemini-3.1-flash-tts-preview` | `backend/src/voice/live.ts` |
| Screen understanding → structured work context | `gemini-2.0-flash` | `backend/src/vision/gemini.ts` |
| Per-pod background music (Interactions API) | `lyria-3-clip-preview` | `backend/src/voice/music.ts` |
| Embeddings for memory recall | `gemini-embedding-001` | `backend/src/memory/vectors.ts` |
**LiveKit** is the real-time layer: screen-share tracks are the input, a typed
data channel (`podman.intervention`) carries cards and messages, audio tracks
carry the spoken alerts and music, and a Python LiveKit Agents worker runs the
live conversation agent in the room.
**MongoDB Atlas** is the memory: `$vectorSearch` recalls similar past events
(exact-signature fallback when needed), and the `outcomes` collection drives the
policy that decides whether and how to act.
**DigitalOcean** hosts it: a static frontend, the API service, and the agent
workers, supervised by systemd. Mongo connectivity is required at boot — services
fail loudly rather than degrade silently.
---
## How it works
1. Engineers open the PWA and join a pod room.
2. The API mints a LiveKit token via `POST /api/token`.
3. The PWA publishes screen share into the room on "Share my screen".
4. The PodMan vision agent subscribes to the screen-share tracks.
5. The agent samples frames, sends them to Gemini Vision, records structured
observations in MongoDB.
6. Each engineer runs the git watcher so PodMan has deterministic
dirty/unpushed truth.
7. The detector fuses live screen context, git truth, GitHub state, and recalled
memory.
8. The policy gate decides whether and how to act — card, Hermes message, or
urgent voice — reusing what worked before.
9. Urgent escalations are spoken via Gemini TTS over a LiveKit audio track.
10. The teammate's accept/dismiss is saved as an outcome, closing the
continual-learning loop.
Separately, any teammate can start a **live voice conversation** with PodMan
(Gemini Live API) to ask about current work, git state, or where something lives
in the repo — answered with real tool calls, not guesses.
2. The backend API mints a LiveKit token via `POST /api/token`.
3. The PWA publishes screen share into the pod room when the engineer chooses
"Share my screen".
4. The PodMan agent worker joins the same room and subscribes to screen-share
tracks.
5. The agent samples frames, sends them to Gemini Vision, and records structured
observations in MongoDB.
6. Each engineer runs the git watcher so PodMan has deterministic dirty/unpushed
state.
7. The detector combines live screen context, git truth, GitHub state, and team
memory.
8. PodMan sends the smallest useful intervention: card first, Hermes message for
coordination, voice only when urgent.
9. The user's response is saved as an outcome, closing the continual-learning
loop.
---
## Public interfaces
| Interface | Purpose |
| ----------------------------------------------------------- | ------------------------------------------------- |
| `GET /health` | API health check |
| `POST /api/token` | Mint LiveKit room tokens |
| `POST /api/sync-pr` | Create a visible sync PR artifact |
| `POST /api/outcome` | Store accepted/dismissed intervention outcomes |
| `GET /api/memory/stats` | Memory collection counts (live learning evidence) |
| `GET/POST/PATCH/DELETE /api/pods` | Pod CRUD |
| `POST/DELETE /api/pods/:id/members` | Pod membership |
| LiveKit topic `podman.intervention` | Intervention data channel |
| Wire messages `COLLISION`, `ACK`, `GIT_REPORT`, `VOICE_CUE` | Agent/PWA contract |
| Interface | Purpose |
| ----------------------------------------------------------- | ---------------------------------------------- |
| `GET /health` | API health check |
| `POST /api/token` | Mint LiveKit room tokens |
| `POST /api/sync-pr` | Create a visible sync PR artifact |
| `POST /api/outcome` | Store accepted/dismissed intervention outcomes |
| `GET /api/memory/stats` | Show memory collection counts |
| `GET/POST/PATCH/DELETE /api/pods` | Pod CRUD |
| `POST/DELETE /api/pods/:id/members` | Pod membership |
| LiveKit topic `podman.intervention` | Intervention data channel |
| Wire messages `COLLISION`, `ACK`, `GIT_REPORT`, `VOICE_CUE` | Shared agent/PWA message contract |
---
## Monorepo layout
| Folder | What |
| ----------- | -------------------------------------------------------------------------- |
| `frontend/` | React + Vite PWA — pods, LiveKit room UI, screen share, intervention cards |
| `backend/` | Express API plus the LiveKit vision agent worker |
| `agents/` | Python LiveKit Agents worker for the Gemini Live conversation agent |
| `shared/` | Shared TypeScript types and LiveKit data message contracts |
| `database/` | MongoDB setup and seed utilities |
| `infra/` | DigitalOcean specs, Caddyfile, systemd units |
| `scripts/` | Local git watcher + deploy/verify tooling |
| `docs/` | Integration specs and the demo script |
| Folder | What |
| ----------- | -------------------------------------------------------------------------------- |
| `frontend/` | React + Vite PWA for pods, LiveKit room UI, screen share, and intervention cards |
| `backend/` | Express API plus separate LiveKit agent worker |
| `shared/` | Shared TypeScript types and LiveKit data message contracts |
| `database/` | MongoDB setup and seed utilities |
| `infra/` | DigitalOcean App Platform specs and Dockerfile |
| `scripts/` | Local git watcher for demo laptops |
| `docs/` | Canonical plan and deeper sponsor/integration notes |
---
## Docs
| File | What |
| ---------------------------------------------- | ----------------------------------------- |
| [`docs/PLAN.md`](docs/PLAN.md) | Canonical master plan and source of truth |
| [`docs/idea.md`](docs/idea.md) | Product concept and demo framing |
| [`docs/livekit.md`](docs/livekit.md) | LiveKit notes and room model |
| [`docs/gemini.md`](docs/gemini.md) | Gemini vision and voice notes |
| [`docs/mongodb.md`](docs/mongodb.md) | MongoDB memory design |
| [`docs/digitalocean.md`](docs/digitalocean.md) | Deployment notes |
| [`docs/demo-setup.md`](docs/demo-setup.md) | Demo laptop and stage checklist |
---
## Prizes targeted
- **Best Gemini:** structured vision over live IDE context, with voice as an
optional escalation path.
- **Best LiveKit:** realtime screen-share tracks, presence, data packets, and
eventual voice in one pod room.
- **Best DigitalOcean:** frontend static site, API service, and LiveKit agent
worker deployment.
- **MongoDB + Voyage story:** persistent memory first, vector recall once exact
signature recall is proven.
---
## Quick start
```bash
cp .env.example .env
# fill in LIVEKIT_*, GEMINI_*, GITHUB_*, MONGODB_URI
# fill in LIVEKIT_*, GEMINI_*, GITHUB_*, and MONGODB_URI
pnpm install
pnpm --filter @podman/backend dev # API on :8787
pnpm --filter @podman/backend dev:agent # PodMan LiveKit vision agent
pnpm --filter @podman/backend dev:agent # PodMan LiveKit agent
pnpm --filter @podman/frontend dev # PWA on :5173
```
The live conversation agent (Gemini Live API) runs from `agents/podman-live-conversation/`.
---
## Git watcher - run this on every demo laptop
## Git watcher — run on every demo laptop
Each engineer runs this before the demo. It polls the local git working tree
every 15 seconds and writes git state to MongoDB so PodMan has deterministic
dirty/unpushed truth that vision alone cannot reliably infer.
Each engineer runs this in a terminal before the demo. It polls the local git
working tree every 15 seconds and writes git state to MongoDB so PodMan has
deterministic dirty/unpushed truth that vision alone cannot reliably infer.
```bash
# from the repo root
@@ -332,9 +239,16 @@ node scripts/podman-agent.mjs --name <yourname> --pod <podId>
```bash
node scripts/podman-agent.mjs --name alice --pod demo-pod
node scripts/podman-agent.mjs --name bob --pod demo-pod
node scripts/podman-agent.mjs --name bob --pod demo-pod
node scripts/podman-agent.mjs --name carol --pod demo-pod
```
**Requirements:** `MONGODB_URI` exported (or in `backend/.env`), `pnpm install`
run first, launched from the repo root.
The script logs one line per cycle: branch, changed file count, and latest
commit. Leave it running in a background terminal tab throughout the session.
Stop with `Ctrl+C`.
**Requirements:**
- `MONGODB_URI` must be exported in the shell or present in `backend/.env`.
- Run `pnpm install` first so workspace dependencies are available.
- Run from the repo root.
@@ -1,8 +0,0 @@
LIVEKIT_URL=wss://stackauthnov28-kt4gd6fq.livekit.cloud
LIVEKIT_API_KEY=
LIVEKIT_API_SECRET=
GOOGLE_API_KEY=
GEMINI_CONVERSATION_MODEL=gemini-3.1-flash-live-preview
GEMINI_CONVERSATION_VOICE=Aoede
PODMAN_BACKEND_URL=http://127.0.0.1:8787
INTERNAL_AGENT_TOKEN=
-22
View File
@@ -1,22 +0,0 @@
# PodMan Live Conversation Agent
Private 1:1 LiveKit Agent worker for PodMan Live Conversation.
Run locally:
```bash
cd agents/podman-live-conversation
uv sync --extra test
cp .env.example .env.local
uv run agent.py dev
```
Required env:
- `LIVEKIT_URL`
- `LIVEKIT_API_KEY`
- `LIVEKIT_API_SECRET`
- `GOOGLE_API_KEY` or `GEMINI_API_KEY`
- `PODMAN_BACKEND_URL`
- `INTERNAL_AGENT_TOKEN`
-439
View File
@@ -1,439 +0,0 @@
import asyncio
import json
import logging
import os
import subprocess
import time
from typing import Any
from urllib import error, request
from dotenv import load_dotenv
from livekit import agents
from livekit.agents import Agent, AgentServer, AgentSession, RunContext, function_tool
from livekit.plugins import google
load_dotenv(".env.local")
if not os.getenv("GOOGLE_API_KEY") and os.getenv("GEMINI_API_KEY"):
os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
logger = logging.getLogger("podman-live-conversation")
AGENT_NAME = "podman-live-conversation"
MODEL = os.getenv("GEMINI_CONVERSATION_MODEL", "gemini-3.1-flash-live-preview")
VOICE = os.getenv("GEMINI_CONVERSATION_VOICE", "Aoede")
BACKEND_URL = os.getenv("PODMAN_BACKEND_URL", "http://127.0.0.1:8787").rstrip("/")
INTERNAL_AGENT_TOKEN = os.getenv("INTERNAL_AGENT_TOKEN", "")
REPO_SLUG = os.getenv("PODMAN_REPO_SLUG", "karti-ai/podman")
def _resolve_repo_root() -> str:
override = os.getenv("PODMAN_REPO_ROOT")
if override:
return override
here = os.path.dirname(os.path.abspath(__file__))
try:
out = subprocess.run(
["git", "-C", here, "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
timeout=5,
)
if out.returncode == 0 and out.stdout.strip():
return out.stdout.strip()
except Exception:
pass
return os.path.abspath(os.path.join(here, "..", ".."))
REPO_ROOT = _resolve_repo_root()
INSTRUCTIONS = """You are PodMan, a concise real-time engineering teammate.
You are in a private 1:1 voice conversation with one developer.
Use PodMan tools before making claims about current work, git state, collisions, blockers,
team memory, or recent decisions. Keep spoken answers short. Prefer one useful next step.
If a critical collision event arrives, stop the current turn and state the alert immediately.
To find code, files, symbols, or how something is implemented in the repository, call search_repo.
For git commit history, authorship, recent changes, or which commit introduced something, call
repo_recent_commits or repo_find_commits.
For complex repository, terminal, GitHub, MongoDB, build, install, deploy, or multi-step tasks,
call delegate_to_hermes. Do not run those actions directly. If the user says stop, wait, cancel,
or change of plans while Hermes is running, call abort_active_hermes_job immediately.
Do not reveal raw secrets, API keys, private tokens, or another teammate's private notes."""
def parse_metadata(raw: str | None) -> dict[str, str]:
try:
data = json.loads(raw or "{}")
except json.JSONDecodeError:
return {}
return {str(k): str(v) for k, v in data.items() if v is not None}
def request_json(path: str, *, method: str = "GET", body: dict[str, Any] | None = None) -> Any:
if not INTERNAL_AGENT_TOKEN:
raise RuntimeError("INTERNAL_AGENT_TOKEN is not configured")
data = None if body is None else json.dumps(body).encode("utf-8")
req = request.Request(
f"{BACKEND_URL}{path}",
data=data,
method=method,
headers={
"authorization": f"Bearer {INTERNAL_AGENT_TOKEN}",
"content-type": "application/json",
},
)
try:
with request.urlopen(req, timeout=5) as res:
payload = res.read().decode("utf-8")
return json.loads(payload) if payload else {}
except error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace")
raise RuntimeError(f"PodMan backend returned {exc.code}: {detail}") from exc
async def _run_git(args: list[str], timeout: float = 15.0) -> tuple[int, str, str]:
"""Run a read-only git command inside the repo checkout and capture its output."""
try:
proc = await asyncio.create_subprocess_exec(
"git",
"-C",
REPO_ROOT,
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
out, err = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except asyncio.TimeoutError:
return 124, "", "git command timed out"
except FileNotFoundError:
return 127, "", "git is not available on this host"
return proc.returncode, out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
class PodManLiveAgent(Agent):
def __init__(self, pod_id: str, identity: str, session_id: str, conversation_room: str) -> None:
super().__init__(instructions=INSTRUCTIONS)
self.pod_id = pod_id
self.identity = identity
self.session_id = session_id
self.conversation_room = conversation_room
self.active_hermes_job_id: str | None = None
self.last_spoken_progress_at = 0.0
@function_tool()
async def get_active_pod_context(self, context: RunContext) -> str:
"""Get the current PodMan context for this developer and pod."""
data = await asyncio.to_thread(
request_json,
f"/api/internal/pods/{self.pod_id}/live-context?identity={self.identity}",
)
return json.dumps(data, ensure_ascii=True)[:12000]
@function_tool()
async def record_conversation_note(self, context: RunContext, note: str, kind: str = "summary") -> str:
"""Store a useful decision, outcome, or preference learned during this conversation."""
await asyncio.to_thread(
request_json,
f"/api/internal/pods/{self.pod_id}/live-conversation/{self.session_id}/note",
method="POST",
body={"identity": self.identity, "kind": kind, "note": note},
)
return "Saved to PodMan memory."
@function_tool()
async def get_recent_changes(self, context: RunContext) -> str:
"""Get recent local git and activity signals for this developer."""
data = await asyncio.to_thread(
request_json,
f"/api/internal/pods/{self.pod_id}/live-context?identity={self.identity}",
)
focused = {
"identity": data.get("identity"),
"currentGitState": data.get("currentGitState"),
"memberHistory": data.get("memberHistory"),
"recentCollisions": data.get("recentCollisions"),
}
return json.dumps(focused, ensure_ascii=True)[:8000]
@function_tool()
async def search_team_memory(self, context: RunContext, query: str) -> str:
"""Search current compact team memory for information relevant to a query."""
data = await asyncio.to_thread(
request_json,
f"/api/internal/pods/{self.pod_id}/live-context?identity={self.identity}",
)
haystack = json.dumps(data, ensure_ascii=True)
query_terms = [term.lower() for term in query.split() if len(term) > 2]
if not query_terms:
return haystack[:6000]
snippets = []
lower = haystack.lower()
for term in query_terms[:8]:
idx = lower.find(term)
if idx >= 0:
snippets.append(haystack[max(0, idx - 400) : idx + 1200])
return "\n---\n".join(snippets)[:8000] or haystack[:6000]
@function_tool()
async def search_repo(self, context: RunContext, query: str, max_results: int = 12) -> str:
"""Search the team's code repository (github.com/karti-ai/podman) for code, symbols,
filenames, config, or any text. Use this to find where something is implemented or which
files mention a term before answering questions about the codebase. Searches the live
local checkout of the main branch, so results are always current.
"""
cleaned = " ".join(query.split()).strip()
if not cleaned:
return "Provide a non-empty search query."
limit = max(1, min(int(max_results or 12), 40))
cmd = [
"rg",
"--line-number",
"--no-heading",
"--color",
"never",
"--smart-case",
"--max-count",
"3",
"--max-columns",
"240",
"-g",
"!*.lock",
"-g",
"!pnpm-lock.yaml",
"-g",
"!uv.lock",
"-g",
"!*.min.*",
"--",
cleaned,
REPO_ROOT,
]
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=15)
except asyncio.TimeoutError:
return "Repo search timed out. Try a more specific query."
except FileNotFoundError:
return "Repo search is unavailable on this host (ripgrep is not installed)."
if proc.returncode not in (0, 1): # rg: 0=match, 1=no match, 2=error
return f"Repo search failed: {stderr.decode('utf-8', 'replace')[:300]}"
prefix = REPO_ROOT + os.sep
lines: list[str] = []
for line in stdout.decode("utf-8", "replace").splitlines():
lines.append(line[len(prefix) :] if line.startswith(prefix) else line)
if len(lines) >= limit:
break
if not lines:
return f'No matches for "{cleaned}" in {REPO_SLUG}.'
body = "\n".join(lines)
return f'Matches for "{cleaned}" in {REPO_SLUG} (path:line):\n{body}'[:7000]
@function_tool()
async def repo_recent_commits(
self, context: RunContext, path: str = "", author: str = "", limit: int = 15
) -> str:
"""Show recent git commit history for github.com/karti-ai/podman: who committed what and when.
Optionally scope to a file or folder (path) or filter by author name/email (author).
Use this for questions about recent changes, authorship, or a specific file's history.
"""
n = max(1, min(int(limit or 15), 50))
args = [
"log",
f"--max-count={n}",
"--no-color",
"--date=short",
"--pretty=format:%h | %an | %ad | %s",
]
if author.strip():
args.append(f"--author={author.strip()}")
if path.strip():
args += ["--", path.strip()]
code, out, err = await _run_git(args)
if code != 0:
return f"Git history lookup failed: {err.strip()[:300] or 'unknown error'}"
out = out.strip()
if not out:
scope = f" for {path.strip()}" if path.strip() else ""
who = f" by {author.strip()}" if author.strip() else ""
return f"No commits found{scope}{who}."
return f"Recent commits in {REPO_SLUG} (hash | author | date | subject):\n{out}"[:7000]
@function_tool()
async def repo_find_commits(
self, context: RunContext, query: str, by: str = "message", limit: int = 15
) -> str:
"""Find commits in github.com/karti-ai/podman. by='message' searches commit messages;
by='code' finds commits that added or removed the query text in the code (pickaxe).
Use by='code' for "which commit introduced X"; use by='message' for "commits about X".
"""
cleaned = " ".join(query.split()).strip()
if not cleaned:
return "Provide a non-empty query."
n = max(1, min(int(limit or 15), 50))
args = [
"log",
f"--max-count={n}",
"--no-color",
"--date=short",
"--pretty=format:%h | %an | %ad | %s",
]
mode = by.strip().lower()
if mode == "code":
args.append(f"-S{cleaned}")
else:
mode = "message"
args += ["-i", f"--grep={cleaned}"]
code, out, err = await _run_git(args)
if code != 0:
return f"Commit search failed: {err.strip()[:300] or 'unknown error'}"
out = out.strip()
if not out:
return f'No commits found matching "{cleaned}" (by {mode}).'
return (
f'Commits in {REPO_SLUG} matching "{cleaned}" (by {mode}) — hash | author | date | subject:\n{out}'[
:7000
]
)
@function_tool()
async def delegate_to_hermes(
self,
context: RunContext,
prompt: str,
context_scope: str = "current_repo",
target_repository: str = "",
risk_level: str = "read_only",
requires_confirmation: bool = False,
success_criteria: list[str] | None = None,
) -> str:
"""Hand off a complex engineering task to Hermes, PodMan's autonomous backend execution engine.
Use this for filesystem, terminal, GitHub, MongoDB, build, install, deploy, test,
or multi-step repository tasks. Do not use this for simple conversational answers.
"""
body = {
"prompt": prompt,
"contextScope": context_scope,
"targetRepository": target_repository or "karti-ai/podman",
"riskLevel": risk_level,
"requiresConfirmation": requires_confirmation,
"successCriteria": success_criteria or ["Hermes completes the requested inspection."],
"podId": self.pod_id,
"identity": self.identity,
"sessionId": self.session_id,
"conversationRoom": self.conversation_room,
}
job = await asyncio.to_thread(request_json, "/api/internal/hermes/jobs", method="POST", body=body)
self.active_hermes_job_id = str(job["id"])
return json.dumps(
{
"status": "accepted",
"job_id": self.active_hermes_job_id,
"spoken_ack": "Hermes is starting that now. I will keep you posted.",
},
ensure_ascii=True,
)
@function_tool()
async def abort_active_hermes_job(self, context: RunContext, reason: str = "User changed plans") -> str:
"""Abort the currently running Hermes job immediately."""
if not self.active_hermes_job_id:
return "No active Hermes job is running."
job = await asyncio.to_thread(
request_json,
f"/api/internal/hermes/jobs/{self.active_hermes_job_id}/abort",
method="POST",
body={"reason": reason},
)
return json.dumps(
{
"status": job.get("status", "aborting"),
"job_id": self.active_hermes_job_id,
"spoken_ack": "Stopped. Hermes is aborting the job before making further changes.",
},
ensure_ascii=True,
)
def should_speak_progress(self, event: dict[str, Any]) -> bool:
event_type = event.get("type")
if event_type in {"completed", "failed", "aborted", "needs_confirmation"}:
return True
if event_type not in {"heartbeat", "step_started", "step_completed"}:
return False
monotonic = time.monotonic()
if monotonic - self.last_spoken_progress_at < 8:
return False
self.last_spoken_progress_at = monotonic
return True
server = AgentServer()
@server.rtc_session(agent_name=AGENT_NAME)
async def entrypoint(ctx: agents.JobContext):
metadata = parse_metadata(getattr(ctx.job, "metadata", None))
pod_id = metadata.get("podId", "demo-pod")
identity = metadata.get("identity", "developer")
session_id = metadata.get("sessionId", "unknown")
session = AgentSession(
llm=google.realtime.RealtimeModel(
model=MODEL,
voice=VOICE,
),
)
agent = PodManLiveAgent(
pod_id=pod_id,
identity=identity,
session_id=session_id,
conversation_room=ctx.room.name,
)
def on_data_received(*args: Any):
payload = args[0] if args else b""
if isinstance(payload, str):
raw = payload
else:
raw = bytes(payload).decode("utf-8", "replace")
try:
msg = json.loads(raw)
except json.JSONDecodeError:
return
msg_type = msg.get("type")
if msg_type == "HERMES_JOB_EVENT":
event = msg.get("event") or {}
summary = str(event.get("message") or "").strip()
if str(event.get("type")) in {"completed", "failed", "aborted"}:
agent.active_hermes_job_id = None
elif msg_type == "LIVE_CONVERSATION_EVENT":
event = msg.get("event") or {}
summary = str(event.get("summary") or "").strip()
else:
return
if not summary:
return
async def interrupt_and_say() -> None:
try:
if msg_type == "LIVE_CONVERSATION_EVENT":
await session.interrupt(force=True)
except Exception as exc:
logger.warning("interrupt failed: %s", exc)
if msg_type == "LIVE_CONVERSATION_EVENT" or agent.should_speak_progress(event):
await session.say(summary, allow_interruptions=True, add_to_chat_ctx=True)
asyncio.create_task(interrupt_and_say())
ctx.room.on("data_received", on_data_received)
await session.start(room=ctx.room, agent=agent)
await ctx.connect()
if __name__ == "__main__":
agents.cli.run_app(server)
@@ -1,19 +0,0 @@
[project]
name = "podman-live-conversation"
version = "0.1.0"
description = "PodMan private LiveKit/Gemini live conversation agent"
requires-python = ">=3.10,<3.14"
dependencies = [
"livekit-agents[google]>=1.6.4,<1.7",
"python-dotenv>=1.0.0",
]
[project.optional-dependencies]
test = ["pytest>=8.0.0"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["."]
@@ -1,26 +0,0 @@
from agent import PodManLiveAgent, parse_metadata
def test_parse_metadata_accepts_valid_json():
assert parse_metadata('{"podId":"demo-pod","identity":"yahya","sessionId":"s1"}') == {
"podId": "demo-pod",
"identity": "yahya",
"sessionId": "s1",
}
def test_parse_metadata_handles_bad_json():
assert parse_metadata("not json") == {}
def test_hermes_terminal_events_always_speak():
agent = PodManLiveAgent("demo-pod", "yahya", "s1", "room")
assert agent.should_speak_progress({"type": "completed"}) is True
assert agent.should_speak_progress({"type": "failed"}) is True
assert agent.should_speak_progress({"type": "aborted"}) is True
def test_hermes_progress_is_throttled():
agent = PodManLiveAgent("demo-pod", "yahya", "s1", "room")
assert agent.should_speak_progress({"type": "heartbeat"}) is True
assert agent.should_speak_progress({"type": "step_started"}) is False
File diff suppressed because it is too large Load Diff
-57
View File
@@ -1,11 +1,6 @@
import type { Room } from '@livekit/rtc-node';
import { Room as LiveKitRoom } from '@livekit/rtc-node';
import { AccessToken } from 'livekit-server-sdk';
import type { Collision, DataMessage, HermesMessage, Intervention } from '@podman/shared';
import { DATA_TOPIC } from '@podman/shared';
import { env } from '../env.js';
import { speak } from '../voice/live.js';
import { notifyCriticalLiveConversations } from '../live-conversation/sessions.js';
const encoder = new TextEncoder();
@@ -42,55 +37,3 @@ export async function publishHermesMessage(
topic: DATA_TOPIC,
});
}
export async function publishHermesIntervention(
room: Room,
collision: Collision,
intervention: Intervention,
voiceLine?: string,
): Promise<void> {
const data: DataMessage = { type: 'COLLISION', collision, intervention };
await room.localParticipant?.publishData(encoder.encode(JSON.stringify(data)), {
reliable: true,
topic: DATA_TOPIC,
});
await publishHermesMessage(room, collision, intervention);
void notifyCriticalLiveConversations(collision, intervention, voiceLine).catch((err) =>
console.warn(`[live-conversation] critical notify failed: ${(err as Error).message}`),
);
if (voiceLine) await speak(room, voiceLine, { priority: 'critical' });
}
async function hermesToken(roomName: string): Promise<string> {
const at = new AccessToken(env.LIVEKIT_API_KEY, env.LIVEKIT_API_SECRET, {
identity: `podman-hermes-${Date.now()}`,
name: 'PodMan Hermes',
ttl: '10m',
});
at.addGrant({
roomJoin: true,
room: roomName,
canPublish: true,
canSubscribe: true,
canPublishData: true,
});
return at.toJwt();
}
export async function notifyHermesInterventionInRoom(
roomName: string,
collision: Collision,
intervention: Intervention,
voiceLine?: string,
): Promise<void> {
const room = new LiveKitRoom();
try {
await room.connect(env.LIVEKIT_URL, await hermesToken(roomName), {
autoSubscribe: false,
dynacast: false,
});
await publishHermesIntervention(room, collision, intervention, voiceLine);
} finally {
await room.disconnect().catch(() => {});
}
}
-174
View File
@@ -1,174 +0,0 @@
import type { EngineerContext, MemberWorkHistory, MemberWorkHistoryFile } from '@podman/shared';
import { getDb } from '../memory/db.js';
import { parseGitStatusPath } from '../graph/live.js';
interface EngineerStateDoc {
_id: string;
podId: string;
name: string;
changedFiles?: string[];
branch?: string | null;
recentCommit?: string | null;
gitUpdatedAt?: Date | string;
updatedAt?: Date | string;
}
interface FileAccumulator {
file: string;
observations: number;
gitChanges: number;
firstSeenAt: number;
lastSeenAt: number;
confidenceSum: number;
confidenceCount: number;
activities: Set<string>;
current: boolean;
}
function toIso(ms: number): string {
return new Date(ms).toISOString();
}
function dateMs(value: string | Date | undefined): number {
if (value instanceof Date) return value.getTime();
if (value) {
const parsed = Date.parse(value);
if (Number.isFinite(parsed)) return parsed;
}
return 0;
}
function clean(value: string | undefined): string {
return value?.trim() ?? '';
}
function sameMember(a: string | undefined, b: string): boolean {
return clean(a).toLowerCase() === b.trim().toLowerCase();
}
function addFile(files: Map<string, FileAccumulator>, file: string, at: number): FileAccumulator {
const existing = files.get(file);
if (existing) {
if (at > 0) {
existing.firstSeenAt = Math.min(existing.firstSeenAt || at, at);
existing.lastSeenAt = Math.max(existing.lastSeenAt, at);
}
return existing;
}
const acc: FileAccumulator = {
file,
observations: 0,
gitChanges: 0,
firstSeenAt: at,
lastSeenAt: at,
confidenceSum: 0,
confidenceCount: 0,
activities: new Set<string>(),
current: false,
};
files.set(file, acc);
return acc;
}
export async function getMemberWorkHistory(
podId: string,
member: string,
options: { hours?: number; limit?: number } = {},
): Promise<MemberWorkHistory> {
const db = await getDb();
const windowHours = Math.min(Math.max(options.hours ?? 24, 1), 168);
const limit = Math.min(Math.max(options.limit ?? 80, 10), 200);
const since = new Date(Date.now() - windowHours * 60 * 60 * 1000).toISOString();
const [observations, gitState] = await Promise.all([
db
.collection<EngineerContext>('observations')
.find({ podId, observedAt: { $gte: since } }, { projection: { _id: 0 } })
.sort({ observedAt: -1 })
.limit(500)
.toArray(),
db.collection<EngineerStateDoc>('engineer_states').findOne({
podId,
name: { $regex: `^${member.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, $options: 'i' },
}),
]);
const files = new Map<string, FileAccumulator>();
const timeline: MemberWorkHistory['timeline'] = [];
const memberObservations = observations.filter((doc) => sameMember(doc.engineerId, member));
for (const doc of memberObservations) {
const file = clean(doc.currentFile);
if (!file) continue;
const at = dateMs(doc.observedAt);
const acc = addFile(files, file, at);
acc.observations += 1;
acc.current ||= timeline.length === 0;
if (typeof doc.confidence === 'number') {
acc.confidenceSum += doc.confidence;
acc.confidenceCount += 1;
}
const activity = clean(doc.activity);
if (activity) acc.activities.add(activity);
timeline.push({
id: `vision:${doc.engineerId}:${doc.observedAt}:${file}`,
at: doc.observedAt,
source: 'vision',
file,
title: activity || `Worked in ${file}`,
detail: clean(doc.currentSymbol) ? `symbol ${doc.currentSymbol}` : undefined,
confidence: doc.confidence,
});
}
const gitAt = dateMs(gitState?.gitUpdatedAt ?? gitState?.updatedAt);
for (const raw of gitState?.changedFiles ?? []) {
const file = parseGitStatusPath(raw);
if (!file) continue;
const acc = addFile(files, file, gitAt || Date.now());
acc.gitChanges += 1;
acc.current = true;
timeline.push({
id: `git:${gitState?._id}:${gitAt}:${file}`,
at: toIso(gitAt || Date.now()),
source: 'git',
file,
title: `Local change in ${file}`,
detail: [gitState?.branch ? `branch ${gitState.branch}` : undefined, gitState?.recentCommit]
.filter(Boolean)
.join(' · '),
});
}
const fileRows: MemberWorkHistoryFile[] = [...files.values()]
.sort((a, b) => b.lastSeenAt - a.lastSeenAt || b.observations - a.observations)
.slice(0, 12)
.map((file) => ({
file: file.file,
observations: file.observations,
gitChanges: file.gitChanges,
firstSeenAt: toIso(file.firstSeenAt || file.lastSeenAt || Date.now()),
lastSeenAt: toIso(file.lastSeenAt || file.firstSeenAt || Date.now()),
confidenceAvg: file.confidenceCount
? Math.round((file.confidenceSum / file.confidenceCount) * 100) / 100
: null,
activities: [...file.activities].slice(0, 3),
current: file.current,
}));
timeline.sort((a, b) => Date.parse(b.at) - Date.parse(a.at));
return {
podId,
member,
generatedAt: new Date().toISOString(),
windowHours,
totals: {
files: fileRows.length,
observations: memberObservations.length,
gitChanges: gitState?.changedFiles?.length ?? 0,
},
files: fileRows,
timeline: timeline.slice(0, limit),
};
}
-197
View File
@@ -1,197 +0,0 @@
import type {
Collision,
EngineerContext,
Intervention,
InterventionOutcome,
PodActivityEvent,
} from '@podman/shared';
import { getDb } from '../memory/db.js';
interface EngineerStateDoc {
_id: string;
podId: string;
name: string;
changedFiles?: string[];
diffStat?: string | null;
recentCommit?: string | null;
branch?: string | null;
gitUpdatedAt?: Date | string;
updatedAt?: Date | string;
}
function toIso(value: Date | string | undefined): string {
if (value instanceof Date) return value.toISOString();
if (value) return new Date(value).toISOString();
return new Date(0).toISOString();
}
function clean(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed || undefined;
}
function shortFiles(files: string[] | undefined): string {
if (!files?.length) return 'clean working tree';
const sample = files.slice(0, 3).join(', ');
return files.length > 3 ? `${sample}, +${files.length - 3} more` : sample;
}
function observationEvent(doc: EngineerContext): PodActivityEvent {
const file = clean(doc.currentFile);
const symbol = clean(doc.currentSymbol);
return {
id: `observation:${doc.engineerId}:${doc.observedAt}`,
podId: doc.podId,
kind: 'observation',
source: 'vision',
actor: doc.engineerId,
actors: [doc.engineerId],
file,
imageUrl: doc.screenshotDataUrl,
title: file ? `Working in ${file}` : 'Screen context updated',
detail: [
symbol ? `symbol ${symbol}` : undefined,
clean(doc.activity),
doc.hasUnpushedChanges ? 'unpushed changes visible' : undefined,
`confidence ${Math.round(doc.confidence * 100)}%`,
]
.filter(Boolean)
.join(' · '),
severity: doc.hasUnpushedChanges ? 'warn' : 'info',
at: doc.observedAt,
};
}
function gitEvent(doc: EngineerStateDoc): PodActivityEvent {
const changedFiles = doc.changedFiles ?? [];
return {
id: `git:${doc._id}:${toIso(doc.gitUpdatedAt ?? doc.updatedAt)}`,
podId: doc.podId,
kind: 'git',
source: 'git',
actor: doc.name,
actors: [doc.name],
title: changedFiles.length ? `${changedFiles.length} local file changes` : 'Git state is clean',
detail: [
doc.branch ? `branch ${doc.branch}` : undefined,
shortFiles(changedFiles),
doc.recentCommit ? `head ${doc.recentCommit}` : undefined,
]
.filter(Boolean)
.join(' · '),
severity: changedFiles.length ? 'warn' : 'info',
at: toIso(doc.gitUpdatedAt ?? doc.updatedAt),
};
}
function collisionEvent(doc: Collision): PodActivityEvent {
return {
id: `collision:${doc.id}`,
podId: doc.podId,
kind: 'collision',
source: 'memory',
actor: doc.engineers[0],
actors: doc.engineers,
file: doc.file,
title: `${doc.engineers.join(' + ')} conflict on ${doc.file}`,
detail: [
doc.symbol ? `symbol ${doc.symbol}` : undefined,
doc.githubState?.unpushed ? 'unpushed local changes involved' : undefined,
doc.githubState?.openPrs?.length
? `open PRs ${doc.githubState.openPrs.join(', ')}`
: undefined,
]
.filter(Boolean)
.join(' · '),
severity: doc.severity,
at: doc.detectedAt,
};
}
function interventionEvent(doc: Intervention): PodActivityEvent {
return {
id: `intervention:${doc.id}`,
podId: doc.podId,
kind: 'intervention',
source: 'hermes',
title: `Hermes ${doc.status} ${doc.suggestedAction.kind.replaceAll('_', ' ')}`,
detail: doc.message,
severity: doc.status === 'accepted' ? 'success' : doc.status === 'dismissed' ? 'info' : 'warn',
at: doc.createdAt,
};
}
function outcomeEvent(doc: InterventionOutcome): PodActivityEvent {
return {
id: `outcome:${doc.interventionId}:${doc.recordedAt}`,
podId: doc.podId,
kind: 'outcome',
source: 'policy',
title: doc.accepted ? 'Intervention accepted' : 'Intervention dismissed',
detail: doc.wasRealCollision ? 'confirmed real collision' : 'marked as false positive',
severity: doc.accepted ? 'success' : 'info',
at: doc.recordedAt,
};
}
export async function listPodActivity(podId: string, limit = 80): Promise<PodActivityEvent[]> {
const db = await getDb();
const [observations, gitStates, collisions, interventions, outcomes] = await Promise.all([
db
.collection<EngineerContext>('observations')
.find({ podId }, { projection: { _id: 0 } })
.sort({ observedAt: -1 })
.limit(limit)
.toArray(),
db
.collection<EngineerStateDoc>('engineer_states')
.find(
{ podId },
{
projection: {
_id: 1,
podId: 1,
name: 1,
changedFiles: 1,
diffStat: 1,
recentCommit: 1,
branch: 1,
gitUpdatedAt: 1,
updatedAt: 1,
},
},
)
.sort({ gitUpdatedAt: -1 })
.limit(limit)
.toArray(),
db
.collection<Collision>('collisions')
.find({ podId }, { projection: { _id: 0 } })
.sort({ detectedAt: -1 })
.limit(limit)
.toArray(),
db
.collection<Intervention>('interventions')
.find({ podId }, { projection: { _id: 0 } })
.sort({ createdAt: -1 })
.limit(limit)
.toArray(),
db
.collection<InterventionOutcome>('outcomes')
.find({ podId }, { projection: { _id: 0 } })
.sort({ recordedAt: -1 })
.limit(limit)
.toArray(),
]);
return [
...observations.map(observationEvent),
...gitStates.map(gitEvent),
...collisions.map(collisionEvent),
...interventions.map(interventionEvent),
...outcomes.map(outcomeEvent),
]
.filter((event) => event.at !== new Date(0).toISOString())
.sort((a, b) => Date.parse(b.at) - Date.parse(a.at))
.slice(0, limit);
}
+14 -117
View File
@@ -6,7 +6,6 @@ import {
VideoStream,
VideoBufferType,
dispose,
type VideoFrameEvent,
type RemoteTrack,
type RemoteTrackPublication,
type RemoteParticipant,
@@ -20,8 +19,6 @@ import { initMemory } from './memory/db.js';
const POD_ROOM = process.env.POD_ROOM ?? 'demo-pod';
const HERMES_IDENTITY = 'podman-hermes';
const SAMPLE_INTERVAL_MS = 1000; // ~1 fps to the vision model
const SCREEN_THUMBNAIL_WIDTH = 360;
const SHUTDOWN_GRACE_MS = 5000;
async function agentToken(room: string): Promise<string> {
const at = new AccessToken(env.LIVEKIT_API_KEY, env.LIVEKIT_API_SECRET, {
@@ -33,20 +30,6 @@ async function agentToken(room: string): Promise<string> {
return at.toJwt();
}
async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {
let timer: NodeJS.Timeout | undefined;
try {
return await Promise.race([
promise,
new Promise<null>((resolve) => {
timer = setTimeout(() => resolve(null), ms);
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}
async function main() {
// MongoDB is mandatory. Verify the connection before joining the room so bad
// creds / unreachable Atlas fail loudly at boot, not silently mid-demo.
@@ -62,57 +45,6 @@ async function main() {
console.log(`[agent] ${HERMES_IDENTITY} joined room ${POD_ROOM}`);
const lastSent = new Map<string, number>();
const inFlight = new Set<string>();
const activeStreams = new Map<string, ReadableStreamDefaultReader<VideoFrameEvent>>();
const streamKey = (
track: RemoteTrack,
pub: RemoteTrackPublication,
participant: RemoteParticipant,
) => `${participant.identity}:${pub.sid ?? track.sid ?? 'screen'}`;
const stopStream = async (key: string) => {
const reader = activeStreams.get(key);
if (!reader) return;
activeStreams.delete(key);
await reader.cancel().catch(() => {});
try {
reader.releaseLock();
} catch {
/* already released */
}
};
const processFrame = async (engineerId: string, event: VideoFrameEvent) => {
const now = Date.now();
if (now - (lastSent.get(engineerId) ?? 0) < SAMPLE_INTERVAL_MS) return;
if (inFlight.has(engineerId)) return;
lastSent.set(engineerId, now);
inFlight.add(engineerId);
try {
const rgba = event.frame.convert(VideoBufferType.RGBA);
const pixels = Buffer.from(rgba.data);
const raw = { width: rgba.width, height: rgba.height, channels: 4 } as const;
const [jpeg, thumbnail] = await Promise.all([
sharp(pixels, { raw })
.resize({ width: 1280, withoutEnlargement: true })
.jpeg({ quality: 70 })
.toBuffer(),
sharp(pixels, { raw })
.resize({ width: SCREEN_THUMBNAIL_WIDTH, withoutEnlargement: true })
.jpeg({ quality: 42 })
.toBuffer(),
]);
await podman.onScreenFrame(
engineerId,
jpeg,
`data:image/jpeg;base64,${thumbnail.toString('base64')}`,
);
} finally {
inFlight.delete(engineerId);
}
};
room.on(
RoomEvent.TrackSubscribed,
@@ -120,65 +52,30 @@ async function main() {
if (track.kind !== TrackKind.KIND_VIDEO || pub.source !== TrackSource.SOURCE_SCREENSHARE)
return;
const id = participant.identity;
const key = streamKey(track, pub, participant);
const stream = new VideoStream(track);
void stopStream(key);
const reader = stream.getReader();
activeStreams.set(key, reader);
void (async () => {
try {
while (activeStreams.get(key) === reader) {
const { done, value } = await reader.read();
if (done) break;
void processFrame(id, value).catch((err) =>
console.error(`[agent] frame sample failed for ${id}: ${(err as Error).message}`),
);
}
} catch (err) {
console.error(`[agent] screen stream failed for ${id}: ${(err as Error).message}`);
} finally {
if (activeStreams.get(key) === reader) activeStreams.delete(key);
await reader.cancel().catch(() => {});
try {
reader.releaseLock();
} catch {
/* already released */
}
for await (const event of stream) {
const now = Date.now();
if (now - (lastSent.get(id) ?? 0) < SAMPLE_INTERVAL_MS) continue; // THROTTLE
lastSent.set(id, now);
const rgba = event.frame.convert(VideoBufferType.RGBA);
const jpeg = await sharp(Buffer.from(rgba.data), {
raw: { width: rgba.width, height: rgba.height, channels: 4 },
})
.resize({ width: 1280, withoutEnlargement: true })
.jpeg({ quality: 70 })
.toBuffer();
await podman.onScreenFrame(id, jpeg);
}
})();
},
);
room.on(
RoomEvent.TrackUnsubscribed,
(track: RemoteTrack, pub: RemoteTrackPublication, participant: RemoteParticipant) => {
void stopStream(streamKey(track, pub, participant));
},
);
room.on(RoomEvent.ParticipantDisconnected, (participant: RemoteParticipant) => {
for (const key of [...activeStreams.keys()]) {
if (key.startsWith(`${participant.identity}:`)) void stopStream(key);
}
});
let shuttingDown = false;
const shutdown = async () => {
if (shuttingDown) return;
shuttingDown = true;
await withTimeout(
Promise.all([...activeStreams.keys()].map(stopStream)).then(() => room.disconnect()),
SHUTDOWN_GRACE_MS,
);
await withTimeout(dispose(), SHUTDOWN_GRACE_MS);
await room.disconnect();
await dispose();
process.exit(0);
};
room.on(RoomEvent.Disconnected, () => {
if (!shuttingDown) {
console.error('[agent] LiveKit disconnected; exiting so systemd restarts the worker');
process.exit(1);
}
});
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
+24 -101
View File
@@ -1,5 +1,6 @@
import { RoomEvent, type Room } from '@livekit/rtc-node';
import type { EngineerContext, Collision, Intervention, DataMessage } from '@podman/shared';
import { DATA_TOPIC } from '@podman/shared';
import { analyzeFrame } from '../vision/gemini.js';
import { detectCollisions } from '../collision/detector.js';
import { getGithubState } from '../github/client.js';
@@ -9,52 +10,15 @@ import {
recordIntervention,
updateInterventionStatus,
} from '../memory/store.js';
import { getGitStates, type GitState } from '../memory/db.js';
import { getGitStates } from '../memory/db.js';
import { recallSimilar } from '../memory/vectors.js';
import { shouldIntervene, preferredAction } from '../memory/policy.js';
import { publishHermesIntervention } from '../action/hermes.js';
/** Strip a git-status prefix ("M ", "?? ") and reduce a path to its lowercased
* basename — matches comparableFile() in memory/store.ts so keys line up. */
function comparableBasename(raw?: string): string {
return (
(raw ?? '')
.trim()
.replace(/^(\?\?|[MADRCU!]{1,2})\s+/, '')
.split(/[\\/]/)
.pop()
?.toLowerCase() ?? ''
);
}
/** Canonicalize an engineer name for case/whitespace-insensitive matching, so
* "Karti" and "karti" resolve to the same engineer's git state. */
function canonicalName(raw?: string): string {
return (raw ?? '').trim().toLowerCase();
}
/** Git ground truth: do ALL involved engineers currently have the collided file
* in their changedFiles? Computed at detection time while git state is fresh. */
function engineersOverlapOnFile(collision: Collision, gitStates: Map<string, GitState>): boolean {
const target = comparableBasename(collision.file);
if (!target || collision.engineers.length < 2) return false;
const byCanon = new Map<string, string[]>();
for (const [name, st] of gitStates) byCanon.set(canonicalName(name), st.changedFiles);
return collision.engineers.every((e) =>
(byCanon.get(canonicalName(e)) ?? []).some((f) => comparableBasename(f) === target),
);
}
import { speak } from '../voice/live.js';
import { publishHermesMessage } from '../action/hermes.js';
export class PodMan {
private contexts = new Map<string, EngineerContext>();
/**
* Conflicts we have already voiced and that are still unresolved, keyed by
* file (see conflictKey). Edge-triggered alerting: speak once when a conflict
* appears, stay quiet while it persists. A conflict is re-armed (deleted
* here) by onScreenFrame as soon as a detection cycle no longer sees it, so a
* resolved-then-recurring conflict alerts again.
*/
private activeConflicts = new Set<string>();
private encoder = new TextEncoder();
constructor(
private room: Room,
@@ -71,20 +35,15 @@ export class PodMan {
if (c)
c.hasUnpushedChanges = msg.report.unpushedCount > 0 || msg.report.dirtyFiles.length > 0;
}
if (msg.type === 'ACK') {
void updateInterventionStatus(msg.interventionId, msg.status).catch((err) =>
console.error(`[memory] intervention ack failed: ${(err as Error).message}`),
);
}
if (msg.type === 'ACK') void updateInterventionStatus(msg.interventionId, msg.status);
} catch {
/* ignore malformed */
}
});
}
async onScreenFrame(engineerId: string, jpeg: Buffer, screenshotDataUrl?: string): Promise<void> {
async onScreenFrame(engineerId: string, jpeg: Buffer): Promise<void> {
const ctx = await analyzeFrame(engineerId, this.podId, jpeg);
if (screenshotDataUrl) ctx.screenshotDataUrl = screenshotDataUrl;
this.contexts.set(engineerId, ctx);
await recordObservation(ctx);
@@ -97,63 +56,26 @@ export class PodMan {
}
const github = await getGithubState(); // cached
const collisions = detectCollisions([...this.contexts.values()], github, gitStates);
// Re-arm: any conflict we previously voiced that is no longer present has
// resolved, so allow it to alert again if it recurs.
const current = new Set(collisions.map((c) => this.conflictKey(c)));
for (const key of this.activeConflicts) {
if (!current.has(key)) this.activeConflicts.delete(key);
}
// Capture git ground-truth overlap now, while engineer_states are fresh, so
// the outcome-time verifier never depends on a stale sidecar or a late click.
for (const collision of collisions) {
collision.gitOverlap = engineersOverlapOnFile(collision, gitStates);
}
const collisions = detectCollisions([...this.contexts.values()], github);
for (const collision of collisions) await this.handle(collision);
}
/**
* Stable identity for a conflict, independent of the Date.now() baked into
* collision.id. Mirrors comparableFile() in memory/store.ts so keys line up:
* strip any git-status prefix ("M ", "?? ") and reduce to a lowercased
* basename.
*/
private conflictKey(collision: Collision): string {
return comparableBasename(collision.file);
}
private async handle(collision: Collision): Promise<void> {
const key = this.conflictKey(collision);
if (this.activeConflicts.has(key)) return; // single-shot: already voiced, still unresolved
const prior = await recallSimilar(collision); // Loop A: exact/vector recall raises confidence
// Only escalate to critical (which triggers the spoken alert) when the
// recalled prior was an *accepted real* collision. Blanket-escalating every
// recall — including dismissed/false-positive priors — masked the learned
// routing in preferredAction and made recalled noise scream "CRITICAL".
// (RSI Step 2 — continual-learning/policy.md:62-63, plan.md:66)
if (prior?.priorOutcome?.accepted && prior?.priorOutcome?.wasRealCollision) {
collision.severity = 'critical';
}
if (prior) collision.severity = 'critical';
if (!shouldIntervene(collision, prior)) return; // Loop B: policy gate
this.activeConflicts.add(key); // claim now we're alerting; re-armed in onScreenFrame on resolution
await recordCollision(collision);
const action = preferredAction(collision, prior);
const names = collision.engineers.join(' + ');
const shortFile = collision.file.split('/').pop() ?? collision.file;
// Terse, demo-centered alert — short and direct, not chatty AI prose.
const names = collision.engineers.join(' and ');
const message =
`Conflict: ${names} both on ${shortFile}` +
(collision.githubState?.unpushed ? ' (unpushed).' : '.') +
(prior ? ' Seen before.' : '');
// Spoken line stays short, but uses natural phrasing for Gemini TTS prosody.
const voiceLine = `${names} are both editing ${shortFile}. Please sync before pushing.`;
`${names} are both editing ${collision.file}` +
(collision.githubState?.unpushed ? ' and one has unpushed changes.' : '.') +
(prior?.priorOutcome?.accepted
? ` I've seen this conflict pattern before; last time the team accepted the ${prior.priorIntervention?.suggestedAction.kind.replaceAll('_', ' ') ?? 'suggested'} action.`
: prior
? ` I've seen this conflict pattern before.`
: '');
const intervention: Intervention = {
id: `int_${Date.now()}`,
@@ -174,11 +96,12 @@ export class PodMan {
};
await recordIntervention(intervention);
await publishHermesIntervention(
this.room,
collision,
intervention,
collision.severity === 'critical' ? voiceLine : undefined,
);
const data: DataMessage = { type: 'COLLISION', collision, intervention };
await this.room.localParticipant?.publishData(this.encoder.encode(JSON.stringify(data)), {
reliable: true,
topic: DATA_TOPIC,
});
await publishHermesMessage(this.room, collision, intervention);
if (collision.severity === 'critical') await speak(this.room, message);
}
}
+15 -65
View File
@@ -1,84 +1,34 @@
import type { EngineerContext, Collision, GithubStateSnapshot } from '@podman/shared';
import type { GitState } from '../memory/db.js';
/**
* Collapse any path-ish string to a comparable file key.
*
* Vision reads paths at inconsistent depths ("agent.ts" vs
* "backend/src/agent.ts"), and git status lines carry a status prefix
* ("M README.md", "?? test.txt"). Reduce both to a lowercased basename so the
* same file matches regardless of how it was observed. Basename matching can
* over-group two same-named files in different dirs, but for live coordination
* that bias toward firing is the right trade.
*/
function fileKey(raw?: string): string | undefined {
if (!raw) return undefined;
const stripped = raw.trim().replace(/^(\?\?|[MADRCU!]{1,2})\s+/, ''); // drop git status prefix
const base = stripped.split(/[\\/]/).pop()?.trim();
if (!base) return undefined;
return base.toLowerCase();
function normalize(path?: string): string | undefined {
if (!path) return undefined;
return path.replace(/^\.?\/?(src\/)?/, 'src/').toLowerCase();
}
interface Touch {
engineerId: string;
unpushed: boolean;
display: string; // original path/name to show in the card
}
/**
* Detect same-file collisions from two fused signals:
* 1. Vision — what each engineer currently has on screen.
* 2. Git ground truth — each engineer's dirty/unpushed `changedFiles`.
*
* Git overlap is deterministic and does not require both engineers to have the
* file on screen at the same instant, so it is the reliable demo path.
*/
export function detectCollisions(
contexts: EngineerContext[],
github: GithubStateSnapshot,
gitStates?: Map<string, GitState>,
): Collision[] {
const byFile = new Map<string, Touch[]>();
const add = (key: string | undefined, touch: Touch): void => {
if (!key) return;
(byFile.get(key) ?? byFile.set(key, []).get(key)!).push(touch);
};
// Signal 1: live vision context.
const byFile = new Map<string, EngineerContext[]>();
for (const c of contexts) {
add(fileKey(c.currentFile), {
engineerId: c.engineerId,
unpushed: c.hasUnpushedChanges === true,
display: c.currentFile ?? '',
});
}
// Signal 2: git ground truth (a dirty changed file is unpushed by definition).
if (gitStates) {
for (const [engineerId, git] of gitStates) {
for (const changed of git.changedFiles) {
add(fileKey(changed), { engineerId, unpushed: true, display: changed });
}
}
const f = normalize(c.currentFile);
if (!f) continue;
(byFile.get(f) ?? byFile.set(f, []).get(f)!).push(c);
}
const out: Collision[] = [];
for (const [, touches] of byFile) {
const engineers = [...new Set(touches.map((t) => t.engineerId))];
if (engineers.length < 2) continue; // need two distinct people on one file
for (const [file, group] of byFile) {
const engineers = [...new Set(group.map((g) => g.engineerId))];
if (engineers.length < 2) continue;
const anyUnpushed = touches.some((t) => t.unpushed) || github.unpushed === true;
const anyUnpushed = group.some((g) => g.hasUnpushedChanges) || github.unpushed === true;
if (!anyUnpushed) continue; // the crux GitHub alone cannot answer
// Show the most specific path we saw for this file.
const display =
touches.map((t) => t.display).sort((a, b) => b.length - a.length)[0] ?? touches[0]!.display;
out.push({
id: `col_${fileKey(display)}_${Date.now()}`,
podId: contexts[0]?.podId ?? 'demo-pod',
file: display,
symbol: contexts.find((c) => c.currentSymbol)?.currentSymbol,
id: `col_${file}_${Date.now()}`,
podId: group[0]!.podId,
file,
symbol: group.find((g) => g.currentSymbol)?.currentSymbol,
engineers,
severity: 'warn',
githubState: { ...github, unpushed: anyUnpushed },
-5
View File
@@ -21,14 +21,10 @@ export const env = {
LIVEKIT_URL: req('LIVEKIT_URL'),
LIVEKIT_API_KEY: req('LIVEKIT_API_KEY'),
LIVEKIT_API_SECRET: req('LIVEKIT_API_SECRET'),
LIVEKIT_AGENT_NAME: opt('LIVEKIT_AGENT_NAME'),
LIVEKIT_CONVERSATION_AGENT_NAME: opt('LIVEKIT_CONVERSATION_AGENT_NAME', 'podman-live-conversation'),
// Gemini
GEMINI_API_KEY: reqAny('GEMINI_API_KEY', ['GOOGLE_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY']),
GEMINI_VISION_MODEL: opt('GEMINI_VISION_MODEL', 'gemini-2.0-flash'),
GEMINI_LIVE_MODEL: opt('GEMINI_LIVE_MODEL', 'gemini-3.1-flash-tts-preview'),
GEMINI_CONVERSATION_MODEL: opt('GEMINI_CONVERSATION_MODEL', 'gemini-3.1-flash-live-preview'),
GEMINI_TTS_VOICE: opt('GEMINI_TTS_VOICE', 'Charon'),
GEMINI_EMBEDDING_MODEL: opt('GEMINI_EMBEDDING_MODEL', 'gemini-embedding-001'),
// GitHub
GITHUB_TOKEN: req('GITHUB_TOKEN'),
@@ -40,7 +36,6 @@ export const env = {
// Server
PORT: Number(opt('PORT', '8787')),
NUDGE_COOLDOWN_MS: Number(opt('NUDGE_COOLDOWN_MS', '180000')),
INTERNAL_AGENT_TOKEN: opt('INTERNAL_AGENT_TOKEN'),
} as const;
export function repoParts(): { owner: string; repo: string } {
+37 -68
View File
@@ -8,9 +8,45 @@ import type { PodGraph } from '@podman/shared';
* auth* — is the continual-learning story the demo lights up.
*/
export function createDemoPodGraph(podId: string): PodGraph {
const base = Date.now();
const at = (secAgo: number): string => new Date(base - secAgo * 1000).toISOString();
return {
podId,
generatedAt: new Date().toISOString(),
loop: [
{ key: 'observe', title: 'OBSERVE', value: '5', detail: '~5/s vision contexts', active: false },
{ key: 'store', title: 'STORE', value: '124', detail: 'memory vectors · Atlas', active: false },
{ key: 'predict', title: 'PREDICT', value: '1', detail: 'open risk path', active: true },
{ key: 'outcome', title: 'OUTCOME', value: '1/0', detail: 'accepted · dismissed', active: false },
{ key: 'adapt', title: 'ADAPT', value: '3', detail: 'learned owners', active: false },
],
activity: [
{
id: 'demo-learn',
at: at(20),
kind: 'learned_from',
text: 'Memory updated: Karti owns auth.ts (confidence ↑)',
},
{ id: 'demo-out', at: at(24), kind: 'outcome', text: 'Intervention accepted by the pod' },
{
id: 'demo-warn',
at: at(40),
kind: 'warns',
text: 'PodMan: "Karti & Yahya are both in auth.ts — open a sync PR?" → card sent',
},
{
id: 'demo-col',
at: at(58),
kind: 'collision',
text: 'Critical overlap on auth.ts · Karti + Yahya',
},
{
id: 'demo-edit',
at: at(72),
kind: 'editing',
text: 'Yahya opened auth.ts — unpushed changes',
},
],
// Kept consistent with the graph below (3 owner engineers, 1 collision file,
// 1 of 1 interventions accepted) so the numbers never contradict the picture.
metrics: [
@@ -30,73 +66,6 @@ export function createDemoPodGraph(podId: string): PodGraph {
detail: 'Interventions accepted vs total this session.',
},
],
loop: {
activeStep: 'adapt',
steps: [
{
key: 'observe',
label: 'Observe',
value: '2',
detail: 'Screen context and local git state show two active editors.',
status: 'complete',
},
{
key: 'store',
label: 'Store',
value: '7',
detail: 'Observations, collisions, interventions, and outcomes are in MongoDB.',
status: 'complete',
},
{
key: 'predict',
label: 'Predict',
value: '2',
detail: 'Same-file risk paths are detected before push.',
status: 'complete',
},
{
key: 'outcome',
label: 'Outcome',
value: '6',
detail: 'Accepted and dismissed outcomes supervise future routing.',
status: 'complete',
},
{
key: 'adapt',
label: 'Adapt',
value: '1',
detail: 'Accepted real collision created a learned_from edge.',
status: 'complete',
},
],
},
activity: [
{
id: 'demo-learned-auth',
at: new Date().toISOString(),
kind: 'learned',
title: 'Learned Karti owns auth.ts',
detail: 'Accepted sync PR outcome created a durable learned_from path.',
nodeId: 'engineer:karti',
edgeId: 'e7',
},
{
id: 'demo-intervention-sync-pr',
at: new Date().toISOString(),
kind: 'intervention',
title: 'Intervention: sync PR',
detail: 'PodMan offered a small coordination card before voice.',
nodeId: 'intervention:sync-pr',
},
{
id: 'demo-collision-auth',
at: new Date().toISOString(),
kind: 'collision',
title: 'Collision risk on auth.ts',
detail: 'Karti and Yahya converged on unpushed work.',
nodeId: 'collision:auth',
},
],
nodes: [
{
id: 'engineer:shakthi',
@@ -255,7 +224,7 @@ export function createDemoPodGraph(podId: string): PodGraph {
source: 'collision:auth',
target: 'intervention:sync-pr',
kind: 'warns',
label: 'routes',
label: 'nudges',
strength: 0.9,
},
{
+234 -164
View File
@@ -3,11 +3,16 @@ import type {
PodGraphNode,
PodGraphEdge,
PodGraphMetric,
PodLearningLoop,
PodGraphActivity,
PodGraphNodeKind,
PodGraphEdgeKind,
PodGraphNodeStatus,
LearningStage,
LearningStageKey,
ActivityEvent,
EngineerContext,
Collision,
Intervention,
InterventionOutcome,
} from '@podman/shared';
import { collections, getGitStates, getDb } from '../memory/db.js';
@@ -150,75 +155,183 @@ function layout(nodes: PodGraphNode[]): void {
const SEVERITY_WEIGHT: Record<string, number> = { info: 0.4, warn: 0.7, critical: 1 };
function buildLoop(input: {
observations: number;
gitStates: number;
collisions: number;
interventions: number;
outcomes: number;
acceptedReal: number;
learnedEdges: number;
}): PodLearningLoop {
const stored = input.observations + input.gitStates + input.interventions + input.outcomes;
return {
activeStep:
input.acceptedReal > 0
? 'adapt'
: input.outcomes > 0
? 'outcome'
: input.collisions > 0
? 'predict'
: input.observations + input.gitStates > 0
? 'store'
: 'observe',
steps: [
{
key: 'observe',
label: 'Observe',
value: String(input.observations + input.gitStates),
detail: 'Recent vision observations plus local git-state reports.',
status: input.observations + input.gitStates > 0 ? 'complete' : 'quiet',
},
{
key: 'store',
label: 'Store',
value: String(stored),
detail: 'MongoDB records available to recall for this pod.',
status: stored > 0 ? 'complete' : 'quiet',
},
{
key: 'predict',
label: 'Predict',
value: String(input.collisions),
detail: 'Distinct collision signatures detected from live work.',
status: input.collisions > 0 ? 'complete' : 'quiet',
},
{
key: 'outcome',
label: 'Outcome',
value: String(input.outcomes),
detail: 'Accepted and dismissed intervention outcomes.',
status: input.outcomes > 0 ? 'complete' : 'quiet',
},
{
key: 'adapt',
label: 'Adapt',
value: String(input.learnedEdges),
detail: 'Learned graph edges created from accepted real outcomes.',
status: input.acceptedReal > 0 ? 'complete' : 'planned',
},
],
};
/** Parse any timestamp-ish value to epoch ms (0 when missing/unparseable). */
function ms(t: string | Date | null | undefined): number {
if (!t) return 0;
const v = new Date(t).getTime();
return Number.isFinite(v) ? v : 0;
}
function pushActivity(
activity: PodGraphActivity[],
item: PodGraphActivity,
seen: Set<string>,
): void {
if (seen.has(item.id)) return;
seen.add(item.id);
activity.push(item);
const OBSERVE_WINDOW_MS = 60_000;
/**
* Live counts for the learning-loop rail (observe→store→predict→outcome→adapt).
* The "active" stage is the one whose latest underlying event is most recent —
* with deeper stages winning ties so the rail lights up at the furthest point
* the pod reached this session. Additive: derived from already-fetched docs.
*/
function buildLoop(opts: {
now: number;
observations: EngineerContext[];
collisions: Collision[];
outcomes: InterventionOutcome[];
riskPaths: number;
vectorCount: number;
learnedOwners: number;
}): LearningStage[] {
const { now, observations, collisions, outcomes, riskPaths, vectorCount, learnedOwners } = opts;
const recentObs = observations.filter((o) => now - ms(o.observedAt) < OBSERVE_WINDOW_MS).length;
const rate = (recentObs / 60).toFixed(1);
const accepted = outcomes.filter((o) => o.accepted).length;
const dismissed = outcomes.filter((o) => !o.accepted).length;
// Latest event time per stage; `store` sits just behind `predict` so a shared
// collision timestamp resolves to PREDICT rather than STORE.
const latestObs = Math.max(0, ...observations.map((o) => ms(o.observedAt)));
const latestCol = Math.max(0, ...collisions.map((c) => ms(c.detectedAt)));
const latestOut = Math.max(0, ...outcomes.map((o) => ms(o.recordedAt)));
const latestAdapt = Math.max(
0,
...outcomes.filter((o) => o.accepted && o.wasRealCollision).map((o) => ms(o.recordedAt)),
);
const refs: Array<[LearningStageKey, number]> = [
['observe', latestObs],
['store', latestCol ? latestCol - 1 : 0],
['predict', latestCol],
['outcome', latestOut],
['adapt', latestAdapt],
];
let activeKey: LearningStageKey = 'observe';
let best = 0;
for (const [k, t] of refs) {
if (t > 0 && t >= best) {
best = t;
activeKey = k;
}
}
const stages: Array<Omit<LearningStage, 'active'>> = [
{ key: 'observe', title: 'OBSERVE', value: String(recentObs), detail: `~${rate}/s vision contexts` },
{ key: 'store', title: 'STORE', value: String(vectorCount), detail: 'memory vectors · Atlas' },
{
key: 'predict',
title: 'PREDICT',
value: String(riskPaths),
detail: `open risk path${riskPaths === 1 ? '' : 's'}`,
},
{ key: 'outcome', title: 'OUTCOME', value: `${accepted}/${dismissed}`, detail: 'accepted · dismissed' },
{
key: 'adapt',
title: 'ADAPT',
value: String(learnedOwners),
detail: `learned owner${learnedOwners === 1 ? '' : 's'}`,
},
];
return stages.map((s) => ({ ...s, active: s.key === activeKey }));
}
/**
* Merge + time-sort recent events into the activity stream feed. Reuses the same
* de-noise (isFilePath / ENGINEER_NOISE / signature collapse) as the graph so
* the feed never shows junk paths or test-artifact engineers. Capped to 8.
*/
function buildActivity(opts: {
observations: EngineerContext[];
collisions: Collision[];
interventions: Intervention[];
outcomes: InterventionOutcome[];
ownership: Record<string, string>;
}): ActivityEvent[] {
const { observations, collisions, interventions, outcomes, ownership } = opts;
const cleanEng = (n: string): boolean => Boolean(n) && !ENGINEER_NOISE.test(n);
const out: ActivityEvent[] = [];
// editing — newest observation per (engineer, file); observations arrive desc.
const seenEdit = new Set<string>();
for (const o of observations) {
if (!o.engineerId || !cleanEng(o.engineerId)) continue;
const file = o.currentFile ? normalizeFile(o.currentFile) : '';
if (!isFilePath(file)) continue;
const key = `${o.engineerId.toLowerCase()}|${file}`;
if (seenEdit.has(key)) continue;
seenEdit.add(key);
out.push({
id: `edit:${o.engineerId}:${file}`,
at: o.observedAt,
kind: 'editing',
text: `${o.engineerId} opened ${shortLabel(file)}${
o.hasUnpushedChanges ? ' — unpushed changes' : ''
}`,
});
}
// collision — collapse by signature, newest first.
const seenCol = new Set<string>();
for (const c of collisions) {
const file = normalizeFile(c.file);
if (!isFilePath(file)) continue;
const sig = (c as { memorySignature?: string }).memorySignature ?? `${file}#${c.symbol ?? ''}`;
if (seenCol.has(sig)) continue;
seenCol.add(sig);
const engs = c.engineers.filter(cleanEng);
if (!engs.length) continue;
out.push({
id: `col:${c.id}`,
at: c.detectedAt,
kind: 'collision',
text: `${c.severity === 'critical' ? 'Critical overlap' : 'Overlap'} on ${shortLabel(
file,
)} · ${engs.join(' + ')}`,
});
}
// warns — interventions PodMan raised.
for (const iv of interventions) {
if (!iv.message) continue;
const msg = iv.message.length > 64 ? `${iv.message.slice(0, 61)}` : iv.message;
out.push({
id: `warn:${iv.id}`,
at: iv.createdAt,
kind: 'warns',
text: `PodMan: "${msg}" → card sent`,
});
}
// outcome + learned_from — the supervised learning beat.
const colById = new Map(collisions.map((c) => [c.id, c]));
const ivById = new Map(interventions.map((i) => [i.id, i]));
for (const o of outcomes) {
if (!o.accepted) continue;
out.push({
id: `out:${o.interventionId}`,
at: o.recordedAt,
kind: 'outcome',
text: 'Intervention accepted by the pod',
});
if (!o.wasRealCollision) continue;
const iv = ivById.get(o.interventionId);
const col = iv ? colById.get(iv.collisionId) : colById.get(o.collisionId);
if (!col) continue;
const file = normalizeFile(col.file);
if (!isFilePath(file)) continue;
const owner =
(o as { learnedOwner?: string }).learnedOwner ??
ownership[file] ??
col.engineers.find(cleanEng) ??
col.engineers[0];
if (!owner) continue;
out.push({
id: `learn:${o.interventionId}`,
at: o.recordedAt,
kind: 'learned_from',
text: `Memory updated: ${owner} owns ${shortLabel(file)} (confidence ↑)`,
});
}
out.sort((a, b) => ms(b.at) - ms(a.at));
return out.slice(0, 8);
}
export async function materializePodGraph(podId: string): Promise<PodGraph | null> {
@@ -247,8 +360,6 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
}
const b: Builder = { nodes: new Map(), edges: new Map() };
const activity: PodGraphActivity[] = [];
const activityIds = new Set<string>();
const now = Date.now();
// 1. Baseline engineer nodes from the roster.
@@ -268,18 +379,6 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
if (isFilePath(file)) {
const f = upsertNode(b, 'file', file, { label: shortLabel(file), summary: file });
upsertEdge(b, eng, f, 'editing', o.activity ?? 'edits', Math.max(0.4, o.confidence ?? 0.5));
pushActivity(
activity,
{
id: `editing:${o.engineerId}:${file}:${String(o.observedAt ?? '')}`,
at: String(o.observedAt ?? new Date().toISOString()),
kind: 'editing',
title: `${o.engineerId} editing ${shortLabel(file)}`,
detail: o.activity ?? 'Vision observed active work.',
nodeId: f,
},
activityIds,
);
}
}
@@ -338,18 +437,6 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
const eng = upsertNode(b, 'engineer', name, { label: name });
upsertEdge(b, eng, cNode, 'collides', 'in', SEVERITY_WEIGHT[col.severity] ?? 0.7);
}
pushActivity(
activity,
{
id: `collision:${col.id}`,
at: col.detectedAt,
kind: 'collision',
title: `Collision risk on ${shortLabel(file)}`,
detail: `${col.engineers.join(' + ')} converged on ${file}.`,
nodeId: cNode,
},
activityIds,
);
sigToNode.set(sig, cNode);
colNodeFor.set(col.id, cNode);
if (!isPriority) distinctCollisions++;
@@ -392,19 +479,7 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
: 'watch',
summary: iv.message,
});
upsertEdge(b, colNode, ivNode, 'warns', 'routes', 0.85);
pushActivity(
activity,
{
id: `intervention:${iv.id}`,
at: iv.createdAt,
kind: 'intervention',
title: `Intervention: ${b.nodes.get(ivNode)?.label ?? iv.kind}`,
detail: iv.message,
nodeId: ivNode,
},
activityIds,
);
upsertEdge(b, colNode, ivNode, 'warns', 'nudges', 0.85);
ivNodeForCol.set(colNode, ivNode);
}
@@ -427,34 +502,8 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
if (ivNode) {
const ivObj = b.nodes.get(ivNode);
if (ivObj) ivObj.status = 'learned';
const before = b.edges.size;
upsertEdge(b, ivNode, engNode, 'learned_from', `learned: owns ${file}`, 0.6);
const edgeId = `${'learned_from'}:${ivNode}->${engNode}`;
pushActivity(
activity,
{
id: `learned:${out.interventionId}:${owner}:${file}`,
at: out.recordedAt,
kind: 'learned',
title: `Learned ${owner} owns ${shortLabel(file)}`,
detail: 'Accepted real outcome created a durable learned_from path.',
nodeId: engNode,
edgeId: before === b.edges.size ? undefined : edgeId,
},
activityIds,
);
}
pushActivity(
activity,
{
id: `outcome:${out.interventionId}:${out.recordedAt}`,
at: out.recordedAt,
kind: 'outcome',
title: out.accepted ? 'Outcome accepted' : 'Outcome dismissed',
detail: out.wasRealCollision ? 'Marked as a real collision.' : 'Marked as noise.',
},
activityIds,
);
}
// Prune test-artifact engineers, then anything left orphaned by that.
@@ -500,26 +549,22 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
layout(nodes);
const acceptedReal = outcomeDocs.filter((o) => o.accepted && o.wasRealCollision).length;
const totalOutcomes = outcomeDocs.length;
// Raw distinct collision signatures — kept for the learning-loop throughput view.
const riskPaths = new Set(
collisionDocs.map(
(col) =>
(col as { memorySignature?: string }).memorySignature ??
`${normalizeFile(col.file)}#${col.symbol ?? ''}`,
),
).size;
// Headline metric cards are derived from the FINAL de-noised graph so they match
// what's drawn. Counting raw collision signatures / accepted-outcome rows inflates
// them with test churn (e.g. 50 "risk paths" for 4 files), which reads as fake.
// Metrics are derived from the FINAL de-noised graph (not raw docs) so the
// numbers match what's actually on screen. Counting raw collision signatures /
// accepted-outcome rows inflates them with test churn (e.g. 50 "risk paths" for
// 2 files), which reads as fake — these count distinct visible entities instead.
const finalEdges = [...b.edges.values()];
// Open risk paths = distinct files carrying a surviving collision (the triangles).
const riskFiles = new Set<string>();
for (const e of finalEdges) {
if (e.kind === 'touches' && b.nodes.get(e.source)?.kind === 'file') riskFiles.add(e.source);
}
const openRiskPaths = riskFiles.size || nodes.filter((n) => n.kind === 'collision').length;
const collisionNodeCount = nodes.filter((n) => n.kind === 'collision').length;
const riskPaths = riskFiles.size || collisionNodeCount;
// Learned owners = distinct engineers PodMan retained as owners from accepted
// interventions (the owns / learned_from edges actually drawn).
const ownerSet = new Set<string>();
for (const e of finalEdges) {
if (e.kind === 'learned_from') ownerSet.add(e.target);
@@ -527,6 +572,10 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
}
const learnedOwners = [...ownerSet].filter((id) => b.nodes.get(id)?.kind === 'engineer').length;
const acceptedReal = outcomeDocs.filter((o) => o.accepted && o.wasRealCollision).length;
const totalOutcomes = outcomeDocs.length;
const acceptRate = totalOutcomes ? Math.round((acceptedReal / totalOutcomes) * 100) : null;
const metrics: PodGraphMetric[] = [
{
label: 'Learned owners',
@@ -535,17 +584,46 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
},
{
label: 'Open risk paths',
value: String(openRiskPaths),
detail: `${openRiskPaths === 1 ? 'File' : 'Files'} with two or more converging editors.`,
value: String(riskPaths),
detail: `${riskPaths === 1 ? 'File' : 'Files'} with two or more converging editors.`,
},
{
label: 'Accept rate',
value: totalOutcomes ? `${Math.round((acceptedReal / totalOutcomes) * 100)}%` : '—',
value: acceptRate == null ? '—' : `${acceptRate}%`,
detail: 'Interventions accepted vs total this session.',
},
];
const learnedEdges = [...b.edges.values()].filter((e) => e.kind === 'learned_from').length;
activity.sort((a, z) => String(z.at).localeCompare(String(a.at)));
// Stored vectors for the STORE stage: prefer a real memory_vectors count,
// fall back to collisions carrying an embedding, then to collision count.
let vectorCount = 0;
try {
vectorCount = await db.collection('memory_vectors').countDocuments({ podId });
} catch {
/* memory_vectors is optional */
}
if (!vectorCount)
vectorCount = collisionDocs.filter(
(c) => (c as { embedding?: number[] }).embedding?.length,
).length;
if (!vectorCount) vectorCount = collisionDocs.length;
const loop = buildLoop({
now,
observations,
collisions: collisionDocs,
outcomes: outcomeDocs,
riskPaths,
vectorCount,
learnedOwners,
});
const activity = buildActivity({
observations,
collisions: collisionDocs,
interventions: interventionDocs,
outcomes: outcomeDocs,
ownership,
});
return {
podId,
@@ -553,15 +631,7 @@ export async function materializePodGraph(podId: string): Promise<PodGraph | nul
nodes,
edges: [...b.edges.values()],
metrics,
loop: buildLoop({
observations: observations.length,
gitStates: gitStates.size,
collisions: riskPaths,
interventions: interventionDocs.length,
outcomes: totalOutcomes,
acceptedReal,
learnedEdges,
}),
activity: activity.slice(0, 12),
loop,
activity,
};
}
-349
View File
@@ -1,349 +0,0 @@
import { randomUUID } from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { Room as LiveKitRoom } from '@livekit/rtc-node';
import { AccessToken } from 'livekit-server-sdk';
import {
DATA_TOPIC,
type DataMessage,
type HermesJob,
type HermesJobEvent,
type HermesJobEventType,
type HermesJobInput,
type HermesJobStatus,
type HermesRiskLevel,
} from '@podman/shared';
import { env, repoParts } from '../env.js';
import { getDb } from '../memory/db.js';
const execFileAsync = promisify(execFile);
const encoder = new TextEncoder();
const MAX_OUTPUT = 3_000;
const COMMAND_TIMEOUT_MS = 45_000;
const runners = new Map<string, AbortController>();
function now(): string {
return new Date().toISOString();
}
function truncate(value: string): string {
return value.length > MAX_OUTPUT ? `${value.slice(0, MAX_OUTPUT)}\n...[truncated]` : value;
}
function redact(value: string): string {
return value
.replace(/AIza[0-9A-Za-z_-]{20,}/g, '[redacted-google-key]')
.replace(/API[_-]?SECRET=[^\s]+/gi, 'API_SECRET=[redacted]')
.replace(/TOKEN=[^\s]+/gi, 'TOKEN=[redacted]')
.replace(/mongodb(\+srv)?:\/\/[^@\s]+@/gi, 'mongodb$1://[redacted]@');
}
function normalizeRisk(value: unknown): HermesRiskLevel {
return value === 'safe_write' ||
value === 'commit_allowed' ||
value === 'deploy_allowed' ||
value === 'read_only'
? value
: 'read_only';
}
async function hermesJobs() {
return (await getDb()).collection<HermesJob>('hermes_jobs');
}
async function hermesJobEvents() {
return (await getDb()).collection<HermesJobEvent>('hermes_job_events');
}
export async function ensureHermesJobIndexes(): Promise<void> {
const db = await getDb();
await Promise.allSettled([
db.collection('hermes_jobs').createIndex({ id: 1 }, { unique: true }),
db.collection('hermes_jobs').createIndex({ sessionId: 1, status: 1, updatedAt: -1 }),
db.collection('hermes_jobs').createIndex({ podId: 1, updatedAt: -1 }),
db.collection('hermes_job_events').createIndex({ jobId: 1, createdAt: 1 }),
db.collection('hermes_job_events').createIndex({ sessionId: 1, createdAt: -1 }),
]);
}
export async function createHermesJob(input: Partial<HermesJobInput>): Promise<HermesJob> {
const prompt = typeof input.prompt === 'string' ? input.prompt.trim() : '';
if (!prompt) throw new Error('prompt is required');
const createdAt = now();
const job: HermesJob = {
id: `hermes_job_${randomUUID()}`,
podId: input.podId || 'demo-pod',
identity: input.identity || 'developer',
sessionId: input.sessionId || 'unknown',
conversationRoom: input.conversationRoom,
prompt,
contextScope: input.contextScope || 'current_repo',
targetRepository: input.targetRepository || env.GITHUB_REPO,
riskLevel: normalizeRisk(input.riskLevel),
requiresConfirmation: input.requiresConfirmation === true,
successCriteria: Array.isArray(input.successCriteria)
? input.successCriteria.map(String).filter(Boolean).slice(0, 8)
: ['Hermes reports what it inspected and what changed.'],
parentJobId: input.parentJobId,
status: 'queued',
createdAt,
updatedAt: createdAt,
};
await (await hermesJobs()).insertOne(job);
await appendHermesJobEvent(job.id, 'accepted', 'Hermes accepted the task.', {
riskLevel: job.riskLevel,
contextScope: job.contextScope,
});
void runHermesJob(job.id);
return job;
}
export async function getHermesJob(jobId: string): Promise<HermesJob | null> {
return (await hermesJobs()).findOne({ id: jobId }, { projection: { _id: 0 } });
}
export async function getActiveHermesJobForSession(sessionId: string): Promise<HermesJob | null> {
return (await hermesJobs()).findOne(
{ sessionId, status: { $in: ['queued', 'running', 'waiting_for_confirmation', 'aborting'] } },
{ projection: { _id: 0 }, sort: { updatedAt: -1 } },
);
}
export async function getLatestHermesJobForSession(sessionId: string): Promise<HermesJob | null> {
return (await hermesJobs()).findOne(
{ sessionId },
{ projection: { _id: 0 }, sort: { updatedAt: -1 } },
);
}
export async function listHermesJobEvents(jobId: string, limit = 40): Promise<HermesJobEvent[]> {
return (await hermesJobEvents())
.find({ jobId }, { projection: { _id: 0 } })
.sort({ createdAt: 1 })
.limit(Math.min(limit, 200))
.toArray();
}
export async function appendHermesJobEvent(
jobId: string,
type: HermesJobEventType,
message: string,
data?: Record<string, unknown>,
): Promise<HermesJobEvent> {
const job = await getHermesJob(jobId);
if (!job) throw new Error('job not found');
const event: HermesJobEvent = {
id: `hermes_evt_${randomUUID()}`,
jobId,
podId: job.podId,
sessionId: job.sessionId,
type,
message: redact(truncate(message)),
data,
createdAt: now(),
};
await (await hermesJobEvents()).insertOne(event);
await (
await hermesJobs()
).updateOne(
{ id: jobId },
{ $set: { updatedAt: event.createdAt, lastHeartbeatAt: event.createdAt } },
);
if (job.conversationRoom) {
void publishHermesJobEvent(job.conversationRoom, event).catch((err) =>
console.warn(`[hermes-job] data publish failed: ${(err as Error).message}`),
);
}
return event;
}
export async function abortHermesJob(jobId: string): Promise<HermesJob | null> {
const job = await getHermesJob(jobId);
if (!job) return null;
const abortAt = now();
await (
await hermesJobs()
).updateOne(
{ id: jobId },
{ $set: { status: 'aborting', abortRequestedAt: abortAt, updatedAt: abortAt } },
);
runners.get(jobId)?.abort();
await appendHermesJobEvent(jobId, 'heartbeat', 'Hermes is aborting the current job.');
return getHermesJob(jobId);
}
async function setStatus(jobId: string, status: HermesJobStatus, patch: Partial<HermesJob> = {}) {
await (
await hermesJobs()
).updateOne({ id: jobId }, { $set: { status, updatedAt: now(), ...patch } });
}
async function publishHermesJobEvent(roomName: string, event: HermesJobEvent): Promise<void> {
const room = new LiveKitRoom();
try {
const at = new AccessToken(env.LIVEKIT_API_KEY, env.LIVEKIT_API_SECRET, {
identity: `podman-hermes-job-${Date.now()}`,
name: 'PodMan Hermes jobs',
ttl: '5m',
});
at.addGrant({
roomJoin: true,
room: roomName,
canPublish: true,
canSubscribe: false,
canPublishData: true,
});
await room.connect(env.LIVEKIT_URL, await at.toJwt(), {
autoSubscribe: false,
dynacast: false,
});
const data: DataMessage = { type: 'HERMES_JOB_EVENT', event };
await room.localParticipant?.publishData(encoder.encode(JSON.stringify(data)), {
reliable: true,
topic: DATA_TOPIC,
});
} finally {
await room.disconnect().catch(() => {});
}
}
async function runCommand(
jobId: string,
label: string,
command: string,
args: string[],
signal: AbortSignal,
): Promise<string> {
await appendHermesJobEvent(jobId, 'step_started', `${label} started.`);
const started = Date.now();
const { stdout, stderr } = await execFileAsync(command, args, {
cwd: process.cwd(),
timeout: COMMAND_TIMEOUT_MS,
signal,
maxBuffer: 1024 * 1024,
});
const output = redact(truncate([stdout, stderr].filter(Boolean).join('\n').trim()));
await appendHermesJobEvent(jobId, 'step_output', output || `${label} produced no output.`, {
label,
durationMs: Date.now() - started,
});
await appendHermesJobEvent(jobId, 'step_completed', `${label} completed.`);
return output;
}
function wantsBuild(prompt: string, criteria: string[]): boolean {
const haystack = `${prompt} ${criteria.join(' ')}`.toLowerCase();
return /build|typecheck|test|lint|broken|failing|verify/.test(haystack);
}
function wantsMongo(prompt: string, scope: string): boolean {
return scope === 'mongodb' || /mongo|database|telemetry|logs?|memory/.test(prompt.toLowerCase());
}
function wantsGithub(prompt: string, scope: string): boolean {
return (
scope === 'github' || /github|branch|pr|pull request|commit|diff/.test(prompt.toLowerCase())
);
}
async function inspectMongo(jobId: string) {
await appendHermesJobEvent(jobId, 'step_started', 'MongoDB inspection started.');
const db = await getDb();
const [observations, collisions, interventions, outcomes, jobs] = await Promise.all([
db.collection('observations').estimatedDocumentCount(),
db.collection('collisions').estimatedDocumentCount(),
db.collection('interventions').estimatedDocumentCount(),
db.collection('outcomes').estimatedDocumentCount(),
db.collection('hermes_jobs').estimatedDocumentCount(),
]);
await appendHermesJobEvent(
jobId,
'step_output',
`MongoDB is reachable. Counts: observations=${observations}, collisions=${collisions}, interventions=${interventions}, outcomes=${outcomes}, hermes_jobs=${jobs}.`,
);
await appendHermesJobEvent(jobId, 'step_completed', 'MongoDB inspection completed.');
}
async function inspectGithub(jobId: string) {
await appendHermesJobEvent(jobId, 'step_started', 'GitHub repository inspection started.');
const { owner, repo } = repoParts();
const res = await fetch(`https://api.github.com/repos/${owner}/${repo}`, {
headers: {
accept: 'application/vnd.github+json',
authorization: `Bearer ${env.GITHUB_TOKEN}`,
'x-github-api-version': '2022-11-28',
},
});
if (!res.ok) throw new Error(`GitHub repo check returned ${res.status}`);
const body = (await res.json()) as {
full_name?: string;
default_branch?: string;
open_issues_count?: number;
};
await appendHermesJobEvent(
jobId,
'step_output',
`GitHub ${body.full_name ?? `${owner}/${repo}`} is reachable. Default branch=${body.default_branch ?? 'unknown'}, open issue count=${body.open_issues_count ?? 0}.`,
);
await appendHermesJobEvent(jobId, 'step_completed', 'GitHub repository inspection completed.');
}
async function runHermesJob(jobId: string): Promise<void> {
const job = await getHermesJob(jobId);
if (!job) return;
const controller = new AbortController();
runners.set(jobId, controller);
try {
await setStatus(jobId, 'running', { startedAt: now() });
await appendHermesJobEvent(jobId, 'heartbeat', 'Hermes is gathering repository context.');
const outputs: string[] = [];
outputs.push(
await runCommand(
jobId,
'Git status',
'git',
['status', '--short', '--branch'],
controller.signal,
),
);
outputs.push(
await runCommand(jobId, 'Git diff summary', 'git', ['diff', '--stat'], controller.signal),
);
if (wantsGithub(job.prompt, job.contextScope)) await inspectGithub(jobId);
if (wantsMongo(job.prompt, job.contextScope)) await inspectMongo(jobId);
if (wantsBuild(job.prompt, job.successCriteria)) {
outputs.push(
await runCommand(jobId, 'TypeScript typecheck', 'pnpm', ['typecheck'], controller.signal),
);
}
if (job.riskLevel === 'deploy_allowed' && job.requiresConfirmation) {
await setStatus(jobId, 'waiting_for_confirmation');
await appendHermesJobEvent(
jobId,
'needs_confirmation',
'Hermes needs confirmation before deploy-level actions.',
);
return;
}
const finalSummary = `Hermes completed the task. It inspected repository state${wantsMongo(job.prompt, job.contextScope) ? ', MongoDB' : ''}${wantsGithub(job.prompt, job.contextScope) ? ', and GitHub' : ''}. ${outputs.some((o) => /error|failed/i.test(o)) ? 'Review the recorded output for warnings.' : 'No blocking error was reported by the completed checks.'}`;
await setStatus(jobId, 'completed', { completedAt: now(), finalSummary });
await appendHermesJobEvent(jobId, 'completed', finalSummary);
} catch (err) {
const aborted = controller.signal.aborted;
const message = aborted
? 'Hermes aborted the job before making further changes.'
: (err as Error).message;
await setStatus(jobId, aborted ? 'aborted' : 'failed', {
completedAt: now(),
finalSummary: message,
error: aborted ? undefined : message,
});
await appendHermesJobEvent(jobId, aborted ? 'aborted' : 'failed', message);
} finally {
runners.delete(jobId);
}
}
-80
View File
@@ -1,80 +0,0 @@
import { getDb } from '../memory/db.js';
import { getMemberWorkHistory } from '../activity/member-history.js';
const DEFAULT_LIMIT = 8;
function sinceIso(hours: number): string {
return new Date(Date.now() - hours * 60 * 60 * 1000).toISOString();
}
export async function getLiveConversationContext(podId: string, identity: string) {
const db = await getDb();
const since = sinceIso(12);
const [pod, history, gitState, collisions, interventions, outcomes] = await Promise.all([
db.collection('pods').findOne({ id: podId }, { projection: { _id: 0 } }),
getMemberWorkHistory(podId, identity, { hours: 24, limit: 30 }).catch(() => null),
db.collection('engineer_states').findOne(
{ podId, name: identity },
{
projection: {
_id: 0,
name: 1,
branch: 1,
changedFiles: 1,
recentCommit: 1,
gitUpdatedAt: 1,
},
},
),
db
.collection('collisions')
.find({ podId, detectedAt: { $gte: since } }, { projection: { _id: 0, embedding: 0 } })
.sort({ detectedAt: -1 })
.limit(DEFAULT_LIMIT)
.toArray(),
db
.collection('interventions')
.find({ podId, createdAt: { $gte: since } }, { projection: { _id: 0 } })
.sort({ createdAt: -1 })
.limit(DEFAULT_LIMIT)
.toArray(),
db
.collection('outcomes')
.find({ podId, recordedAt: { $gte: since } }, { projection: { _id: 0 } })
.sort({ recordedAt: -1 })
.limit(DEFAULT_LIMIT)
.toArray(),
]);
return {
pod,
identity,
generatedAt: new Date().toISOString(),
currentGitState: gitState,
memberHistory: history,
recentCollisions: collisions,
recentInterventions: interventions,
recentOutcomes: outcomes,
};
}
export async function recordLiveConversationNote(input: {
podId: string;
sessionId: string;
identity?: string;
note: string;
kind?: string;
}) {
const note = input.note.trim();
if (!note) throw new Error('note is required');
const doc = {
podId: input.podId,
sessionId: input.sessionId,
identity: input.identity,
kind: input.kind || 'summary',
note: note.slice(0, 4000),
createdAt: new Date().toISOString(),
};
await (await getDb()).collection('conversation_notes').insertOne(doc);
return { ...doc, _id: undefined };
}
-193
View File
@@ -1,193 +0,0 @@
import { randomUUID } from 'node:crypto';
import { AccessToken, RoomAgentDispatch, RoomConfiguration } from 'livekit-server-sdk';
import { Room as LiveKitRoom } from '@livekit/rtc-node';
import type { Collision, DataMessage, Intervention, LiveConversationEvent } from '@podman/shared';
import { DATA_TOPIC } from '@podman/shared';
import { env } from '../env.js';
import { closeRoom } from '../livekit/rooms.js';
import { speakInRoom } from '../voice/live.js';
const encoder = new TextEncoder();
const DEFAULT_AGENT = 'podman-live-conversation';
export interface LiveConversationSession {
sessionId: string;
podId: string;
identity: string;
displayName: string;
room: string;
url: string;
startedAt: string;
lastEventAt?: string;
endedAt?: string;
}
const sessions = new Map<string, LiveConversationSession>();
function sessionKey(podId: string, identity: string): string {
return `${podId}:${identity.toLowerCase()}`;
}
function cleanPart(value: string): string {
return value
.trim()
.toLowerCase()
.replace(/[^a-z0-9_-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 48);
}
function agentName(): string {
return env.LIVEKIT_CONVERSATION_AGENT_NAME || DEFAULT_AGENT;
}
function tokenFor(room: string, identity: string, name: string, metadata: object): Promise<string> {
const at = new AccessToken(env.LIVEKIT_API_KEY, env.LIVEKIT_API_SECRET, {
identity,
name,
ttl: '4h',
metadata: JSON.stringify(metadata),
});
at.addGrant({ roomJoin: true, room, canPublish: true, canSubscribe: true, canPublishData: true });
return at.toJwt();
}
export async function startLiveConversation(input: {
podId: string;
identity: string;
displayName?: string;
}): Promise<LiveConversationSession & { token: string }> {
const identity = input.identity.trim();
if (!identity) throw new Error('identity is required');
const existing = activeLiveConversation(input.podId, identity);
if (existing) {
return {
...existing,
token: await tokenFor(existing.room, identity, existing.displayName, {
podId: input.podId,
identity,
sessionId: existing.sessionId,
mode: 'podman-live-conversation',
}),
};
}
const sessionId = randomUUID();
const room = `podman-live:${cleanPart(input.podId)}:${cleanPart(identity)}:${sessionId.slice(0, 8)}`;
const displayName = input.displayName?.trim() || identity;
const metadata = { podId: input.podId, identity, sessionId, mode: 'podman-live-conversation' };
const at = new AccessToken(env.LIVEKIT_API_KEY, env.LIVEKIT_API_SECRET, {
identity,
name: displayName,
ttl: '4h',
metadata: JSON.stringify(metadata),
});
at.addGrant({ roomJoin: true, room, canPublish: true, canSubscribe: true, canPublishData: true });
at.roomConfig = new RoomConfiguration({
name: room,
emptyTimeout: 60,
departureTimeout: 15,
agents: [
new RoomAgentDispatch({
agentName: agentName(),
metadata: JSON.stringify(metadata),
}),
],
});
const session: LiveConversationSession = {
sessionId,
podId: input.podId,
identity,
displayName,
room,
url: env.LIVEKIT_URL,
startedAt: new Date().toISOString(),
};
sessions.set(sessionKey(input.podId, identity), session);
return { ...session, token: await at.toJwt() };
}
export function activeLiveConversation(
podId: string,
identity: string,
): LiveConversationSession | null {
const session = sessions.get(sessionKey(podId, identity));
return session && !session.endedAt ? session : null;
}
export function listActiveLiveConversations(podId: string): LiveConversationSession[] {
return [...sessions.values()].filter((session) => session.podId === podId && !session.endedAt);
}
export async function stopLiveConversation(
podId: string,
sessionId: string,
): Promise<LiveConversationSession | null> {
const session = [...sessions.values()].find(
(candidate) => candidate.podId === podId && candidate.sessionId === sessionId,
);
if (!session) return null;
session.endedAt = new Date().toISOString();
await closeRoom(session.room);
return session;
}
async function publishPrivateConversationEvent(
roomName: string,
event: LiveConversationEvent,
): Promise<void> {
const room = new LiveKitRoom();
try {
const token = await tokenFor(roomName, `podman-live-router-${Date.now()}`, 'PodMan live router', {
mode: 'podman-live-router',
});
await room.connect(env.LIVEKIT_URL, token, { autoSubscribe: false, dynacast: false });
const data: DataMessage = { type: 'LIVE_CONVERSATION_EVENT', event };
await room.localParticipant?.publishData(encoder.encode(JSON.stringify(data)), {
reliable: true,
topic: DATA_TOPIC,
});
} finally {
await room.disconnect().catch(() => {});
}
}
export async function notifyCriticalLiveConversations(
collision: Collision,
intervention: Intervention,
voiceLine?: string,
): Promise<void> {
if (collision.severity !== 'critical') return;
const recipients = new Set(collision.engineers.map((name) => name.toLowerCase()));
const active = listActiveLiveConversations(collision.podId).filter((session) =>
recipients.has(session.identity.toLowerCase()),
);
if (active.length === 0) return;
await Promise.allSettled(
active.map(async (session) => {
const createdAt = new Date().toISOString();
session.lastEventAt = createdAt;
const summary =
voiceLine ||
`Critical collision in ${collision.file}. ${collision.engineers.join(
' and ',
)} should sync before pushing.`;
await publishPrivateConversationEvent(session.room, {
id: `live_evt_${Date.now()}_${session.sessionId.slice(0, 8)}`,
podId: collision.podId,
sessionId: session.sessionId,
kind: 'critical_collision',
severity: 'critical',
summary,
interrupt: true,
createdAt,
collisionId: collision.id,
interventionId: intervention.id,
});
await speakInRoom(session.room, summary, { priority: 'critical' });
}),
);
}
-21
View File
@@ -57,8 +57,6 @@ export interface GitState {
gitUpdatedAt: Date | null;
}
const GIT_STATE_TTL_MS = Number(process.env.GIT_STATE_TTL_MS ?? '120000');
/** Fetch latest git state per engineer for a pod from the engineer_states collection.
* Returns a map keyed by engineer name (matches --name arg used in podman-agent.mjs). */
export async function getGitStates(podId: string): Promise<Map<string, GitState>> {
@@ -73,17 +71,7 @@ export async function getGitStates(podId: string): Promise<Map<string, GitState>
}>('engineer_states');
const docs = await col.find({ podId }).toArray();
const map = new Map<string, GitState>();
const now = Date.now();
for (const doc of docs) {
const updatedAt = doc.gitUpdatedAt ? new Date(doc.gitUpdatedAt) : null;
if (
updatedAt &&
!Number.isNaN(updatedAt.getTime()) &&
GIT_STATE_TTL_MS > 0 &&
now - updatedAt.getTime() > GIT_STATE_TTL_MS
) {
continue;
}
map.set(doc.name, {
changedFiles: doc.changedFiles ?? [],
branch: doc.branch ?? null,
@@ -114,15 +102,6 @@ export async function initMemory(): Promise<void> {
['collisions.file', () => c.collisions.createIndex({ podId: 1, file: 1, detectedAt: -1 })],
['interventions.collisionId', () => c.interventions.createIndex({ collisionId: 1 })],
['outcomes.interventionId', () => c.outcomes.createIndex({ interventionId: 1 })],
['hermes_jobs.id', () => db.collection('hermes_jobs').createIndex({ id: 1 }, { unique: true })],
[
'hermes_jobs.session',
() => db.collection('hermes_jobs').createIndex({ sessionId: 1, status: 1, updatedAt: -1 }),
],
[
'hermes_job_events.job',
() => db.collection('hermes_job_events').createIndex({ jobId: 1, createdAt: 1 }),
],
];
for (const [name, make] of indexes) {
try {
+2 -7
View File
@@ -12,16 +12,11 @@ export function shouldIntervene(collision: Collision, prior: RecalledCollision |
if (collision.severity === 'info') return false;
const priorOutcome = prior?.priorOutcome;
// Suppress when the identical prior was dismissed (accepted === false). The
// former `&& !priorOutcome.wasRealCollision` term was dead code: outcomes are
// recorded with wasRealCollision hardcoded true, so the gate never fired and
// the 85 real dismissals in Atlas were ignored. Dismissals are the negative
// signal per continual-learning/policy.md:41 + spec.md:163. (RSI Step 1)
if (priorOutcome && !priorOutcome.accepted) return false;
if (priorOutcome && !priorOutcome.accepted && !priorOutcome.wasRealCollision) return false;
const cooldown = cooldownMs();
const last = lastNudgeByPod.get(collision.podId) ?? 0;
if (cooldown > 0 && Date.now() - last < cooldown) {
if (cooldown > 0 && Date.now() - last < cooldown && collision.severity !== 'critical') {
return false;
}
+4 -78
View File
@@ -5,18 +5,9 @@ import type {
InterventionOutcome,
InterventionStatus,
} from '@podman/shared';
import { collections, getGitStates } from './db.js';
import { collections } from './db.js';
import { enrichCollisionMemory } from './vectors.js';
function comparableFile(raw?: string): string {
return (raw ?? '')
.trim()
.replace(/^(\?\?|[MADRCU!]{1,2})\s+/, '')
.split(/[\\/]/)
.pop()
?.toLowerCase() ?? '';
}
/**
* Continual-learning memory: persist observations, collisions, interventions,
* and outcomes to MongoDB so later sessions get sharper. MongoDB is mandatory —
@@ -50,31 +41,6 @@ export async function recordIntervention(intervention: Intervention): Promise<vo
);
}
export async function hasRecentInterventionForCollision(
collision: Collision,
windowMs = Number(process.env.NUDGE_COOLDOWN_MS ?? '180000'),
): Promise<boolean> {
if (windowMs <= 0) return false;
const c = await collections();
const since = new Date(Date.now() - windowMs).toISOString();
const recent = await c.collisions
.find({ podId: collision.podId, detectedAt: { $gte: since } })
.sort({ detectedAt: -1 })
.limit(100)
.toArray();
const targetFile = comparableFile(collision.file);
for (const match of recent) {
if (match.id === collision.id || comparableFile(match.file) !== targetFile) continue;
const existing = await c.interventions.findOne({
collisionId: match.id,
createdAt: { $gte: since },
});
if (existing) return true;
}
return false;
}
export async function updateInterventionStatus(
interventionId: string,
status: InterventionStatus,
@@ -84,53 +50,13 @@ export async function updateInterventionStatus(
);
}
/**
* Step 3 — derive whether a flagged collision was REAL from git ground truth,
* instead of trusting the client (which historically hardcoded `true`). A
* collision counts as real only if BOTH named engineers currently have the
* collided file in their git `changedFiles`. Conservative: returns false when
* the collision is orphaned/missing or git state is stale/unavailable.
* Verifier supervision per docs/continual-learning/spec.md:98-108, policy.md:35-42.
*/
export async function deriveWasRealCollision(outcome: InterventionOutcome): Promise<boolean> {
try {
const c = await collections();
const collision = await c.collisions.findOne({ id: outcome.collisionId });
if (!collision) return false;
// Prefer the overlap evidence captured at detection time (fresh git state):
// immune to late clicks, stale sidecars, and the engineer_states TTL.
if (typeof collision.gitOverlap === 'boolean') return collision.gitOverlap;
// Fallback for collisions detected before gitOverlap was captured: re-derive
// from latest git state, matching engineers on case/whitespace-canonical names.
if (!Array.isArray(collision.engineers) || collision.engineers.length < 2) return false;
const target = comparableFile(collision.file);
if (!target) return false;
const byCanon = new Map<string, string[]>();
for (const [name, st] of await getGitStates(outcome.podId)) {
byCanon.set(name.trim().toLowerCase(), st.changedFiles);
}
return collision.engineers.every((e) =>
(byCanon.get(e.trim().toLowerCase()) ?? []).some((f) => comparableFile(f) === target),
);
} catch (err) {
console.error(`[memory] wasRealCollision verifier failed: ${(err as Error).message}`);
return false;
}
}
export async function recordOutcome(outcome: InterventionOutcome): Promise<void> {
// Backend is authoritative for wasRealCollision: derive it from git overlap
// rather than trusting the client-supplied value. (RSI Step 3)
const verified: InterventionOutcome = {
...outcome,
wasRealCollision: await deriveWasRealCollision(outcome),
};
await persist('outcome', async () => {
const c = await collections();
await c.outcomes.insertOne({ ...verified });
await c.outcomes.insertOne({ ...outcome });
await c.interventions.updateOne(
{ id: verified.interventionId },
{ $set: { status: verified.accepted ? 'accepted' : 'dismissed' } },
{ id: outcome.interventionId },
{ $set: { status: outcome.accepted ? 'accepted' : 'dismissed' } },
);
});
}
+5 -427
View File
@@ -1,18 +1,11 @@
import express from 'express';
import cors from 'cors';
import { createServer } from 'node:http';
import type { Socket } from 'node:net';
import { WebSocketServer } from 'ws';
import { AccessToken, RoomAgentDispatch, RoomConfiguration } from 'livekit-server-sdk';
import { AccessToken, RoomConfiguration } from 'livekit-server-sdk';
import { env } from './env.js';
import { createSyncPr } from './github/client.js';
import {
recordCollision,
recordIntervention,
recordOutcome,
hasRecentInterventionForCollision,
memoryStats,
} from './memory/store.js';
import { recordOutcome, memoryStats } from './memory/store.js';
import { closeMemory, initMemory } from './memory/db.js';
import {
listPods,
@@ -26,66 +19,13 @@ import {
} from './pods/store.js';
import { getPresence, closeRoom } from './livekit/rooms.js';
import { loadPodGraph, reachFrom } from './graph/store.js';
import { listPodActivity } from './activity/store.js';
import { getMemberWorkHistory } from './activity/member-history.js';
import { speakInRoom } from './voice/live.js';
import { getPodMusic } from './voice/music.js';
import { notifyHermesInterventionInRoom } from './action/hermes.js';
import {
activeLiveConversation,
startLiveConversation,
stopLiveConversation,
} from './live-conversation/sessions.js';
import {
getLiveConversationContext,
recordLiveConversationNote,
} from './live-conversation/context.js';
import {
abortHermesJob,
appendHermesJobEvent,
createHermesJob,
getActiveHermesJobForSession,
getHermesJob,
getLatestHermesJobForSession,
listHermesJobEvents,
} from './hermes/jobs.js';
import type {
Collision,
HermesJobEventType,
Intervention,
InterventionOutcome,
SuggestedActionKind,
} from '@podman/shared';
import type { InterventionOutcome } from '@podman/shared';
const app = express();
app.use(cors());
app.use(express.json());
app.get('/health', (_req, res) => res.json({ ok: true }));
function stringArray(value: unknown): string[] {
return Array.isArray(value) ? value.map((item) => String(item).trim()).filter(Boolean) : [];
}
function suggestedAction(value: unknown): SuggestedActionKind {
return value === 'open_sync_pr' || value === 'ping_teammate' || value === 'none'
? value
: 'ping_teammate';
}
function hermesJobEventType(value: unknown): HermesJobEventType | null {
return value === 'accepted' ||
value === 'heartbeat' ||
value === 'step_started' ||
value === 'step_output' ||
value === 'needs_confirmation' ||
value === 'step_completed' ||
value === 'aborted' ||
value === 'failed' ||
value === 'completed'
? value
: null;
}
// Mint a LiveKit token for an engineer joining a pod.
app.post('/api/token', async (req, res) => {
const { room, identity, name, githubLogin } = req.body ?? {};
@@ -97,22 +37,9 @@ app.post('/api/token', async (req, res) => {
metadata: JSON.stringify({ githubLogin: githubLogin ?? name }),
});
at.addGrant({ roomJoin: true, room, canPublish: true, canSubscribe: true, canPublishData: true });
const agents = env.LIVEKIT_AGENT_NAME
? [
new RoomAgentDispatch({
agentName: env.LIVEKIT_AGENT_NAME,
metadata: JSON.stringify({ podId: room }),
}),
]
: undefined;
// Auto-clean the room: close 60s after it empties, drop a participant 20s
// after they disconnect. Applied when LiveKit auto-creates the room.
at.roomConfig = new RoomConfiguration({
name: room,
emptyTimeout: 60,
departureTimeout: 20,
agents,
});
at.roomConfig = new RoomConfiguration({ name: room, emptyTimeout: 60, departureTimeout: 20 });
res.json({ token: await at.toJwt(), url: env.LIVEKIT_URL });
});
@@ -209,306 +136,12 @@ app.post('/api/pods/:id/members', async (req, res) => {
}
});
app.post('/api/pods/:id/voice-test', async (req, res) => {
const podId = req.params.id;
const message =
typeof req.body?.message === 'string' && req.body.message.trim()
? req.body.message.trim()
: 'PodMan voice test. Gemini TTS is playing through LiveKit.';
try {
await speakInRoom(podId, message);
res.json({ ok: true });
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.post('/api/pods/:id/live-conversation/start', async (req, res) => {
try {
const identity = typeof req.body?.identity === 'string' ? req.body.identity.trim() : '';
const displayName =
typeof req.body?.displayName === 'string' ? req.body.displayName.trim() : identity;
if (!identity) return res.status(400).json({ error: 'identity is required' });
const pod = await getPod(req.params.id);
if (!pod) return res.status(404).json({ error: 'pod not found' });
res.json(await startLiveConversation({ podId: req.params.id, identity, displayName }));
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.post('/api/pods/:id/live-conversation/:sessionId/stop', async (req, res) => {
try {
const session = await stopLiveConversation(req.params.id, req.params.sessionId);
if (!session) return res.status(404).json({ error: 'session not found' });
res.json({ ok: true, session });
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.get('/api/pods/:id/live-conversation/status', (req, res) => {
const identity = typeof req.query.identity === 'string' ? req.query.identity.trim() : '';
if (!identity) return res.status(400).json({ error: 'identity is required' });
res.json({ active: activeLiveConversation(req.params.id, identity) });
});
app.get('/api/pods/:id/live-conversation/:sessionId/hermes-job', async (req, res) => {
try {
const job = await getLatestHermesJobForSession(req.params.sessionId);
if (!job || job.podId !== req.params.id) return res.json({ job: null, events: [] });
res.json({ job, events: await listHermesJobEvents(job.id, 12) });
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.post('/api/pods/:id/live-conversation/:sessionId/hermes-job/abort', async (req, res) => {
try {
const job = await getActiveHermesJobForSession(req.params.sessionId);
if (!job || job.podId !== req.params.id)
return res.status(404).json({ error: 'active job not found' });
res.json({ job: await abortHermesJob(job.id) });
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
function requireInternalAgent(req: express.Request, res: express.Response): boolean {
const expected = env.INTERNAL_AGENT_TOKEN;
if (!expected) {
res.status(503).json({ error: 'INTERNAL_AGENT_TOKEN is not configured' });
return false;
}
const header = req.header('authorization') ?? '';
const actual = header.startsWith('Bearer ') ? header.slice('Bearer '.length) : '';
if (actual !== expected) {
res.status(401).json({ error: 'unauthorized' });
return false;
}
return true;
}
app.get('/api/internal/pods/:id/live-context', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
try {
const identity = typeof req.query.identity === 'string' ? req.query.identity.trim() : '';
if (!identity) return res.status(400).json({ error: 'identity is required' });
res.json(await getLiveConversationContext(req.params.id, identity));
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.post('/api/internal/pods/:id/live-conversation/:sessionId/note', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
try {
const note = typeof req.body?.note === 'string' ? req.body.note : '';
const identity = typeof req.body?.identity === 'string' ? req.body.identity : undefined;
const kind = typeof req.body?.kind === 'string' ? req.body.kind : undefined;
res.status(201).json(
await recordLiveConversationNote({
podId: req.params.id,
sessionId: req.params.sessionId,
identity,
kind,
note,
}),
);
} catch (e) {
res.status(400).json({ error: (e as Error).message });
}
});
app.post('/api/internal/hermes/jobs', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
try {
res.status(202).json(await createHermesJob(req.body ?? {}));
} catch (e) {
res.status(400).json({ error: (e as Error).message });
}
});
app.get('/api/internal/hermes/jobs/:jobId', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
const job = await getHermesJob(req.params.jobId);
if (!job) return res.status(404).json({ error: 'job not found' });
res.json(job);
});
app.post('/api/internal/hermes/jobs/:jobId/abort', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
const job = await abortHermesJob(req.params.jobId);
if (!job) return res.status(404).json({ error: 'job not found' });
res.json(job);
});
app.get('/api/internal/hermes/jobs/:jobId/events', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
const job = await getHermesJob(req.params.jobId);
if (!job) return res.status(404).json({ error: 'job not found' });
res.json(await listHermesJobEvents(req.params.jobId, 100));
});
app.post('/api/internal/hermes/jobs/:jobId/events', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
try {
const { type, message, data } = req.body ?? {};
const eventType = hermesJobEventType(type);
if (!eventType || typeof message !== 'string') {
return res.status(400).json({ error: 'type and message are required' });
}
res.status(201).json(await appendHermesJobEvent(req.params.jobId, eventType, message, data));
} catch (e) {
res.status(400).json({ error: (e as Error).message });
}
});
app.get('/api/internal/hermes/jobs/:jobId/events/stream', async (req, res) => {
if (!requireInternalAgent(req, res)) return;
const job = await getHermesJob(req.params.jobId);
if (!job) return res.status(404).json({ error: 'job not found' });
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders?.();
let closed = false;
let lastIds = new Set<string>();
const send = async () => {
if (closed) return;
try {
const events = await listHermesJobEvents(req.params.jobId, 100);
const fresh = events.filter((event) => !lastIds.has(event.id));
lastIds = new Set(events.map((event) => event.id));
for (const event of fresh) {
res.write(`event: job-event\n`);
res.write(`data: ${JSON.stringify(event)}\n\n`);
}
const current = await getHermesJob(req.params.jobId);
if (current && ['completed', 'failed', 'aborted'].includes(current.status)) {
res.write(`event: done\n`);
res.write(`data: ${JSON.stringify(current)}\n\n`);
closed = true;
res.end();
} else {
res.write(`: keepalive ${Date.now()}\n\n`);
}
} catch (e) {
res.write(`event: error\n`);
res.write(`data: ${JSON.stringify({ error: (e as Error).message })}\n\n`);
}
};
await send();
const interval = setInterval(() => void send(), 1500);
req.on('close', () => {
closed = true;
clearInterval(interval);
});
});
// Per-pod background music (Lyria), generated once and cached. Streams MP3 the
// frontend loops as a pod-wide LiveKit track (replaces the synthesized beat).
app.get('/api/pods/:id/music', async (req, res) => {
try {
const pod = await getPod(req.params.id);
if (!pod) return res.status(404).json({ error: 'pod not found' });
const mp3 = await getPodMusic(pod.id, pod.name);
res.set('Content-Type', 'audio/mpeg');
res.set('Cache-Control', 'public, max-age=86400');
res.send(mp3);
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.post('/api/pods/:id/hermes/notify', async (req, res) => {
const podId = req.params.id;
const pod = await getPod(podId);
if (!pod) return res.status(404).json({ error: 'pod not found' });
const body = req.body ?? {};
const message = typeof body.message === 'string' ? body.message.trim() : '';
if (!message) return res.status(400).json({ error: 'message is required' });
const now = new Date().toISOString();
const engineers = stringArray(body.engineers);
const recipients = engineers.length ? engineers : pod.members.slice(0, 2);
const file =
typeof body.file === 'string' && body.file.trim() ? body.file.trim() : 'Hermes signal';
const urgent = body.urgency === 'urgent' || body.severity === 'critical';
const collision: Collision = {
id:
typeof body.collisionId === 'string' && body.collisionId
? body.collisionId
: `col_${Date.now()}`,
podId,
file,
symbol: typeof body.symbol === 'string' && body.symbol ? body.symbol : undefined,
engineers: recipients,
severity: urgent ? 'critical' : 'warn',
githubState: { unpushed: body.unpushed !== false },
detectedAt: now,
};
const intervention: Intervention = {
id:
typeof body.interventionId === 'string' && body.interventionId
? body.interventionId
: `int_${Date.now()}`,
collisionId: collision.id,
podId,
kind: urgent ? 'voice' : 'card',
message,
suggestedAction: {
kind: suggestedAction(body.suggestedAction),
params: {
file,
engineers: recipients,
source: 'local-hermes',
},
},
status: 'pending',
createdAt: now,
};
const voiceLine =
urgent && body.speak !== false
? typeof body.voiceLine === 'string' && body.voiceLine.trim()
? body.voiceLine.trim()
: message
: undefined;
try {
if (body.force !== true && (await hasRecentInterventionForCollision(collision))) {
return res.status(202).json({ ok: true, collision, intervention, livekit: 'suppressed' });
}
await recordCollision(collision);
await recordIntervention(intervention);
if (body.dryRun === true) {
return res.status(202).json({ ok: true, collision, intervention, livekit: 'dry-run' });
}
await notifyHermesInterventionInRoom(podId, collision, intervention, voiceLine);
res.status(202).json({ ok: true, collision, intervention, livekit: 'notified' });
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.delete('/api/pods/:id/members/:name', async (req, res) => {
const pod = await removeMember(req.params.id, req.params.name);
if (!pod) return res.status(404).json({ error: 'pod not found' });
res.json(pod);
});
app.get('/api/pods/:id/members/:name/history', async (req, res) => {
try {
const hours = Number(req.query.hours ?? 24) || 24;
const limit = Number(req.query.limit ?? 80) || 80;
res.json(await getMemberWorkHistory(req.params.id, req.params.name, { hours, limit }));
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
// --- Continual-learning graph (team_model view) ---
app.get('/api/pods/:id/graph', async (req, res) => {
try {
@@ -526,58 +159,7 @@ app.get('/api/pods/:id/graph/reach/:node', async (req, res) => {
}
});
app.get('/api/pods/:id/activity', async (req, res) => {
try {
const limit = Math.min(Number(req.query.limit ?? 80) || 80, 200);
res.json(await listPodActivity(req.params.id, limit));
} catch (e) {
res.status(500).json({ error: (e as Error).message });
}
});
app.get('/api/pods/:id/activity/stream', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders?.();
let closed = false;
let lastPayload = '';
const send = async () => {
if (closed) return;
try {
const events = await listPodActivity(req.params.id, 80);
const payload = JSON.stringify(events);
if (payload !== lastPayload) {
lastPayload = payload;
res.write(`event: snapshot\n`);
res.write(`data: ${payload}\n\n`);
} else {
res.write(`: keepalive ${Date.now()}\n\n`);
}
} catch (e) {
res.write(`event: error\n`);
res.write(`data: ${JSON.stringify({ error: (e as Error).message })}\n\n`);
}
};
await send();
const interval = setInterval(() => void send(), 1500);
req.on('close', () => {
closed = true;
clearInterval(interval);
});
});
const http = createServer(app);
const sockets = new Set<Socket>();
http.on('connection', (socket) => {
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
});
// ws relay: the agent pushes collision/intervention JSON here; PWAs subscribed by pod receive it.
const wss = new WebSocketServer({ server: http, path: '/api/events' });
@@ -609,11 +191,7 @@ async function shutdown(signal: NodeJS.Signals): Promise<void> {
console.log(`[server] ${signal} received; shutting down`);
for (const client of clients) client.close();
wss.close();
for (const socket of sockets) socket.destroy();
await Promise.race([
new Promise<void>((resolve) => http.close(() => resolve())),
new Promise<void>((resolve) => setTimeout(resolve, 5000)),
]);
await new Promise<void>((resolve) => http.close(() => resolve()));
await closeMemory().catch((e) => console.warn(`[memory] close failed: ${(e as Error).message}`));
process.exit(0);
}
+28 -169
View File
@@ -3,46 +3,19 @@ import {
AudioFrame,
AudioSource,
LocalAudioTrack,
Room,
TrackPublishOptions,
TrackSource,
type LocalParticipant,
type Room,
} from '@livekit/rtc-node';
import { GoogleGenAI, Modality, type LiveServerMessage, type Session } from '@google/genai';
import { AccessToken } from 'livekit-server-sdk';
import { DATA_TOPIC, type DataMessage } from '@podman/shared';
import { env } from '../env.js';
const SAMPLE_RATE = 24_000;
const CHANNELS = 1;
const FRAME_SAMPLES = SAMPLE_RATE / 10;
const SUBSCRIBER_READY_MS = 1_500;
const AUDIO_PREROLL_MS = 800;
const AUDIO_TAIL_MS = 1_500;
const AUDIO_HOLD_MS = 5_000;
const VOICE_QUEUE_MS = 60_000;
const VOICE_TRACK_PREFIX = 'podman-hermes-voice';
const encoder = new TextEncoder();
const ai = new GoogleGenAI({ apiKey: env.GEMINI_API_KEY });
let voiceQueue: Promise<void> = Promise.resolve();
export interface SpeakOptions {
priority?: 'normal' | 'critical';
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function ttsPrompt(message: string): string {
return [
'Speak this PodMan coordination alert as a calm, natural engineering teammate.',
'Use warm human pacing, clear pronunciation, and a brief pause after the first sentence.',
'Do not add extra words, labels, markdown, or sound effects.',
'',
message,
].join('\n');
}
async function publishVoiceCue(room: Room, message: string): Promise<void> {
const cue: DataMessage = { type: 'VOICE_CUE', text: message };
@@ -52,24 +25,12 @@ async function publishVoiceCue(room: Room, message: string): Promise<void> {
});
}
async function unpublishVoiceTracks(localParticipant: LocalParticipant): Promise<void> {
const publications = Array.from(localParticipant.trackPublications.values()).filter(
(publication) => publication.name?.startsWith(VOICE_TRACK_PREFIX) && publication.sid,
);
for (const publication of publications) {
await localParticipant.unpublishTrack(publication.sid!, true).catch((err) => {
console.warn(`[voice] stale track cleanup failed: ${(err as Error).message}`);
});
}
}
function audioFrameFromBase64(data: string, mimeType?: string): AudioFrame | null {
if (mimeType && !mimeType.includes('audio')) return null;
const buf = Buffer.from(data, 'base64');
if (buf.byteLength < 2) return null;
const bytes = buf.byteLength % 2 === 0 ? buf : buf.subarray(0, buf.byteLength - 1);
const samples = new Int16Array(bytes.byteLength / 2);
for (let i = 0; i < samples.length; i += 1) samples[i] = bytes.readInt16LE(i * 2);
const samples = new Int16Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 2);
return new AudioFrame(samples, SAMPLE_RATE, CHANNELS, samples.length / CHANNELS);
}
@@ -92,7 +53,7 @@ function framesFromPcmBase64(data: string, mimeType?: string): AudioFrame[] {
const samples = frame.data;
const frames: AudioFrame[] = [];
for (let offset = 0; offset < samples.length; offset += FRAME_SAMPLES) {
const chunk = samples.slice(offset, Math.min(offset + FRAME_SAMPLES, samples.length));
const chunk = samples.subarray(offset, Math.min(offset + FRAME_SAMPLES, samples.length));
frames.push(new AudioFrame(chunk, SAMPLE_RATE, CHANNELS, chunk.length / CHANNELS));
}
return frames;
@@ -101,11 +62,10 @@ function framesFromPcmBase64(data: string, mimeType?: string): AudioFrame[] {
async function generateTtsFrames(message: string): Promise<AudioFrame[]> {
const res = await ai.models.generateContent({
model: env.GEMINI_LIVE_MODEL,
contents: [{ parts: [{ text: ttsPrompt(message) }] }],
contents: [{ parts: [{ text: message }] }],
config: {
responseModalities: [Modality.AUDIO],
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: env.GEMINI_TTS_VOICE } } },
temperature: 0.8,
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } } },
},
});
const parts = res.candidates?.[0]?.content?.parts ?? [];
@@ -114,60 +74,29 @@ async function generateTtsFrames(message: string): Promise<AudioFrame[]> {
);
}
function fallbackVoiceLine(message: string): string {
const clean = message.replace(/^heads up[.!]?\s*/i, '').trim();
if (clean && clean !== message) return clean;
return 'PodMan noticed a critical conflict. Please sync with the team before pushing.';
}
async function speakWithTts(source: AudioSource, message: string): Promise<number> {
let frames: AudioFrame[];
try {
frames = await generateTtsFrames(message);
} catch (err) {
const fallback = fallbackVoiceLine(message);
console.warn(`[voice] Gemini TTS retrying with fallback line: ${(err as Error).message}`);
frames = await generateTtsFrames(fallback);
}
if (frames.length === 0) throw new Error('Gemini TTS returned no audio frames');
const durationMs = frames.reduce(
(sum, frame) => sum + (frame.samplesPerChannel / frame.sampleRate) * 1000,
0,
);
console.log(
`[voice] publishing Gemini TTS audio frames=${frames.length} durationMs=${Math.round(durationMs)}`,
);
for (const frame of frames) {
async function speakWithTts(source: AudioSource, message: string): Promise<void> {
for (const frame of await generateTtsFrames(message)) {
await source.captureFrame(frame);
}
return durationMs;
}
async function speakWithLive(source: AudioSource, message: string): Promise<number> {
let durationMs = 0;
async function speakWithLive(source: AudioSource, message: string): Promise<void> {
let done: () => void = () => {};
const donePromise = new Promise<void>((resolve) => {
done = resolve;
});
const session: Session = await ai.live.connect({
model: env.GEMINI_LIVE_MODEL,
config: {
responseModalities: [Modality.AUDIO],
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: env.GEMINI_TTS_VOICE } } },
temperature: 0.8,
},
config: { responseModalities: [Modality.AUDIO] },
callbacks: {
onmessage: (event) => {
void (async () => {
for (const frame of audioFrames(event)) {
durationMs += (frame.samplesPerChannel / frame.sampleRate) * 1000;
await source.captureFrame(frame);
}
for (const frame of audioFrames(event)) await source.captureFrame(frame);
if (event.serverContent?.turnComplete || event.serverContent?.generationComplete) done();
})();
},
onerror: (event) => {
console.warn(`[voice] Gemini voice error: ${event.message}`);
console.warn(`[voice] Gemini Live error: ${event.message}`);
done();
},
onclose: done,
@@ -175,106 +104,36 @@ async function speakWithLive(source: AudioSource, message: string): Promise<numb
});
session.sendClientContent({
turns: [{ role: 'user', parts: [{ text: ttsPrompt(message) }] }],
turns: [{ role: 'user', parts: [{ text: message }] }],
turnComplete: true,
});
await Promise.race([donePromise, new Promise((resolve) => setTimeout(resolve, 15_000))]);
session.close();
return durationMs;
}
async function waitForVoicePlayout(source: AudioSource): Promise<void> {
if (source.queuedDuration <= 0) return;
const queuedMs = Math.round(source.queuedDuration);
console.log(`[voice] waiting for queued audio playout queuedMs=${queuedMs}`);
await Promise.race([
source.waitForPlayout(),
new Promise((resolve) => setTimeout(resolve, VOICE_QUEUE_MS + 2_000)),
]);
console.log('[voice] queued audio playout complete');
}
async function captureSilence(source: AudioSource, durationMs: number): Promise<void> {
const totalSamples = Math.max(1, Math.round((SAMPLE_RATE * durationMs) / 1000));
for (let offset = 0; offset < totalSamples; offset += FRAME_SAMPLES) {
const samples = Math.min(FRAME_SAMPLES, totalSamples - offset);
await source.captureFrame(new AudioFrame(new Int16Array(samples), SAMPLE_RATE, CHANNELS, samples));
}
}
async function speakAudio(room: Room, message: string): Promise<void> {
const localParticipant = room.localParticipant;
if (!localParticipant) return;
await unpublishVoiceTracks(localParticipant);
const source = new AudioSource(SAMPLE_RATE, CHANNELS, VOICE_QUEUE_MS);
const track = LocalAudioTrack.createAudioTrack(`${VOICE_TRACK_PREFIX}-${Date.now()}`, source);
const options = new TrackPublishOptions();
options.source = TrackSource.SOURCE_MICROPHONE;
let publicationSid: string | undefined;
try {
const publication = await localParticipant.publishTrack(track, options);
publicationSid = publication.sid;
await delay(SUBSCRIBER_READY_MS);
await captureSilence(source, AUDIO_PREROLL_MS);
const audioDurationMs = env.GEMINI_LIVE_MODEL.includes('tts')
? await speakWithTts(source, message)
: await speakWithLive(source, message);
await captureSilence(source, AUDIO_TAIL_MS);
await waitForVoicePlayout(source);
const manualHoldMs = Math.ceil(audioDurationMs + AUDIO_TAIL_MS + AUDIO_HOLD_MS);
console.log(`[voice] holding track for subscriber playout holdMs=${manualHoldMs}`);
await delay(manualHoldMs);
} catch (err) {
console.warn(`[voice] Gemini voice publish failed: ${(err as Error).message}`);
} finally {
if (publicationSid) {
await localParticipant.unpublishTrack(publicationSid, true).catch((err) => {
console.warn(`[voice] track unpublish failed: ${(err as Error).message}`);
});
}
await source.close().catch(() => {});
}
}
/**
* Speak a message into the LiveKit room using Gemini audio. A data-channel
* Speak a message into the LiveKit room using Gemini Live audio. A data-channel
* VOICE_CUE is sent first so clients still get the cue if audio generation or
* publishing fails.
*/
export async function speak(room: Room, message: string, options: SpeakOptions = {}): Promise<void> {
export async function speak(room: Room, message: string): Promise<void> {
await publishVoiceCue(room, message);
if (options.priority === 'critical') {
await speakAudio(room, message);
return;
}
voiceQueue = voiceQueue.catch(() => {}).then(() => speakAudio(room, message));
await voiceQueue;
}
if (!room.localParticipant) return;
const source = new AudioSource(SAMPLE_RATE, CHANNELS);
const track = LocalAudioTrack.createAudioTrack('podman-hermes-voice', source);
const options = new TrackPublishOptions();
options.source = TrackSource.SOURCE_MICROPHONE;
export async function speakInRoom(
roomName: string,
message: string,
options: SpeakOptions = {},
): Promise<void> {
const room = new Room();
try {
const at = new AccessToken(env.LIVEKIT_API_KEY, env.LIVEKIT_API_SECRET, {
identity: `podman-voice-${Date.now()}`,
name: 'PodMan voice',
ttl: '5m',
});
at.addGrant({
roomJoin: true,
room: roomName,
canPublish: true,
canSubscribe: true,
canPublishData: true,
});
await room.connect(env.LIVEKIT_URL, await at.toJwt());
await speak(room, message, options);
} finally {
await room.disconnect().catch(() => {});
const publication = await room.localParticipant.publishTrack(track, options);
if (env.GEMINI_LIVE_MODEL.includes('tts')) await speakWithTts(source, message);
else await speakWithLive(source, message);
if (publication.sid) await room.localParticipant.unpublishTrack(publication.sid, true);
await source.close();
} catch (err) {
console.warn(`[voice] Gemini Live publish failed: ${(err as Error).message}`);
await source.close().catch(() => {});
}
}
-94
View File
@@ -1,94 +0,0 @@
import { Buffer } from 'node:buffer';
import { getDb } from '../memory/db.js';
import { env } from '../env.js';
// Lyria 3 is reached via the Gemini "interactions" endpoint (not :predict, which
// is the Vertex path). The clip model returns a ~30s base64 MP3.
const MUSIC_MODEL = process.env.GEMINI_MUSIC_MODEL ?? 'lyria-3-clip-preview';
const INTERACTIONS_URL = 'https://generativelanguage.googleapis.com/v1beta/interactions';
interface PodMusicDoc {
podId: string;
name: string; // pod name the vocal was generated for
model: string;
mp3Base64: string;
createdAt: string;
}
interface InteractionContent {
type?: string;
data?: string;
text?: string;
}
interface InteractionResponse {
steps?: Array<{ content?: InteractionContent[] }>;
output_audio?: { data?: string };
}
/**
* Background "hold music" prompt: opens with the pod name sung once, then a calm
* instrumental bed that loops. Keep it unobtrusive — this is fill, not a song.
*/
function musicPrompt(podName: string): string {
return [
'Calm soothing instrumental background hold music for a tech app, like gentle on-hold lobby music.',
`It opens in the first three seconds with a soft gentle voice clearly saying the words "${podName}" one time,`,
'and after that opening it is purely instrumental with warm electric piano, gentle synth pads and a soft relaxed beat.',
'Unobtrusive, pleasant and steady with no climax, designed to loop seamlessly as quiet background fill.',
'No other lyrics or vocals after the opening.',
].join(' ');
}
function extractAudioBase64(data: InteractionResponse): string | null {
for (const step of data.steps ?? []) {
for (const c of step.content ?? []) {
if (c.type === 'audio' && c.data) return c.data;
}
}
return data.output_audio?.data ?? null;
}
async function generate(podName: string): Promise<Buffer> {
const res = await fetch(INTERACTIONS_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-goog-api-key': env.GEMINI_API_KEY },
body: JSON.stringify({ model: MUSIC_MODEL, input: musicPrompt(podName) }),
});
if (!res.ok) {
throw new Error(`Lyria ${res.status}: ${(await res.text()).slice(0, 300)}`);
}
const data = (await res.json()) as InteractionResponse;
const b64 = extractAudioBase64(data);
if (!b64) throw new Error('Lyria returned no audio');
return Buffer.from(b64, 'base64');
}
/**
* The pod's background-music MP3, generated by Lyria on first request and cached
* in the `pod_music` collection. Regenerated if the pod name changes so the sung
* name stays correct. Lyria generation is slow (~20s); the cache makes every
* call after the first instant.
*/
export async function getPodMusic(podId: string, podName: string): Promise<Buffer> {
const db = await getDb();
const col = db.collection<PodMusicDoc>('pod_music');
const cached = await col.findOne({ podId });
if (cached && cached.name === podName && cached.model === MUSIC_MODEL && cached.mp3Base64) {
return Buffer.from(cached.mp3Base64, 'base64');
}
const mp3 = await generate(podName);
await col.updateOne(
{ podId },
{
$set: {
podId,
name: podName,
model: MUSIC_MODEL,
mp3Base64: mp3.toString('base64'),
createdAt: new Date().toISOString(),
},
},
{ upsert: true },
);
return mp3;
}
+293
View File
@@ -0,0 +1,293 @@
# Team Memory Graph — Redesign Brief (fresh-session handoff)
> **You are a fresh Claude Code session with no prior context. Read this whole file first.**
> Your job: rebuild the **live "Team memory" graph view** so the **light/real-data** version is as
> polished and functional as the original **dark Bauhaus mock**, and make the graph **dynamic**
> (force-directed + animated), not the current dead static-column layout.
> **Do not rewrite the backend materializer — it is good.** The problem is 100% the frontend rendering.
---
## 0. Mission (one paragraph)
PodMan's "Team memory" is a per-pod graph of who owns/edits which files, where work collides, and what
PodMan learned from accepted interventions — the continual-learning loop made legible in 10 seconds.
A **dark Bauhaus mock** of this view looks great (clean 3-panel layout, a learning-loop rail, an activity
stream, a readable graph). The **shipped light version on real data looks terrible** (a hairball of red
edges, overlapping labels, a static lifeless layout, and it's missing the learning-loop rail + activity
stream entirely). Make the light version match the mock's structure/polish/functionality, in the app's
**light shadcn theme**, and make the **graph dynamic** (organic force-directed layout, draggable,
animated transitions). Keep using **real data** from the existing materializer.
---
## 1. The two reference points
### A. The dark Bauhaus mock = what "good" looks like (target structure)
A single dark card titled **"PODMAN — CONTINUAL-LEARNING OBSERVATORY"** with a `LIVE · POD demo-pod`
status. Layout:
- **Left rail — WORKFLOW METRICS**: a vertical stack of bordered cards, each a big numeral + an
UPPERCASE tracked label + a one-line detail, with a colored left-accent bar:
`03 PODS WATCHED`, `05 ENGINEERS LIVE`, `02 COLLISIONS OPEN (▲ auth.ts critical)`,
`01 INTERVENTION SENT`, `86% ACCEPT RATE (▲ +14% this session)`, `124 MEMORY VECTORS`.
- **Center — the GRAPH**: sparse, geometric, readable. Node shapes encode kind
(engineer = filled square, file = outlined square, feature = circle, collision = triangle,
intervention = diamond). One **risk path is lit** (Karti+Yahya → auth.ts → collision → sync PR →
`learned_from`), everything else dimmed. Edges color-coded (`collides` red, `warns` amber/orange,
`learned_from` dashed violet, `owns` blue, `editing` paper, `touches` grey).
- **Right rail — LEARNING LOOP**: a vertical 5-step stepper with the active step highlighted/pulsing:
`01 OBSERVE (vision → 5 contexts/s)``02 STORE (124 vectors · Atlas)`
`03 PREDICT (2 collisions flagged)` [active] → `04 OUTCOME (1 accepted · 0 dismissed)`
`05 ADAPT (Karti→auth ownership +)`. Arrows between steps.
- **Bottom-left — ACTIVITY STREAM**: a time-stamped feed with colored kind-tags:
`15:48 EDITING Yahya opened auth.ts — unpushed changes detected`,
`15:48 COLLISION Critical overlap on auth.ts · Karti + Yahya`,
`15:49 WARNS PodMan spoke: "open a sync PR?" → card sent`,
`15:49 OUTCOME Sync PR accepted by the pod`,
`15:49 LEARNED_FROM Memory updated: Karti owns auth (confidence ↑)`.
- **Bottom-right — SELECTED NODE**: click a node → kind / name / relationships count / severity / a
one-line "why" (`Two engineers editing the same file before push — the signal git can't see.`).
- **Legend**: engineer / file / feature / collision / intervention · collides / warns / learned_from.
It reads in 10 seconds because it is **sparse, color-coded, and tells the loop story** with the rails +
stream, not just a node blob. (The full mock HTML/CSS is reproduced in **Appendix A** — port its
structure to light shadcn.)
### B. The shipped light version = what's wrong (the thing to fix)
Same data, but: a **hairball** — every engineer fans red `collides` edges to ~6 collision triangles
(all labeled `sync PR`); **file labels overlap** in a dim middle column; the graph uses a **static
deterministic column layout** (`x` by kind, `y` evenly spread) so it looks dead/lifeless; and it is
**missing the LEARNING LOOP rail and the ACTIVITY STREAM** entirely — it's just a metrics rail + the bare
graph + a selected-node panel. (Two already-fixed-on-branch items: garbage collision labels
`infra/README.md### Running the git watcher` and full-path bleed — see PR #7 / commit `a21a289`,
`shortLabel` in `live.ts`. Build on top of that, don't redo it.)
---
## 2. The gap to close (light vs mock)
| Mock has | Light version | Action |
| ---------------------------------------- | ------------------------------- | ---------------------------------- |
| Workflow metrics rail | ✅ has it (3 metrics) | keep; restyle to match |
| **Learning loop rail (observe→…→adapt)** | ❌ missing | **build it** (needs live counts) |
| **Activity stream feed** | ❌ missing | **build it** (needs an event feed) |
| Selected-node panel | ✅ has it | keep |
| **Dynamic / animated graph** | ❌ static columns | **replace the layout** |
| Sparse, lit "risk path" | partial (Risk-path mode exists) | improve emphasis + spacing |
| Legend | ✅ | keep |
---
## 3. Current architecture (build on this — do NOT rewrite the materializer)
**Backend (good, keep):**
- `backend/src/graph/live.ts``materializePodGraph(podId)`: builds the graph from the real Mongo
collections (`pods`, `engineer_states`, `observations`, `collisions`, `interventions`, `outcomes`).
It already de-noises hard: collapses collisions by `memorySignature`, caps to 8, collapses
interventions to one per collision, filters junk files (`isFilePath`), prunes test-artifact engineers
(`ENGINEER_NOISE`), caps files to 9, short labels (`shortLabel`). Output is ~20 clean nodes for
`demo-pod`. **This is solid — extend it, don't replace it.**
- `backend/src/graph/store.ts``loadPodGraph(podId)`: live materializer → seeded `team_model.graph`
→ demo fallback (`createDemoPodGraph`). Plus `reachFrom` (`$graphLookup`).
- Route: `GET /api/pods/:id/graph` returns `PodGraph` (also `/graph/reach/:node`).
- `backend/src/memory/db.ts``collections()`, `getGitStates(podId)`, `getDb()`.
- WS bus: `backend/src/server.ts` hosts `ws /api/events` (the agent + `/api/outcome` broadcast here).
**Frontend (this is where the work is):**
- `frontend/src/components/GraphView.tsx`**the thing you redesign** (~90% of the work). Currently:
fetches `/api/pods/:id/graph`, renders a bespoke SVG with the static column layout, Risk/Learning/Whole
toggles, a metrics rail, a selected-node panel, a legend. Composed from shadcn primitives (`Button`,
`Badge`) + Tailwind utilities. Theme-aware via shadcn tokens.
- `frontend/src/lib/graph.ts``fetchPodGraph(podId)`.
- Opened from each `PodCard`'s `⋯` menu → "Team memory" (`onOpenGraph(pod.id)` in
`frontend/src/App.tsx`). It is a conditional render (no route).
**Data contract** (`shared/src/graph.ts`):
```ts
PodGraph = { podId, generatedAt, nodes: PodGraphNode[], edges: PodGraphEdge[], metrics: PodGraphMetric[] }
PodGraphNode = { id, kind, label, summary, weight 0..1, status: 'stable'|'active'|'risk'|'learned', x, y }
// kind: 'engineer'|'feature'|'file'|'collision'|'intervention'
PodGraphEdge = { id, source, target, kind, label, strength 0..1 }
// kind: 'owns'|'editing'|'touches'|'collides'|'warns'|'learned_from'
PodGraphMetric = { label, value, detail }
```
**Theme / components (HARD RULE):** the app is **light shadcn**, built from the **ruixen registry**
add primitives with `npx shadcn@latest add "https://ruixen.com/r/[component]"` and compose from
`@/components/ui/*` (`Button`, `Badge`, `Card`, `Tabs`, `ToggleGroup`, etc.) using the design tokens
(`var(--card)` / `--foreground` / `--muted-foreground` / `--border`, `--chart-1..5`). Only the SVG/canvas
graph is bespoke. Match `frontend/src/App.tsx`'s `StatPill`/`BriefLine` utility patterns.
---
## 4. Target design (build this)
A light shadcn page with the **mock's structure**:
```
┌───────────────────────────────────────────────────────────────────────┐
│ Header: "Team memory · What PodMan learned · <pod>" [← Pods] │
├───────────────────────────────────────────────────────────────────────┤
│ Toggles: Risk path | Learning edges | Whole graph (keep) │
├──────────────┬──────────────────────────────────┬─────────────────────┤
│ WORKFLOW │ │ LEARNING LOOP │
│ METRICS │ DYNAMIC GRAPH CANVAS │ observe→store→ │
│ (cards) │ (force-directed + animated) │ predict→outcome→ │
│ │ │ adapt (active pulses)│
├──────────────┴──────────────────────────────────┴─────────────────────┤
│ ACTIVITY STREAM (time-tagged feed) │ SELECTED NODE (detail) │
└───────────────────────────────────────────────────────────────────────┘
```
- **Light shadcn** throughout (theme-aware; follows dark mode if the app ever toggles). Keep the
geometric **node-shape + color encoding** (it's the legible part) but on light surfaces with the
app's hues (engineer blue `#2563eb`, file slate outline `#475569`, feature amber `#d97706`,
collision red `#dc2626`, intervention violet `#7c3aed`; edges: collides red, warns amber,
learned_from dashed violet, owns blue, editing slate, touches faint slate).
- **Default to "Risk path"**: light the collision→intervention→`learned_from` chain; dim the rest.
---
## 5. Make the graph DYNAMIC (the headline new requirement)
The static column layout (`live.ts` `layout()` sets `x`/`y` by kind) looks dead. Replace the frontend
rendering with a **dynamic** graph. Pick one (recommended order):
1. **`d3-force` force-directed (recommended).** Add `d3-force` (small). Run a force simulation on the
`PodGraph` nodes/edges: link force (by `edge.strength`), charge/repulsion, center, collision radius
(by `node.weight`). Render nodes/edges as SVG, update positions per tick. Make nodes **draggable**
(pin on drag). Animate new nodes/edges fading in on data refresh, and the `learned_from` dashed
stroke animating. Ignore the server's `x`/`y` (or use them as initial positions). Keep node shapes.
2. `react-force-graph` / `force-graph` (canvas) — heavier, faster for big graphs; overkill at ~20 nodes
but fine.
3. A custom animated **layered** layout (engineers → files → collisions → interventions columns, but
with curved edges, eased position transitions on refresh, and gentle idle motion). Lighter-weight
than d3-force; still feels alive if you animate transitions.
**Realtime/dynamic data:** poll `GET /api/pods/:id/graph` every ~5s and **animate the diff** between
snapshots (don't hard-replace). Optionally subscribe to `ws /api/events` for instant nudges. New
collisions/interventions should visibly animate in; the `learned_from` edge + gold node should pop on a
new accepted outcome.
**De-hairball:** even force-directed, ~6 collisions × 3 engineers = many `collides` edges. Mitigate:
bundle/curve edges, lower non-risk edge opacity, default to Risk-path emphasis, size nodes by `weight`,
and keep label collision-avoidance (offset labels, hide on overlap, show on hover/select).
---
## 6. Data for the new panels (extend the materializer or add endpoints)
The mock's **Learning Loop** and **Activity Stream** need data the current `PodGraph` doesn't carry. Two
options: (a) extend `materializePodGraph` to also return `loop` + `activity`, or (b) add small endpoints.
Recommended: extend the return type (additive to `shared/src/graph.ts`).
- **Learning loop counts** (`observe→store→predict→outcome→adapt`):
- observe = recent `observations` count (e.g. last 60s) / rate
- store = `memory_vectors` or `collisions.embedding` count (Voyage vectors)
- predict = open `collisions` (distinct signatures) count
- outcome = `outcomes` accepted vs dismissed counts
- adapt = `team_model.ownership` entries / learned owners count
- mark the "active" stage = the most recent activity.
- **Activity stream**: merge + time-sort recent events from `collisions.detectedAt`,
`interventions.createdAt`, `outcomes.recordedAt`, `engineer_states.gitUpdatedAt` → a typed feed
`{ at, kind: 'editing'|'collision'|'warns'|'outcome'|'learned_from', text }`. Cap to ~8 most recent.
(`backend/src/memory/db.ts` `collections()` gives you `observations/collisions/interventions/outcomes`;
`getGitStates` gives engineer_states; `team_model` is `db.collection('team_model')`.)
---
## 7. Files to touch
- **`frontend/src/components/GraphView.tsx`** — the redesign (force-directed graph + 3-panel layout +
learning-loop rail + activity stream). May split into `GraphCanvas.tsx`, `LearningLoop.tsx`,
`ActivityStream.tsx`, `MetricsRail.tsx`.
- **`frontend/src/lib/graph.ts`** — add fetches for loop/activity if you add endpoints.
- **`backend/src/graph/live.ts`** (extend, don't rewrite) — emit `loop` + `activity` in the result;
keep all the de-noise.
- **`shared/src/graph.ts`** — add `loop`/`activity` types to `PodGraph` (additive).
- **deps**`d3-force` (+ `@types/d3-force`) via pnpm in `frontend`.
- Possibly add a ruixen primitive (e.g. `timeline`, `stepper`) via the shadcn CLI if one fits.
---
## 8. Constraints & gotchas (READ — these will bite you)
- **The materializer is good — do not rewrite it.** It already de-noises (caps, collapse-by-signature,
engineer/file filters, short labels). The bad UI is the **frontend layout/render**, not the data.
- **PWA service worker caches aggressively** — after any deploy, hard-refresh (Cmd-Shift-R) or test in a
private window, or you'll think nothing changed.
- **Deploy = merge to `main`** (DO `deploy_on_push: true`). `main` is shared by ~4 engineers and moves
fast. Work on a branch, open a PR, merge. Don't push to `main` directly.
- **`learned_from` "money" edge won't render on `demo-pod`** right now — its one accepted outcome is
orphaned (points at a collision deleted by test churn). It needs **one intact accept flow** (real
collision → intervention → someone clicks Accept) to draw. To demo, seed a clean chain or clear test
docs (writes to shared Atlas — confirm scope first).
- **Atlas creds rotate frequently**`podman/.env`'s `MONGODB_URI` may be stale; the **deployed env**
has the working one. If local Mongo auth fails, that's why.
- **Build verification**: some sandboxes can't run `pnpm`/`vite`/shadcn deps (`lucide-react`,
`@radix-ui`). Verify the frontend with `pnpm build` in a real env or CI before merging. Backend
typecheck excludes uninstalled `ws`/`sharp`/`@livekit/rtc-node` noise.
- **Compose from ruixen/shadcn primitives** (`npx shadcn add ruixen.com/r/[component]`,
`@/components/ui/*`); only the SVG/canvas graph is bespoke. Match `StatPill`/`BriefLine` in `App.tsx`.
- **Light theme + tokens** — never hardcode dark colors for chrome; use `var(--card)/--foreground/…`.
Keep fixed semantic hues only for the node/edge kind encoding.
---
## 9. Acceptance criteria
- Light Team-memory page matches the mock's structure: **metrics rail + dynamic graph + learning-loop
rail + activity stream + selected-node panel + legend**.
- **Graph is dynamic**: force-directed (or animated layered), **draggable**, **animates** new
nodes/edges and refresh transitions; **no overlapping labels, no hairball**.
- Reads in 10s; the **risk/money path is obvious** by default.
- **Light shadcn** theme, theme-aware; composed from ruixen primitives.
- Uses **real data** from `materializePodGraph`; graceful demo fallback when empty.
- `pnpm build` + typechecks pass; deploys; verified after a hard-refresh.
---
## 10. Suggested first moves for the new session
1. Read this file + `docs/graph.md` + `docs/live-ui-spec.md` (R1/R2 sections) + `CLAUDE.md`.
2. `git fetch`; branch off `main` (or `feat/live-graph-glue`, which has the latest graph work).
3. Hit the live data once: `curl https://165-22-129-249.sslip.io/api/pods/demo-pod/graph` — that's the
real `PodGraph` you'll render.
4. Build a `d3-force` `GraphCanvas` first (replace the static layout), get it draggable + animated.
5. Add `LearningLoop` + `ActivityStream` (extend the materializer to feed them).
6. Polish to the mock; `pnpm build`; PR → main → redeploy → hard-refresh.
---
## Appendix A — the dark mock (reference structure to port to light)
The mock is a single dark card. Structure + the exact content to reproduce (in light shadcn):
- Header: brand glyph (blue square + amber circle + red triangle + outlined square) + `PODMAN /
CONTINUAL-LEARNING OBSERVATORY` + `● LIVE · POD demo-pod`.
- Grid `180px 1fr 196px`: **metrics rail** | **graph** | **learning-loop rail**.
- Metrics cards: big `Archivo`-weight numeral, uppercase tracked label, muted detail, colored
left-accent (blue/red/yellow/violet/green).
- Graph: SVG, geometric node shapes by kind, color-coded edges, one lit risk path, dim others; click a
node → highlight its incident edges + neighbors, fill the selected-node panel.
- Learning-loop rail: 5 bordered steps with number + UPPERCASE title + muted sub; the active step has a
pulsing left bar; `↓` arrows between.
- Legend row (node kinds + edge kinds).
- Activity stream (time + colored tag + text) and selected-node panel below.
Palette used (port to shadcn tokens for chrome; keep these as node/edge hues):
`bg #0c0c0e`, `panel #141417`, `line #2a2a31`, `paper/text #ECE7DA`, `muted #8d897e`,
`blue #3B5BFF`, `red #E2403A`, `amber #F6C445`, `violet #8b6cff`, `green #46c07a`.
For light: chrome → `var(--card)/--foreground/--border/--muted-foreground`; node/edge hues →
blue `#2563eb`, slate `#475569`, amber `#d97706`, red `#dc2626`, violet `#7c3aed` (light-readable).
> The dark mock was a `show_widget` demo (not a saved file). If you want the literal HTML/CSS, ask the
> user to paste it, or reconstruct from this appendix — the **structure + content above is the spec**.
> Goal: same structure, same legibility, **light theme + dynamic graph**.
+483
View File
@@ -0,0 +1,483 @@
# Team Memory Graph - Codex Redesign Brief
> **Read this whole file before touching code.**
> This is a fresh-session handoff for rebuilding PodMan's live **Team memory** graph UI.
> The goal is not to tweak labels or add another filter. The goal is to make the
> real-data light UI as polished, legible, and functional as the original dark
> Bauhaus mock, while keeping the graph backed by live MongoDB data.
## 0. Mission
PodMan's Team memory view should make the recursive self-improvement loop visible:
who is working, which files overlap, where collisions happen, which intervention was
sent, and what PodMan learned from accepted outcomes.
The current light real-data implementation proves the backend can materialize a graph,
but the UI does not yet tell the story. It still reads as a static node-link diagram:
edges dominate, labels collide, the layout feels fixed, and the important loop
`observe -> store -> predict -> outcome -> adapt` is not visible.
Rebuild the Team memory experience so it has the narrative clarity of the dark
Bauhaus mock, in the app's light shadcn/ruixen visual system, with a dynamic graph
that animates and responds to live data changes.
## 1. Current State
Branch context:
- Work is on `feat/live-graph-glue`.
- The live graph backend exists and should be reused.
- A PR for the live graph glue already exists, and later commits have continued
refining readability.
- The current file requested by the user is this document:
`codex_team_memory_redisgn.md`.
Important existing files:
- `backend/src/graph/live.ts`
Builds `PodGraph` from real Mongo collections:
`pods`, `engineer_states`, `observations`, `collisions`, `interventions`,
and `outcomes`.
- `backend/src/graph/store.ts`
Loads live graph first, then seeded `team_model.graph`, then demo fallback.
- `shared/src/graph.ts`
Defines the graph contract.
- `frontend/src/components/GraphView.tsx`
Current frontend graph rendering. This is the main file to redesign.
- `frontend/src/lib/graph.ts`
Fetches the graph.
- `frontend/src/App.tsx` and `frontend/src/components/PodCard.tsx`
Open Team memory per pod.
Do **not** start by rewriting the backend materializer. It already does the most
important real-data work: filtering noisy files, collapsing repeated collisions,
capping graph size, shortening labels, and pruning test engineers. The redesign is
primarily a frontend information-architecture and interaction problem.
## 2. Reference Screens
### Current Light Real-Data UI
The light UI is technically real and connected to live data, but it fails visually.
Observed problems:
- The graph is too static and column-like.
- Red collision edges dominate the canvas.
- Labels overlap and fight for attention.
- Interventions repeat as a row of identical diamonds.
- The right panel says "It learned" but does not explain the actual workflow state.
- The screen lacks an activity stream.
- The screen lacks the explicit learning-loop rail from the dark mock.
- The viewer cannot quickly answer:
- What happened?
- Who collided?
- What did PodMan do?
- Did the team accept it?
- What changed in memory?
The current light version proves data plumbing. It does not yet work as a demo
surface.
### Dark Bauhaus Mock
The dark mock is the quality target. Do not copy the dark palette wholesale, but
copy the structure, density, and storytelling.
The mock has:
- A strong title bar:
`PODMAN / CONTINUAL-LEARNING OBSERVATORY`
- A live status indicator:
`LIVE - POD demo-pod`
- A left metrics rail:
workflow metrics as compact, high-contrast cards.
- A center graph:
sparse, geometric, readable, with one primary path emphasized.
- A right learning-loop rail:
`Observe -> Store -> Predict -> Outcome -> Adapt`
- A bottom activity stream:
timestamped events with type badges.
- A selected-node detail panel:
kind, relationships, severity, explanation.
- A legend:
node shapes and edge colors.
The mock works because it is not just a graph. It is an observatory. It tells the
loop story.
## 3. Product Goal
Team memory should be the "it learned" surface.
In a 10-second demo, a viewer should understand:
1. Two engineers are converging on the same file.
2. PodMan detected the risk before a push.
3. PodMan suggested an intervention.
4. The team accepted or dismissed the intervention.
5. PodMan retained that outcome as memory.
6. Future collisions become more informed.
The graph should support that story, not overwhelm it.
## 4. Target Layout
Build a light shadcn page with the same conceptual structure as the dark mock.
```text
+--------------------------------------------------------------------------+
| Header: Team memory - What PodMan learned - <pod> [<- Pods] |
+--------------------------------------------------------------------------+
| Mode controls: Risk path | Learning edges | Whole graph |
+---------------+--------------------------------------+-------------------+
| Workflow | | Learning loop |
| metrics | Dynamic graph canvas | Observe |
| cards | | Store |
| | | Predict |
| | | Outcome |
| | | Adapt |
+---------------+--------------------------------------+-------------------+
| Activity stream | Selected node details |
+--------------------------------------------------------------------------+
```
Required panels:
- **Header**
- Pod name / id.
- Live/generated timestamp.
- Back to pods action.
- **Mode controls**
- Risk path.
- Learning edges.
- Whole graph.
- **Workflow metrics rail**
- Learned owners.
- Open risk paths.
- Accept rate.
- Optional: observations, interventions, memory vectors if available.
- **Dynamic graph canvas**
- Force-directed or animated layered graph.
- Geometric node shapes.
- Curved or bundled edges.
- Labels should not overlap by default.
- Hover/select reveals full details.
- **Learning loop rail**
- Observe.
- Store.
- Predict.
- Outcome.
- Adapt.
- Active/current step should pulse or be highlighted.
- **Activity stream**
- Recent editing, collision, warning, outcome, learned events.
- Compact rows with timestamp + colored type badge.
- **Selected node**
- Default state explains the loop.
- Selected state shows node kind, name, relationships, severity/status, and
why this node matters.
## 5. Visual Direction
Use the app's light shadcn/ruixen design system for chrome.
Hard rules:
- Use `@/components/ui/*` primitives where possible.
- If a primitive is missing, add it through:
`npx shadcn@latest add "https://ruixen.com/r/[component]"`
- Do not make the entire UI a bespoke CSS island.
- The graph canvas itself may be bespoke SVG/canvas.
- The rest should be composed from cards, badges, buttons, tabs/toggles, and
utility classes consistent with `App.tsx`.
Keep semantic graph colors:
- Engineer: blue.
- File: slate outline.
- Feature: amber circle.
- Collision: red triangle.
- Intervention: violet diamond.
- `collides`: red edge.
- `warns`: amber/orange edge.
- `learned_from`: dashed violet edge.
- `owns`: blue edge.
- `editing` / `touches`: muted slate.
Use light surfaces:
- Background: app background token.
- Panels: `card`.
- Borders: `border`.
- Text: `foreground`.
- Supporting copy: `muted-foreground`.
The result should feel like the dark mock translated into the app's light command
center, not a random analytics dashboard.
## 6. Dynamic Graph Requirement
The current graph is too static. Replace or augment the static column layout.
Preferred implementation:
- Use `d3-force` in the frontend.
- Initialize nodes from server `x/y` when useful, but let the simulation settle.
- Use:
- link force by edge strength.
- charge force for separation.
- center force.
- collision force based on node radius.
- optional x/y bias by kind to preserve rough story flow.
- Make nodes draggable.
- Preserve node shape encoding.
- Animate:
- new nodes fading/scaling in.
- new edges drawing/fading in.
- `learned_from` dashed edge flowing or pulsing.
- active collision/intervention pulse.
If `d3-force` is too much for the current branch, use an animated layered layout:
- Engineers left.
- Files mid-left.
- Collisions center/right.
- Interventions right.
- Curved edges.
- Smooth transitions between graph snapshots.
- Gentle idle motion only if it helps.
Do not leave the final version as static fixed columns.
## 7. De-Hairball Rules
Default screen should show the risk path, not every possible relationship.
Rules:
- Default mode: `Risk path`.
- Whole graph can exist, but it is not the demo default.
- Dim non-selected/non-risk edges aggressively.
- Use curved edges or edge bundling.
- Hide low-priority labels until hover/select.
- Prefer file basename/short path on canvas.
- Put full path in selected-node panel.
- Group repeated collisions by signature.
- Cap visible collisions/interventions for demo readability.
- Preserve all data in the payload; choose a readable default projection.
The graph is not an exhaustive database browser. It is a story-first visualization.
## 8. Data Model To Use
Current `PodGraph` contract:
```ts
interface PodGraph {
podId: string;
generatedAt: string;
nodes: PodGraphNode[];
edges: PodGraphEdge[];
metrics: PodGraphMetric[];
}
```
Node kinds:
- `engineer`
- `file`
- `feature`
- `collision`
- `intervention`
Edge kinds:
- `owns`
- `editing`
- `touches`
- `collides`
- `warns`
- `learned_from`
Statuses:
- `stable`
- `active`
- `risk`
- `learned`
Existing collections behind the materializer:
- `pods`
- `engineer_states`
- `observations`
- `collisions`
- `interventions`
- `outcomes`
Important caveat:
The current `demo-pod` accepted outcome chain may be orphaned from test churn.
If `learned_from` does not show, confirm whether there is an intact:
```text
collision -> intervention -> accepted outcome
```
Do not assume the UI is broken until this data chain is verified.
## 9. Extend Data For Missing Panels
The current graph contract does not fully support the dark mock's learning-loop
rail or activity stream.
Recommended additive extension:
```ts
interface PodGraphLoopStep {
id: 'observe' | 'store' | 'predict' | 'outcome' | 'adapt';
label: string;
value: string;
detail: string;
status: 'idle' | 'active' | 'complete';
}
interface PodGraphActivity {
id: string;
at: string;
kind: 'editing' | 'collision' | 'warns' | 'outcome' | 'learned_from';
label: string;
detail: string;
nodeId?: string;
edgeId?: string;
}
interface PodGraph {
...
loop?: PodGraphLoopStep[];
activity?: PodGraphActivity[];
}
```
Possible data mappings:
- Observe:
recent `observations`.
- Store:
stored observations / vectorized collisions / memory documents.
- Predict:
distinct live collisions.
- Outcome:
accepted vs dismissed outcomes.
- Adapt:
learned owners / `learned_from` edges / `team_model.ownership`.
Activity stream source:
- `engineer_states.gitUpdatedAt` -> editing/git state.
- `collisions.detectedAt` -> collision.
- `interventions.createdAt` -> warns/intervention.
- `outcomes.recordedAt` -> outcome.
- accepted real outcome -> learned_from/adapt event.
Cap activity rows to 8-10.
## 10. Suggested Implementation Plan
1. Create a new branch from the current graph branch or latest `main`.
2. Read:
- this file.
- `claude_team_memory_redesign.md`.
- `docs/graph.md`.
- `docs/live-ui-spec.md` if present.
- `frontend/src/components/GraphView.tsx`.
- `backend/src/graph/live.ts`.
3. Add graph UI subcomponents:
- `MetricsRail`.
- `GraphCanvas`.
- `LearningLoopRail`.
- `ActivityStream`.
- `SelectedNodePanel`.
4. Implement the dynamic graph canvas first.
5. Add the learning-loop rail and activity stream.
6. Polish interaction states:
- hover.
- selected node.
- selected edge/path.
- empty/live-loading/offline.
7. Verify with local live data.
8. Capture screenshots at desktop and narrow widths.
9. Run:
- `pnpm build` or local `vite build`.
- `tsc` for shared/backend/frontend.
10. Open a PR. Do not push directly to `main`.
## 11. Acceptance Criteria
The redesign is acceptable only when:
- The default view is readable in 10 seconds.
- The graph is dynamic, not static columns.
- It includes metrics, graph, learning-loop rail, activity stream, selected-node
panel, and legend.
- The primary risk path is obvious.
- Labels do not overlap in the default view.
- Whole graph mode exists but can be visually denser.
- It uses real data from the materializer.
- It remains composed from light shadcn/ruixen primitives where possible.
- It builds successfully.
- It is verified after a hard refresh because the PWA can cache stale bundles.
## 12. What Not To Do
- Do not make a marketing page.
- Do not make a generic dashboard.
- Do not rewrite the backend materializer unless the UI needs a small additive
field.
- Do not return to the dark UI wholesale.
- Do not keep the static column layout as the final answer.
- Do not show raw full paths as always-on canvas labels.
- Do not show every edge at equal opacity.
- Do not hide the learning loop in copy only; it needs a visible rail or panel.
## 13. Demo Script The UI Should Support
The final UI should support this story:
1. Engineer A and Engineer B work in the same repo.
2. One has unpushed changes.
3. PodMan observes the overlap.
4. A collision node appears and pulses.
5. PodMan sends a sync PR / warning intervention.
6. The intervention diamond appears.
7. The team accepts.
8. The outcome appears in the activity stream.
9. A `learned_from` edge appears or pulses.
10. The learning-loop rail advances to Adapt.
That is the recursive self-improvement moment. Everything else is supporting
evidence.
## 14. Open Questions For The Implementer
- Should dynamic layout be `d3-force` or animated layered SVG?
- Should loop/activity be added to `PodGraph` or exposed as separate endpoints?
- Should the demo seed one intact accepted outcome chain?
- Should `Whole graph` be hidden behind an explicit "inspect full graph" affordance?
- Should mobile show a simplified activity-first version instead of the full graph?
Answer these in code comments or PR notes when implementing.
## 15. Final Reminder
The backend now has real graph glue. The UI needs to become a **live learning
observatory**, not a static graph dump.
Make the light version earn the same reaction as the dark Bauhaus mock:
```text
I can see what happened.
I can see what PodMan did.
I can see what it learned.
```
+730
View File
@@ -0,0 +1,730 @@
# PodMan - Canonical Master Plan
> Source of truth for PodMan product intent, current implementation truth, demo
> strategy, public interfaces, risks, sponsor story, and next build order.
>
> If this file conflicts with `README.md`, `docs/idea.md`, `docs/livekit.md`,
> `docs/gemini.md`, `docs/mongodb.md`, `docs/digitalocean.md`,
> `docs/demo-setup.md`, or `docs/superpowers/specs/*`, follow this file and
> treat the older docs as reference material to reconcile later.
---
## 1. Product thesis
**PodMan sees active work before it becomes visible to GitHub, remembers how the
team works, researches better paths in the background, and coordinates teammates
without being intrusive.**
GitHub knows pushed branches, PRs, issues, and comments. It cannot see the most
expensive coordination failures while they are still forming on laptops: two
engineers editing the same unpushed file, someone blocked on an endpoint a
teammate is nearly done with, duplicated work starting silently, or a team
walking into a dead-end implementation path.
PodMan puts engineers in a consented LiveKit pod, watches live IDE/screen
context, fuses that with scheduled local git reports, GitHub state, MongoDB team
memory, and background research, then routes only useful interventions through
Hermes. The default is a small visual card. Hermes can message teammates when
the team needs coordination. Voice is reserved for urgent escalation.
**One-line product definition:** PodMan is a non-intrusive, continual-learning
team assistant for active coding.
**One-line demo promise:** PodMan notices live work, finds a better path,
remembers a previous intervention, and escalates only when the team actually
needs it.
---
## 2. Product contract
### Inputs
- **Live IDE/screen context:** engineers join a LiveKit room and publish screen
share so the backend agent can sample real work in progress.
- **Scheduled local git state:** each laptop should report dirty files,
unpushed commits, branch, and latest commit about every minute. This is the
deterministic fallback for facts vision cannot reliably infer.
- **MongoDB team memory:** ownership, current tasks, blockers, repeated
mistakes, preferred tools, decisions, intervention history, and outcomes.
- **GitHub repo state:** public repo metadata, branches, PR artifacts, and
issue/PR state when it exists.
- **Background research signals:** tool, repo, skill, package, docs, and
dead-end evidence discovered while teammates are working.
### Outputs
- **Default:** small visual intervention card in the PodMan frontend.
- **Coordination:** Hermes message to the right teammate(s) or project channel.
- **Urgent escalation:** voice only when timing or risk justifies interruption.
- **Action path:** optional sync PR, research recommendation, summary, fix
suggestion, or teammate notification.
### Memory rules
- Remember team-level work patterns, not raw screen recordings.
- Store structured observations, collisions, interventions, outcomes, and pod
state.
- Add exact-signature recall before vector recall: normalized file, symbol,
engineer pair, event type, and accepted/dismissed outcome.
- Privacy must stay explicit: engineers consent by joining the pod and sharing
screen context; do not store raw screenshots, full recordings, or secrets.
### Non-goals
- Not a dashboard as the product center.
- Not a screenshot analyzer with no action loop.
- Not sponsor-padding; every sponsor technology must be load-bearing or clearly
marked as optional polish.
- Not a task manager, Slack clone, full auth system, or general surveillance
tool.
---
## 3. Track fit: Continual Learning
PodMan fits **Continual Learning** because the system gets more useful from team
history and intervention outcomes.
- **Team model:** observations build ownership, hotspot, blocker, tool, and
decision memory per pod.
- **Outcome loop:** accepted, dismissed, and confirmed interventions become
supervision for future thresholds and routing.
- **Session compounding:** a later similar situation should reference prior
memory, choose a better action sooner, or lower the noise level.
- **Visible demo proof:** the first intervention writes memory; the second
similar situation retrieves it and says, in effect, "I have seen this pattern
before."
The learning proof should not depend on Atlas Vector Search being finished.
Exact MongoDB recall is enough for the MVP learning beat.
---
## 4. Current implementation truth
Verified on `2026-06-27` from local repo inspection, authenticated `gh`, and
the current remote plan commit.
### GitHub state
- Repo: <https://github.com/karti-ai/podman>
- Visibility: public
- Default branch: `main`
- Current local branch: `main`
- Local branch state during this rewrite: behind `origin/main` by two commits
- Issues: none
- PRs: none
- `origin/main` latest relevant commits:
- `8271188 feat(frontend): live room view, beat connectivity test, session resume`
- `65a0791 docs(plan): audit server state + mark tasks 1-5 done, reflect actual arch`
### Working / started
- Monorepo packages exist: `frontend`, `backend`, `shared`, `database`, and
`infra`.
- Backend is split into two processes:
- API service in `backend/src/server.ts`.
- LiveKit agent worker in `backend/src/agent.ts`.
- Backend API exposes:
- `GET /health`
- `POST /api/token`
- `POST /api/sync-pr`
- `POST /api/outcome`
- `GET /api/memory/stats`
- `GET /api/pods`
- `POST /api/pods`
- `GET /api/pods/:id`
- `PATCH /api/pods/:id`
- `DELETE /api/pods/:id`
- `POST /api/pods/:id/members`
- `DELETE /api/pods/:id/members/:name`
- Remote API health check returned `{"ok":true}` at
`http://165.22.129.249:8787/health` during verification.
- The LiveKit agent uses `@livekit/rtc-node` to join as `podman-agent`, subscribe
to `TrackSource.SOURCE_SCREENSHARE`, sample frames near 1 fps, convert frames
to RGBA, and encode downscaled JPEGs with `sharp`.
- Gemini vision is wired in `backend/src/vision/gemini.ts` with JSON structured
output, response schema, low media resolution, and model ID from env.
- Collision detection exists and groups engineer contexts by normalized file,
then fires when 2+ engineers touch the same file and at least one unpushed or
dirty signal exists.
- Shared LiveKit data topic and wire messages exist:
- topic: `podman.intervention`
- messages: `COLLISION`, `VOICE_CUE`, `ACK`, `GIT_REPORT`
- MongoDB persistence groundwork exists for observations, collisions,
interventions, outcomes, and pods.
- Frontend has pod selection, pod join, post-join pod view, LiveKit join helper,
and dev-mode fallback.
- `origin/main` adds live room participants, active-speaker state, session
resume, a "Play beat" audio connectivity test, and a deliberate "Share my
screen" button that publishes with `Track.Source.ScreenShare`. Merge that
remote commit before doing more frontend work on the local checkout.
- DigitalOcean infra scaffolding exists:
- `infra/.do/app.yaml` is the split App Platform direction.
- `infra/app.yaml` is an older single-service backend spec and should be
treated as legacy until reconciled.
### Server snapshot
From the remote plan snapshot and health check on `2026-06-27`:
- Backend API: running on `http://165.22.129.249:8787` and `/health` returned
`{"ok":true}`.
- Frontend: reported running on `:81`; port `80` was already taken.
- Agent worker: reported not running; it still needs LiveKit credentials and
`pnpm --filter @podman/backend dev:agent`.
- Treat this as operational evidence, not architecture truth. Reverify before
demo.
### Partial / completed since the original audit
- `backend/src/voice/live.ts` now publishes a `VOICE_CUE` fallback and attempts
Gemini audio publication into LiveKit. The agent only calls it for critical
interventions so voice remains an urgent escalation path.
- Hermes now has a data-channel teammate message path via `HERMES_MESSAGE` on
the existing `podman.intervention` topic. This is the MVP notification bridge,
not a Slack/Discord integration.
- `backend/src/memory/vectors.ts` implements exact-signature recall first and
can use Voyage/Gemini embeddings with Atlas Vector Search when configured.
- Exact-signature recall now attaches prior interventions/outcomes and prefers
accepted real collisions, giving the learning beat deterministic MongoDB
proof before vector search.
- `backend/src/memory/policy.ts` now uses severity, per-pod cooldown, and prior
outcome history. It is still a simple policy, not a trained threshold model.
- `POST /api/sync-pr` now creates a visible Markdown sync artifact commit before
opening the PR.
- Frontend `PodView` renders intervention cards, Hermes messages, voice cues,
and the accepted sync PR artifact link.
- Browser screen publishing exists, but the active join path must be proven to
tag tracks as screen share so the backend agent can filter them correctly. The
`origin/main` screen-share button appears to address this; local code remains
behind until that commit is merged.
- `GIT_REPORT` exists in shared types and agent handling. `scripts/podman-agent.mjs`
is the finished per-laptop git sidecar — polls every 15 s, upserts git fields
to `engineer_states` collection. The backend agent now fuses those Mongo
git-state fields into live contexts before collision detection; direct
LiveKit `GIT_REPORT` publication from the sidecar remains optional.
- Background research recommendations are a product requirement and demo goal,
not an implemented research agent yet.
- Deployment reliability is partial; API health is reachable, but API/static
site/worker together must still be reverified before demo.
- Env docs now align on `gemini-3.5-flash` for vision and
`gemini-3.1-flash-tts-preview` for voice. The backend still preserves a Gemini
Live path for future available Live models.
### Not yet proven
- Real browser -> LiveKit room -> backend agent screen-frame capture end to end.
- Real Gemini inference from a live shared IDE frame using the stage key/model.
- Real data-channel intervention card rendering in the active frontend.
- Hermes message routing to teammates.
- Voice escalation heard by participants through LiveKit.
- A meaningful real sync PR flow with correct GitHub scopes and artifact.
- Atlas Vector Search / Voyage recall path.
- DigitalOcean static site + API service + LiveKit agent worker all running
together.
- Background research recommendation that is both timely and evidence-backed.
---
## 5. Architecture to build toward
```
Engineer browser PWA
- joins a pod room
- publishes screen share and optional mic
- receives intervention cards and voice
|
v
LiveKit room
- one room per pod
- screen-share tracks are the live work signal
- small reliable data packets carry interventions
|
v
PodMan backend agent worker
- @livekit/rtc-node room participant
- screen-track subscription
- frame throttle and JPEG encode
- Gemini structured vision
- scheduled GIT_REPORT fusion
- GitHub state fusion
- collision, blocker, duplicate-work, and dead-end detection
- MongoDB memory recall and policy
|
v
Hermes action layer
- visual card routing
- teammate messages
- urgent voice escalation
- optional research/action/sync PR workflows
|
v
Backend API + MongoDB + GitHub
- token minting, pod CRUD, outcomes, memory stats
- observations, collisions, interventions, outcomes, pod memory
- public repo state and PR artifacts
```
The backend must remain split:
- **API service:** routable HTTP process with `/api/*` endpoints and health
checks.
- **Agent worker:** outbound LiveKit participant with no HTTP health-check port
requirement.
This split matters for DigitalOcean App Platform: the LiveKit agent should be a
worker, not a web service that App Platform expects to health-check over HTTP.
---
## 6. Public interfaces to preserve
Do not rename or reshape these without updating frontend, backend, docs, and demo
scripts together.
### Backend HTTP
- `GET /health`
- `POST /api/token`
- `POST /api/sync-pr`
- `POST /api/outcome`
- `GET /api/memory/stats`
- `GET /api/pods`
- `POST /api/pods`
- `GET /api/pods/:id`
- `PATCH /api/pods/:id`
- `DELETE /api/pods/:id`
- `POST /api/pods/:id/members`
- `DELETE /api/pods/:id/members/:name`
### LiveKit data channel
- Topic: `podman.intervention`
- Core messages:
- `COLLISION`: agent -> PWA; contains `collision` and `intervention`.
- `ACK`: PWA -> agent/API; intervention response.
- `GIT_REPORT`: local git sidecar -> agent; dirty/unpushed ground truth.
- `VOICE_CUE`: text cue/fallback for voice escalation.
### Required environment
```bash
LIVEKIT_URL=
LIVEKIT_API_KEY=
LIVEKIT_API_SECRET=
GEMINI_API_KEY=
GEMINI_VISION_MODEL=
GEMINI_LIVE_MODEL=
GITHUB_TOKEN=
GITHUB_REPO=karti-ai/podman
MONGODB_URI=
VOYAGE_API_KEY=
POD_ROOM=demo-pod
PORT=8787
VITE_BACKEND_URL=http://localhost:8787
VITE_LIVEKIT_URL=
```
Keep all non-`VITE_` secrets server-side.
---
## 7. Critical implementation callouts
### LiveKit
- Screen share is a video track. The backend agent should consume raw screen
frames through `@livekit/rtc-node`.
- The agent must filter screen share, not webcam:
`pub.source === TrackSource.SOURCE_SCREENSHARE`.
- Frontend publishing must tag the track as screen share; otherwise the agent can
miss it.
- Throttle aggressively. Screens can arrive near video frame rate; Gemini should
receive sampled frames only.
- Keep reliable data packets small. Use them for intervention metadata, not
screenshots, large diffs, or research dumps. Treat reliable payloads as
roughly 15 KiB max.
- A historical closed `livekit/node-sdks` issue reported high memory use when
consuming video; run memory checks during agent frame tests and stop if the
loop leaks.
### Gemini
- Use structured output for vision: JSON mime type plus response schema.
- Use low media resolution for ambient screen watching; reserve higher
resolution for debugging or targeted inspection.
- Never expose `GEMINI_API_KEY` to the browser.
- Gemini Live API is still a risk for the first demo path. Use card + Hermes
message first; add browser TTS or pre-generated voice fallback before relying
on Gemini Live for stage audio.
- Keep model IDs in env so preview/availability changes do not require code
changes.
### MongoDB
- Local MongoDB is fine for dev CRUD and memory counts.
- Atlas or Atlas Local is needed for the sponsor-grade Vector Search story.
- Build exact-signature recall first:
normalized file + symbol + engineer pair + event type + outcome.
- Writes from the agent should be best-effort. Mongo hiccups should degrade
memory, not kill live detection.
- Do not store raw screenshots or recordings.
### GitHub
- The repo is public and currently has no issue/PR backlog, so do not make the
plan issue-driven yet.
- GitHub cannot see local dirty files or unpushed commits. That is still a core
product moat.
- Sync PRs should use deterministic GitHub REST/Octokit flows, not browser
automation.
- Verify token scopes and demo repo permissions before stage time.
### DigitalOcean
- Use App Platform as:
- static site for frontend,
- HTTP service for API,
- worker for the LiveKit agent.
- Do not model the agent worker as a health-checked HTTP service.
- Keep a local and recorded fallback even if deployment works; venue network is a
stage risk.
### Hermes
- Treat Hermes as the action and messaging layer, not as a replacement for the
current implemented backend agent until code changes make that real.
- Hermes should choose the least intrusive channel:
card -> message -> voice.
- Hermes can own research summaries, teammate notification, sync PR initiation,
and urgent escalation once those workflows exist.
---
## 8. Build ladder
Do not mark a rung done until it is proven in logs, UI, or a visible external
artifact.
### P0 - make the live loop undeniable
1. **Preserve and reconcile the plan**
- Merge local `docs/PLAN.md` with `origin/main:docs/PLAN.md`.
- Keep both the broad product thesis and concrete server/current-state facts.
- After the docs are safe, merge or rebase the two newer `origin/main` commits
before implementing frontend work.
2. **Browser publish proof**
- Start backend API and frontend.
- Join a real LiveKit room from the browser.
- Confirm the browser publishes a screen-share track with the correct source.
3. **Agent frame proof**
- Start `pnpm --filter @podman/backend dev:agent`.
- Confirm room join, screen-track subscription, frame sampling, and JPEG
encode logs.
- Watch process memory while consuming frames.
4. **Gemini vision proof**
- Send one live sampled IDE frame to Gemini.
- Log parsed JSON with `currentFile`, `currentSymbol`, `activity`,
`hasUnpushedChanges`, and `confidence`.
- Add a confidence/logging gate if noisy frames cause bad reads.
5. **Scheduled git truth** ✅ partial
- `scripts/podman-agent.mjs` polls every 15 s: `git status --short`,
`git diff --stat HEAD`, `git log --oneline -1`, `git branch --show-current`.
- Upserts `changedFiles`, `diffStat`, `recentCommit`, `branch`, `gitUpdatedAt`
to `engineer_states` collection in MongoDB (upsert by `podId::name` key).
- **Still needed:** fuse `engineer_states` git fields into the collision
detector, and/or publish `GIT_REPORT` data channel messages so the agent
worker can incorporate git truth into vision-based decisions.
6. **Intervention card + Hermes notification**
- Publish a real intervention on `podman.intervention`.
- Render it as a small card in the frontend.
- Route a Hermes message to the affected teammate(s) or project channel once
the bridge exists.
7. **Background research recommendation**
- When the team is heading into a poor tool/repo/skill choice or dead end,
produce a recommendation card with short evidence.
- Minimum evidence: why it matters, what to use instead, and who should act.
8. **Learning proof**
- First intervention writes observation/collision/recommendation/outcome
memory.
- Second similar situation retrieves exact prior memory and changes the
message: "I have seen this pattern before."
9. **Urgency routing**
- Default to card.
- Escalate to Hermes message when coordination involves other teammates.
- Escalate to voice only when urgent.
10. **Action artifact**
- If demo uses same-file collision, click the card to open a real draft sync
PR or visible GitHub artifact.
- If demo uses research recommendation, show the accepted recommendation and
memory outcome instead.
11. **Deployment or fallback proof**
- Prove API/static/worker deployment together, or explicitly run local with a
recorded backup.
- Keep backup video on a separate device.
### P1 - polish the money moment
- Add visible live inference captions in the PWA.
- Add a small memory stats panel backed by `/api/memory/stats`.
- Add browser-side TTS or pre-generated voice fallback for urgent interventions.
- Add Hermes notification bridge once the target channel is chosen.
- Improve research cards with compatibility, install effort, docs quality, repo
health, and security/trust signals.
### P2 - sponsor and scale polish
- Implement Voyage embedding + Atlas Vector Search recall.
- Improve policy learning from outcomes.
- Deploy DigitalOcean static site + API service + worker as the submission path.
- Add optional GitHub issue/PR backlog integration after issues/PRs actually
exist.
### Cut if behind
- Webcam grid.
- Mic transcription.
- Full auth/accounts.
- Slack/Linear/Jira integrations unless Hermes requires one immediately.
- Complex dashboards.
- Server-published audio if browser/pre-generated voice proves escalation.
- Vector Search if exact Mongo recall demonstrates the learning beat.
---
## 9. Critical 3-minute demo script
**Rule:** open on one active IDE, not a grid. PodMan is an agent, not a
dashboard.
1. **0:00 - Set the scene**
- One engineer is actively coding in the IDE.
- The presenter says: "This work is not pushed yet. GitHub cannot see it."
2. **0:20 - Show the live signal**
- Show a compact caption: current file, inferred task, git dirty/unpushed
state.
- Show that PodMan is watching consented screen context, not stored
recordings.
3. **0:40 - Introduce the better-tool moment**
- A teammate starts down a weak path: wrong package, dead repo, bad API,
duplicated effort, or risky implementation.
- PodMan has been researching in the background.
4. **1:05 - Money moment**
- PodMan shows a small card:
"This path is likely a dead end. Use X instead; it matches our stack and is
actively maintained."
- The card names the affected teammate and the suggested action.
5. **1:25 - Hermes coordination**
- Hermes notifies the right teammate(s), not the whole room.
- No voice yet unless the situation is urgent.
6. **1:50 - Learning beat**
- A similar issue appears.
- PodMan references memory:
"I have seen this pattern before. Last time the team accepted the X
recommendation."
- Show `/api/memory/stats` or the visible memory indicator.
7. **2:20 - Urgency escalation**
- Raise the severity with a same-file collision, blocking dependency, failing
test, or imminent bad push.
- Hermes escalates to voice only now.
8. **2:40 - Close**
- Show the public repo, deployed/local URL, and memory stats.
- Closing line: "PodMan coordinates work while it is still happening."
### Reliable fallback demo
If the research recommendation is not reliable by stage time, use the same-file
collision fallback:
1. Two engineers open the same visible file.
2. `GIT_REPORT` or vision marks one as dirty/unpushed.
3. Agent publishes `COLLISION` on `podman.intervention`.
4. Frontend renders the card.
5. The card opens a sync PR artifact.
6. A second similar collision retrieves prior memory.
---
## 10. Sponsor strategy
### Gemini
Gemini must be load-bearing for the vision loop:
- live IDE/screen frame -> structured work context,
- optional message/recommendation generation,
- optional Live voice only after card/Hermes routing is stable.
Do not overclaim voice if it is using browser/pre-generated TTS. Say plainly that
it is the reliability fallback.
### LiveKit
LiveKit is the real-time spine:
- engineers join one pod room,
- screen-share tracks carry active work context,
- PodMan joins as a participant,
- data packets carry interventions,
- voice can be added as urgent escalation.
Pitch line: "Unpushed work is invisible to GitHub, so real-time presence is the
only way to coordinate before the push."
### MongoDB + Voyage
MongoDB is the learning proof:
- observations, collisions, recommendations, interventions, and outcomes persist,
- prior memory changes a later intervention,
- exact recall is the MVP,
- Voyage + Atlas Vector Search is the stronger sponsor-grade version after exact
recall works.
### DigitalOcean
DigitalOcean earns its place when:
- frontend runs as a static site,
- API runs as an HTTP service,
- LiveKit agent runs as a worker,
- public URL is shown in submission or demo.
Local fallback is acceptable for stage reliability, but the submission should
include the deployment URL if possible.
---
## 11. Risks and mitigations
| Risk | Mitigation |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Looks like a dashboard | Keep the UI quiet. Hero is card/message/action, not a grid. |
| Looks like a screenshot analyzer | Always show screen signal + git truth + memory + action. |
| Interrupts too much | Default to cards, escalate to Hermes messages, reserve voice for urgency. |
| Overclaims implemented features | Mark voice, Hermes bridge, vectors, adaptive policy, research agent, real sync PR, and DO worker deploy incomplete until proven. |
| Vision misses unpushed state | Use scheduled `GIT_REPORT` for deterministic dirty/unpushed truth. |
| Research recommendation lacks evidence | Show only concise evidence: stack fit, repo/tool health, install effort, docs/trust signal. |
| No visible learning | Build exact Mongo recall before vector search. |
| LiveKit frame loop leaks memory | Monitor agent memory during video consumption; throttle hard. |
| GitHub issue/PR backlog absent | Do not invent issue-driven backlog; repo currently has no issues or PRs. |
| Venue network failure | Rehearse on hotspot and keep recorded backup. |
| DO worker deploy hangs | Deploy agent as worker, not health-checked service. |
---
## 12. Documentation reconciliation tasks
After this plan is accepted, update the supporting docs so they stop conflicting
with this file:
- `README.md`: replace POST-screenshot-first language with LiveKit screen-track
agent architecture and Hermes action-layer wording.
- `docs/idea.md`: broaden from blocker/dependency voice demo to card/message/
urgent-voice coordination plus research and memory.
- `docs/livekit.md`: remove "Hermes does NOT subscribe to engineer screen
tracks"; current architecture uses backend agent screen subscription.
- `docs/gemini.md`: keep structured vision, but mark Gemini Live as P1 and avoid
claiming voice is implemented.
- `docs/mongodb.md`: align collection names with current code
(`observations`, `collisions`, `interventions`, `outcomes`, `pods`) and add
exact-signature recall.
- `docs/digitalocean.md`: split API service and agent worker; do not deploy the
worker as a health-checked HTTP service; mark `infra/app.yaml` legacy or
reconcile it with `infra/.do/app.yaml`.
- `docs/demo-setup.md`: update the script to include better-tool research,
learning recall, Hermes notification, and urgency-based voice.
---
## 13. Acceptance checklist
Before saying PodMan is demo-ready:
- [ ] `pnpm format:check` passes or all failures are documented as unrelated.
- [ ] `pnpm typecheck` passes.
- [ ] Browser joins a real LiveKit room.
- [ ] Browser publishes a screen-share track with the correct source.
- [ ] Backend agent subscribes to the screen-share track.
- [ ] Agent logs at least one parsed Gemini context from a real IDE screen.
- [x] Local git report supplies dirty/unpushed truth on a schedule (`scripts/podman-agent.mjs` — 15 s poll → MongoDB `engineer_states`). Agent fusion still needed.
- [x] Frontend renders a real intervention card.
- [x] Hermes notification path works for teammate messages over the LiveKit data
channel.
- [ ] Voice is heard only for urgent escalation or a fallback is declared.
- [x] Outcome ACK writes to MongoDB and updates intervention status.
- [x] `/api/memory/stats` shows counts increasing.
- [x] Second similar situation uses prior exact memory in the message.
- [ ] Research recommendation card is evidence-backed, or fallback collision demo
is used.
- [x] Sync PR action creates a visible GitHub artifact if used in demo.
- [ ] DigitalOcean deployment or local fallback is rehearsed.
- [ ] Backup recording is ready on a separate device.
---
## 14. Evidence appendix
### Repo and GitHub state
- Public repo: <https://github.com/karti-ai/podman>
- Verified with authenticated `gh` on `2026-06-27`.
- Default branch: `main`.
- No GitHub issues or PRs existed at verification time.
### Hackathon / event
- AI Engineer World's Fair: <https://www.ai.engineer/worldsfair/2026>
- Cerebral Valley hackathon page:
<https://cerebralvalley.ai/e/aiewf-hackathon-2026>
### LiveKit
- Screen share docs: <https://docs.livekit.io/transport/media/screenshare/>
- Data packets docs: <https://docs.livekit.io/transport/data/packets/>
- Node SDK reference: <https://docs.livekit.io/reference/client-sdk-node/>
- Node SDK releases: <https://github.com/livekit/node-sdks/releases>
- Node SDK issue risk: <https://github.com/livekit/node-sdks/issues/444>
### Gemini
- Structured output:
<https://ai.google.dev/gemini-api/docs/structured-output>
- Media resolution: <https://ai.google.dev/gemini-api/docs/media-resolution>
- Live API: <https://ai.google.dev/gemini-api/docs/live-api>
### DigitalOcean
- App Platform app spec:
<https://docs.digitalocean.com/products/app-platform/reference/app-spec/>
### MongoDB
- Vector Search index type:
<https://www.mongodb.com/docs/vector-search/index/vector-search-type/>
- Node driver Atlas Vector Search:
<https://www.mongodb.com/docs/drivers/node/current/atlas-vector-search/>
+89
View File
@@ -0,0 +1,89 @@
# Agent Learning Plan
Status: draft
Goal: ship a visible recursive self-improvement loop without overbuilding
## Must-Have
1. Store agent runs.
2. Store trace summaries.
3. Store active and candidate strategy versions.
4. Attach verifier or outcome evidence.
5. Show one strategy improvement in the demo narrative.
## Build Order
### R1: Trace the run
Write one `agent_runs` record for an important coordination decision and append
trace events for:
- observation
- recall
- prediction
- intervention
- outcome
- adaptation
### R2: Version the strategy
Create an active strategy version for one of:
- collision detector threshold
- intervention routing
- graph discovery filter
- card wording prompt
### R3: Score the outcome
Use the simplest verifier:
- accepted real collision = useful
- dismissed = noisy
- no response after cooldown = uncertain
### R4: Propose a narrow change
Examples:
- "For this exact signature, prefer sync PR card."
- "For dismissed docs-only overlaps, suppress voice escalation."
- "For repeated auth.ts collisions, raise severity."
### R5: Promote or reject
Promote only when evidence is strong enough. Otherwise keep the candidate as
rejected or open.
## Demo Path
1. Show baseline strategy.
2. Trigger a collision.
3. Accept or dismiss the intervention.
4. Store outcome.
5. Show a candidate strategy update.
6. Promote it.
7. Trigger a similar event.
8. Show changed behavior.
## Nice-to-Have
- Strategy comparison panel.
- Model-generated prompt patch with verifier.
- Vector recall over strategy history.
- Rollback UI.
## Cut
- Full autonomous code rewriting.
- Multi-agent strategy debates.
- Long-term benchmark suite.
- Training a model.
## Acceptance Criteria
- The demo can point to a MongoDB record proving the agent changed behavior.
- The changed behavior is visible.
- The strategy has a parent and evidence.
- Rejected or failed changes are not deleted.
+84
View File
@@ -0,0 +1,84 @@
# Agent Learning Policy
Status: draft
Scope: guardrails for recursive self-improvement
## Prime Rule
PodMan may improve its agent behavior only when the improvement is narrow,
evidence-backed, versioned, and reversible.
## Allowed Learning
PodMan may learn:
- Which prompt version produces clearer interventions.
- Which detector threshold reduces false positives.
- Which routing channel gets accepted without being intrusive.
- Which verifier best predicts user acceptance.
- Which graph-discovery rule produces cleaner risk paths.
## Disallowed Learning
PodMan must not:
- Promote a strategy because the model says it is better.
- Rewrite broad system behavior from one example.
- Hide failures, dismissals, or rejected candidates.
- Learn from raw screenshots, secrets, or private terminal content.
- Turn voice into the default route.
- Create irreversible actions without human approval.
## Promotion Rules
A candidate strategy can become active only when all are true:
1. It has a parent strategy version.
2. It describes one concrete behavior change.
3. It has a verifier plan.
4. It has evidence from a run, outcome, or test.
5. It improves or fixes the target metric.
6. It does not increase user interruption without payoff.
## Rejection Rules
Reject and retain the candidate when:
- The verifier regresses.
- The change is too broad.
- The evidence is missing.
- The candidate conflicts with privacy rules.
- The candidate makes the demo less stable.
## Evidence Strength
| Evidence | Strength | Use |
| --- | --- | --- |
| Model opinion | Weak | Proposal only |
| Trace observation | Medium | Candidate rationale |
| Human accepted outcome | Strong | Promotion candidate |
| Human dismissed outcome | Strong | Suppression or rejection |
| Automated verifier | Strong | Promotion or rejection |
| Repeated accepted exact signature | Strong | Policy confidence increase |
## Versioning Rules
- Strategy versions are immutable after promotion or rejection.
- There is one active version per `podId + kind`.
- A rollback activates the previous version; it does not edit history.
- Parent-child lineage must be preserved.
## Safety Rules
- Store summaries, not raw sensitive content.
- Prefer deterministic checks over model judgment.
- Use exact MongoDB recall before vector recall.
- Ask for approval before changing code or data with external effects.
- Treat hackathon demo stability as a hard constraint.
## Demo Honesty
Seeded strategy versions are acceptable when labeled as demo-backed. Do not claim
a strategy was learned live unless a run and outcome actually created the
promotion evidence.
+74
View File
@@ -0,0 +1,74 @@
# Agent Learning Prompt
Use this prompt for an agent responsible for improving PodMan's own behavior.
## Prompt
You are PodMan's agent-learning evaluator.
Your job is to inspect a completed agent run, identify one narrow improvement,
define how to verify it, and decide whether to propose, promote, or reject a
strategy change.
You must not claim improvement without evidence. You must not propose broad
rewrites. Keep every change small, reversible, and tied to a run or outcome.
## Inputs
- Current active strategy version.
- Agent run summary.
- Trace events.
- Intervention outcome.
- Verifier result.
- Recent false positives or accepted events.
- Current demo constraints.
## Procedure
1. Identify the target behavior.
2. Identify the failure or success evidence.
3. Decide whether a strategy change is warranted.
4. Propose one narrow change.
5. Define the verifier.
6. Decide status: no change, candidate, promote, reject.
7. Write a short explanation suitable for the Team memory activity stream.
## Output Format
```text
Target
- Strategy kind:
- Active version:
- Behavior under review:
Evidence
- Run:
- Outcome:
- Verifier:
- Confidence:
Decision
- Status:
- Proposed change:
- Why this is narrow:
- Risk:
Verifier
- Metric:
- Passing condition:
- Failing condition:
Memory Write
- Collection:
- Record summary:
- Graph/activity summary:
```
## Hard Rules
- Exact outcomes beat model opinion.
- Rejected candidates stay in memory.
- No raw screenshots or secrets.
- No broad policy change from one weak signal.
- No voice-first behavior.
+185
View File
@@ -0,0 +1,185 @@
# Agent Learning Spec
Status: draft
Scope: how PodMan agents improve their own prompts, policies, detectors, and routing behavior
Owner: agent learning / recursive self-improvement
## Purpose
Agent learning is the recursive self-improvement layer. It is not the same as
team memory. Team memory learns about engineers and work. Agent learning learns
which agent strategies produce better outcomes.
The demo claim:
1. PodMan tries a coordination strategy.
2. The run is traced in MongoDB.
3. A verifier or human outcome scores it.
4. Gemini or another agent proposes a narrow strategy change.
5. The new strategy is versioned.
6. A later run uses the improved strategy and shows a better result.
## Core Objects
### Agent run
One attempt to execute a goal.
```text
agent_runs
runId
podId
goal
trigger
strategyVersionId
status
startedAt
completedAt
score
verifierSummary
inputRefs
outputRefs
```
Allowed `status` values:
```text
running, succeeded, failed, improved, regressed, abandoned
```
### Trace event
Append-only event log for a run.
```text
agent_trace_events
runId
podId
step
phase
eventType
inputSummary
outputSummary
toolName
error
metrics
createdAt
```
### Strategy version
Versioned prompt, detector rule, policy, verifier, or routing strategy.
```text
strategy_versions
strategyVersionId
podId
kind
name
parentVersionId
status
summary
promptText
policy
verifier
metrics
createdAt
promotedAt
```
Allowed `kind` values:
```text
prompt, policy, detector, verifier, routing
```
Allowed `status` values:
```text
candidate, active, retired, rejected
```
### Learning proposal
A candidate change before promotion.
```text
learning_proposals
proposalId
podId
sourceRunId
targetKind
parentVersionId
proposedChange
rationale
verifierPlan
status
createdAt
resolvedAt
```
Allowed `status` values:
```text
open, accepted, rejected, superseded
```
## MongoDB Indexes
| Collection | Index | Purpose |
| --- | --- | --- |
| `agent_runs` | `{ podId: 1, startedAt: -1 }` | Recent run history |
| `agent_runs` | `{ podId: 1, strategyVersionId: 1 }` | Compare strategy performance |
| `agent_trace_events` | `{ runId: 1, step: 1 }` | Reconstruct run |
| `strategy_versions` | `{ podId: 1, kind: 1, status: 1 }` | Find active strategy |
| `strategy_versions` | `{ podId: 1, createdAt: -1 }` | Version history |
| `learning_proposals` | `{ podId: 1, status: 1 }` | Open candidate changes |
## Learning Loop
```text
observe run -> score run -> propose change -> test candidate -> promote or reject
```
Agent learning must always connect these records:
```text
agent_run -> trace_events -> verifier result -> learning_proposal -> strategy_version
```
## Verifier Contract
Every promoted strategy needs a verifier signal.
Allowed verifier types:
- Human accepted or dismissed outcome.
- Test pass or fail result.
- Reduced false positive rate.
- Reduced intervention count with same or better accepted outcomes.
- Faster successful run.
- Better graph discovery precision.
- Explicit demo operator approval.
Self-evaluation alone is not enough to promote a strategy.
## Relationship to Team Graph
Agent learning can appear in the Team memory graph as activity and loop status,
but it should not clutter the main risk graph by default.
Graph discovery may show:
- `agent_run` activity in the stream.
- `strategy_versions` count in the learning loop.
- A selected-node detail saying a policy changed because a prior outcome was
dismissed or accepted.
## Acceptance Criteria
- Every strategy change has a parent.
- Every promoted strategy cites evidence.
- Rejected strategies are retained with a reason.
- Agent traces are append-only.
- The system can answer: "What changed, why, and did it help?"
+69
View File
@@ -0,0 +1,69 @@
# Continual Learning Plan
Status: draft
Goal: prove PodMan learns from outcomes in the hackathon demo
## Must-Have Demo Loop
1. Observe two engineers touching the same file.
2. Store the observation and git state in MongoDB.
3. Predict a collision.
4. Send a card or Hermes message.
5. Record accept or dismiss outcome.
6. Adapt `team_model`.
7. Show the learned graph edge or changed future behavior.
## Build Order
### R1: Make exact recall reliable
- Normalize file paths.
- Build stable memory signatures.
- Look up prior accepted and dismissed outcomes.
- Prefer exact recall over vector recall.
### R2: Make outcomes update memory
- Accepted real collision creates or strengthens ownership.
- Accepted real collision creates `learned_from`.
- Dismissed outcome lowers confidence or suppresses route.
### R3: Expose loop data to the graph
- Add optional loop snapshot.
- Add optional activity stream.
- Keep existing `PodGraph` fields stable.
### R4: Show the observatory
- Render observe/store/predict/outcome/adapt.
- Show recent activity.
- Make selected-node detail explain why memory changed.
### R5: Prepare a clean demo chain
- Ensure one collision -> intervention -> accepted outcome exists.
- Ensure repeated signature recalls prior memory.
- Verify graph shows learned ownership.
## Nice-to-Have
- Atlas Vector Search over memory summaries.
- Confidence scoring per ownership edge.
- Per-file memory timeline.
- Strategy promotion tied to outcomes.
## Cut
- Raw screenshot storage.
- Full autonomous training.
- Broad dashboard metrics.
- Multi-pod learning generalization.
## Acceptance Criteria
- A judge can see what changed in memory.
- The second similar event behaves differently.
- Exact MongoDB records prove the loop.
- The graph remains legible with real data.
+97
View File
@@ -0,0 +1,97 @@
# Continual Learning Policy
Status: draft
Scope: what PodMan may learn about a team
## Prime Rule
PodMan learns coordination patterns, not personal surveillance profiles.
## Allowed Memory
PodMan may store:
- File and symbol ownership.
- Active file overlap.
- Repeated collision signatures.
- Intervention history.
- Accepted and dismissed outcomes.
- Routing preferences by event type and severity.
- Summaries of decisions relevant to future coordination.
## Forbidden Memory
PodMan must not store:
- Raw screenshots.
- Screen recordings.
- Secrets or credentials.
- Full terminal logs.
- Personal performance judgments.
- Private content unrelated to the coding task.
## Evidence Policy
| Evidence | Can predict? | Can adapt memory? |
| --- | --- | --- |
| Vision only | Yes, low confidence | No |
| Git watcher | Yes | No, unless repeated |
| GitHub state | Yes | No, unless verified |
| Accepted real outcome | Yes | Yes |
| Dismissed outcome | Yes, for suppression | Yes, as negative signal |
| Verifier result | Yes | Yes |
## Intervention Policy
Use the least intrusive channel:
1. Watch quietly.
2. Card.
3. Hermes message.
4. Voice.
Voice is only for urgent, high-confidence, time-sensitive risks.
## Adaptation Policy
Allowed adaptations:
- Add learned ownership after accepted real outcome.
- Raise confidence for repeated accepted signatures.
- Lower confidence for dismissed signatures.
- Prefer the previously accepted intervention kind.
- Suppress repeated low-value warnings.
Disallowed adaptations:
- Broad threshold changes from one example.
- Treating vector similarity as proof.
- Hiding dismissals.
- Making interruption more aggressive without evidence.
## Retention Policy
Keep:
- Outcomes.
- Signatures.
- Team model memory.
- Strategy metrics.
Summarize or expire:
- Old observations.
- Low-confidence vision-only events.
- Detailed trace text.
Delete immediately:
- Secrets.
- Accidental raw sensitive captures.
## Demo Policy
Seeded data is acceptable only if the demo script is honest about it. Live
learning requires a live or staged outcome write that visibly updates the graph
or future decision.
+87
View File
@@ -0,0 +1,87 @@
# Continual Learning Prompt
Use this prompt for the agent that decides what PodMan should remember from a
coordination event.
## Prompt
You are PodMan's continual-learning memory agent.
Your job is to inspect observations, collisions, interventions, and outcomes,
then decide what team memory should be updated. You must separate observed
facts, inferred risks, human outcomes, and durable learned memory.
Do not claim something was learned unless an accepted real outcome, verifier, or
human label supports it.
## Inputs
- Pod id.
- Recent engineer states.
- Recent observations.
- Candidate collision.
- Prior exact-signature memory.
- Intervention record.
- Outcome record.
- Current team model.
## Procedure
1. Normalize file and symbol.
2. Build exact signature.
3. Check prior accepted and dismissed outcomes.
4. Classify the current event.
5. Decide whether memory should change.
6. Emit the graph impact.
7. Write a short explanation.
## Output Format
```text
Event
- Signature:
- Engineers:
- File:
- Symbol:
- Evidence:
Prior Memory
- Accepted matches:
- Dismissed matches:
- Ownership:
Decision
- Memory action:
- Confidence:
- Reason:
Graph Impact
- Nodes:
- Edges:
- Activity text:
Safety
- Sensitive data present:
- Redaction needed:
```
## Memory Actions
Allowed actions:
- no_change
- strengthen_signature
- weaken_signature
- create_learned_owner
- update_route_preference
- suppress_signature
- request_human_label
## Hard Rules
- Exact recall before vector recall.
- Dismissals are learning signals.
- `learned_from` requires accepted real outcome.
- Store summaries, not raw screen content.
- Prefer less intrusive future behavior when uncertain.
+217
View File
@@ -0,0 +1,217 @@
# Continual Learning Spec
Status: draft
Scope: how PodMan learns team memory from live work and outcomes
Owner: continual learning / Team memory
## Purpose
Continual learning is the product proof that PodMan gets more useful from use.
It learns team-level coordination memory: ownership, repeated collisions,
accepted interventions, dismissed noise, and preferred routing.
The visible loop:
```text
observe -> store -> predict -> outcome -> adapt
```
## Source Collections
### `engineer_states`
Latest per-engineer state from vision and local git.
Key fields:
- `podId`
- `name`
- `currentFile`
- `changedFiles`
- `branch`
- `confidence`
- `visionUpdatedAt`
- `gitUpdatedAt`
- `updatedAt`
### `observations`
Structured perception events.
Key fields:
- `podId`
- `engineerId`
- `currentFile`
- `symbol`
- `activity`
- `confidence`
- `observedAt`
### `collisions`
Predicted risk events.
Key fields:
- `id`
- `podId`
- `file`
- `symbol`
- `engineers`
- `severity`
- `status`
- `memorySignature`
- `detectedAt`
### `interventions`
Actions PodMan sent or suggested.
Key fields:
- `id`
- `podId`
- `collisionId`
- `kind`
- `channel`
- `message`
- `suggestedAction`
- `createdAt`
### `outcomes`
Human or verifier supervision.
Key fields:
- `id`
- `podId`
- `interventionId`
- `collisionId`
- `accepted`
- `wasRealCollision`
- `learnedOwner`
- `recordedAt`
### `team_model`
Durable pod memory.
Key fields:
- `podId`
- `graph`
- `ownership`
- `collisionSignatures`
- `interventionPolicy`
- `updatedAt`
### `memory_vectors`
Optional semantic recall. Exact recall comes first.
Key fields:
- `podId`
- `sourceKind`
- `sourceId`
- `text`
- `embedding`
- `embeddingModel`
- `tags`
## Learning Rules
### Observe
Write structured evidence from vision, git, GitHub, and agent traces.
### Store
Persist source records and materialized summaries. Do not store raw screenshots
or recordings.
### Predict
Create a collision when multiple engineers converge on the same normalized file
or symbol and at least one signal shows active or unpushed work.
### Outcome
Record whether the intervention was accepted, dismissed, real, or false.
### Adapt
Only accepted real outcomes can create `learned_from` graph edges. Dismissals
adapt suppression, routing, or confidence.
## Exact Signature
Use deterministic signatures:
```text
podId:eventType:normalizedFile:symbol:sortedEngineers
```
Rules:
- Sort engineer names.
- Normalize file paths.
- Use `*` for missing symbol.
- Never include timestamps.
## UI-Facing Loop Snapshot
The graph response may include:
```text
loop
activeStep
steps[]
key
label
value
detail
status
```
Step mapping:
| Step | Source |
| --- | --- |
| Observe | recent observations and git updates |
| Store | team model, graph records, memory vectors |
| Predict | open collisions |
| Outcome | accepted and dismissed outcomes |
| Adapt | learned owners, learned edges, strategy changes |
## Activity Stream
The graph response may include:
```text
activity[]
id
at
kind
title
detail
nodeId
edgeId
```
Allowed `kind` values:
```text
editing, collision, intervention, outcome, learned, agent
```
## Acceptance Criteria
- The system can show one accepted outcome changing future memory.
- Exact recall works without vector search.
- The Team memory graph can explain the learning loop.
- Dismissals and false positives are retained.
- The demo does not rely on raw screenshots or hidden state.
+108
View File
@@ -0,0 +1,108 @@
# Demo Setup
Pre-stage checklist for the 3-minute live demo. Do this on all 3 laptops before walking on stage.
---
## Before demo day
- [ ] `demo-pod` room created in LiveKit Cloud dashboard
- [ ] Hermes deployed on DO (or confirmed running locally as fallback)
- [ ] MongoDB Atlas cluster running, `MONGODB_URI` set in Hermes env
- [ ] All `.env` vars populated and verified via `GET /health` returning `{ ok: true }`
- [ ] Record a backup video of the full demo working end-to-end
- [ ] Rehearse the demo script 3× with real audio
---
## Laptop setup (all 3 machines)
### Editor settings
- Font size: **18pt or larger** — Gemini Vision must read file names and code
- Single editor window — no split panes, no overlapping terminals
- File tab visible with full file name shown (not truncated)
- Light or dark theme is fine — avoid low-contrast themes
### Browser
- Chrome (best `getDisplayMedia` support)
- PWA tab open and joined to `demo-pod`
- Earbuds / headphones plugged in and tested
- Volume: medium — PodMan voice should be clearly audible but not startle
### Screen layout
- Editor takes 2/3 of screen
- Terminal takes bottom 1/3 (always visible)
- No other windows on top
---
## Demo file setup
Pre-create these files in the demo repo before the demo:
**Alice's machine:**
- Open `auth/middleware.ts` — has visible function stubs
- Terminal shows nothing running initially, then `Server running on :3001` at the right moment
**Bob's machine:**
- Open `frontend/login.tsx` — has visible form component code
- Terminal idle
**Carol's machine:**
- Open `frontend/integration.ts` or similar
- Terminal shows: `curl http://localhost:3001/auth``curl: (7) Failed to connect`
---
## Demo script timing
| Time | Action | Who |
| ----- | ----------------------------------------------- | ----------- |
| 0:00 | All three join `demo-pod` | All |
| 0:05 | PodMan greets by voice | Hermes auto |
| 0:20 | Alice opens `auth/middleware.ts`, starts typing | Alice |
| 0:45 | Bob opens `frontend/login.tsx` | Bob |
| 0:50 | Carol runs `curl` command, sees error | Carol |
| ~1:20 | BLOCKER_DETECTED nudge fires | Hermes auto |
| 1:50 | Alice starts her server (`node server.js`) | Alice |
| ~2:00 | DEPENDENCY_READY nudge fires | Hermes auto |
| 2:20 | Optional: show session 2 ownership warm-start | Presenter |
| 2:45 | Close | Presenter |
---
## Gemini Vision reliability tips
- Keep font at 18pt+ throughout the demo — do not zoom out
- Avoid opening file picker dialogs or overlapping modals during the demo
- File names in editor tabs must be fully visible (not `auth/middle...`)
- If Hermes logs show `confidence < 0.6` frames: bump font size, ensure file tab is clear
- Terminal output must be on a single line — avoid long stack traces during demo
---
## Cooldown note
Hermes has a 3-minute cooldown between nudges per pod. For the demo, if you need to trigger a second event quickly:
Option 1: restart Hermes between the two demo scenarios (resets cooldown state)
Option 2: set `NUDGE_COOLDOWN_MS=0` via env var during demo (add this override to Hermes)
---
## Fallback plan
If any system fails on stage:
1. **Hermes unreachable:** switch to local (`pnpm --filter backend dev`) — PWA auto-falls back to `localhost:8787`
2. **Gemini Vision low confidence:** presenter narrates what PodMan "saw" while playing the backup video
3. **LiveKit audio not working:** play backup video — show the nudge text cards on screen instead
4. **Full system failure:** play the backup recording, narrate the demo live
Always have the backup video on a separate device, not the same laptop running Hermes.
-141
View File
@@ -1,141 +0,0 @@
# PodMan — 4-Minute Demo Script
**Theme:** Continual Learning. **Hard limit:** 4:00. Practice to land at 3:45.
**The one-line story:** writing code isn't the bottleneck anymore — *coordinating
who's writing what* is. PodMan is a pair programmer for the whole team: it watches
every member's work in real time, gives everyone live status without anyone having
to interrupt anyone, and learns your team's dynamics so it nudges less and helps
more over time.
**The hook to land:** a "quick five-minute question" actually costs ~25 minutes of
lost focus — for two people. PodMan removes the reason to ask. Multiply the saved
recovery time across every teammate, every day, and that is the value.
---
## The script (4:00)
### 0:000:30 — The problem + hook
> "AI made writing code easy. The thing still slowing teams down is coordination
> — checking each other's work, re-planning collisions, and the constant 'what
> are you working on?' A five-minute question really costs both people 25 minutes
> of lost focus. PodMan is a pair programmer for the whole team: it watches
> everyone's work live, so anyone can see another's status without interrupting
> them — and it learns your team as it goes."
*On screen:* the pod view, two teammates joined, screen-share tiles live.
### 0:301:05 — Real-time team awareness (LiveKit + Gemini Vision)
- Point at the two live screen tiles. "These are real screen shares over
**LiveKit**. Our agent subscribes to the tracks and samples frames."
- "Each frame goes to **Gemini Vision**, which returns structured context — file,
symbol, activity — not a chatbot, a perception layer."
- Show the live activity stream filling in (Signals vs Reasoning sections).
- Land the value: "This is the part that replaces 'what are you working on?' —
every teammate's current work is just *visible*, in real time. Nobody had to
ask."
*Built-by-us callout:* `backend/src/vision/gemini.ts`, the LiveKit agent worker.
### 1:051:50 — The catch (detection + first intervention)
- Have alice and bob both edit the **same file** with unpushed changes.
- "Normally nobody notices until merge time. GitHub can't see this — nothing's
pushed. Our detector fuses live screen context with **local git truth** from a
watcher on each laptop."
- A collision card appears: *"alice + bob both on detector.ts (unpushed)."*
- Let the **Gemini TTS** urgent voice fire once over LiveKit: *"alice and bob are
both editing detector.ts. Please sync before pushing."*
- Land the value: "That's a merge conflict and a wasted afternoon caught before it
happened — and neither of them had to be tracking the other."
*Built-by-us callout:* `collision/detector.ts`, `action/hermes.ts`,
`voice/live.ts`.
### 1:502:50 — Continual learning (the theme — the money shot)
This is the differentiator. Two beats, both from pre-seeded memory:
1. **It learned to stay quiet.** Trigger a pattern that was dismissed as a false
alarm earlier. "Last session a teammate marked this kind of alert as not a
real conflict. Watch — PodMan stays silent. No nagging." (No card fires.)
2. **It learned to escalate.** Trigger the real-conflict pattern that was
accepted before. The card now says **"Seen before."** and goes straight to
the spoken urgent cue.
- "The only input was one accept/dismiss tap. No retraining, no labeling. This is
**MongoDB Atlas vector search** recalling similar past events plus a policy
that adapts on the recalled outcome."
- Optional: show `/api/memory/stats` counts climbing — accumulated experience.
*Built-by-us callout:* `memory/vectors.ts` ($vectorSearch), `memory/policy.ts`
(outcome-conditioned gate), `memory/store.ts`.
### 2:503:30 — The five-minute meeting, killed (Gemini Live API)
- Frame it: "Instead of breaking a teammate's focus to ask what they're up to,
you ask PodMan."
- Open the live voice conversation. Ask out loud: *"PodMan, what is everyone
working on, and where is the collision detector implemented?"*
- It answers with **real tool calls**`search_repo`, git history, current
collisions — not guesses.
- "This is the **Gemini Live API**, streaming speech-to-speech over LiveKit, with
custom function tools we wrote so it grounds every answer in the actual repo
and live state. That's the status sync, answered in seconds, with zero recovery
tax on anyone else."
*Built-by-us callout:* `agents/podman-live-conversation/agent.py`.
### 3:303:50 — Stack + close
- "All on **DigitalOcean** — static frontend, API, and agent workers, supervised
by systemd. The ambient score is **Gemini Lyria** generated per pod through the
Interactions API."
- Close: "Engineering ability stopped being the bottleneck — coordination is.
PodMan gives a whole team real-time awareness without the interruptions, catches
collisions before they cost an afternoon, and learns each team's dynamics so it
helps more over time. Saved focus, multiplied across every teammate. That's
continual learning, shipped."
### 3:504:00 — Buffer / Q&A handoff
---
## Sponsor-prize coverage (say each at least once)
| Prize | Spoken moment | Segment |
| --- | --- | --- |
| **Gemini** | Vision perception, Live API agent w/ tools, TTS voice, Lyria score | 0:30, 1:05, 2:50, 3:30 |
| **LiveKit** | "real screen shares over LiveKit", agent subscribes, TTS audio track, live voice | 0:30, 1:05, 3:30 |
| **MongoDB** | "Atlas vector search recalling past events" | 1:50 |
| **DigitalOcean** | "all on DigitalOcean, systemd-supervised workers" | 3:30 |
---
## If something breaks (live recovery)
| Failure | Recovery |
| --- | --- |
| Voice doesn't fire | Cut to the card; say the line aloud; cards are the default path anyway. |
| Live conversation drops | Skip 2:503:30; lean longer on the learning beat. |
| Collision won't trigger | Use the backup recording for that beat; keep narrating. |
| Agent flapping | Pre-checked — but if so, `systemctl restart podman-platform-agent`. |
**Rule:** never debug on stage. Narrate, fall back to recording, keep moving.
---
## Tight timing summary
| Time | Beat |
| --- | --- |
| 0:00 | Problem (coordination cost) + hook + original-work line |
| 0:30 | Real-time team awareness — LiveKit + Gemini Vision |
| 1:05 | The catch — collision caught before merge |
| 1:50 | **Continual learning — quiet + escalate** |
| 2:50 | The five-minute meeting, killed — Gemini Live conversation |
| 3:30 | DigitalOcean + Lyria + close |
| 3:50 | Buffer |
+4 -18
View File
@@ -58,13 +58,6 @@ The mirror at `infra/.do/app.yaml` is kept identical for DO UI/import workflows.
- No HTTP route and no HTTP health check
- Default room: `POD_ROOM=demo-pod`
### Worker: live conversation agent (Python)
- Source: `agents/podman-live-conversation/`
- The Gemini Live voice agent (`gemini-3.1-flash-live-preview`), run with `uv`.
- On the droplet it runs as `podman-live-conversation-agent.service`
(`infra/systemd/`). It is separate from the Node services and the TS agent.
---
## Required Runtime Environment
@@ -73,15 +66,10 @@ The mirror at `infra/.do/app.yaml` is kept identical for DO UI/import workflows.
LIVEKIT_URL=wss://your-livekit-server.livekit.cloud
LIVEKIT_API_KEY=...
LIVEKIT_API_SECRET=...
LIVEKIT_CONVERSATION_AGENT_NAME=podman-live-conversation
GEMINI_API_KEY=... # GOOGLE_API_KEY also accepted
GEMINI_API_KEY=...
GEMINI_VISION_MODEL=gemini-2.0-flash
GEMINI_LIVE_MODEL=gemini-3.1-flash-tts-preview # TTS voice
GEMINI_CONVERSATION_MODEL=gemini-3.1-flash-live-preview
GEMINI_EMBEDDING_MODEL=gemini-embedding-001
GEMINI_TTS_VOICE=Charon
# GEMINI_MUSIC_MODEL=lyria-3-clip-preview # optional override
GEMINI_LIVE_MODEL=gemini-3.1-flash-tts-preview
GITHUB_TOKEN=...
GITHUB_REPO=karti-ai/podman
@@ -94,10 +82,8 @@ PORT=8787
POD_ROOM=demo-pod
```
`VOYAGE_API_KEY` is optional. Without it, Gemini embeddings provide vector
recall; without any embedding provider, recall degrades to exact signature
matching. The Lyria background score uses the Gemini Interactions API and the
same `GEMINI_API_KEY`.
`VOYAGE_API_KEY` is optional for local/demo fallback. Without it, Mongo exact
signature recall still works; Atlas Vector Search recall is skipped.
---
+96 -77
View File
@@ -1,118 +1,137 @@
# Gemini Integration Spec
Status: active / matches code.
PodMan uses Gemini for five jobs, all through the `@google/genai` SDK
(`GoogleGenAI`) with a single `GEMINI_API_KEY` (`GOOGLE_API_KEY` /
`GOOGLE_GENERATIVE_AI_API_KEY` also accepted):
1. **Vision** — turn screen frames into structured work context.
2. **Embeddings** — vector recall over past coordination events.
3. **TTS voice** — spoken urgent escalations over LiveKit.
4. **Live conversation** — a real-time voice agent teammates talk to.
5. **GenMedia (Lyria)** — a per-pod background score.
Collision detection and intervention text are **deterministic in code**, not
Gemini calls. PodMan does not ask Gemini "is this a conflict?" — that is decided
by `backend/src/collision/detector.ts` from fused vision + git truth. This is a
deliberate reliability choice for the live demo.
PodMan uses Gemini for two distinct jobs: **vision** (understanding screens) and **voice** (speaking nudges).
---
## 1. Vision — screen understanding
## 1. Vision — Screen Understanding
**Model:** `GEMINI_VISION_MODEL` (default `gemini-2.0-flash`)
**Code:** `backend/src/vision/gemini.ts``analyzeFrame()`
**Model:** `gemini-2.0-flash` (fast, cheap, strong multimodal)
**Trigger:** the LiveKit agent samples a JPEG frame from each engineer's
screen-share track (not an HTTP upload — frames arrive over LiveKit).
**Trigger:** every 30s per active engineer, when Hermes receives a `POST /ingest` frame
**Input:** a single base64 JPEG, sampled at low media resolution.
**Input:** base64-encoded JPEG, max 1280×720, ~5080KB after compression
**Output:** structured JSON via `responseJsonSchema` (no markdown parsing):
**Prompt:**
```
You are analyzing a software engineer's screen during a coding session.
Extract the following JSON. If you cannot determine a field with confidence above 0.7, set it to null.
```ts
{
currentFile: string, // open file path, e.g. src/auth/session.ts
currentSymbol: string, // function/class under the cursor
activity: string, // editing | reading | debugging | terminal | PR review
hasUnpushedChanges: boolean, // dirty git gutter / modified markers visible
confidence: number // 0..1
"currentFile": "string | null", // active file visible in editor tab or title bar
"inferredTask": "string | null", // 1 sentence: what the engineer appears to be doing
"terminalVisible": true | false, // is a terminal or CLI panel visible
"recentTerminalOutput": "string | null", // last meaningful line of terminal output if visible
"confidence": 0.01.0 // your overall confidence in this extraction
}
Respond with valid JSON only. No explanation. No markdown.
```
**Latency/cost levers (in code):**
**Confidence gate:** if `confidence < 0.6`, Hermes discards the frame — no state update, no event detection triggered.
- `thinkingConfig: { thinkingBudget: 0 }` — minimal thinking for the ambient loop.
- `mediaResolution: MEDIA_RESOLUTION_LOW` — smaller image tokens.
- Missing `confidence` defaults to `0.5`.
**Rate limit:** 1 call per engineer per 30s. With 3 engineers = 6 calls/min ≈ $0.002/min at Flash pricing.
**Demo reliability:** large editor font, single window, visible file tab. This is
the primary lever for clean reads.
**Demo setup requirement:** editors must have large font (18pt+), single window, file name clearly visible in tab. This is the primary reliability lever.
---
## 2. Embeddings — semantic recall
## 2. Event Detection — Coordination Awareness
**Model:** `GEMINI_EMBEDDING_MODEL` (default `gemini-embedding-001`, 768 dims)
**Code:** `backend/src/memory/vectors.ts`
**Model:** `gemini-2.0-flash` (text only, fast)
Each collision is embedded into a short memory text (`file`, `symbol`,
`engineers`, `severity`, unpushed flag) and stored on the `collisions` document.
On a new collision PodMan embeds the query and runs MongoDB Atlas `$vectorSearch`
(index `collision_embedding`) to recall similar past events and their outcomes.
**Trigger:** after every successful state write to MongoDB, Hermes runs event detection over all active engineer contexts.
**Provider order:** Voyage (`VOYAGE_API_KEY`, `voyage-4-lite`) is tried first when
present; Gemini embeddings are the fallback. Without either, recall degrades to
exact signature/file matching — the demo still works.
**Input:** JSON snapshot of all engineers' current states + ownership map
**Prompt:**
```
You are a team coordination agent. Below is the current state of each engineer on the team.
Engineer states:
{{engineerStates}}
Ownership map (who owns which files):
{{ownershipMap}}
Detect if any of these coordination events are occurring:
- DEPENDENCY_READY: an engineer who was blocked or waiting now has what they need because another engineer completed relevant work
- BLOCKER_DETECTED: an engineer appears stuck (same file, error in terminal, no progress) and another teammate could help
- DUPLICATE_WORK: two or more engineers are working on the same file simultaneously
If an event is detected, respond with:
{
"event": "DEPENDENCY_READY" | "BLOCKER_DETECTED" | "DUPLICATE_WORK" | null,
"involvedEngineers": ["engineerId", ...],
"file": "string | null",
"reason": "1 sentence explanation"
}
If no event, respond with { "event": null }.
Respond with valid JSON only.
```
---
## 3. TTS voice — urgent escalation over LiveKit
## 3. Nudge Generation — Voice Message
**Model:** `GEMINI_LIVE_MODEL` (default `gemini-3.1-flash-tts-preview`)
**Default voice:** `GEMINI_TTS_VOICE` (default `Charon`)
**Code:** `backend/src/voice/live.ts``speak()` / `speakInRoom()`
**Model:** `gemini-2.0-flash` (text only)
Flow: a short, natural voice line is generated for a critical collision, returned
as audio, and published as a LiveKit microphone-source audio track. The track is
held for the audio duration plus tail/hold so browsers do not cut playout short.
Browser audio must be unlocked by a user gesture first. The frontend always
renders the `VOICE_CUE` text as a fallback. See `docs/livekit.md` for delivery.
**Trigger:** when event detection returns a non-null event
**Input:** event type + engineer names + file + reason
**Prompt:**
```
You are PodMan, a friendly AI teammate. Generate a short spoken message (12 sentences max) to notify the team about this coordination event.
Event: {{eventType}}
Engineers involved: {{engineerNames}}
File: {{file}}
Context: {{reason}}
Rules:
- Use first names only
- Be direct and specific
- Do not use filler words
- Sound natural when spoken aloud
- Do not start with "Hey" or "Attention"
Respond with the message text only.
```
**Example output:**
> "Carol — Alice just got the auth endpoint running. You're clear to integrate."
---
## 4. Live conversation — real-time voice agent
## 4. Voice Output — Gemini TTS via LiveKit
**Model:** `GEMINI_CONVERSATION_MODEL` (default `gemini-3.1-flash-live-preview`)
**Code:** `agents/podman-live-conversation/agent.py` (Python LiveKit Agents,
`google.realtime.RealtimeModel`)
**Model:** `gemini-3.1-flash-tts-preview`
A teammate can start a live, streaming speech-to-speech session with PodMan. The
agent answers using **function tools** rather than guessing, including:
**Integration:** Hermes generates Gemini TTS audio and publishes it as a LiveKit audio track. The code still preserves a Gemini Live path for future available Live models.
- `get_active_pod_context`, `get_recent_changes`, `search_team_memory`
- `search_repo`, `repo_recent_commits`, `repo_find_commits` (repo + git history)
- `record_conversation_note`
- `delegate_to_hermes`, `abort_active_hermes_job` (hands work to the async Hermes
job runner — see `docs/hermes.md`)
**Flow:**
Started/stopped via `POST /api/pods/:id/live-conversation/start` and `.../stop`.
1. Nudge message text generated (step 3)
2. Hermes passes text to Gemini Live via LiveKit Agents
3. Gemini Live streams audio back in real-time
4. LiveKit publishes audio into the pod room
5. All participants hear it through their audio output
---
**Why Gemini Live (not plain TTS):**
## 5. GenMedia — Lyria background score
**Model:** `lyria-3-clip-preview` (override with `GEMINI_MUSIC_MODEL`)
**Endpoint:** Gemini **Interactions API** (`/v1beta/interactions`)
**Code:** `backend/src/voice/music.ts`
A pod-specific ~30s clip is generated through the Interactions API, cached in
MongoDB, and served via `GET /api/pods/:id/music` to play as ambient room audio.
- Streams audio directly — no intermediate WAV file conversion
- Latency ~300500ms from text to first audio packet
- Natural-sounding voice
- Strong prize story: Gemini Live 2.5 is the headline model
---
## Cooldown
Per-pod cooldown (`NUDGE_COOLDOWN_MS`, default 180000 ms / 3 min) gates repeated
interventions. Implemented in `backend/src/memory/policy.ts`, not in Gemini.
Per-pod cooldown of **3 minutes** between nudges. Prevents spam if multiple events fire simultaneously. Implemented in Hermes, not in Gemini.
+69
View File
@@ -0,0 +1,69 @@
# Graph Discovery Plan
Status: draft
Goal: make MongoDB graph discovery visible as a dynamic learning observatory
## Must-Have
1. Keep live materializer as source of graph truth.
2. Add optional loop and activity fields.
3. Build a dynamic graph layout.
4. Default to risk path.
5. Make selected-node detail explain the story.
## Build Order
### R1: Stabilize discovered graph
- Keep file and engineer noise filters.
- Keep collision collapse.
- Keep priority for accepted-outcome paths.
- Keep graph size capped.
### R2: Add observatory data
- Compute learning-loop snapshot.
- Compute activity stream.
- Preserve current graph contract.
### R3: Improve path selection
- Pick one primary risk path.
- Include learned path when present.
- Dim unrelated collisions and repeated interventions.
### R4: Render dynamically
- Use `d3-force` or animated layered layout.
- Make nodes draggable.
- Curve or bundle edges.
- Animate `learned_from`.
### R5: Verify with real data
- Fetch live `demo-pod` graph.
- Confirm labels do not collide badly.
- Confirm red edges do not dominate.
- Confirm activity and loop explain the graph.
## Nice-to-Have
- Reachability panel using `$graphLookup`.
- Hover path previews.
- Edge bundling by file or collision.
- Time scrubber for graph snapshots.
## Cut
- Generic analytics dashboard.
- Large graph database migration.
- Rendering every historical event.
- Static fixed-column final layout.
## Acceptance Criteria
- Risk path is obvious in 10 seconds.
- Learned path is visible when data exists.
- Whole graph mode exists but is not the default.
- The graph remains backed by MongoDB, not hardcoded mock data.
+83
View File
@@ -0,0 +1,83 @@
# Graph Discovery Policy
Status: draft
Scope: graph hygiene, evidence thresholds, and UI truthfulness
## Prime Rule
The graph must be sparse enough to explain the learning loop and truthful enough
to audit from MongoDB.
## Node Policy
Create nodes only when they add explanation value.
Allowed:
- Current engineers.
- Real files.
- Current or recent collisions.
- Interventions tied to surviving collisions.
- Learned ownership paths.
Avoid:
- Test engineers.
- Scratch files.
- URLs or environment values misread as files.
- Repeated identical intervention diamonds.
- Orphan nodes with no story value.
## Edge Policy
Edges need evidence.
| Edge | Required evidence |
| --- | --- |
| `editing` | observation or git state |
| `touches` | file involved in collision |
| `collides` | collision prediction |
| `warns` | intervention record |
| `learned_from` | accepted real outcome |
| `owns` | learned or configured ownership |
## De-Hairball Policy
Default mode must not show every relationship equally.
Rules:
- Default to risk path.
- Collapse repeated collision signatures.
- Cap files and collisions.
- Dim non-risk edges.
- Bundle or curve dense edges.
- Hide low-priority labels until hover or select.
- Prefer selected-node explanation over labels everywhere.
## Truthfulness Policy
- Do not show `learned_from` for orphaned or dismissed outcomes.
- Do not label vector similarity as learned memory.
- Do not show demo seed as live learning unless labeled.
- Do not hide false positives from activity or memory.
## Privacy Policy
Graph labels should not expose secrets, raw terminal output, or sensitive file
contents. File paths are acceptable when they are repo paths and not secret
values.
## Visual Policy
Semantic colors stay stable:
- Engineer: blue.
- File: slate.
- Feature: amber.
- Collision: red.
- Intervention: violet.
- Learned: violet dashed edge.
Chrome should use the app's light shadcn tokens.
+81
View File
@@ -0,0 +1,81 @@
# Graph Discovery Prompt
Use this prompt for an agent that materializes or reviews PodMan's Team memory
graph.
## Prompt
You are PodMan's graph discovery agent.
Your job is to turn MongoDB records into a sparse, truthful graph that explains
the continual-learning loop. Do not maximize node count. Maximize legibility and
evidence.
The default output should show the risk path and learned path, not every
possible edge.
## Inputs
- Pod id.
- Pod roster.
- Recent engineer states.
- Recent observations.
- Collisions.
- Interventions.
- Outcomes.
- Team model.
- Existing graph nodes and edges.
## Procedure
1. Normalize file paths.
2. Remove noise.
3. Create engineer and file nodes.
4. Collapse repeated collisions by signature.
5. Preserve accepted-outcome paths.
6. Create intervention nodes for surviving collisions.
7. Create learned edges only from accepted real outcomes.
8. Select the primary risk path.
9. Build activity and loop summaries.
10. Explain selected-node stories.
## Output Format
```text
Graph Summary
- Pod:
- Nodes:
- Edges:
- Primary risk path:
- Learned path:
Discovery Decisions
- Collapsed:
- Dropped as noise:
- Preserved because learned:
Loop
- Observe:
- Store:
- Predict:
- Outcome:
- Adapt:
Activity
- Recent events:
Risks
- Missing evidence:
- Potential hairball:
- Demo caveat:
```
## Hard Rules
- No `learned_from` without accepted real outcome.
- No raw screenshots or secrets in labels.
- Do not rewrite the backend materializer unless explicitly asked.
- Prefer additive graph fields.
- Default to risk path.
- Keep whole graph optional.
+146
View File
@@ -0,0 +1,146 @@
# Graph Discovery Spec
Status: draft
Scope: how PodMan discovers graph nodes, edges, risk paths, and learning paths from MongoDB
Owner: graph discovery / Team memory observatory
## Purpose
Graph discovery turns MongoDB memory into a legible Team memory graph. It is not
only layout. It decides which relationships matter, which path is highlighted,
and which evidence explains the graph.
The graph must answer:
1. Who is working?
2. Which files or symbols overlap?
3. Where is the risk?
4. What did PodMan do?
5. What outcome changed memory?
## Source Data
Graph discovery reads:
- `pods`
- `engineer_states`
- `observations`
- `collisions`
- `interventions`
- `outcomes`
- `team_model`
- `graph_nodes`
- `graph_edges`
- optional `memory_vectors`
- optional `agent_runs`
- optional `strategy_versions`
## UI Graph Contract
```text
PodGraph
podId
generatedAt
nodes
edges
metrics
loop?
activity?
```
Node kinds:
```text
engineer, feature, file, collision, intervention
```
Edge kinds:
```text
owns, editing, touches, collides, warns, learned_from
```
## Discovery Rules
### Engineer nodes
Create from pod roster, recent observations, git state, or collision membership.
### File nodes
Create only from normalized real file paths. Reject noise such as URLs, env
values, scratch names, and non-file strings.
### Collision nodes
Create from distinct collision signatures. Collapse repeats. Prioritize
collisions referenced by accepted outcomes.
### Intervention nodes
Create one visible intervention per surviving collision unless whole-graph mode
explicitly expands history.
### Learned paths
Create `learned_from` only when an accepted real outcome links an intervention
to a durable memory update.
## Path Modes
### Risk path
Default mode. Highlight the clearest current chain:
```text
engineer -> file -> collision -> intervention -> learned owner
```
Dim unrelated graph material.
### Learning edges
Highlight `learned_from`, `owns`, and the outcomes that produced them.
### Whole graph
Show all materialized nodes and edges with de-emphasized non-critical edges.
## MongoDB Traversal
Use `graph_edges` for reachability:
```text
source -> target -> next target
```
Primary traversal questions:
- What risks does this engineer reach?
- Which files feed this collision?
- Which intervention came from this collision?
- Which learned owner came from this intervention?
## Metrics
Minimum metrics:
- Learned owners.
- Open risk paths.
- Accept rate.
Optional metrics:
- Observations.
- Interventions.
- Memory vectors.
- Strategy versions.
## Acceptance Criteria
- Default graph is not a hairball.
- Every visible learned edge has outcome evidence.
- Every selected node can explain why it matters.
- Activity stream matches graph events.
- Graph can be rebuilt from MongoDB source records.
+3 -6
View File
@@ -1,9 +1,8 @@
# Continual-Learning Graph Spec
> Owner: graph data + visualization. Status: demo-backed / active.
> Owner: graph data + visualization. Status: demo-backed (live `team_model` reads land later).
> Satisfies the documentation-first gate for the `backend/src/graph/*` and
> `frontend/src/components/GraphView.tsx` files. This file is the canonical
> graph spec.
> `frontend/src/components/GraphView.tsx` files.
## What this is (and is NOT)
@@ -27,9 +26,7 @@ The graph lives in two places, both keyed by `podId`:
{ podId, graph: PodGraph, updatedAt }
```
`GET /api/pods/:podId/graph` returns the live materialized graph first, then
`team_model.graph`, then a labeled demo graph when neither live nor seeded
data exists.
`GET /api/pods/:podId/graph` returns `team_model.graph`, or a demo graph when none exists yet.
2. **Normalized (for traversal):** the same nodes/edges are mirrored into two collections so
the model can be walked with MongoDB `$graphLookup` (the graph-database pattern):
-101
View File
@@ -1,101 +0,0 @@
# Hermes Spec
Status: active / matches code.
"Hermes" is PodMan's **action layer** — the part that turns a detected problem
into something a teammate sees, hears, or gets done. It spans three things:
1. **Interventions** — cards, messages, and urgent voice in the pod room.
2. **Async jobs** — longer tasks delegated from the live conversation agent.
3. **Ops watchdog** — keeps the production services healthy.
The LiveKit identity for the main agent is `podman-hermes`.
---
## 1. Interventions
**Code:** `backend/src/agent/podman.ts`, `backend/src/action/hermes.ts`,
`backend/src/voice/live.ts`.
When the agent detects a collision, it runs the learning loop (recall → policy
gate; see `docs/cont_learning.md`) and then publishes the **least intrusive**
intervention that fits:
- **Card / message** — a data-channel packet on the `podman.intervention` topic
(`publishHermesIntervention` / `publishHermesMessage`). Default path.
- **Urgent voice** — only for `critical` collisions. `speak()` generates Gemini
TTS audio and publishes it as a LiveKit audio track.
Intervention text is short and deterministic (template, not an LLM call):
`Conflict: alice + bob both on detector.ts (unpushed). Seen before.` The spoken
line is phrased for natural TTS prosody. Each intervention is persisted to the
`interventions` collection; the teammate's accept/dismiss returns via
`POST /api/outcome`.
A per-pod cooldown (`NUDGE_COOLDOWN_MS`, default 3 min) and a single-shot
"active conflict" guard prevent repeat nagging; a conflict re-arms once it
resolves.
---
## 2. Async Hermes jobs
**Code:** `backend/src/hermes/jobs.ts`. **Storage:** `hermes_jobs` +
`hermes_job_events` (see `docs/mongodb.md`).
The live conversation agent can hand a longer task to Hermes via its
`delegate_to_hermes` tool. Lifecycle:
```
queued → running → (waiting_for_confirmation) → completed | aborted | failed
```
`createHermesJob()` records the job, emits an `accepted` event, and kicks off
`runHermesJob()` in the background. The runner gathers context and runs scoped,
read-mostly steps based on the prompt and success criteria:
- always: `git status --short --branch`, `git diff --stat`
- if the ask mentions GitHub: a repo reachability check via the GitHub API
- if it mentions Mongo/memory/telemetry: collection counts
- if it mentions build/test/typecheck/broken: `pnpm typecheck`
**Confirmation gate:** if `riskLevel === 'deploy_allowed'` and
`requiresConfirmation`, the job parks at `waiting_for_confirmation` instead of
acting. **Abort:** `abortHermesJob()` signals the runner's `AbortController`.
Every step appends a `hermes_job_event` (redacted + truncated), which is both
stored and published live to the room as a `HERMES_JOB_EVENT` data message from a
short-lived `podman-hermes-job-*` identity. The conversation UI streams these via
`GET /api/.../hermes-job/events/stream`.
**Endpoints:** `POST /api/internal/hermes/jobs`,
`GET /api/internal/hermes/jobs/:jobId`, `.../abort`, `.../events`,
`.../events/stream`, plus the pod-scoped `.../live-conversation/:sessionId/hermes-job`.
---
## 3. Ops watchdog
**Code:** `scripts/hermes-watchdog.mjs`, `scripts/hermes-sync-deploy.mjs`,
`scripts/hermes-notify.mjs`. **Detail:** `docs/digitalocean.md`.
systemd supervises the app processes; Hermes owns the loop around them:
- `pnpm hermes:watchdog` checks systemd services, public routes, `/health`,
`/api/pods`, and `pnpm deploy:doctor`. Failures trigger targeted restarts.
- `podman-hermes-watchdog.timer` runs it every 5 minutes.
- `podman-hermes-sync-deploy.timer` polls `origin/main` every 2 minutes and, on a
clean tree, fast-forwards, builds, publishes `frontend/dist`, restarts
API/agent/Caddy, and runs the strict watchdog.
- Reports go to `/var/log/podman/hermes-watchdog-latest.json`; set
`PODMAN_ALERT_WEBHOOK_URL` to forward failures to Discord/Slack/webhook.
---
## What Hermes is NOT
- Not an autonomous code-writing agent. Job steps are scoped, read-mostly checks;
deploy-level actions require explicit confirmation.
- Not a second collision detector. Detection is deterministic
(`collision/detector.ts`); Hermes only acts on the result.
+93
View File
@@ -0,0 +1,93 @@
# PodMan — Idea
## One-line value prop
PodMan is a real-time AI team coordination agent that watches consented work signals, maintains live project memory, and proactively notifies collaborators when dependencies, blockers, or handoffs emerge — before anyone has to ask.
---
## Problem
Teams working on the same project lose time because progress is fragmented across people, editors, terminals, and half-finished messages. Coordination gaps — a completed endpoint, a resolved blocker, two engineers duplicating work — are discovered too late, causing idle time, broken handoffs, and missed dependencies.
Slack doesn't help. Stand-ups are too slow. GitHub only knows pushed state.
---
## Solution
PodMan is an ambient AI agent that:
1. Watches each engineer's screen via periodic snapshots (consented, browser-native)
2. Extracts structured context using Gemini Vision — current file, inferred task, terminal state
3. Maintains a shared live model of the team in MongoDB Atlas — who is doing what, who owns which files
4. Detects coordination events: dependency ready, blocker detected, duplicate work
5. Speaks proactively into the team's LiveKit room — engineers hear PodMan through their earbuds without leaving their editor
**The AI's job is not to chat. It is to notice what teammates miss and say so, exactly when it matters.**
---
## Target user
Small software teams: hackathon squads, startup engineering teams, student dev teams collaborating in real time on a shared codebase.
---
## Core AI job
- Maintain per-person live context (file, task, terminal)
- Infer shared project state (who owns what, what's blocked, what's ready)
- Detect 3 coordination event types:
- `DEPENDENCY_READY` — engineer A was waiting on work engineer B just completed
- `BLOCKER_DETECTED` — engineer appears stuck; another teammate can unblock
- `DUPLICATE_WORK` — 2+ engineers working on the same file simultaneously
- Generate a 12 sentence proactive voice nudge
- Deliver it into the LiveKit room via Gemini Live 2.5
---
## How it fits the Continual Learning track
PodMan builds an **ownership map** in MongoDB that persists across sessions:
- Session 1: PodMan needs 35 minutes of screen observations to infer who owns what
- Session 2+: PodMan already knows. First nudge fires in under 30 seconds.
The system gets demonstrably more useful the more it is used, with no user configuration required. That is the track definition met exactly.
---
## Architecture (one paragraph)
Each engineer opens a browser PWA on their laptop. The PWA captures a screen frame every 30 seconds via `getDisplayMedia` and POSTs it to Hermes, the server-side orchestrator running on DigitalOcean. Hermes calls Gemini Vision to extract structured context, writes it to MongoDB Atlas, updates the ownership map, and runs event detection across all active engineers. When a coordination event fires, Hermes generates a short spoken message and publishes it as audio into the team's LiveKit room via Gemini Live 2.5. Engineers hear PodMan through their earbuds. No Slack. No tab switching. No interruption to the editor flow.
---
## Demo wow moment
> Alice is building the auth endpoint. Carol is visibly blocked — her terminal shows `connection refused`. PodMan detects the blocker and says aloud: "Carol, looks like you're waiting on auth. Alice is actively building it — hang tight."
>
> Two minutes later, Alice's server starts. PodMan says: "Carol, Bob — Alice just got the auth endpoint running. You're clear to integrate."
>
> Nobody asked. Nobody pinged anyone on Slack. PodMan just knew.
---
## What PodMan is NOT
- Not a chat interface
- Not a dashboard product
- Not raw surveillance — engineers consent by joining the room and sharing their screen
- Not a task manager
- Not a GitHub integration (v1)
---
## Prize alignment
| Prize | How PodMan earns it |
| --------------------- | ----------------------------------------------------------------------------------------------------- |
| Best Gemini 3.5 / 2.5 | Gemini Vision for screen understanding + Gemini Live 2.5 for voice output |
| Best LiveKit | LiveKit is the real-time backbone for room presence and voice delivery — load-bearing, not decorative |
| Best DigitalOcean | Hermes deployed on DigitalOcean App Platform; MongoDB Atlas on DO-adjacent infrastructure |
+57 -57
View File
@@ -1,24 +1,15 @@
# LiveKit Integration Spec
Status: active / matches code.
LiveKit is the real-time backbone for PodMan. It carries the **screen-share
perception input**, the **intervention data channel**, and **all room audio**
(Gemini TTS escalations, the Lyria score, and the live conversation agent). It is
load-bearing, not decorative.
LiveKit is the real-time backbone for PodMan. It handles room presence and voice delivery. It is load-bearing — not decorative.
---
## Room structure
- One LiveKit room per pod: `room = podId`.
- Engineers join as named participants (e.g. `alice`, `bob`).
- PodMan runs **multiple agent identities** in/around a room:
- `podman-hermes` — the main vision + intervention agent (`@livekit/rtc-node`).
- `podman-live-conversation` — the Gemini Live voice agent (Python).
- short-lived `podman-hermes-job-*` publishers for async job events.
- A fixed identity matters: a second `podman-hermes` evicts the first and they
flap, dropping interventions. systemd keeps exactly one alive in production.
- One LiveKit room per project pod: `room = podId`
- Engineers join as named participants (e.g. `alice`, `bob`)
- Hermes joins as `podman-hermes`
- All participants stay connected for the duration of the session
---
@@ -26,79 +17,88 @@ load-bearing, not decorative.
**Joining:**
1. PWA calls `POST /api/token` with `{ podId, identity }` `{ token, url }`.
2. LiveKit client connects with the token.
3. PWA publishes the screen track via `getDisplayMedia`.
4. PWA enables mic for ambient presence (used by the conversation agent).
1. PWA calls `POST /pods/:podId/token` → receives `{ token, url }`
2. LiveKit client connects to the room with the token
3. PWA publishes screen track via `getDisplayMedia`
4. PWA sets mic enabled for ambient presence
**Receiving:**
- Subscribes to remote agent audio tracks (TTS, Lyria, conversation) and attaches
them to a hidden audio sink.
- Browser autoplay restrictions apply: the PWA calls `room.startAudio()` from a
user gesture (`Enable audio`, `Test PodMan voice`, `Share screen`, first room
click).
- Listens on the data channel for cards and `VOICE_CUE` fallback text.
- LiveKit client automatically receives Hermes audio track
- No special subscription needed — LiveKit delivers audio to all participants
- PWA also listens for data channel messages from Hermes for UI card updates
**Data channel listener (PWA):**
```ts
room.on(RoomEvent.DataReceived, (payload, participant) => {
if (!participant?.identity.startsWith('podman-')) return;
const msg = JSON.parse(new TextDecoder().decode(payload));
// msg.type: COLLISION | ACK | GIT_REPORT | VOICE_CUE | HERMES_JOB_EVENT
appendInterventionToFeed(msg);
if (participant?.identity !== 'podman-hermes') return;
const nudge = JSON.parse(new TextDecoder().decode(payload));
// nudge: { type, message, involvedEngineers, file, sentAt }
appendNudgeToFeed(nudge);
});
```
All data messages share the `podman.intervention` topic (`DATA_TOPIC`).
---
## Agent side (`podman-hermes`)
## Hermes side (LiveKit Agent)
**Framework:** `@livekit/rtc-node`. **Code:** `backend/src/agent/podman.ts`,
`backend/src/action/hermes.ts`, `backend/src/voice/live.ts`.
**Framework:** LiveKit Agents (Node.js)
1. Subscribes to engineers' screen-share tracks and samples frames for Gemini
Vision.
2. Detects collisions, gates them through the learning policy, then publishes a
card/message on the data channel.
3. For critical collisions, generates Gemini TTS audio and publishes it as a
microphone-source audio track, held for the audio duration plus a tail/hold
window so subscribers finish playout. Voice publishing logs frame count,
estimated duration, queued playout, and hold time for diagnostics.
**Startup:**
---
1. Hermes mints its own token via the same `createPodToken` function with `identity: 'podman-hermes'`
2. Connects to the configured room as `podman-hermes`
3. Registers as a LiveKit Agent with Gemini Live 2.5 as voice provider
## Live conversation agent (`podman-live-conversation`)
**Voice delivery:**
**Framework:** LiveKit Agents for Python (`AgentSession`, `function_tool`,
`google.realtime.RealtimeModel`). **Code:**
`agents/podman-live-conversation/agent.py`.
1. Nudge message text is ready (from Gemini text generation)
2. Hermes passes text to Gemini Live 2.5 via LiveKit Agents voice pipeline
3. Audio streams into the room in real-time
4. All participants hear it
Joins the pod room on demand (`POST /api/pods/:id/live-conversation/start`),
streams speech-to-speech with Gemini Live, and answers using repo/git/memory
function tools. It can delegate long tasks to the async Hermes job runner and
narrate progress. See `docs/hermes.md`.
**Data channel message (sent alongside audio):**
```ts
const nudge = {
type: 'DEPENDENCY_READY' | 'BLOCKER_DETECTED' | 'DUPLICATE_WORK',
message: string, // the spoken text
involvedEngineers: string[],
file: string | null,
sentAt: string, // ISO timestamp
};
room.localParticipant.publishData(
new TextEncoder().encode(JSON.stringify(nudge)),
{ reliable: true }
);
```
---
## Token endpoint
`POST /api/token` mints room tokens for engineers and agents alike. Grants:
Already implemented at `POST /api/token`.
Hermes uses the same endpoint. Grants:
- `roomJoin: true`
- `canPublish: true` (audio + screen)
- `canPublishData: true` (data channel)
- `canPublish: true` (for audio track)
- `canPublishData: true` (for data channel)
- `canSubscribe: true`
Short-lived job publishers use `canSubscribe: false`.
---
## Gemini voice model
- Model ID: `gemini-3.1-flash-tts-preview`
- Hermes generates Gemini TTS audio and publishes it as a LiveKit audio track.
- The backend keeps a Gemini Live path for future model availability, but the verified deployment path uses TTS.
---
## What LiveKit does NOT do in PodMan
- No video tracks published by agents.
- No mic transcription outside the live conversation agent.
- No custom SFU mixing — standard room behavior is sufficient.
- No video tracks from Hermes
- No mic transcription (not needed for v1)
- No SFU mixing — standard room behavior is sufficient
+114 -161
View File
@@ -1,190 +1,143 @@
# MongoDB Atlas Integration Spec
Status: demo-backed / active
MongoDB Atlas is PodMan's shared memory. It stores live work observations,
collision predictions (with vector embeddings for recall), interventions,
outcomes, latest engineer state, the materialized Team memory graph, and async
Hermes job runs.
See also:
- [`docs/cont_learning.md`](cont_learning.md) for outcome-backed team memory,
graph materialization, and `$graphLookup` traversal.
MongoDB Atlas is PodMan's shared memory. It stores live engineer state, the ownership map that enables continual learning, coordination events, and nudge history.
---
## Current Collections
## Collections
### `engineer_states`
Latest context per engineer. The local git watcher writes git fields; the vision
pipeline may write screen-derived fields. Each writer updates only its own
fields so MongoDB upserts merge cleanly.
Latest context per engineer. Two writers, one collection — vision pipeline upserts vision fields, git watcher script upserts git fields independently. Hermes reads the merged document for event detection.
Key fields:
```ts
{
_id: string, // engineerId (stable across sessions)
podId: string,
name: string, // display name
- `podId`
- `name`
- `currentFile`
- `inferredTask`
- `confidence`
- `changedFiles`
- `diffStat`
- `recentCommit`
- `branch`
- `visionUpdatedAt`
- `gitUpdatedAt`
- `updatedAt`
// --- Vision fields (written by Hermes via POST /ingest) ---
currentFile: string | null, // active file inferred from screen
inferredTask: string | null, // what engineer appears to be doing
terminalVisible: boolean,
recentTerminalOutput: string | null,
confidence: number, // Gemini Vision confidence (01)
visionUpdatedAt: Date,
Primary use: deterministic dirty/unpushed truth for collision detection and
graph discovery.
// --- Git fields (written directly by scripts/podman-agent.mjs) ---
changedFiles: string[], // files with uncommitted changes (git status)
diffStat: string | null, // e.g. "auth/middleware.ts | 24 +++++"
recentCommit: string | null, // most recent commit message
branch: string | null, // current branch name
gitUpdatedAt: Date,
### `observations`
// --- Shared ---
updatedAt: Date // most recent write from either source
}
```
Structured perception events from consented screen context and agent inference.
**Index:** `{ podId: 1, updatedAt: -1 }`
Key fields:
**Two writers, no conflict:** vision upsert uses `$set` on vision fields only; git upsert uses `$set` on git fields only. MongoDB upsert semantics merge them cleanly.
- `podId`
- `engineerId`
- `currentFile`
- `symbol`
- `activity`
- `confidence`
- `observedAt`
Primary use: observe/store proof and active editing edges in the Team memory
graph.
### `collisions`
Predicted coordination risks, with memory enrichment for recall.
Key fields:
- `id`
- `podId`
- `file`
- `symbol`
- `engineers`
- `severity`
- `memorySignature`
- `githubState`
- `detectedAt`
- `memoryText` — short text embedded for recall
- `embedding` — vector (Voyage `voyage-4-lite` or Gemini `gemini-embedding-001`)
- `embeddingProvider``voyage` | `gemini`
Vector index `collision_embedding` (Atlas Vector Search) powers `$vectorSearch`
recall in `backend/src/memory/vectors.ts`. When Atlas vector search is
unavailable, recall falls back to app-side cosine, then exact signature/file
matching.
Primary use: collision cards, vector + signature recall, and graph risk paths.
### `interventions`
Actions PodMan sent or suggested.
Key fields:
- `id`
- `podId`
- `collisionId`
- `kind`
- `message`
- `suggestedAction`
- `status`
- `createdAt`
Primary use: closing the loop from prediction to a visible card, Hermes message,
or urgent voice cue.
### `outcomes`
Human or verifier supervision recorded through `POST /api/outcome`.
Key fields:
- `podId`
- `interventionId`
- `collisionId`
- `accepted`
- `wasRealCollision`
- `recordedAt`
Primary use: accepted and dismissed outcomes drive exact recall, suppression,
and learned graph paths.
### `team_model`
Durable per-pod summary memory.
Key fields:
- `podId`
- `ownership`
- `hotspots`
- `graph`
- `updatedAt`
Primary use: stable Team memory, including seeded `graph` snapshots used after
live materialization and before demo fallback.
### `graph_nodes` and `graph_edges`
Normalized mirror of the Team memory graph for MongoDB traversal.
Indexes:
- `graph_nodes`: `{ podId: 1, id: 1 }` unique
- `graph_edges`: `{ podId: 1, source: 1 }`
Primary use: `GET /api/pods/:podId/graph/reach/:id` with `$graphLookup`.
### `hermes_jobs` and `hermes_job_events`
Async Hermes task runs delegated from the live conversation agent (see
`docs/hermes.md`).
- `hermes_jobs` — one doc per job (`id` unique; `{ sessionId, status, updatedAt }`
index). Fields: `id`, `podId`, `sessionId`, `prompt`, `contextScope`,
`riskLevel`, `successCriteria`, `status`, `finalSummary`, timestamps.
- `hermes_job_events` — append-only step log (`{ jobId, createdAt }` index):
`accepted`, `heartbeat`, `step_started`, `step_output`, `needs_confirmation`,
`step_completed`, `completed`, `aborted`, `failed`. Output is redacted +
truncated before storage and mirrored to the room over LiveKit.
Primary use: durable, replayable record of what Hermes did, streamed live to the
conversation UI.
**Usage:** Hermes reads all documents for a given `podId` after each update to run event detection. Both vision and git context are available in the same document — `changedFiles` provides ground truth, `currentFile` provides screen context.
---
## Graph Truth Order
### `ownership_map`
`GET /api/pods/:podId/graph` follows this order:
Tracks who works on which files. Built up over the session. **Persists across sessions** — this is the continual learning artifact.
1. Live graph from real collections.
2. Seeded graph from `team_model.graph` and mirrored graph records.
3. Demo fallback graph for stage safety.
```ts
{
_id: string, // `${podId}:${file}`
podId: string,
file: string,
primaryOwner: string, // engineerId with most recent activity on this file
contributors: string[], // all engineerIds observed on this file
observationCount: number, // total frames where this file was seen
lastSeenAt: Date
}
```
Seeded and fallback graphs are acceptable for demos only when labeled honestly.
**Index:** `{ podId: 1, file: 1 }` (unique)
**Upsert logic:**
- On each context update where `currentFile` is non-null:
- Increment `observationCount`
- Update `primaryOwner` to the engineer with the most recent `lastSeenAt` on this file
- Add engineerId to `contributors` if not present
- Update `lastSeenAt`
**Continual learning:** Hermes loads this collection on startup for the pod. If history exists, it pre-populates the in-memory ownership cache before the first frame arrives.
---
## Demo Proof Path
### `events`
Observe screen/git state -> detect collision -> send intervention -> accept or
dismiss outcome -> recall similar event -> show changed graph or changed
behavior.
Every coordination event detected by Hermes.
```ts
{
_id: ObjectId,
podId: string,
type: 'DEPENDENCY_READY' | 'BLOCKER_DETECTED' | 'DUPLICATE_WORK',
involvedEngineers: string[],
file: string | null,
reason: string, // 1-sentence explanation from Gemini
nudgeSent: boolean, // false if suppressed by cooldown
detectedAt: Date
}
```
**Index:** `{ podId: 1, detectedAt: -1 }`
---
## What MongoDB Does Not Store
### `nudges`
- Raw screenshot frames.
- Screen recordings.
- Secrets or credentials.
- Full terminal logs.
- Full Gemini response objects beyond extracted fields needed for memory.
Every voice nudge sent to the room.
```ts
{
_id: ObjectId,
podId: string,
eventId: ObjectId, // ref to events collection
targetEngineers: string[],
message: string, // the spoken text
sentAt: Date
}
```
**Index:** `{ podId: 1, sentAt: -1 }`
**Cooldown check:** before sending a nudge, Hermes queries this collection for any nudge in the last 3 minutes for the same `podId`. If found, suppresses the new nudge and marks the event as `nudgeSent: false`.
---
## Hermes startup sequence
```
1. Connect to Atlas using MONGODB_URI
2. Load ownership_map for this podId
3. Build in-memory cache: Map<file, { primaryOwner, contributors }>
4. Begin accepting /ingest requests
```
---
## Atlas configuration
- **Cluster tier:** M0 (free) is sufficient for hackathon scale
- **Region:** same as DigitalOcean deployment (e.g. NYC1)
- **Auth:** connection string in `MONGODB_URI` env var
- **Collections created automatically** on first write (no schema migration needed)
---
## What MongoDB does NOT store
- Raw screenshot frames (too large — frames are processed in-memory by Hermes and discarded)
- Full Gemini response objects (only extracted fields are stored)
- Session recordings
@@ -0,0 +1,135 @@
---
name: podman-design
description: Full system design for PodMan — real-time AI team coordination agent using Gemini Vision, Gemini Live 2.5, LiveKit, and MongoDB Atlas
metadata:
type: project
---
# PodMan — System Design
## Concept
PodMan is a real-time AI team coordination agent for software teams. Engineers join a LiveKit room with earbuds. Each engineer's browser PWA captures their screen every 30s and sends it to Hermes (server-side orchestrator on DigitalOcean). Hermes uses Gemini Vision to extract structured context per engineer, detects coordination events, and speaks proactive nudges into the room via Gemini Live 2.5 through LiveKit. MongoDB Atlas stores team state and an ownership map that persists across sessions.
**Track:** Continual Learning — the ownership map makes PodMan faster and smarter each session with no user configuration.
---
## Architecture
```
┌──────────────── Engineer laptop (Browser PWA) ──────────────────┐
│ getDisplayMedia → frame every 30s │
│ HTTP POST /ingest → { screenshot, engineerId, podId } │
│ LiveKit room joined → receives voice audio from Hermes │
│ Earbuds: hears PodMan proactive nudges │
└──────────────────────────────────────────────────────────────────┘
│ POST /ingest
┌────────────────── HERMES (DigitalOcean) ─────────────────────────┐
│ 1. Receive frame → Gemini Vision → EngineerContext │
│ 2. Write context to MongoDB (per-user state) │
│ 3. Update ownership map (file → engineer) │
│ 4. Run event detector over all active contexts │
│ 5. If event detected → Gemini generates voice message │
│ 6. Push audio into LiveKit room via Gemini Live 2.5 │
└──────────────────────────────────────────────────────────────────┘
│ read/write
MongoDB Atlas
(engineer_states, ownership_map,
events, nudges)
```
---
## Components
### PWA (local agent)
- Joins LiveKit room via existing `joinPod` flow
- Captures frame every 30s via `getDisplayMedia`, compresses to JPEG (1280×720, quality 0.7)
- POSTs `{ engineerId, podId, screenshotBase64, capturedAt }` to `POST /ingest`
- Receives Hermes audio track (automatic via LiveKit)
- Listens for data channel messages → renders nudge feed
- Two screens: join screen (built), active session screen (to build)
### Hermes (orchestrator)
- Express server + LiveKit Agent on DigitalOcean
- `POST /ingest`: receives frame, queues for vision
- Vision pipeline: Gemini 2.0 Flash → `EngineerContext`
- Confidence gate: discard frames with confidence < 0.6
- State writer: upsert `engineer_states` + `ownership_map` in MongoDB
- Event detector: Gemini text prompt over all active states
- Nudge generator: Gemini text → 12 sentence spoken message
- Voice publisher: Gemini Live 2.5 via LiveKit Agents → audio into room
- Data channel: sends structured nudge payload alongside audio
- Cooldown: 3 min between nudges per pod
### Gemini usage
- **Vision:** `gemini-2.0-flash` — screen → `{ currentFile, inferredTask, terminalVisible, recentTerminalOutput, confidence }`
- **Event detection:** `gemini-2.0-flash` — all engineer states → `{ event, involvedEngineers, file, reason }`
- **Nudge generation:** `gemini-2.0-flash` — event → spoken message text
- **Voice:** `gemini-3.1-flash-tts-preview` via LiveKit audio publication — text → audio
### MongoDB Atlas (4 collections)
- `engineer_states`: latest context per engineer, upserted each ingest
- `ownership_map`: file → primaryOwner + contributors, persists across sessions (continual learning)
- `events`: all detected coordination events
- `nudges`: all voice nudges sent + cooldown history
### LiveKit
- One room per pod
- Engineers publish screen track (used client-side for capture — Hermes does not subscribe)
- Hermes joins as `podman-hermes`, publishes audio + data channel messages
- Engineers receive audio automatically
---
## Event types
| Event | Trigger | Example nudge |
| ------------------ | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `BLOCKER_DETECTED` | Engineer stuck (error in terminal, same file N frames) + teammate can help | "Carol, looks like you're waiting on auth. Alice is actively building it — hang tight." |
| `DEPENDENCY_READY` | Engineer A completes work that Engineer B was waiting on | "Carol, Bob — Alice just got the auth endpoint running. You're clear to integrate." |
| `DUPLICATE_WORK` | 2+ engineers on same file simultaneously | "Alice and Bob — you're both in login.tsx. Coordinate before pushing." |
---
## Continual learning story
The `ownership_map` collection persists across sessions. On Hermes startup:
1. Load ownership map for this pod from Atlas
2. Build in-memory cache: `Map<file, { primaryOwner, contributors }>`
3. Event detection uses priors immediately — no ramp-up phase
**Demo:** Session 1 takes 3 min to first nudge. Session 2 fires in < 30 seconds. That is the learning, visible on stage.
---
## Demo flow (3 min)
1. **(0:00)** Three engineers join pod. PodMan greets by voice.
2. **(0:20)** Alice opens `auth/middleware.ts`. Hermes infers ownership.
3. **(0:45)** Bob opens `frontend/login.tsx`. Carol's terminal shows connection refused.
4. **(1:20) BLOCKER_DETECTED:** "Carol, looks like you're waiting on auth. Alice is actively building it — hang tight."
5. **(2:00) DEPENDENCY_READY:** "Carol, Bob — Alice just got the auth endpoint running. You're clear to integrate."
6. **(2:20)** Optional: session 2 warm-start comparison.
7. **(2:45)** Close: "PodMan — the teammate that sees what Slack can't."
---
## Key risks
| Risk | Mitigation |
| -------------------------------------------- | ------------------------------------------------- |
| Gemini Vision accuracy | Large font, single editor window, confidence gate |
| Gemini Live 2.5 + LiveKit Agents integration | Build together hour 57, have TTS fallback |
| Frame POST latency | JPEG compression, target < 500ms |
| Event false positives | 3-min cooldown, pre-staged demo |
| DO deploy failure | Hermes runs local, PWA defaults to localhost:8787 |
+1 -7
View File
@@ -3,13 +3,7 @@ import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: [
'**/dist/**',
'**/build/**',
'**/node_modules/**',
'**/.venv/**',
'**/*.config.*',
],
ignores: ['**/dist/**', '**/build/**', '**/node_modules/**', '**/*.config.*'],
},
js.configs.recommended,
...tseslint.configs.recommended,
-21
View File
@@ -30,27 +30,6 @@
content="Ambient AI teammate that catches merge collisions before anyone pushes."
/>
<meta name="twitter:image" content="https://www.podman.live/og.png" />
<script>
// Tear down any service worker we shipped earlier (vite-plugin-pwa).
// PodMan runs no PWA in production: we deploy continuously and SW-driven
// reloads break the live demo. This unregisters leftover workers and
// clears their caches on every load so previously-affected browsers
// self-heal — no manual DevTools needed. It does NOT reload the page and
// is a no-op once nothing is registered.
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.getRegistrations()
.then((regs) => regs.forEach((r) => r.unregister()))
.catch(() => {});
if (window.caches && caches.keys) {
caches
.keys()
.then((keys) => keys.forEach((k) => caches.delete(k)))
.catch(() => {});
}
}
</script>
</head>
<body>
<div id="root"></div>
+9 -69
View File
@@ -42,26 +42,6 @@ import { Skeleton } from '@/components/ui/skeleton';
const SESSION_KEY = 'podman.session';
const fmt = new Intl.NumberFormat('en', { notation: 'compact' });
function pathPodId(): string | null {
const [segment] = window.location.pathname.split('/').filter(Boolean);
return segment ? decodeURIComponent(segment) : null;
}
function setPodPath(podId: string, replace = false): void {
const next = `/${encodeURIComponent(podId)}`;
if (window.location.pathname === next) return;
window.history[replace ? 'replaceState' : 'pushState']({}, '', next);
}
function setHomePath(): void {
if (window.location.pathname === '/') return;
window.history.pushState({}, '', '/');
}
function replacePath(path: string): void {
window.history.replaceState({}, '', path || '/');
}
export default function App() {
const [pods, setPods] = useState<Pod[]>([]);
const [loading, setLoading] = useState(true);
@@ -105,20 +85,13 @@ export default function App() {
return n;
});
async function connectToPod(podId: string, who: string, replaceRoute = false) {
const previousPath = window.location.pathname;
setPodPath(podId, replaceRoute);
try {
const result = await joinPod(podId, who, who);
setRoom(result.room);
setDevMode(result.mode === 'dev');
setMember(who);
setJoinedPodId(podId);
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ podId, member: who }));
} catch (e) {
replacePath(previousPath);
throw e;
}
async function connectToPod(podId: string, who: string) {
const result = await joinPod(podId, who, who);
setRoom(result.room);
setDevMode(result.mode === 'dev');
setMember(who);
setJoinedPodId(podId);
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ podId, member: who }));
}
useEffect(() => {
@@ -151,14 +124,8 @@ export default function App() {
}, [joinedPodId]);
useEffect(() => {
const routedPodId = pathPodId();
const raw = sessionStorage.getItem(SESSION_KEY);
if (!raw) {
if (routedPodId) {
setError(`Enter your name to join ${routedPodId}.`);
}
return;
}
if (!raw) return;
let saved: { podId: string; member: string };
try {
saved = JSON.parse(raw);
@@ -166,11 +133,10 @@ export default function App() {
sessionStorage.removeItem(SESSION_KEY);
return;
}
const podId = routedPodId ?? saved.podId;
setRestoring(true);
void (async () => {
try {
await connectToPod(podId, saved.member, !!routedPodId);
await connectToPod(saved.podId, saved.member);
} catch {
sessionStorage.removeItem(SESSION_KEY);
} finally {
@@ -179,30 +145,6 @@ export default function App() {
})();
}, []);
useEffect(() => {
const onPopState = () => {
const routedPodId = pathPodId();
if (!routedPodId) {
room?.disconnect();
setRoom(null);
setJoinedPodId(null);
return;
}
const raw = sessionStorage.getItem(SESSION_KEY);
if (!raw) return;
try {
const saved = JSON.parse(raw) as { member: string };
if (saved.member && routedPodId !== joinedPodId) {
void connectToPod(routedPodId, saved.member, true);
}
} catch {
sessionStorage.removeItem(SESSION_KEY);
}
};
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, [joinedPodId, room]);
async function run(key: string, fn: () => Promise<void>) {
startPending(key);
setError(null);
@@ -237,7 +179,6 @@ export default function App() {
run(id, async () => {
await api.deletePod(id);
setPods((cur) => cur.filter((x) => x.id !== id));
if (pathPodId() === id) setHomePath();
});
const handleAddMember = (id: string, name: string) =>
run(id, async () => upsert(await api.addMember(id, name)));
@@ -274,7 +215,6 @@ export default function App() {
setRoom(null);
setJoinedPodId(null);
sessionStorage.removeItem(SESSION_KEY);
setHomePath();
void refresh();
}
+5 -1
View File
@@ -169,7 +169,11 @@ export function GraphView({ podId, onClose }: { podId: string; onClose: () => vo
/>
</div>
{graph.loop?.steps?.length ? <LearningLoop loop={graph.loop} /> : <div />}
{graph.loop?.length ? (
<LearningLoop stages={graph.loop} />
) : (
<div />
)}
</div>
{/* Activity stream · selected node */}
+35 -10
View File
@@ -2,6 +2,7 @@ import { useState } from 'react';
import {
BrainCircuitIcon,
MoreHorizontalIcon,
PlusIcon,
Trash2Icon,
UserRoundIcon,
VideoIcon,
@@ -15,6 +16,7 @@ import {
CardAction,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card';
@@ -41,9 +43,9 @@ export function PodCard({
pod,
busy,
presence,
onJoin: _onJoin,
onJoin,
onAddAndJoin,
onAddMember: _onAddMember,
onAddMember,
onRemoveMember: _onRemoveMember,
onUpdate,
onDelete,
@@ -70,6 +72,7 @@ export function PodCard({
const inRoom = (name: string) => presence.some((p) => p.toLowerCase() === name.toLowerCase());
const active = presence.length > 0;
const primaryMember = pod.members[0] ?? '';
function saveEdit() {
onUpdate(pod.id, {
@@ -80,12 +83,11 @@ export function PodCard({
setEditing(false);
}
// One action: enter your name, hit Join → added to the roster (deduped
// server-side) and connected to the room in a single step.
function join() {
function submitMember(join: boolean) {
const name = newMember.trim();
if (!name) return;
onAddAndJoin(pod, name);
if (join) onAddAndJoin(pod, name);
else onAddMember(pod.id, name);
setNewMember('');
}
@@ -163,16 +165,39 @@ export function PodCard({
value={newMember}
onChange={(e) => setNewMember(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') join();
if (e.key === 'Enter') submitMember(true);
}}
/>
<Button className="min-w-24" onClick={join} disabled={busy || !newMember.trim()}>
<VideoIcon data-icon="inline-start" />
Join
<Button
variant="outline"
size="icon"
onClick={() => submitMember(false)}
disabled={busy || !newMember.trim()}
>
<PlusIcon />
<span className="sr-only">Add member</span>
</Button>
</div>
</div>
</CardContent>
<CardFooter className="justify-between gap-2">
<Button
variant="outline"
onClick={() => primaryMember && onJoin(pod, primaryMember)}
disabled={busy || !primaryMember}
>
<VideoIcon data-icon="inline-start" />
Join
</Button>
<Button
className="min-w-28"
onClick={() => submitMember(true)}
disabled={busy || !newMember.trim()}
>
Add and join
</Button>
</CardFooter>
</Card>
<Dialog open={editing} onOpenChange={setEditing}>
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,4 @@
import type { PodGraphActivity } from '@podman/shared';
import type { ActivityEvent } from '@podman/shared';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ACTIVITY_TAG } from './encoding.js';
@@ -9,7 +9,7 @@ function timeOf(at: string): string {
return Number.isFinite(t) ? fmtTime.format(t) : '--:--';
}
export function ActivityStream({ events }: { events: PodGraphActivity[] }) {
export function ActivityStream({ events }: { events: ActivityEvent[] }) {
return (
<div className="flex h-full flex-col">
<p className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
@@ -33,14 +33,7 @@ export function ActivityStream({ events }: { events: PodGraphActivity[] }) {
>
{tag.label}
</span>
<span className="min-w-0 flex-1 leading-snug">
<span className="text-foreground/90">{e.title}</span>
{e.detail && (
<span className="block text-xs leading-snug text-muted-foreground">
{e.detail}
</span>
)}
</span>
<span className="min-w-0 flex-1 leading-snug text-foreground/90">{e.text}</span>
</li>
);
})}
+27 -33
View File
@@ -1,49 +1,43 @@
import type { PodLearningLoop } from '@podman/shared';
import type { LearningStage } from '@podman/shared';
import { BLUE } from './encoding.js';
/**
* The continual-learning loop rail: observe store predict outcome adapt.
* The active stage (most-recent activity) gets a pulsing accent bar + ring.
*/
export function LearningLoop({ loop }: { loop: PodLearningLoop }) {
export function LearningLoop({ stages }: { stages: LearningStage[] }) {
return (
<div className="space-y-1">
<p className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
Learning loop
</p>
{loop.steps.map((s, i) => {
const active = s.status === 'active' || s.key === loop.activeStep;
return (
<div key={s.key}>
<div
className="relative overflow-hidden rounded-lg border bg-card py-2 pl-3.5 pr-3 shadow-sm transition-colors data-[active=true]:bg-accent/40"
data-active={active}
style={active ? { boxShadow: `inset 0 0 0 1px ${BLUE}55` } : undefined}
>
<span
aria-hidden
className={`absolute inset-y-0 left-0 w-1 ${active ? 'pm-pulse' : ''}`}
style={{ background: active ? BLUE : 'var(--border)' }}
/>
<div className="flex items-baseline justify-between gap-2">
<p className="text-[0.7rem] font-medium uppercase tracking-wide text-muted-foreground">
<span className="tabular-nums">{String(i + 1).padStart(2, '0')}</span> {s.label}
</p>
<p className="font-heading text-sm font-semibold tabular-nums">{s.value}</p>
</div>
<p className="mt-0.5 text-xs leading-snug text-muted-foreground">{s.detail}</p>
</div>
{i < loop.steps.length - 1 && (
<p
aria-hidden
className="py-0.5 text-center text-xs leading-none text-muted-foreground/60"
>
{stages.map((s, i) => (
<div key={s.key}>
<div
className="relative overflow-hidden rounded-lg border bg-card py-2 pl-3.5 pr-3 shadow-sm transition-colors data-[active=true]:bg-accent/40"
data-active={s.active}
style={s.active ? { boxShadow: `inset 0 0 0 1px ${BLUE}55` } : undefined}
>
<span
aria-hidden
className={`absolute inset-y-0 left-0 w-1 ${s.active ? 'pm-pulse' : ''}`}
style={{ background: s.active ? BLUE : 'var(--border)' }}
/>
<div className="flex items-baseline justify-between gap-2">
<p className="text-[0.7rem] font-medium uppercase tracking-wide text-muted-foreground">
<span className="tabular-nums">{String(i + 1).padStart(2, '0')}</span> {s.title}
</p>
)}
<p className="font-heading text-sm font-semibold tabular-nums">{s.value}</p>
</div>
<p className="mt-0.5 text-xs leading-snug text-muted-foreground">{s.detail}</p>
</div>
);
})}
{i < stages.length - 1 && (
<p aria-hidden className="py-0.5 text-center text-xs leading-none text-muted-foreground/60">
</p>
)}
</div>
))}
</div>
);
}
+4 -5
View File
@@ -4,7 +4,7 @@ import type {
PodGraphNode,
PodGraphEdge,
PodGraphNodeKind,
PodGraphActivityKind,
ActivityKind,
} from '@podman/shared';
/**
@@ -21,13 +21,12 @@ export const VIOLET = '#7c3aed';
export const GREEN = '#16a34a';
/** Tag color + short label per activity-stream kind. */
export const ACTIVITY_TAG: Record<PodGraphActivityKind, { color: string; label: string }> = {
export const ACTIVITY_TAG: Record<ActivityKind, { color: string; label: string }> = {
editing: { color: SLATE, label: 'EDITING' },
collision: { color: RED, label: 'COLLISION' },
intervention: { color: AMBER, label: 'NUDGE' },
warns: { color: AMBER, label: 'WARNS' },
outcome: { color: GREEN, label: 'OUTCOME' },
learned: { color: VIOLET, label: 'LEARNED' },
agent: { color: BLUE, label: 'AGENT' },
learned_from: { color: VIOLET, label: 'LEARNED' },
};
export const KIND_COLOR: Record<PodGraphNodeKind, string> = {
-63
View File
@@ -1,63 +0,0 @@
import { useEffect, useMemo, useState } from 'react';
import type { PodActivityEvent } from '@podman/shared';
import { getPodActivity, podActivityStreamUrl } from '../lib/api';
export function usePodActivity(podId: string | null, me: string) {
const [events, setEvents] = useState<PodActivityEvent[]>([]);
const [connected, setConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!podId) return;
let alive = true;
const load = async () => {
try {
const snapshot = await getPodActivity(podId);
if (alive) {
setEvents(snapshot);
setError(null);
}
} catch (e) {
if (alive) setError((e as Error).message);
}
};
void load();
const source = new EventSource(podActivityStreamUrl(podId));
source.addEventListener('open', () => {
if (alive) setConnected(true);
});
source.addEventListener('snapshot', (event) => {
if (!alive) return;
setEvents(JSON.parse((event as MessageEvent<string>).data) as PodActivityEvent[]);
setConnected(true);
setError(null);
});
source.addEventListener('error', () => {
if (alive) {
setConnected(false);
setError('Realtime activity stream reconnecting');
}
});
return () => {
alive = false;
source.close();
};
}, [podId]);
return useMemo(() => {
const mine = events.filter((event) => belongsTo(event, me));
const team = events.filter((event) => !belongsTo(event, me));
return { events, mine, team, connected, error };
}, [connected, error, events, me]);
}
function belongsTo(event: PodActivityEvent, me: string): boolean {
const normalized = me.trim().toLowerCase();
if (!normalized) return false;
const names = [event.actor, ...(event.actors ?? [])]
.filter(Boolean)
.map((name) => name!.trim().toLowerCase());
return names.includes(normalized);
}
+1 -111
View File
@@ -1,12 +1,4 @@
import type {
InterventionOutcome,
HermesJob,
HermesJobEvent,
MemberWorkHistory,
Pod,
PodActivityEvent,
PodInput,
} from '@podman/shared';
import type { InterventionOutcome, Pod, PodInput } from '@podman/shared';
const BACKEND_URL =
import.meta.env.VITE_BACKEND_URL ||
@@ -21,19 +13,6 @@ export interface MemoryStats {
outcomes: number;
}
export interface LiveConversationSession {
sessionId: string;
podId: string;
identity: string;
displayName: string;
room: string;
url: string;
token: string;
startedAt: string;
lastEventAt?: string;
endedAt?: string;
}
async function json<T>(res: Response): Promise<T> {
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string };
@@ -96,34 +75,6 @@ export async function getMemoryStats(): Promise<MemoryStats> {
return json(await fetch(`${BACKEND_URL}/api/memory/stats`));
}
export async function getPodActivity(id: string, limit = 80): Promise<PodActivityEvent[]> {
return json(
await fetch(`${BACKEND_URL}/api/pods/${encodeURIComponent(id)}/activity?limit=${limit}`),
);
}
export function podActivityStreamUrl(id: string): string {
return `${BACKEND_URL}/api/pods/${encodeURIComponent(id)}/activity/stream`;
}
/** URL of the pod's generated background-music MP3 (looped client-side). */
export function podMusicUrl(id: string): string {
return `${BACKEND_URL}/api/pods/${encodeURIComponent(id)}/music`;
}
export async function getMemberWorkHistory(
podId: string,
member: string,
): Promise<MemberWorkHistory> {
return json(
await fetch(
`${BACKEND_URL}/api/pods/${encodeURIComponent(podId)}/members/${encodeURIComponent(
member,
)}/history?hours=24&limit=80`,
),
);
}
export async function createPod(input: PodInput): Promise<Pod> {
return json(
await fetch(`${BACKEND_URL}/api/pods`, {
@@ -161,67 +112,6 @@ export async function addMember(id: string, name: string): Promise<Pod> {
);
}
export async function testPodVoice(id: string): Promise<void> {
const res = await fetch(`${BACKEND_URL}/api/pods/${encodeURIComponent(id)}/voice-test`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
message: 'PodMan voice test. Gemini TTS is playing through LiveKit.',
}),
});
if (!res.ok) throw new Error(`voice test failed: ${res.status}`);
}
export async function startLiveConversation(
podId: string,
input: { identity: string; displayName?: string },
): Promise<LiveConversationSession> {
return json(
await fetch(`${BACKEND_URL}/api/pods/${encodeURIComponent(podId)}/live-conversation/start`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(input),
}),
);
}
export async function stopLiveConversation(podId: string, sessionId: string): Promise<void> {
const res = await fetch(
`${BACKEND_URL}/api/pods/${encodeURIComponent(
podId,
)}/live-conversation/${encodeURIComponent(sessionId)}/stop`,
{ method: 'POST' },
);
if (!res.ok) throw new Error(`live conversation stop failed: ${res.status}`);
}
export async function getLiveConversationHermesJob(
podId: string,
sessionId: string,
): Promise<{ job: HermesJob | null; events: HermesJobEvent[] }> {
return json(
await fetch(
`${BACKEND_URL}/api/pods/${encodeURIComponent(
podId,
)}/live-conversation/${encodeURIComponent(sessionId)}/hermes-job`,
),
);
}
export async function abortLiveConversationHermesJob(
podId: string,
sessionId: string,
): Promise<{ job: HermesJob | null }> {
return json(
await fetch(
`${BACKEND_URL}/api/pods/${encodeURIComponent(
podId,
)}/live-conversation/${encodeURIComponent(sessionId)}/hermes-job/abort`,
{ method: 'POST' },
),
);
}
export async function removeMember(id: string, name: string): Promise<Pod> {
return json(
await fetch(
-39
View File
@@ -75,42 +75,3 @@ export function startBeat(): BeatHandle {
},
};
}
/**
* Load an MP3 from `url` and loop it as an audio MediaStreamTrack to publish into
* a LiveKit room (and play on local speakers). Used for pod background music
* (Lyria-generated). Pure Web Audio no asset bundling.
*/
export async function startMusic(url: string): Promise<BeatHandle> {
const ctx = new AudioContext();
await ctx.resume();
const res = await fetch(url);
if (!res.ok) throw new Error(`music fetch failed: ${res.status}`);
const buffer = await ctx.decodeAudioData(await res.arrayBuffer());
const dest = ctx.createMediaStreamDestination();
const master = ctx.createGain();
master.gain.value = 0.6;
master.connect(dest); // -> published track (remote listeners)
master.connect(ctx.destination); // -> local speakers (publisher)
const src = ctx.createBufferSource();
src.buffer = buffer;
src.loop = true;
src.connect(master);
src.start();
const track = dest.stream.getAudioTracks()[0]!;
return {
track,
stop: () => {
try {
src.stop();
} catch {
/* already stopped */
}
track.stop();
void ctx.close();
},
};
}
-150
View File
@@ -1,150 +0,0 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { RoomEvent, type Room } from 'livekit-client';
import { DATA_TOPIC, type DataMessage } from '@podman/shared';
import { startBeat, startMusic, type BeatHandle } from '../lib/beat.js';
/** Name of the test-audio track; its presence in the room IS the shared state. */
export const BEAT_TRACK = 'podman-beat';
export interface BeatState {
/** Is the test audio playing anywhere in the pod? */
on: boolean;
/** Display name of the participant who started it (the owner). */
by: string | null;
/** Do I own the beat track (so I can stop it directly)? */
mine: boolean;
}
const OFF: BeatState = { on: false, by: null, mine: false };
/**
* Shared, pod-wide test audio. One participant publishes the `podman-beat`
* track; everyone hears it and sees the same on/off state, derived directly
* from the track's presence (self-syncing across joins/leaves). Any participant
* can stop it: non-owners send BEAT_STOP and the owner unpublishes.
*/
export function useBeat(room: Room | null, musicUrl?: string) {
const [beat, setBeat] = useState<BeatState>(OFF);
const beatRef = useRef<BeatHandle | null>(null);
const stopLocal = useCallback(async () => {
const handle = beatRef.current;
if (!handle) return;
beatRef.current = null;
try {
await room?.localParticipant.unpublishTrack(handle.track);
} finally {
handle.stop();
}
}, [room]);
// Derive the shared state from the podman-beat track across all participants.
useEffect(() => {
if (!room) {
setBeat(OFF);
return;
}
const recompute = () => {
const lp = room.localParticipant;
const localPub = [...lp.trackPublications.values()].find((p) => p.trackName === BEAT_TRACK);
if (localPub) {
setBeat({ on: true, by: lp.name || lp.identity, mine: true });
return;
}
for (const p of room.remoteParticipants.values()) {
const pub = [...p.trackPublications.values()].find((tp) => tp.trackName === BEAT_TRACK);
if (pub) {
setBeat({ on: true, by: p.name || p.identity, mine: false });
return;
}
}
setBeat(OFF);
};
recompute();
const events = [
RoomEvent.LocalTrackPublished,
RoomEvent.LocalTrackUnpublished,
RoomEvent.TrackPublished,
RoomEvent.TrackUnpublished,
RoomEvent.TrackSubscribed,
RoomEvent.TrackUnsubscribed,
RoomEvent.ParticipantConnected,
RoomEvent.ParticipantDisconnected,
] as const;
events.forEach((e) => room.on(e, recompute));
return () => {
events.forEach((e) => room.off(e, recompute));
};
}, [room]);
// The owner honors stop requests from any participant.
useEffect(() => {
if (!room) return;
const onData = (payload: Uint8Array, _p: unknown, _k: unknown, topic?: string) => {
if (topic !== DATA_TOPIC) return;
let msg: DataMessage;
try {
msg = JSON.parse(new TextDecoder().decode(payload)) as DataMessage;
} catch {
return;
}
if (msg.type === 'BEAT_STOP') void stopLocal();
};
room.on(RoomEvent.DataReceived, onData);
return () => {
room.off(RoomEvent.DataReceived, onData);
};
}, [room, stopLocal]);
// Tear down my own track on unmount (e.g. leaving the pod).
const stopLocalRef = useRef(stopLocal);
stopLocalRef.current = stopLocal;
const startingRef = useRef(false);
const unmountedRef = useRef(false);
useEffect(() => {
return () => {
unmountedRef.current = true;
void stopLocalRef.current();
};
}, []);
const toggleBeat = useCallback(async () => {
if (!room) return;
// `beatRef` is the synchronous source of truth for "do I own it" — `beat.mine`
// lags behind the LiveKit track events that recompute it, so gate on the ref.
if (beatRef.current) {
await stopLocal();
return;
}
if (beat.on) {
// Someone else owns it — can't unpublish their track, so ask them to stop.
await room.startAudio().catch(() => {});
await room.localParticipant.publishData(
new TextEncoder().encode(JSON.stringify({ type: 'BEAT_STOP' } satisfies DataMessage)),
{ reliable: true, topic: DATA_TOPIC },
);
return;
}
// Start it. Guard against rapid double-clicks publishing two tracks before the
// LocalTrackPublished event has had a chance to update state.
if (startingRef.current) return;
startingRef.current = true;
try {
await room.startAudio().catch(() => {}); // unlock playback from this gesture
if (unmountedRef.current) return;
const handle = musicUrl ? await startMusic(musicUrl) : startBeat();
beatRef.current = handle;
await room.localParticipant.publishTrack(handle.track, { name: BEAT_TRACK });
if (unmountedRef.current) await stopLocal(); // left mid-publish — clean up
} catch (e) {
beatRef.current?.stop();
beatRef.current = null;
throw e;
} finally {
startingRef.current = false;
}
}, [room, beat, stopLocal, musicUrl]);
return { beat, toggleBeat };
}
+2 -28
View File
@@ -4,27 +4,6 @@ import type { DataMessage, HermesMessage, Intervention, InterventionStatus } fro
import { DATA_TOPIC } from '@podman/shared';
import { createSyncPr, postOutcome } from '../lib/api';
const browserTtsFallbackEnabled = import.meta.env.VITE_ENABLE_BROWSER_TTS_FALLBACK === 'true';
/** Speak a cue in the browser only when the explicit fallback flag is enabled. */
export function speakInBrowser(text: string): void {
if (!browserTtsFallbackEnabled) return;
if (typeof window === 'undefined' || !('speechSynthesis' in window) || !text) return;
const u = new SpeechSynthesisUtterance(text);
u.rate = 1.05;
window.speechSynthesis.cancel(); // drop any queued cue so the latest wins
window.speechSynthesis.speak(u);
}
/** Unlock speechSynthesis from a user gesture when the browser fallback is enabled. */
export function primeSpeech(): void {
if (!browserTtsFallbackEnabled) return;
if (typeof window === 'undefined' || !('speechSynthesis' in window)) return;
const u = new SpeechSynthesisUtterance(' ');
u.volume = 0;
window.speechSynthesis.speak(u);
}
export function useInterventions(room: Room | null) {
const [active, setActive] = useState<Intervention | null>(null);
const [hermes, setHermes] = useState<HermesMessage | null>(null);
@@ -41,10 +20,7 @@ export function useInterventions(room: Room | null) {
setActionUrl(null);
}
if (msg.type === 'HERMES_MESSAGE') setHermes(msg.message);
if (msg.type === 'VOICE_CUE') {
setVoiceCue(msg.text);
speakInBrowser(msg.text);
}
if (msg.type === 'VOICE_CUE') setVoiceCue(msg.text);
};
room.on(RoomEvent.DataReceived, onData);
return () => {
@@ -66,9 +42,7 @@ export function useInterventions(room: Room | null) {
interventionId: active.id,
collisionId: active.collisionId,
podId: active.podId,
// Placeholder only — the backend derives the authoritative value from
// git overlap at outcome time (the client cannot know). (RSI Step 3)
wasRealCollision: false,
wasRealCollision: true,
accepted,
recordedAt: new Date().toISOString(),
});
+9 -5
View File
@@ -1,14 +1,18 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { VitePWA } from 'vite-plugin-pwa';
import { fileURLToPath, URL } from 'node:url';
export default defineConfig({
// No service worker in production. We deploy continuously during the event and
// any SW (even vite-plugin-pwa's self-destroying one) forces open tabs to
// reload, which breaks the live demo. Existing SWs are torn down by the
// cleanup snippet in index.html. Re-add a precaching PWA only post-event.
plugins: [react(), tailwindcss()],
plugins: [
react(),
tailwindcss(),
// Self-destroying during active development: unregisters any previously
// installed service worker and clears its caches so deploys are always
// fresh (no stale UI). Re-enable a precaching PWA before the demo.
VitePWA({ selfDestroying: true }),
],
server: {
port: 5173,
},
-2
View File
@@ -49,7 +49,6 @@ services:
- { key: GEMINI_API_KEY, scope: RUN_TIME, type: SECRET }
- { key: GEMINI_VISION_MODEL, scope: RUN_TIME, value: gemini-2.0-flash }
- { key: GEMINI_LIVE_MODEL, scope: RUN_TIME, value: gemini-3.1-flash-tts-preview }
- { key: GEMINI_TTS_VOICE, scope: RUN_TIME, value: Charon }
- { key: GEMINI_EMBEDDING_MODEL, scope: RUN_TIME, value: gemini-embedding-001 }
- { key: GITHUB_TOKEN, scope: RUN_TIME, type: SECRET }
- { key: GITHUB_REPO, scope: RUN_TIME, value: karti-ai/podman }
@@ -76,7 +75,6 @@ workers:
- { key: GEMINI_API_KEY, scope: RUN_TIME, type: SECRET }
- { key: GEMINI_VISION_MODEL, scope: RUN_TIME, value: gemini-2.0-flash }
- { key: GEMINI_LIVE_MODEL, scope: RUN_TIME, value: gemini-3.1-flash-tts-preview }
- { key: GEMINI_TTS_VOICE, scope: RUN_TIME, value: Charon }
- { key: GEMINI_EMBEDDING_MODEL, scope: RUN_TIME, value: gemini-embedding-001 }
- { key: GITHUB_TOKEN, scope: RUN_TIME, type: SECRET }
- { key: GITHUB_REPO, scope: RUN_TIME, value: karti-ai/podman }
-4
View File
@@ -23,10 +23,6 @@ lk.165-22-129-249.sslip.io {
}
}
gemini.165-22-129-249.sslip.io {
reverse_proxy 127.0.0.1:3000
}
podman.live, www.podman.live {
route {
handle /api/* {
-2
View File
@@ -49,7 +49,6 @@ services:
- { key: GEMINI_API_KEY, scope: RUN_TIME, type: SECRET }
- { key: GEMINI_VISION_MODEL, scope: RUN_TIME, value: gemini-2.0-flash }
- { key: GEMINI_LIVE_MODEL, scope: RUN_TIME, value: gemini-3.1-flash-tts-preview }
- { key: GEMINI_TTS_VOICE, scope: RUN_TIME, value: Charon }
- { key: GEMINI_EMBEDDING_MODEL, scope: RUN_TIME, value: gemini-embedding-001 }
- { key: GITHUB_TOKEN, scope: RUN_TIME, type: SECRET }
- { key: GITHUB_REPO, scope: RUN_TIME, value: karti-ai/podman }
@@ -76,7 +75,6 @@ workers:
- { key: GEMINI_API_KEY, scope: RUN_TIME, type: SECRET }
- { key: GEMINI_VISION_MODEL, scope: RUN_TIME, value: gemini-2.0-flash }
- { key: GEMINI_LIVE_MODEL, scope: RUN_TIME, value: gemini-3.1-flash-tts-preview }
- { key: GEMINI_TTS_VOICE, scope: RUN_TIME, value: Charon }
- { key: GEMINI_EMBEDDING_MODEL, scope: RUN_TIME, value: gemini-embedding-001 }
- { key: GITHUB_TOKEN, scope: RUN_TIME, type: SECRET }
- { key: GITHUB_REPO, scope: RUN_TIME, value: karti-ai/podman }
@@ -1,17 +0,0 @@
[Unit]
Description=PodMan LiveKit Gemini starter agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/root/podman/examples/livekit-gemini-hacker-starter/agent
Environment=PATH=/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ExecStart=/root/.local/bin/uv run agent.py dev
Restart=always
RestartSec=3
KillSignal=SIGTERM
TimeoutStopSec=20
[Install]
WantedBy=multi-user.target
@@ -1,18 +0,0 @@
[Unit]
Description=PodMan LiveKit Gemini starter frontend
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/root/podman/examples/livekit-gemini-hacker-starter/frontend
Environment=NODE_ENV=production
Environment=NEXT_TELEMETRY_DISABLED=1
ExecStart=/usr/bin/pnpm start --hostname 127.0.0.1 --port 3000
Restart=always
RestartSec=3
KillSignal=SIGTERM
TimeoutStopSec=20
[Install]
WantedBy=multi-user.target
@@ -1,20 +0,0 @@
[Unit]
Description=PodMan private LiveKit/Gemini live conversation agent
After=network-online.target podman-platform-api.service
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/root/podman/agents/podman-live-conversation
Environment=PATH=/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EnvironmentFile=/root/podman/backend/.env
ExecStart=/root/.local/bin/uv run agent.py dev
Restart=always
RestartSec=3
MemoryHigh=1024M
MemoryMax=1536M
KillSignal=SIGTERM
TimeoutStopSec=20
[Install]
WantedBy=multi-user.target
@@ -12,9 +12,6 @@ EnvironmentFile=/root/podman/backend/.env
ExecStart=/usr/bin/node dist/agent.js
Restart=always
RestartSec=3
MemoryHigh=1536M
MemoryMax=2G
OOMPolicy=stop
KillSignal=SIGTERM
TimeoutStopSec=20
-3
View File
@@ -22,12 +22,9 @@
"deploy:static:local": "node scripts/deploy-static-local.mjs",
"hermes:watchdog": "node scripts/hermes-watchdog.mjs",
"hermes:watchdog:strict": "node scripts/hermes-watchdog.mjs --strict",
"hermes:notify": "node scripts/hermes-notify.mjs",
"hermes:sync-deploy": "node scripts/hermes-sync-deploy.mjs",
"hermes:install": "node scripts/install-hermes-ops.mjs",
"healthcheck:public": "node scripts/healthcheck-public.mjs",
"livekit:conversation:agent": "cd agents/podman-live-conversation && uv run agent.py dev",
"livekit:conversation:test": "cd agents/podman-live-conversation && uv run pytest",
"verify": "pnpm lint && pnpm typecheck && pnpm build && pnpm verify:backend && pnpm verify:frontend",
"verify:full": "pnpm verify && pnpm verify:infra && pnpm build:container && pnpm verify:containers",
"verify:backend": "node scripts/verify-backend.mjs",
-17
View File
@@ -1,17 +0,0 @@
#!/bin/bash
REPO="/home/ramis/Programming/podman"
LOG="/home/ramis/Programming/podman/scripts/auto-pull.log"
cd "$REPO" || exit 1
# Stash any local changes, pull, pop
git fetch origin main 2>>"$LOG"
LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse origin/main)
if [ "$LOCAL" != "$REMOTE" ]; then
echo "[$(date)] Pulling: $LOCAL -> $REMOTE" >> "$LOG"
git pull --ff-only origin main >> "$LOG" 2>&1
else
echo "[$(date)] Up to date" >> "$LOG"
fi
+3 -12
View File
@@ -240,7 +240,6 @@ async function checkGeminiVision() {
async function checkGeminiVoiceModel() {
const key = configuredGeminiKey();
const model = process.env.GEMINI_LIVE_MODEL ?? 'gemini-3.1-flash-tts-preview';
const voice = process.env.GEMINI_TTS_VOICE ?? 'Charon';
const res = await doFetch(
`https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(key.value)}`,
);
@@ -258,18 +257,10 @@ async function checkGeminiVoiceModel() {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
contents: [
{
parts: [
{
text: 'Speak this as a calm engineering teammate. Say only: PodMan voice check.',
},
],
},
],
contents: [{ parts: [{ text: 'Say clearly: PodMan voice check.' }] }],
generationConfig: {
responseModalities: ['AUDIO'],
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: voice } } },
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } } },
},
}),
},
@@ -278,7 +269,7 @@ async function checkGeminiVoiceModel() {
const ttsBody = await tts.json();
const audio = ttsBody.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
if (!audio) throw new Error('Gemini voice response had no audio');
return `${model}/${voice}, generated ${Buffer.from(audio, 'base64').byteLength} audio bytes`;
return `${model}, generated ${Buffer.from(audio, 'base64').byteLength} audio bytes`;
}
async function checkGeminiEmbeddings() {
-54
View File
@@ -1,54 +0,0 @@
#!/usr/bin/env node
import { existsSync } from 'node:fs';
import { config as loadEnv } from 'dotenv';
const envPath = process.env.DOTENV_CONFIG_PATH ?? (existsSync('.env') ? '.env' : 'backend/.env');
loadEnv({ path: envPath, quiet: true });
function usage() {
console.error(
'Usage: node scripts/hermes-notify.mjs --pod <podId> --message <text> [--engineers alice,bob] [--file path] [--urgent]',
);
process.exit(1);
}
function arg(name) {
const index = process.argv.indexOf(name);
return index === -1 ? '' : (process.argv[index + 1] ?? '');
}
const podId = arg('--pod');
const message = arg('--message');
if (!podId || !message) usage();
const apiBase = (
process.env.PODMAN_API_URL ??
process.env.BACKEND_URL ??
`http://127.0.0.1:${process.env.PORT ?? '8787'}`
).replace(/\/$/, '');
const engineers = arg('--engineers')
.split(',')
.map((name) => name.trim())
.filter(Boolean);
const file = arg('--file');
const urgent = process.argv.includes('--urgent');
const res = await globalThis.fetch(`${apiBase}/api/pods/${encodeURIComponent(podId)}/hermes/notify`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
message,
...(engineers.length ? { engineers } : {}),
...(file ? { file } : {}),
...(urgent ? { urgency: 'urgent' } : {}),
}),
});
const text = await res.text();
if (!res.ok) {
console.error(text);
process.exit(1);
}
console.log(text);
-103
View File
@@ -22,7 +22,6 @@ const env = {
GITHUB_TOKEN: process.env.GITHUB_TOKEN ?? 'verify-github',
GITHUB_REPO: process.env.GITHUB_REPO ?? 'karti-ai/podman',
MONGODB_URI: mongoUri,
INTERNAL_AGENT_TOKEN: process.env.INTERNAL_AGENT_TOKEN ?? 'verify-internal-agent-token',
};
function fail(message) {
@@ -96,105 +95,6 @@ async function verifyApi() {
);
if (!withMember.members.includes('Hermes')) fail('member add did not persist');
const hermesNotify = await json(
await doFetch(`${baseUrl}/api/pods/${encodeURIComponent(created.id)}/hermes/notify`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
message: 'Hermes verification notification.',
engineers: ['Alice', 'Bob'],
file: 'src/verify-hermes.ts',
dryRun: true,
}),
}),
);
if (
hermesNotify.livekit !== 'dry-run' ||
hermesNotify.intervention?.message !== 'Hermes verification notification.'
) {
fail('Hermes notify endpoint returned unexpected payload');
}
const liveConversation = await json(
await doFetch(`${baseUrl}/api/pods/${encodeURIComponent(created.id)}/live-conversation/start`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ identity: 'Alice', displayName: 'Alice' }),
}),
);
if (
typeof liveConversation.token !== 'string' ||
liveConversation.token.split('.').length !== 3 ||
typeof liveConversation.room !== 'string' ||
!liveConversation.room.includes('podman-live:')
) {
fail('live conversation start did not return a private room JWT');
}
const liveStatus = await json(
await doFetch(
`${baseUrl}/api/pods/${encodeURIComponent(
created.id,
)}/live-conversation/status?identity=Alice`,
),
);
if (liveStatus.active?.sessionId !== liveConversation.sessionId) {
fail('live conversation status did not return the active session');
}
await json(
await doFetch(
`${baseUrl}/api/pods/${encodeURIComponent(
created.id,
)}/live-conversation/${encodeURIComponent(liveConversation.sessionId)}/stop`,
{ method: 'POST' },
),
);
const hermesJob = await json(
await doFetch(`${baseUrl}/api/internal/hermes/jobs`, {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${env.INTERNAL_AGENT_TOKEN}`,
},
body: JSON.stringify({
prompt: 'Check repository state for backend verification.',
contextScope: 'current_repo',
riskLevel: 'read_only',
successCriteria: ['Git status is inspected.'],
podId: created.id,
identity: 'Alice',
sessionId: liveConversation.sessionId,
}),
}),
);
if (!hermesJob.id || hermesJob.status !== 'queued') {
fail('Hermes job create returned unexpected payload');
}
let finalJob = hermesJob;
for (let i = 0; i < 30; i++) {
finalJob = await json(
await doFetch(`${baseUrl}/api/internal/hermes/jobs/${encodeURIComponent(hermesJob.id)}`, {
headers: { authorization: `Bearer ${env.INTERNAL_AGENT_TOKEN}` },
}),
);
if (['completed', 'failed', 'aborted'].includes(finalJob.status)) break;
await delay(500);
}
if (finalJob.status !== 'completed') {
fail(`Hermes job did not complete: ${JSON.stringify(finalJob)}`);
}
const hermesEvents = await json(
await doFetch(
`${baseUrl}/api/internal/hermes/jobs/${encodeURIComponent(hermesJob.id)}/events`,
{
headers: { authorization: `Bearer ${env.INTERNAL_AGENT_TOKEN}` },
},
),
);
if (!Array.isArray(hermesEvents) || hermesEvents.length < 1) {
fail('Hermes job events were not persisted');
}
await json(
await doFetch(`${baseUrl}/api/pods/${encodeURIComponent(created.id)}`, { method: 'DELETE' }),
);
@@ -362,9 +262,6 @@ try {
'health',
'token',
'pod-crud',
'hermes-notify',
'live-conversation-session',
'hermes-job-lifecycle',
'collision',
'memory-recall',
'graph',
-1
View File
@@ -24,7 +24,6 @@ const containerEnv = {
GEMINI_API_KEY: process.env.GEMINI_API_KEY ?? 'verify-gemini',
GEMINI_VISION_MODEL: process.env.GEMINI_VISION_MODEL ?? 'gemini-2.0-flash',
GEMINI_LIVE_MODEL: process.env.GEMINI_LIVE_MODEL ?? 'gemini-3.1-flash-tts-preview',
GEMINI_TTS_VOICE: process.env.GEMINI_TTS_VOICE ?? 'Charon',
GEMINI_EMBEDDING_MODEL: process.env.GEMINI_EMBEDDING_MODEL ?? 'gemini-embedding-001',
GITHUB_TOKEN: process.env.GITHUB_TOKEN ?? 'verify-github',
GITHUB_REPO: process.env.GITHUB_REPO ?? 'karti-ai/podman',
+17 -170
View File
@@ -21,17 +21,7 @@ const { DATA_TOPIC } = await import('../shared/dist/messages.js').catch(() => ({
DATA_TOPIC: 'podman.intervention',
}));
const backendRequire = createRequire(new URL('../backend/package.json', import.meta.url));
const {
AudioFrame,
AudioSource,
LocalAudioTrack,
Room,
TrackPublishOptions,
TrackSource,
} = backendRequire('@livekit/rtc-node');
const pods = await fetchJson('/api/pods');
const verifyPod = pods.find((pod) => pod.id === 'frontend-pod') ?? pods[0];
if (!verifyPod) throw new Error('no pods available for frontend verification');
const { Room } = backendRequire('@livekit/rtc-node');
async function stopChild(child) {
if (!child || child.exitCode !== null || child.signalCode !== null) return;
@@ -99,7 +89,7 @@ async function publishIntervention(room, podId) {
podId,
kind: 'card',
message: 'Verification collision: two engineers are editing frontend/src/App.tsx.',
suggestedAction: { kind: 'open_sync_pr' },
suggestedAction: { kind: 'sync_before_push' },
status: 'pending',
createdAt: now,
};
@@ -130,27 +120,6 @@ async function publishDataMessage(room, message) {
});
}
async function publishAudioProbe(room) {
const source = new AudioSource(24_000, 1, 5_000);
const track = LocalAudioTrack.createAudioTrack(`verify-audio-${process.pid}`, source);
const options = new TrackPublishOptions();
options.source = TrackSource.SOURCE_MICROPHONE;
const publication = await room.localParticipant.publishTrack(track, options);
await source.captureFrame(new AudioFrame(new Int16Array(24_000), 24_000, 1, 24_000));
return { source, publication };
}
async function waitForAttachedAudio(page) {
const audioSink = page.getByTestId('livekit-audio-sink');
await audioSink.waitFor({ timeout: 15_000 });
for (let i = 0; i < 30; i++) {
const count = await audioSink.locator('audio').count();
if (count > 0) return;
await delay(250);
}
throw new Error('LiveKit audio track was not attached to the hidden audio sink');
}
async function waitForInterventionCard(page, room, podId) {
const cardText = 'Verification collision: two engineers are editing frontend/src/App.tsx.';
for (let attempt = 1; attempt <= 3; attempt++) {
@@ -199,27 +168,6 @@ async function waitForPublishedScreenShare(roomName) {
);
}
async function boxOf(locator, name) {
const box = await locator.boundingBox();
if (!box) throw new Error(`${name} did not have a visible bounding box`);
return box;
}
function assertNoOverlap(left, main, right, label) {
if (left.x + left.width > main.x + 2) {
throw new Error(`${label}: left sidebar overlaps main workspace`);
}
if (main.x + main.width > right.x + 2) {
throw new Error(`${label}: right sidebar overlaps main workspace`);
}
}
function assertContained(container, child, label) {
if (child.x < container.x - 2 || child.x + child.width > container.x + container.width + 2) {
throw new Error(`${label}: body summary is not contained inside the main workspace`);
}
}
let preview = null;
if (shouldStartPreview) {
preview = spawn(
@@ -279,9 +227,7 @@ page.on('console', (msg) => {
});
page.on('pageerror', (err) => pageErrors.push(err.message));
page.on('requestfailed', (req) => {
const failure = req.failure()?.errorText ?? '';
if (req.url().includes('/activity/stream') && failure.includes('ERR_ABORTED')) return;
failedRequests.push(`${req.url()} ${failure}`.trim());
failedRequests.push(`${req.url()} ${req.failure()?.errorText ?? ''}`.trim());
});
try {
@@ -289,113 +235,29 @@ try {
await page.waitForTimeout(500);
const bodyText = await page.locator('body').innerText();
const hasPodCards = (await page.getByText(verifyPod.name, { exact: true }).count()) > 0;
const hasPodCards =
(await page.locator('text=/Frontend Pod|Backend Pod|graph pod/i').count()) > 0;
const hasOverlay = (await page.locator('vite-error-overlay, .vite-error-overlay').count()) > 0;
if (bodyText.length < 100) throw new Error('frontend rendered too little text');
if (!hasPodCards) throw new Error('pod cards did not render');
if (hasOverlay) throw new Error('Vite error overlay is visible');
await page.getByRole('button', { name: 'Pod actions' }).first().click();
await page.getByRole('menuitem', { name: 'Team memory' }).click();
await page.getByRole('button', { name: 'Team memory' }).click();
await page.getByText('Workflow metrics').waitFor({ timeout: 15_000 });
await page.getByText('Learning edges').waitFor({ timeout: 15_000 });
await page.getByRole('img', { name: 'PodMan team-memory graph' }).waitFor({ timeout: 15_000 });
await page
.getByRole('button', { name: /engineer:/ })
.first()
.click();
await page.getByText('Relationships').waitFor({ timeout: 15_000 });
await page.getByRole('button', { name: 'engineer: Karti' }).click();
await page.getByText('Learned owner of auth; backend + DB wiring.').waitFor({ timeout: 15_000 });
await page.getByRole('button', { name: 'Whole graph' }).click();
await page.getByRole('button', { name: /Pods/i }).click();
const podCard = page
.getByText(verifyPod.name, { exact: true })
const frontendPodCard = page
.getByText('Frontend Pod', { exact: true })
.locator('xpath=ancestor::*[.//input[@placeholder="Your name"]][1]');
await podCard.getByPlaceholder('Your name').first().fill(verifyMember);
await podCard.getByRole('button', { name: 'Join' }).first().click();
await frontendPodCard.getByPlaceholder('Your name').fill(verifyMember);
await frontendPodCard.getByRole('button', { name: 'Add and join' }).click();
await page.getByRole('button', { name: 'Share screen' }).waitFor({ timeout: 15_000 });
await page.getByTestId('live-conversation-toggle').waitFor({ timeout: 15_000 });
await page.getByRole('button', { name: 'Start Live Conversation' }).waitFor({
timeout: 15_000,
});
if (new URL(page.url()).pathname !== `/${verifyPod.id}`) {
throw new Error(`join did not update URL to /${verifyPod.id}: ${page.url()}`);
}
await page.getByRole('heading', { name: 'My stream' }).waitFor({ timeout: 15_000 });
await page.getByRole('heading', { name: 'Team stream' }).waitFor({ timeout: 15_000 });
const bodySummary = page.getByTestId('pod-body-summary');
const mainWorkspace = page.getByTestId('pod-main-workspace');
const mySidebar = page.getByTestId('my-stream-sidebar');
const teamSidebar = page.getByTestId('team-stream-sidebar');
await bodySummary.waitFor({ timeout: 15_000 });
await mainWorkspace.waitFor({ timeout: 15_000 });
await mySidebar.waitFor({ timeout: 15_000 });
await teamSidebar.waitFor({ timeout: 15_000 });
if ((await page.getByTestId('pod-topbar').count()) > 0) {
throw new Error('pod detail view still renders a topbar test id');
}
if ((await bodySummary.getByRole('button', { name: /stream|team/i }).count()) > 0) {
throw new Error('pod body summary contains sidebar stream/team controls');
}
const expandedLayout = {
summary: await boxOf(bodySummary, 'body summary expanded'),
main: await boxOf(mainWorkspace, 'main workspace expanded'),
left: await boxOf(mySidebar, 'my stream sidebar expanded'),
right: await boxOf(teamSidebar, 'team stream sidebar expanded'),
};
assertNoOverlap(
expandedLayout.left,
expandedLayout.main,
expandedLayout.right,
'expanded layout',
);
assertContained(expandedLayout.main, expandedLayout.summary, 'expanded layout');
await page.locator('[data-testid="my-stream-toggle"]:visible').click();
await page.waitForTimeout(300);
const leftCollapsedLayout = {
main: await boxOf(mainWorkspace, 'main workspace after left collapse'),
left: await boxOf(mySidebar, 'my stream sidebar collapsed'),
right: await boxOf(teamSidebar, 'team stream sidebar with left collapsed'),
summary: await boxOf(bodySummary, 'body summary after left collapse'),
};
if (leftCollapsedLayout.left.width >= expandedLayout.left.width - 24) {
throw new Error('my stream sidebar did not collapse into a compact rail');
}
if (leftCollapsedLayout.main.width <= expandedLayout.main.width) {
throw new Error('main workspace did not expand after my stream collapsed');
}
assertNoOverlap(
leftCollapsedLayout.left,
leftCollapsedLayout.main,
leftCollapsedLayout.right,
'left collapsed layout',
);
assertContained(leftCollapsedLayout.main, leftCollapsedLayout.summary, 'left collapsed layout');
await page.locator('[data-testid="team-stream-toggle"]:visible').click();
await page.waitForTimeout(300);
const bothCollapsedLayout = {
main: await boxOf(mainWorkspace, 'main workspace after both collapse'),
left: await boxOf(mySidebar, 'my stream sidebar with both collapsed'),
right: await boxOf(teamSidebar, 'team stream sidebar collapsed'),
summary: await boxOf(bodySummary, 'body summary after both collapse'),
};
if (bothCollapsedLayout.right.width >= expandedLayout.right.width - 24) {
throw new Error('team stream sidebar did not collapse into a compact rail');
}
if (bothCollapsedLayout.main.width <= leftCollapsedLayout.main.width) {
throw new Error('main workspace did not expand after team stream collapsed');
}
assertNoOverlap(
bothCollapsedLayout.left,
bothCollapsedLayout.main,
bothCollapsedLayout.right,
'both collapsed layout',
);
assertContained(bothCollapsedLayout.main, bothCollapsedLayout.summary, 'both collapsed layout');
await page.locator('[data-testid="my-stream-toggle"]:visible').click();
await page.locator('[data-testid="team-stream-toggle"]:visible').click();
await page.waitForTimeout(300);
const joinedText = await page.locator('body').innerText();
const hasPodView =
@@ -410,30 +272,18 @@ try {
await page.getByRole('button', { name: 'Share screen' }).click();
await page.getByRole('button', { name: 'Stop sharing' }).waitFor({ timeout: 15_000 });
await page.getByText(/Screen\s*published/i).waitFor({ timeout: 15_000 });
await waitForPublishedScreenShare(verifyPod.id);
await waitForPublishedScreenShare('frontend-pod');
await page.getByRole('button', { name: 'Stop sharing' }).click();
await page.getByRole('button', { name: 'Share screen' }).waitFor({ timeout: 15_000 });
const publisher = await connectPublisher(verifyPod.id);
const publisher = await connectPublisher('frontend-pod');
try {
const audioProbe = await publishAudioProbe(publisher);
try {
await waitForAttachedAudio(page);
} finally {
if (audioProbe.publication.sid) {
await publisher.localParticipant
.unpublishTrack(audioProbe.publication.sid, true)
.catch(() => {});
}
await audioProbe.source.close().catch(() => {});
}
const intervention = await waitForInterventionCard(page, publisher, verifyPod.id);
const intervention = await waitForInterventionCard(page, publisher, 'frontend-pod');
await publishDataMessage(publisher, {
type: 'HERMES_MESSAGE',
message: {
id: `hermes-${process.pid}`,
podId: verifyPod.id,
podId: 'frontend-pod',
interventionId: intervention.id,
recipients: ['Verify'],
text: 'Hermes verification message routed to the team.',
@@ -460,7 +310,6 @@ try {
}
await page.getByRole('button', { name: 'Leave pod' }).click();
await page.waitForURL((url) => url.pathname === '/', { timeout: 15_000 });
if (consoleErrors.length) throw new Error(`console errors: ${consoleErrors.join(' | ')}`);
if (pageErrors.length) throw new Error(`page errors: ${pageErrors.join(' | ')}`);
@@ -476,9 +325,7 @@ try {
graph: true,
joined: true,
screenShare: 'livekit-published',
audioSink: 'livekit-attached',
intervention: 'collision-hermes-voice',
podId: verifyPod.id,
member: verifyMember,
},
null,
@@ -486,7 +333,7 @@ try {
),
);
} finally {
await doFetch(`${apiBase}/api/pods/${verifyPod.id}/members/${encodeURIComponent(verifyMember)}`, {
await doFetch(`${apiBase}/api/pods/frontend-pod/members/${encodeURIComponent(verifyMember)}`, {
method: 'DELETE',
}).catch(() => {});
await browser.close();
-1
View File
@@ -62,7 +62,6 @@ const runtimeKeys = [
'GEMINI_API_KEY',
'GEMINI_VISION_MODEL',
'GEMINI_LIVE_MODEL',
'GEMINI_TTS_VOICE',
'GEMINI_EMBEDDING_MODEL',
'GITHUB_TOKEN',
'GITHUB_REPO',
-20
View File
@@ -1,20 +0,0 @@
export type PodActivityKind = 'observation' | 'git' | 'collision' | 'intervention' | 'outcome';
export type PodActivitySource = 'vision' | 'git' | 'memory' | 'hermes' | 'policy';
export type PodActivitySeverity = 'info' | 'warn' | 'critical' | 'success';
export interface PodActivityEvent {
id: string;
podId: string;
kind: PodActivityKind;
source: PodActivitySource;
title: string;
detail?: string;
actor?: string;
actors?: string[];
file?: string;
imageUrl?: string;
severity: PodActivitySeverity;
at: string;
}
-72
View File
@@ -1,72 +0,0 @@
export type AgentRunStatus =
| 'running'
| 'succeeded'
| 'failed'
| 'improved'
| 'regressed'
| 'abandoned';
export interface AgentRun {
runId: string;
podId: string;
goal: string;
trigger: string;
strategyVersionId: string;
status: AgentRunStatus;
startedAt: string;
completedAt?: string;
score?: number;
verifierSummary?: string;
inputRefs?: string[];
outputRefs?: string[];
}
export interface AgentTraceEvent {
runId: string;
podId: string;
step: number;
phase: string;
eventType: string;
inputSummary?: string;
outputSummary?: string;
toolName?: string;
error?: string;
metrics?: Record<string, number | string | boolean>;
createdAt: string;
}
export type StrategyVersionKind = 'prompt' | 'policy' | 'detector' | 'verifier' | 'routing';
export type StrategyVersionStatus = 'candidate' | 'active' | 'retired' | 'rejected';
export interface StrategyVersion {
strategyVersionId: string;
podId: string;
kind: StrategyVersionKind;
name: string;
parentVersionId?: string;
status: StrategyVersionStatus;
summary: string;
promptText?: string;
policy?: Record<string, unknown>;
verifier?: Record<string, unknown>;
metrics?: Record<string, number | string | boolean>;
createdAt: string;
promotedAt?: string;
}
export type LearningProposalStatus = 'open' | 'accepted' | 'rejected' | 'superseded';
export interface LearningProposal {
proposalId: string;
podId: string;
sourceRunId: string;
targetKind: StrategyVersionKind;
parentVersionId: string;
proposedChange: string;
rationale: string;
verifierPlan: string;
status: LearningProposalStatus;
createdAt: string;
resolvedAt?: string;
}
-8
View File
@@ -16,14 +16,6 @@ export interface Collision {
severity: CollisionSeverity;
/** Snapshot of relevant GitHub state at detection time. */
githubState?: GithubStateSnapshot;
/**
* Git ground-truth overlap captured AT detection time, while engineer_states
* are still fresh: true when every involved engineer had `file` in their git
* changedFiles. Read as the authoritative wasRealCollision evidence at outcome
* time, so a late click, a stale sidecar, or the engineer_states freshness TTL
* cannot retroactively zero it out.
*/
gitOverlap?: boolean;
detectedAt: string;
}
-2
View File
@@ -16,8 +16,6 @@ export interface EngineerContext {
hasUnpushedChanges?: boolean;
/** 01 confidence in this read of the screen. */
confidence: number;
/** Small redacted-size JPEG data URL for sidebar preview, not the full frame. */
screenshotDataUrl?: string;
/** ISO timestamp of the observation this context came from. */
observedAt: string;
}
+30 -33
View File
@@ -5,7 +5,7 @@
*
* Served embedded in the `team_model` document; mirrored into `graph_nodes` /
* `graph_edges` collections so the model can be walked with MongoDB
* `$graphLookup`. See docs/cont_learning.md.
* `$graphLookup`. See docs/graph.md.
*/
export type PodGraphNodeKind = 'engineer' | 'feature' | 'file' | 'collision' | 'intervention';
@@ -48,39 +48,34 @@ export interface PodGraphMetric {
detail: string;
}
export type PodLearningLoopStepKey = 'observe' | 'store' | 'predict' | 'outcome' | 'adapt';
/** The five stages of PodMan's continual-learning loop, in order. */
export type LearningStageKey = 'observe' | 'store' | 'predict' | 'outcome' | 'adapt';
export type PodLearningLoopStepStatus = 'quiet' | 'active' | 'complete' | 'planned';
export interface PodLearningLoopStep {
key: PodLearningLoopStepKey;
label: string;
value: string;
detail: string;
status: PodLearningLoopStepStatus;
}
export interface PodLearningLoop {
activeStep: PodLearningLoopStepKey;
steps: PodLearningLoopStep[];
}
export type PodGraphActivityKind =
| 'editing'
| 'collision'
| 'intervention'
| 'outcome'
| 'learned'
| 'agent';
export interface PodGraphActivity {
id: string;
at: string;
kind: PodGraphActivityKind;
/** One stage of the learning-loop rail (observe→store→predict→outcome→adapt). */
export interface LearningStage {
key: LearningStageKey;
/** UPPERCASE display title, e.g. "OBSERVE". */
title: string;
/** Headline figure for the stage, e.g. "5/s" or "124". */
value: string;
/** One-line detail under the title. */
detail: string;
nodeId?: string;
edgeId?: string;
/** True for the single most-recently-active stage (pulses in the UI). */
active: boolean;
}
/** Kind of an activity-stream entry (drives the colored tag). */
export type ActivityKind = 'editing' | 'collision' | 'warns' | 'outcome' | 'learned_from';
/** One time-tagged entry in the activity stream. */
export interface ActivityEvent {
/** Stable id (source doc id + kind) so the UI can animate diffs. */
id: string;
/** ISO timestamp the event happened. */
at: string;
kind: ActivityKind;
/** Human-readable line, e.g. "Yahya opened auth.ts — unpushed changes". */
text: string;
}
/** A point-in-time render of a pod's team_model. */
@@ -91,8 +86,10 @@ export interface PodGraph {
nodes: PodGraphNode[];
edges: PodGraphEdge[];
metrics: PodGraphMetric[];
loop?: PodLearningLoop;
activity?: PodGraphActivity[];
/** Continual-learning loop counts (observe→…→adapt). Additive/optional. */
loop?: LearningStage[];
/** Recent activity feed, most-recent first, capped ~8. Additive/optional. */
activity?: ActivityEvent[];
}
/** One node as a standalone document in the `graph_nodes` collection. */
-79
View File
@@ -1,79 +0,0 @@
export type HermesJobStatus =
| 'queued'
| 'running'
| 'waiting_for_confirmation'
| 'aborting'
| 'aborted'
| 'failed'
| 'completed';
export type HermesJobEventType =
| 'accepted'
| 'heartbeat'
| 'step_started'
| 'step_output'
| 'needs_confirmation'
| 'step_completed'
| 'aborted'
| 'failed'
| 'completed';
export type HermesContextScope =
| 'current_pod'
| 'current_repo'
| 'current_file'
| 'github'
| 'mongodb'
| 'terminal'
| 'full_workspace';
export type HermesRiskLevel = 'read_only' | 'safe_write' | 'commit_allowed' | 'deploy_allowed';
export interface HermesJobInput {
prompt: string;
contextScope: HermesContextScope;
targetRepository?: string;
riskLevel: HermesRiskLevel;
requiresConfirmation?: boolean;
successCriteria: string[];
podId: string;
identity: string;
sessionId: string;
conversationRoom?: string;
parentJobId?: string;
}
export interface HermesJob {
id: string;
podId: string;
identity: string;
sessionId: string;
conversationRoom?: string;
prompt: string;
contextScope: HermesContextScope;
targetRepository: string;
riskLevel: HermesRiskLevel;
requiresConfirmation: boolean;
successCriteria: string[];
parentJobId?: string;
status: HermesJobStatus;
finalSummary?: string;
error?: string;
createdAt: string;
updatedAt: string;
startedAt?: string;
completedAt?: string;
lastHeartbeatAt?: string;
abortRequestedAt?: string;
}
export interface HermesJobEvent {
id: string;
jobId: string;
podId: string;
sessionId: string;
type: HermesJobEventType;
message: string;
data?: Record<string, unknown>;
createdAt: string;
}
+5 -38
View File
@@ -1,11 +1,5 @@
export type { Pod, PodInput, Engineer } from './pod.js';
export type { EngineerContext } from './engineer.js';
export type {
PodActivityEvent,
PodActivityKind,
PodActivitySeverity,
PodActivitySource,
} from './activity.js';
export type { Collision, CollisionSeverity, GithubStateSnapshot } from './collision.js';
export type {
Intervention,
@@ -15,46 +9,19 @@ export type {
SuggestedActionKind,
} from './intervention.js';
export * from './messages.js';
export type { HermesMessage, LiveConversationEvent } from './messages.js';
export type {
HermesContextScope,
HermesJob,
HermesJobEvent,
HermesJobEventType,
HermesJobInput,
HermesJobStatus,
HermesRiskLevel,
} from './hermes-job.js';
export type { HermesMessage } from './messages.js';
export type {
PodGraph,
PodGraphNode,
PodGraphEdge,
PodGraphMetric,
PodLearningLoop,
PodLearningLoopStep,
PodLearningLoopStepKey,
PodLearningLoopStepStatus,
PodGraphActivity,
PodGraphActivityKind,
PodGraphNodeKind,
PodGraphEdgeKind,
PodGraphNodeStatus,
LearningStage,
LearningStageKey,
ActivityEvent,
ActivityKind,
GraphNodeDoc,
GraphEdgeDoc,
} from './graph.js';
export type {
AgentRun,
AgentRunStatus,
AgentTraceEvent,
StrategyVersion,
StrategyVersionKind,
StrategyVersionStatus,
LearningProposal,
LearningProposalStatus,
} from './agent-learning.js';
export type {
MemberWorkHistory,
MemberWorkHistoryEvent,
MemberWorkHistoryFile,
MemberWorkHistorySource,
} from './member-history.js';
-36
View File
@@ -1,36 +0,0 @@
export type MemberWorkHistorySource = 'vision' | 'git';
export interface MemberWorkHistoryFile {
file: string;
observations: number;
gitChanges: number;
firstSeenAt: string;
lastSeenAt: string;
confidenceAvg: number | null;
activities: string[];
current: boolean;
}
export interface MemberWorkHistoryEvent {
id: string;
at: string;
source: MemberWorkHistorySource;
file: string;
title: string;
detail?: string;
confidence?: number;
}
export interface MemberWorkHistory {
podId: string;
member: string;
generatedAt: string;
windowHours: number;
totals: {
files: number;
observations: number;
gitChanges: number;
};
files: MemberWorkHistoryFile[];
timeline: MemberWorkHistoryEvent[];
}
+1 -20
View File
@@ -1,5 +1,4 @@
import type { Collision } from './collision.js';
import type { HermesJobEvent } from './hermes-job.js';
import type { Intervention, InterventionStatus } from './intervention.js';
/** Topics multiplexed over the LiveKit data channel. */
@@ -10,12 +9,8 @@ export type DataMessage =
| { type: 'COLLISION'; collision: Collision; intervention: Intervention }
| { type: 'HERMES_MESSAGE'; message: HermesMessage }
| { type: 'VOICE_CUE'; text: string }
| { type: 'LIVE_CONVERSATION_EVENT'; event: LiveConversationEvent }
| { type: 'HERMES_JOB_EVENT'; event: HermesJobEvent }
| { type: 'ACK'; interventionId: string; status: InterventionStatus; note?: string }
| { type: 'GIT_REPORT'; report: LocalGitReport }
/** Any participant → the current test-audio owner: stop publishing the shared beat. */
| { type: 'BEAT_STOP' };
| { type: 'GIT_REPORT'; report: LocalGitReport };
/** A targeted teammate/project-channel notification from the Hermes action layer. */
export interface HermesMessage {
@@ -28,20 +23,6 @@ export interface HermesMessage {
createdAt: string;
}
/** Private-room event that lets PodMan interrupt a 1:1 live conversation. */
export interface LiveConversationEvent {
id: string;
podId: string;
sessionId: string;
kind: 'critical_collision' | 'context_refresh';
severity: 'info' | 'warn' | 'critical';
summary: string;
interrupt: boolean;
createdAt: string;
collisionId?: string;
interventionId?: string;
}
/** Outcome of an intervention — the supervision signal for policy learning. */
export interface InterventionOutcome {
interventionId: string;