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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! The factory's tools, served beside the twelve.
//!
//! Core `hird mcp` serves exactly twelve tools and keeps them. A factory needs
//! four more that no local agent has a use for — CI reporting, a merge, a
//! human's decision, the board — so they live here, in the binary that has a
//! roster to say who may call them. [`FactoryMcp`] wraps a connection's
//! [`HirdMcp`]: it lists the core tools and its own, and routes a call to
//! whichever owns the name. Without a factory policy it is the core server and
//! nothing more.

use std::sync::Arc;

use hird::mcp::HirdMcp;
use hird_factory::{Decision, Factory, Policy, Roles, Stage};
use rmcp::handler::server::tool::ToolCallContext;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CallToolRequestParams, CallToolResponse, DiscoverResult, ListToolsResult,
    PaginatedRequestParams, ServerConfig,
};
use rmcp::service::RequestContext;
use rmcp::{tool, tool_router, ErrorData, RoleServer, ServerHandler};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// The factory a connection belongs to: the policy, and what this token may do.
#[derive(Clone)]
pub struct Membership {
    pub policy: Arc<Policy>,
    pub roles: Roles,
}

/// One connection: the core server, and the factory it belongs to, if any.
#[derive(Clone)]
pub struct FactoryMcp {
    core: Arc<HirdMcp>,
    member: Option<Membership>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GateArgs {
    /// The work task the report is about.
    pub seq: i64,
    /// `pass` or `fail`.
    pub outcome: String,
    /// What the gate printed. Required on a failure: the next builder is
    /// handed it as the reason the work came back.
    #[serde(default)]
    pub output: Option<String>,
    /// A link or id for the run: a CI URL, a job number.
    #[serde(default)]
    pub evidence: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct MergeArgs {
    /// The approved work task that is now merged.
    pub seq: i64,
    /// The commit SHA or PR URL that proves it.
    pub evidence: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DecideArgs {
    /// The work task the decision is about.
    pub seq: i64,
    /// `approve`, `reject`, `answer`, `reopen` or `cancel`.
    pub action: String,
    /// The reason, the findings, or the answer.
    pub text: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct BoardArgs {
    /// Only work at this stage: ready, claimed, built, in_review, approved,
    /// merged, escalated or cancelled.
    #[serde(default)]
    pub stage: Option<String>,
}

#[derive(Serialize)]
struct BoardAnswer {
    roles: String,
    tasks: Vec<hird_factory::ops::BoardRow>,
}

impl FactoryMcp {
    pub fn new(core: HirdMcp, member: Option<Membership>) -> FactoryMcp {
        FactoryMcp {
            core: Arc::new(core),
            member,
        }
    }

    fn member(&self) -> Result<&Membership, String> {
        self.member
            .as_ref()
            .ok_or_else(|| "this queue does not run a factory".to_string())
    }

    /// Run a factory move with this connection's identity and roles.
    fn act<T: Serialize>(
        &self,
        f: impl FnOnce(&Factory<'_>, &str, &Roles) -> hird::error::Result<T>,
    ) -> Result<String, String> {
        let member = self.member()?;
        let actor = self.core.actor();
        let out = self
            .core
            .with_db(|db| f(&Factory::new(db, &member.policy), &actor, &member.roles))
            .map_err(|e| e.to_string())?;
        serde_json::to_string(&out).map_err(|e| format!("failed to encode result: {e}"))
    }

    fn is_factory_tool(name: &str) -> bool {
        Self::tool_router()
            .list_all()
            .iter()
            .any(|t| t.name == name)
    }
}

#[tool_router]
impl FactoryMcp {
    /// CI only. Report a test run on built, in-review or approved work. A
    /// failure sends the work back to the pool with the output in its brief.
    #[tool(name = "factory_gate")]
    async fn factory_gate(&self, Parameters(args): Parameters<GateArgs>) -> Result<String, String> {
        let passed = match args.outcome.trim() {
            "pass" => true,
            "fail" => false,
            other => return Err(format!("outcome must be pass or fail, not {other:?}")),
        };
        let output = args.output.unwrap_or_default();
        let evidence = args.evidence.unwrap_or_default();
        self.act(|factory, actor, roles| {
            factory.report(args.seq, actor, roles, passed, &output, &evidence)
        })
    }

    /// CI or a human. Record that approved work is merged, with the commit SHA
    /// or PR URL that proves it.
    #[tool(name = "factory_merge")]
    async fn factory_merge(
        &self,
        Parameters(args): Parameters<MergeArgs>,
    ) -> Result<String, String> {
        let out = self
            .act(|factory, actor, roles| factory.merge(args.seq, actor, roles, &args.evidence))?;
        // Committed: what waited on this work and on nothing else can go now.
        self.core.announce_unblocked_by(args.seq);
        Ok(out)
    }

    /// Humans only. Approve or reject work under review, answer an escalated
    /// task's question, reopen failed, approved or merged work, or cancel.
    #[tool(name = "factory_decide")]
    async fn factory_decide(
        &self,
        Parameters(args): Parameters<DecideArgs>,
    ) -> Result<String, String> {
        let decision: Decision = args.action.parse()?;
        self.act(|factory, actor, roles| {
            factory.decide(args.seq, actor, roles, decision, &args.text)
        })
    }

    /// Every work task in this project with its factory stage and builders.
    #[tool(name = "factory_board")]
    async fn factory_board(
        &self,
        Parameters(args): Parameters<BoardArgs>,
    ) -> Result<String, String> {
        let want: Option<Stage> = match args.stage.as_deref() {
            None => None,
            Some(name) => Some(
                Stage::ALL
                    .into_iter()
                    .find(|s| s.as_str() == name.trim())
                    .ok_or_else(|| format!("unknown stage {name:?}"))?,
            ),
        };
        let project = self.core.project().to_string();
        self.act(|factory, _, roles| {
            let tasks = factory
                .board(Some(&project))?
                .into_iter()
                .filter(|row| want.is_none_or(|s| row.stage == s))
                .collect();
            Ok(BoardAnswer {
                roles: roles.to_string(),
                tasks,
            })
        })
    }
}

impl ServerHandler for FactoryMcp {
    fn get_info(&self) -> ServerConfig {
        let info = self.core.get_info();
        match &self.member {
            None => info,
            Some(member) => {
                let core = info.instructions.clone().unwrap_or_default();
                info.with_instructions(format!(
                    "{core}\n\nThis queue runs a factory. You hold {}. Work moves ready → \
                     claimed → built → in_review → approved → merged; nobody reviews work \
                     they or their harness ever held. factory_board shows every task's stage.",
                    member.roles
                ))
            }
        }
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        if self.member.is_some() && Self::is_factory_tool(&request.name) {
            if let Some(client) = context.client_info() {
                self.core.name_from_client(&client.name);
            }
            return Self::tool_router()
                .call(ToolCallContext::new(self, request, context))
                .await;
        }
        self.core.call_tool(request, context).await
    }

    async fn list_tools(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        let mut listed = self.core.list_tools(request, context).await?;
        if self.member.is_some() {
            listed.tools.extend(Self::tool_router().list_all());
        }
        Ok(listed)
    }

    async fn discover(
        &self,
        _context: RequestContext<RoleServer>,
    ) -> Result<DiscoverResult, ErrorData> {
        Ok(DiscoverResult::from_server_info(
            self.supported_protocol_versions().into_owned(),
            self.get_info(),
        )
        .with_ttl_ms(0)
        .with_cache_scope(rmcp::model::CacheScope::Private))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hird::config::Config;
    use hird::mcp::Shared;
    use hird::Db;
    use hird_factory::Role;
    use serde_json::Value;
    use std::time::Duration;

    const PROJECT: &str = "/srv/acme";
    const TTL: Duration = Duration::from_secs(900);

    fn shared() -> Arc<Shared> {
        Arc::new(Shared::new(
            Db::open_in_memory().unwrap(),
            Config::default(),
        ))
    }

    fn worker(identity: &str, harness: &str, roles: &[Role]) -> crate::roster::Worker {
        crate::roster::Worker {
            identity: identity.into(),
            harness: Some(harness.into()),
            project: PROJECT.into(),
            capabilities: Vec::new(),
            roles: Roles::new(roles.iter().copied()),
            model: Some(format!("{harness}-model")),
        }
    }

    fn connect(shared: &Arc<Shared>, w: &crate::roster::Worker) -> FactoryMcp {
        let policy = Some(Arc::new(Policy::default()));
        crate::connect(w, policy, shared.clone(), &Config::default(), None).unwrap()
    }

    fn parse(raw: Result<String, String>) -> Value {
        serde_json::from_str(&raw.expect("tool call succeeded")).unwrap()
    }

    /// Claim and finish the way the core tools do: through the session's gate.
    fn claim(m: &FactoryMcp, seq: i64) -> hird::Result<()> {
        let actor = m.core.actor();
        m.core.with_db(|db| {
            db.tasks()
                .gated(m.core.session().gate())
                .claim(seq, &actor, TTL)
                .map(drop)
        })
    }

    fn complete(m: &FactoryMcp, seq: i64, verdict: Option<hird::model::Verdict>) {
        let actor = m.core.actor();
        m.core
            .with_db(|db| {
                db.tasks()
                    .gated(m.core.session().gate())
                    .complete_with(seq, &actor, "done", verdict)
            })
            .unwrap();
    }

    struct Team {
        builder: FactoryMcp,
        reviewer: FactoryMcp,
        ci: FactoryMcp,
        human: FactoryMcp,
    }

    fn team() -> Team {
        let shared = shared();
        Team {
            builder: connect(&shared, &worker("bo", "claude-code", &[Role::Builder])),
            reviewer: connect(&shared, &worker("rae", "codex", &[Role::Reviewer])),
            ci: connect(&shared, &worker("ci", "ci", &[Role::Ci])),
            human: connect(&shared, &worker("ana", "human", &[Role::Human])),
        }
    }

    #[tokio::test]
    async fn work_moves_from_ready_to_merged_through_the_server_and_its_roles() {
        let t = team();
        let seq = t
            .human
            .core
            .with_db(|db| db.tasks().create(PROJECT, "port the loader", "", 0, "cli"))
            .unwrap()
            .seq;

        // Only the builder may build.
        assert!(claim(&t.reviewer, seq).is_err());
        claim(&t.builder, seq).unwrap();
        complete(&t.builder, seq, None);

        let board = parse(
            t.human
                .factory_board(Parameters(BoardArgs { stage: None }))
                .await,
        );
        assert_eq!(board["tasks"][0]["stage"], "built");
        assert_eq!(board["roles"], "human");

        // CI passes it; the builder may not report.
        let pass = || GateArgs {
            seq,
            outcome: "pass".into(),
            output: None,
            evidence: Some("run 7".into()),
        };
        let refused = t
            .builder
            .factory_gate(Parameters(pass()))
            .await
            .unwrap_err();
        assert!(refused.contains("needs the ci role"), "{refused}");
        t.ci.factory_gate(Parameters(pass())).await.unwrap();

        // The review: the builder may not take it, the reviewer may.
        let review = t.human.core.with_db(|db| {
            Factory::new(db, &Policy::default())
                .review_of(seq)
                .unwrap()
                .unwrap()
        });
        assert!(claim(&t.builder, review).is_err());
        claim(&t.reviewer, review).unwrap();
        complete(&t.reviewer, review, Some(hird::model::Verdict::Upheld));

        // Merging needs ci or human, and evidence.
        let merged = parse(
            t.ci.factory_merge(Parameters(MergeArgs {
                seq,
                evidence: "abc1234".into(),
            }))
            .await,
        );
        assert_eq!(
            (merged["from"].as_str(), merged["to"].as_str()),
            (Some("approved"), Some("merged"))
        );

        // Every move is on the trail with its role and the operator's model.
        let trail = t.human.core.with_db(|db| db.audit().for_task(seq)).unwrap();
        let claimed = trail.iter().find(|e| e.kind == "claimed").unwrap();
        assert_eq!(
            (claimed.role.as_str(), claimed.model.as_str()),
            ("builder", "claude-code-model")
        );
        let merge = trail.iter().find(|e| e.kind == "merged").unwrap();
        assert_eq!(
            (merge.role.as_str(), merge.evidence.as_str()),
            ("ci", "abc1234")
        );
    }

    #[tokio::test]
    async fn a_role_comes_from_the_roster_and_never_from_the_client() {
        let t = team();
        let seq = t
            .human
            .core
            .with_db(|db| db.tasks().create(PROJECT, "w", "", 0, "cli"))
            .unwrap()
            .seq;
        // The builder's client calls itself "human"; its harness is pinned,
        // and nothing a client says reaches its roles.
        assert!(!t.builder.core.name_from_client("human"));
        let refused = t
            .builder
            .factory_decide(Parameters(DecideArgs {
                seq,
                action: "cancel".into(),
                text: "mine now".into(),
            }))
            .await
            .unwrap_err();
        assert!(refused.contains("needs the human role"), "{refused}");
        let moved = parse(
            t.human
                .factory_decide(Parameters(DecideArgs {
                    seq,
                    action: "cancel".into(),
                    text: "not needed".into(),
                }))
                .await,
        );
        assert_eq!(moved["to"], "cancelled");
    }

    #[tokio::test]
    async fn a_token_without_a_role_reads_the_board_and_does_nothing_else() {
        let shared = shared();
        let nobody = connect(&shared, &worker("guest", "codex", &[]));
        let seq = nobody
            .core
            .with_db(|db| db.tasks().create(PROJECT, "w", "", 0, "cli"))
            .unwrap()
            .seq;
        assert!(claim(&nobody, seq).is_err());
        let board = parse(
            nobody
                .factory_board(Parameters(BoardArgs { stage: None }))
                .await,
        );
        assert_eq!(board["roles"], "no role");
        assert_eq!(board["tasks"][0]["stage"], "ready");
    }

    #[tokio::test]
    async fn without_a_factory_the_extra_tools_answer_that_there_is_none() {
        let shared = shared();
        let w = worker("ana", "codex", &[]);
        let plain = crate::connect(&w, None, shared, &Config::default(), None).unwrap();
        let err = plain
            .factory_board(Parameters(BoardArgs { stage: None }))
            .await
            .unwrap_err();
        assert!(err.contains("does not run a factory"), "{err}");
        assert!(plain.core.session().gate().is_none());
    }

    #[test]
    fn the_server_adds_exactly_four_tools_and_none_collide_with_core() {
        let names: Vec<String> = FactoryMcp::tool_router()
            .list_all()
            .into_iter()
            .map(|t| t.name.to_string())
            .collect();
        assert_eq!(
            names.len(),
            4,
            "factory_board, factory_decide, factory_gate, factory_merge: {names:?}"
        );
        assert!(names.iter().all(|n| n.starts_with("factory_")));
    }

    /// Approve dependency work through the server: claim, build, pass CI,
    /// review and uphold.
    async fn approve(t: &Team, seq: i64) {
        claim(&t.builder, seq).unwrap();
        complete(&t.builder, seq, None);
        t.ci.factory_gate(Parameters(GateArgs {
            seq,
            outcome: "pass".into(),
            output: None,
            evidence: Some("run 1".into()),
        }))
        .await
        .unwrap();
        let review = t.human.core.with_db(|db| {
            Factory::new(db, &Policy::default())
                .review_of(seq)
                .unwrap()
                .unwrap()
        });
        claim(&t.reviewer, review).unwrap();
        complete(&t.reviewer, review, Some(hird::model::Verdict::Upheld));
    }

    /// Work filed through the server waits on its dependencies until they are
    /// merged; the merge that clears the last one is what announces it, and
    /// a cycle is refused here exactly as it is locally.
    #[tokio::test]
    async fn a_merge_releases_dependents_and_the_herald_hears_only_the_last_one() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("herald.log");
        let config = Config {
            dispatch_hook: format!("echo \"$HIRD_EVENT $HIRD_TASK\" >> {}", log.display()),
            ..Config::default()
        };
        let shared = Arc::new(Shared::new(Db::open_in_memory().unwrap(), config.clone()));
        let join = |w: &crate::roster::Worker| {
            crate::connect(
                w,
                Some(Arc::new(Policy::default())),
                shared.clone(),
                &config,
                None,
            )
            .unwrap()
        };
        let t = Team {
            builder: join(&worker("bo", "claude-code", &[Role::Builder])),
            reviewer: join(&worker("rae", "codex", &[Role::Reviewer])),
            ci: join(&worker("ci", "ci", &[Role::Ci])),
            human: join(&worker("ana", "human", &[Role::Human])),
        };
        let file = |title: &str| {
            t.human
                .core
                .with_db(|db| db.tasks().create(PROJECT, title, "", 0, "cli"))
                .unwrap()
                .seq
        };
        let (first, second, next) = (file("lexer"), file("parser"), file("checker"));
        t.human.core.with_db(|db| {
            db.deps().add(next, first, "cli").unwrap();
            db.deps().add(next, second, "cli").unwrap();
            let cycle = db.deps().add(first, next, "cli").unwrap_err();
            assert!(cycle.to_string().contains("cycle"), "{cycle}");
        });
        approve(&t, first).await;
        approve(&t, second).await;

        let merge = |seq| MergeArgs {
            seq,
            evidence: format!("sha-{seq}"),
        };
        t.ci.factory_merge(Parameters(merge(first))).await.unwrap();
        let refused = claim(&t.builder, next).unwrap_err().to_string();
        assert!(refused.contains(&format!("{second} (parser)")), "{refused}");
        assert!(!refused.contains(&format!("{first} (lexer)")), "{refused}");

        t.ci.factory_merge(Parameters(merge(second))).await.unwrap();
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        let heard = loop {
            let heard = std::fs::read_to_string(&log).unwrap_or_default();
            if heard.contains(&format!("unblocked {next}")) {
                break heard;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "the merge never announced task {next}; log so far:\n{heard}"
            );
            std::thread::sleep(Duration::from_millis(20));
        };
        // Once, from the last merge: the first merge left it held, and the
        // herald does not summon anyone to held work.
        assert_eq!(
            heard.matches(&format!("unblocked {next}")).count(),
            1,
            "{heard}"
        );
        claim(&t.builder, next).unwrap();
    }
}