hird-server 0.3.0

The central queue: hird served over HTTP for harnesses on other machines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! `/watch`: the factory floor, live, in a browser.
//!
//! `hird web` is the local board, drawn from the same SQLite file the agents
//! use. A factory runs on `hird-server`, though, and only the server knows the
//! roster: who is a builder, who reviews, which token is CI. So this view
//! lives here, beside the MCP endpoints, under the same rules:
//!
//! - **It is read-only.** Every route is a `GET`. The page has no button that
//!   writes. Moves stay with the four factory tools and the CLI.
//! - **It asks for a token.** The page itself carries no data and is served to
//!   anyone; every data route needs a bearer token from the roster, refused
//!   with the same answer the MCP endpoint gives. Any role may watch, which is
//!   what `factory_board` already allows.
//! - **It shows no tokens.** The crew is the roster's identities, harnesses,
//!   roles and models, never its credentials.
//!
//! The page polls once a second. Each poll sweeps expired leases (announcing
//! them when a dispatch hook is configured, as `hird web` does), so a lapsed
//! lease shows as lapsed rather than as a builder who is still working.

use std::collections::BTreeMap;
use std::sync::Arc;

use axum::body::Body;
use axum::extract::{Path, Query, State};
use axum::http::{header, Request, StatusCode};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use hird::identity::{principal_name, AgentId};
use hird::mcp::Shared;
use hird::model::now_ts;
use hird::repo::TrailEntry;
use hird_factory::ops::BoardRow;
use hird_factory::{Factory, Policy, Role};
use serde::{Deserialize, Serialize};

use crate::roster::{Roster, Worker};

/// The page, embedded so the binary stays one file.
const PAGE: &str = include_str!("watch.html");

/// How much of the trail a page starts with.
const TAIL: usize = 120;
/// How much of it one poll may catch up on.
const CATCH_UP: usize = 500;

#[derive(Clone)]
pub struct Watch {
    shared: Arc<Shared>,
    workers: Arc<BTreeMap<String, Worker>>,
    /// `None` when the roster turns no factory on: stages are still derived,
    /// under the default policy, and the page says the factory is off.
    policy: Option<Policy>,
}

impl Watch {
    pub fn new(roster: &Roster, shared: Arc<Shared>) -> Watch {
        Watch {
            shared,
            workers: Arc::new(
                roster
                    .entries()
                    .map(|(token, worker)| (token.clone(), worker.clone()))
                    .collect(),
            ),
            policy: roster.factory().cloned(),
        }
    }

    pub fn router(self) -> Router {
        Router::new()
            .route("/watch", get(page))
            .route("/watch/api/floor", get(floor))
            .route("/watch/api/task/{seq}", get(task))
            .with_state(self)
    }

    /// The roster entry a request's bearer token names.
    fn caller(&self, request: &Request<Body>) -> Option<&Worker> {
        let token = crate::bearer(request)?;
        self.workers.get(token)
    }

    fn policy(&self) -> Policy {
        self.policy.clone().unwrap_or_default()
    }
}

fn unauthorized() -> Response {
    (
        StatusCode::UNAUTHORIZED,
        [(header::WWW_AUTHENTICATE, "Bearer realm=\"hird\"")],
        "this queue is not open to unnamed callers\n",
    )
        .into_response()
}

fn failed(status: StatusCode, message: impl Into<String>) -> Response {
    (status, Json(serde_json::json!({ "error": message.into() }))).into_response()
}

async fn page() -> Html<&'static str> {
    Html(PAGE)
}

#[derive(Debug, Deserialize)]
struct FloorQuery {
    /// The last trail cursor the page has; absent on the first poll.
    after: Option<i64>,
}

/// Everything the page draws, in one answer.
#[derive(Debug, Serialize)]
struct Floor {
    now: String,
    project: String,
    factory: bool,
    policy: Policy,
    me: CrewMember,
    crew: Vec<CrewMember>,
    board: Vec<BoardRow>,
    trail: Vec<TrailEntry>,
    /// Where the next poll picks the trail up.
    cursor: Option<i64>,
}

/// One roster entry, as the floor shows it: never its token.
#[derive(Debug, Clone, Serialize)]
struct CrewMember {
    identity: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    harness: Option<String>,
    roles: Vec<Role>,
    #[serde(skip_serializing_if = "Option::is_none")]
    model: Option<String>,
    /// The start every actor string of this worker's sessions shares.
    prefix: String,
    /// When any of its sessions last wrote to the trail.
    #[serde(skip_serializing_if = "Option::is_none")]
    last_seen: Option<String>,
}

/// The start of every actor string a worker's sessions record: who, then the
/// pinned harness when there is one, normalized the way sessions are.
fn prefix(worker: &Worker) -> String {
    match &worker.harness {
        Some(harness) => {
            let actor = AgentId::new(harness.clone(), "s")
                .acting_for(worker.identity.clone())
                .as_actor();
            actor.strip_suffix('s').unwrap_or(&actor).to_string()
        }
        None => format!(
            "{}/",
            principal_name(&worker.identity).unwrap_or_else(|| worker.identity.clone())
        ),
    }
}

fn member(worker: &Worker) -> CrewMember {
    CrewMember {
        identity: worker.identity.clone(),
        harness: worker.harness.clone(),
        roles: worker.roles.iter().collect(),
        model: worker.model.clone(),
        prefix: prefix(worker),
        last_seen: None,
    }
}

async fn floor(
    State(watch): State<Watch>,
    Query(query): Query<FloorQuery>,
    request: Request<Body>,
) -> Response {
    let Some(caller) = watch.caller(&request) else {
        return unauthorized();
    };
    let project = caller.project.clone();
    let policy = watch.policy();
    // Sweep first, so what the page draws is what a claim would now find.
    watch.shared.sweep();
    let answer = watch.shared.with_db(|db| {
        let board = Factory::new(db, &policy).board(Some(&project))?;
        let trail = match query.after {
            None => db.audit().trail(Some(&project), None, TAIL)?,
            Some(after) => db.audit().trail(Some(&project), Some(after), CATCH_UP)?,
        };
        let mut crew = Vec::new();
        let mut seen = std::collections::BTreeSet::new();
        for worker in watch.workers.values() {
            if worker.project != project {
                continue;
            }
            let mut member = member(worker);
            // One person may hold several tokens for one harness; the floor
            // shows them once.
            if !seen.insert(member.prefix.clone()) {
                continue;
            }
            member.last_seen = db.audit().last_seen(&member.prefix)?;
            crew.push(member);
        }
        crew.sort_by(|a, b| a.prefix.cmp(&b.prefix));
        let cursor = trail.last().map(|e| e.cursor).or(query.after);
        Ok::<_, hird::error::Error>(Floor {
            now: now_ts(),
            project: project.clone(),
            factory: watch.policy.is_some(),
            policy: policy.clone(),
            me: member(caller),
            crew,
            board,
            trail,
            cursor,
        })
    });
    match answer {
        Ok(floor) => Json(floor).into_response(),
        Err(e) => failed(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
    }
}

async fn task(
    State(watch): State<Watch>,
    Path(seq): Path<i64>,
    request: Request<Body>,
) -> Response {
    let Some(caller) = watch.caller(&request) else {
        return unauthorized();
    };
    let policy = watch.policy();
    let view = watch.shared.with_db(|db| -> hird::error::Result<_> {
        let task = db.tasks().get(seq)?;
        if task.project != caller.project {
            return Err(hird::error::Error::TaskNotFound { seq });
        }
        Factory::new(db, &policy).view(seq)
    });
    match view {
        Ok(view) => Json(view).into_response(),
        Err(e @ hird::error::Error::TaskNotFound { .. }) => {
            failed(StatusCode::NOT_FOUND, e.to_string())
        }
        Err(e) => failed(StatusCode::UNPROCESSABLE_ENTITY, e.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hird::config::Config;
    use hird::Db;
    use serde_json::Value;

    const ROSTER: &str = r#"
project = "/srv/acme"
[factory]
max_attempts = 3

[[worker]]
token = "builder-token-0123456789abcdef"
identity = "ana"
harness = "claude-code"
model = "model-a"
roles = ["builder"]

[[worker]]
token = "human-token-0123456789abcdef0"
identity = "dee"
harness = "human"
roles = ["human"]

[[worker]]
token = "other-project-0123456789abcd"
identity = "zed"
project = "/srv/other"
"#;

    fn watch() -> Watch {
        let roster = Roster::parse(ROSTER).unwrap();
        let shared = Arc::new(Shared::new(
            Db::open_in_memory().unwrap(),
            Config::default(),
        ));
        Watch::new(&roster, shared)
    }

    fn request(token: Option<&str>) -> Request<Body> {
        let mut builder = Request::builder().uri("/watch/api/floor");
        if let Some(token) = token {
            builder = builder.header(header::AUTHORIZATION, format!("Bearer {token}"));
        }
        builder.body(Body::empty()).unwrap()
    }

    async fn body(response: Response) -> (StatusCode, String) {
        let status = response.status();
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, String::from_utf8(bytes.to_vec()).unwrap())
    }

    async fn poll(w: &Watch, token: &str, after: Option<i64>) -> Value {
        let (status, text) = body(
            floor(
                State(w.clone()),
                Query(FloorQuery { after }),
                request(Some(token)),
            )
            .await,
        )
        .await;
        assert_eq!(status, StatusCode::OK, "{text}");
        serde_json::from_str(&text).unwrap()
    }

    #[tokio::test]
    async fn the_page_is_public_and_holds_no_data() {
        let Html(page) = page().await;
        assert!(page.contains("factory floor"));
        assert!(!page.contains("/srv/acme"));
    }

    #[tokio::test]
    async fn the_floor_is_refused_without_a_rostered_token() {
        let w = watch();
        for token in [None, Some("not-a-token-at-all-0123456789")] {
            let (status, text) = body(
                floor(
                    State(w.clone()),
                    Query(FloorQuery { after: None }),
                    request(token),
                )
                .await,
            )
            .await;
            assert_eq!(status, StatusCode::UNAUTHORIZED);
            assert!(text.contains("not open to unnamed callers"), "{text}");
        }
        let task = task(State(w.clone()), Path(1), request(None)).await;
        assert_eq!(task.status(), StatusCode::UNAUTHORIZED);
    }

    /// The floor names the crew of the caller's project, by identity, harness,
    /// roles and model, and never by token.
    #[tokio::test]
    async fn the_floor_shows_the_crew_and_board_and_never_a_token() {
        let w = watch();
        let seq = w.shared.with_db(|db| {
            db.tasks()
                .create("/srv/acme", "port the loader", "", 0, "cli")
                .unwrap()
                .seq
        });
        w.shared.with_db(|db| {
            db.tasks()
                .create("/srv/other", "not ours", "", 0, "cli")
                .unwrap();
        });
        let floor = poll(&w, "human-token-0123456789abcdef0", None).await;
        let text = floor.to_string();
        for token in ["builder-token", "human-token", "other-project"] {
            assert!(!text.contains(token), "a token leaked: {text}");
        }
        assert_eq!(floor["factory"], true);
        assert_eq!(floor["me"]["identity"], "dee");
        let crew: Vec<&str> = floor["crew"]
            .as_array()
            .unwrap()
            .iter()
            .map(|m| m["identity"].as_str().unwrap())
            .collect();
        assert_eq!(crew, vec!["ana", "dee"], "only this project's crew");
        assert_eq!(floor["crew"][0]["prefix"], "ana/claude-code:");
        assert_eq!(floor["crew"][0]["model"], "model-a");
        let board = floor["board"].as_array().unwrap();
        assert_eq!(board.len(), 1, "only this project's work");
        assert_eq!(board[0]["seq"], seq);
        assert_eq!(board[0]["stage"], "ready");
        assert_eq!(floor["trail"][0]["kind"], "created");
    }

    /// The trail is followed by cursor: a poll returns only what was written
    /// since the last one, with role and model on each move.
    #[tokio::test]
    async fn the_trail_is_followed_from_the_cursor_the_last_poll_returned() {
        let w = watch();
        let seq = w.shared.with_db(|db| {
            db.tasks()
                .create("/srv/acme", "port the loader", "", 0, "cli")
                .unwrap()
                .seq
        });
        let first = poll(&w, "human-token-0123456789abcdef0", None).await;
        let cursor = first["cursor"].as_i64().unwrap();
        let quiet = poll(&w, "human-token-0123456789abcdef0", Some(cursor)).await;
        assert!(quiet["trail"].as_array().unwrap().is_empty());
        assert_eq!(quiet["cursor"], cursor, "a quiet poll keeps its place");

        w.shared.with_db(|db| {
            db.audit()
                .declare(
                    "ana/claude-code:a1",
                    &hird::repo::Stamp {
                        model: Some("model-a".into()),
                        role: Some("builder".into()),
                    },
                )
                .unwrap();
            db.tasks()
                .claim(
                    seq,
                    "ana/claude-code:a1",
                    std::time::Duration::from_secs(60),
                )
                .unwrap();
        });
        let next = poll(&w, "human-token-0123456789abcdef0", Some(cursor)).await;
        let trail = next["trail"].as_array().unwrap();
        assert_eq!(trail.len(), 1);
        assert_eq!(trail[0]["kind"], "claimed");
        assert_eq!(trail[0]["role"], "builder");
        assert_eq!(trail[0]["model"], "model-a");
        assert_eq!(next["board"][0]["stage"], "claimed");
        assert_eq!(next["board"][0]["holder"], "ana/claude-code:a1");
        assert!(next["crew"][0]["last_seen"].is_string());
    }

    #[tokio::test]
    async fn a_task_opens_in_full_and_only_in_the_callers_project() {
        let w = watch();
        let (ours, theirs) = w.shared.with_db(|db| {
            let ours = db
                .tasks()
                .create("/srv/acme", "port the loader", "the brief", 0, "cli")
                .unwrap()
                .seq;
            let theirs = db
                .tasks()
                .create("/srv/other", "not ours", "", 0, "cli")
                .unwrap()
                .seq;
            (ours, theirs)
        });
        let req = || request(Some("builder-token-0123456789abcdef"));
        let (status, text) = body(task(State(w.clone()), Path(ours), req()).await).await;
        assert_eq!(status, StatusCode::OK, "{text}");
        let view: Value = serde_json::from_str(&text).unwrap();
        assert_eq!(view["body"], "the brief");
        assert_eq!(view["stage"], "ready");
        assert_eq!(view["trail"][0]["kind"], "created");
        assert!(view["attempts_detail"].as_array().unwrap().is_empty());

        let (status, _) = body(task(State(w.clone()), Path(theirs), req()).await).await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        let (status, _) = body(task(State(w.clone()), Path(999), req()).await).await;
        assert_eq!(status, StatusCode::NOT_FOUND);
    }

    /// A lease that lapsed shows as lapsed: the poll sweeps before it reads.
    #[tokio::test]
    async fn watching_sweeps_expired_leases_before_drawing() {
        let w = watch();
        let seq = w.shared.with_db(|db| {
            let seq = db
                .tasks()
                .create("/srv/acme", "port the loader", "", 0, "cli")
                .unwrap()
                .seq;
            db.tasks()
                .claim(
                    seq,
                    "ana/claude-code:a1",
                    std::time::Duration::from_millis(1),
                )
                .unwrap();
            seq
        });
        std::thread::sleep(std::time::Duration::from_millis(20));
        let floor = poll(&w, "human-token-0123456789abcdef0", None).await;
        assert_eq!(floor["board"][0]["seq"], seq);
        assert_eq!(floor["board"][0]["stage"], "ready");
    }
}