ziyuan-cli 1.49.0

紫垣 ZiYuan:用中国古代朝廷角色组织多智能体协作的命令行工具,改动须用户审阅批准才写入文件。
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! 执行各子命令:调用 `Session` 的用例并打印结果。

mod execution;

pub(crate) use execution::{execute_revert, github};

use std::env;
use std::error::Error;
use std::io::{self, Write};
use ziyuan_app::{
    ABOLITION_NOTE, Session, demotion_note, describe_record, duzhi_report, format_time,
    history_entries, kaocheng_grade, kaocheng_report, suspicion_status, tz_offset,
};
use ziyuan_core::{AgentId, BudgetScope, GovernanceMode, NO_ART, Persona, Seal, TaskId};
use ziyuan_governance::TaskStatus;
use ziyuan_storage::EventLog;

use crate::args::{BudgetExportFormat, Command};
use crate::backend::{model_label, resolved_backend, worker_backend, workspace_price_for};
use crate::output::{cost_note, print_draft};

pub(crate) fn execute(
    session: &mut Session<EventLog>,
    command: Command,
) -> Result<(), Box<dyn Error>> {
    match command {
        Command::Help
        | Command::Version
        | Command::Init
        | Command::Migrate
        | Command::Doctor
        | Command::Login(_)
        | Command::Logout
        | Command::Serve { .. }
        | Command::Tui
        | Command::Completions(_)
        | Command::Text(_)
        | Command::Note(_)
        | Command::Follow(_) => {
            unreachable!("在 run 中处理")
        }
        Command::Court => {
            let court = session.court();
            println!("朝廷制度:{} ({})", court.mode().label(), court.mode());
            if court.in_retreat() {
                println!("皇帝:西苑修道中,司礼监代批(`ziyuan return` 回朝)");
            }
            println!(
                "在册官员:{};有职官员:{};已完成任务:{}",
                court.agents().count(),
                court.appointed_count(),
                court.completed_count()
            );
            println!("默认承办模型:{}", model_label());
            println!(
                "模型用量:{}{}",
                court.total_usage(),
                cost_note(court.tasks())
            );
            if let (Some(limit), Some(left)) =
                (court.budget(BudgetScope::Court), court.treasury_remaining())
            {
                println!("朝廷度支:{limit} tokens,余 {left}(`ziyuan budget` 查看奏销)");
            }
            println!(
                "调度中枢:{}",
                match court.mode() {
                    GovernanceMode::Chancellor => "中书省(右丞相,左丞相署理)",
                    GovernanceMode::DirectRule => "皇帝直领六部",
                    GovernanceMode::Cabinet => "内阁(首辅,次辅署理)",
                }
            );
            let vacancies = ziyuan_app::vacancies(court);
            if !vacancies.is_empty() {
                println!("朝堂缺位:");
                for note in vacancies {
                    println!("  - {note}");
                }
            }
        }
        Command::Officials => {
            let court = session.court();
            let default = model_label();
            for agent in court.agents() {
                let model = court.model_of(agent.id).unwrap_or(&default);
                let office = match court.office_of(agent.id) {
                    Some(o) => match demotion_note(court, agent.id) {
                        Some(note) => format!("{}({},{note})", o.label(), o.rank(court.mode())),
                        None => format!("{}({})", o.label(), o.rank(court.mode())),
                    },
                    None if court.is_purged(agent.id) => "已革职".into(),
                    None => "未任官职".into(),
                };
                let art = court.art_name(agent.id);
                println!(
                    "#{:<3} {:<6} 字{} 号{} {:<18} {} {} 模型 {} (完成 {} 件)",
                    agent.id.0,
                    agent.name,
                    court.courtesy_name(agent.id),
                    if art.is_empty() { NO_ART } else { &art },
                    office,
                    agent.speciality.label(),
                    Persona::of(agent.id).label(),
                    model,
                    court.recorded_completions(agent.id)
                );
            }
        }
        Command::Recruit(name, department) => {
            let id = session.recruit(name, department)?;
            let name = &session.court().agent(id).expect("刚招募").name;
            println!("诏令已颁:招募官员 #{} {}(未授官职)。", id.0, name);
        }
        Command::Rename {
            agent,
            name,
            courtesy,
            art,
        } => println!("{}", session.rename(agent, name, courtesy, art)?),
        cmd @ (Command::Edict { .. }
        | Command::EdictFromPlan { .. }
        | Command::EdictRevise { .. }
        | Command::EdictFollowUp { .. }
        | Command::EdictResumeFailed { .. }
        | Command::Run(_, _)
        | Command::Tasks
        | Command::Diff(_, _, _)
        | Command::Apply(_, _, _)
        | Command::Discard(_)) => {
            execution::execute_edict_flow(session, cmd)?;
        }
        Command::Revert { .. } => unreachable!("已在 main 分派"),
        Command::Cancel(task) => {
            session.cancel(task)?;
            println!("诏令 #{} 已撤销。", task.0);
        }
        Command::Retreat(on) => {
            let note = session.retreat(on)?;
            if on {
                println!("诏令已颁:朕移居西苑修道,朝政付内阁与司礼监。");
            } else {
                println!("诏令已颁:朕回朝亲政。");
            }
            println!("史官记:{note}");
        }
        Command::Reform(mode) => {
            let note = session.reform(mode)?;
            println!(
                "诏令已颁:制度改为{}。旧制度的中书省/内阁官职自动撤销。",
                mode.label()
            );
            println!("史官记:{note}");
            if mode != GovernanceMode::DirectRule {
                println!("提示:新制度如无协调者,请先任命。 ");
            }
        }
        Command::ModelList => {
            let cwd = env::current_dir()?;
            let config = ziyuan_llm::ModelsConfig::load(&cwd).map_err(|e| e.to_string())?;
            match resolved_backend() {
                Some(r) => println!(
                    "默认承办模型:{} [{}]",
                    r.model_label,
                    r.provider_kind.label()
                ),
                None => println!("默认承办模型:演示(未接模型)"),
            }
            match config {
                Some(cfg) if !cfg.profiles.is_empty() => {
                    println!("多模型配置(.ziyuan/models.json,仅记录环境变量名、不含明文密钥):");
                    for p in cfg.summaries() {
                        let key_note = match &p.api_key_env {
                            Some(var) if p.api_key_ready => format!("{var}(已就绪)"),
                            Some(var) => format!("{var}(未设置)"),
                            None if p.provider == "chatgpt" => {
                                if p.api_key_ready {
                                    "ChatGPT 订阅(已登录)".into()
                                } else {
                                    "ChatGPT 订阅(未登录)".into()
                                }
                            }
                            None => "无需凭据".into(),
                        };
                        let def = if p.is_default { " [默认]" } else { "" };
                        println!(
                            "  {:<20} [{}] 模型 {}  凭据 {}{}",
                            p.name, p.provider_label, p.model, key_note, def
                        );
                    }
                }
                _ => {
                    println!(
                        "尚未配置 .ziyuan/models.json(可按需登记 openai / anthropic / gemini / chatgpt 配置,并用 `ziyuan model --dept <部门> <配置名>` 分派)。"
                    );
                }
            }
            let court = session.court();
            let overrides: Vec<_> = ziyuan_core::Office::all()
                .into_iter()
                .filter_map(|o| court.office_model(o).map(|m| (o, m)))
                .collect();
            if overrides.is_empty() {
                println!("各官职模型分派:全部沿用默认。");
            } else {
                println!("各官职模型分派:");
                for (office, model) in overrides {
                    println!("  {:<24}({})→ {model}", office.code(), office.label());
                }
            }
        }
        Command::Model(office, model) => {
            session.set_office_model(office, model.clone())?;
            match model {
                Some(m) => println!("诏令已颁:{}改用模型 {m}。", office.label()),
                None => println!("诏令已颁:{}恢复默认模型。", office.label()),
            }
        }
        Command::ModelDept(department, model) => {
            let offices = session.set_department_model(department, model.clone())?;
            let labels: Vec<_> = offices.iter().map(|o| o.label()).collect();
            match model {
                Some(m) => println!(
                    "诏令已颁:{}({})改用模型 {m}。",
                    department.label(),
                    labels.join("、")
                ),
                None => println!(
                    "诏令已颁:{}({})恢复默认模型。",
                    department.label(),
                    labels.join("、")
                ),
            }
        }
        Command::Ceiling(office, ceiling) => {
            session.set_office_ceiling(office, ceiling.clone())?;
            match ceiling {
                Some(seal) => println!("诏令已颁:{}玉玺上限为 {seal}。", office.label()),
                None => println!("诏令已颁:{}取消玉玺上限。", office.label()),
            }
        }
        Command::Purge(id) => {
            session.purge(id)?;
            println!("诏令已颁:官员 #{} 革职,削去仕籍,永不叙用。", id.0);
        }
        Command::Abolish => {
            println!("{}", session.abolish_chancellery()?);
            println!("诏令已颁:罢中书省,制度改为废相亲政。");
            println!("史官记:{ABOLITION_NOTE}");
        }
        Command::Draft(task) => {
            let tasks = match task {
                Some(task) => vec![task],
                None => {
                    let court = session.court();
                    court
                        .tasks()
                        .filter(|t| court.needs_approval(t) && t.draft.is_none())
                        .map(|t| t.edict.id)
                        .collect()
                }
            };
            if tasks.is_empty() {
                println!("没有待票拟的诏令。");
            } else {
                let backend = worker_backend()?;
                for task in tasks {
                    session.draft(task, backend.as_ref())?;
                    print_draft(session, task);
                }
                println!("请 `ziyuan approve <诏令ID|all>` 批红,或 `ziyuan redraft` 改票。");
            }
        }
        Command::Censor(task) => {
            let tasks = match task {
                Some(task) => vec![task],
                None => session
                    .court()
                    .tasks()
                    .filter(|t| {
                        matches!(t.status, TaskStatus::Completed { .. }) && t.censure.is_none()
                    })
                    .map(|t| t.edict.id)
                    .collect(),
            };
            if tasks.is_empty() {
                println!("没有待复核的诏令。");
            }
            let backend = if tasks.is_empty() {
                None
            } else {
                Some(worker_backend()?)
            };
            for task in tasks {
                let backend = backend.as_deref().expect("有诏令时已构造后端");
                session.censor(task, &env::current_dir()?, backend)?;
                let court = session.court();
                let censure = court
                    .task(task)
                    .and_then(|t| t.censure.as_ref())
                    .expect("刚复核");
                let censor = court.agent(censure.censor).map_or("?", |a| a.name.as_str());
                println!(
                    "诏令 #{} 都察院复核:左都御史{censor}{}({})",
                    task.0,
                    censure.verdict.label(),
                    censure.evidence
                );
                let entry = court.task(task).expect("刚复核的诏令");
                println!(
                    "验功所据:{}",
                    ziyuan_app::test_evidence(entry, session.history()?)
                );
                for line in censure.note.lines().filter(|l| !l.trim().is_empty()) {
                    println!("  {line}");
                }
            }
        }
        Command::Kaocheng => println!("{}", kaocheng_report(session.court())),
        Command::Post {
            department,
            station,
            urgent,
            text,
        } => {
            let edict = session.post(department, text, Seal::default(), &station, urgent)?;
            let task = session.court().task(edict.id).expect("刚入队");
            let speed = if urgent { ",八百里加急" } else { "" };
            println!(
                "驿传:诏令 #{} 自「{station}」入队({}{speed})。",
                edict.id.0,
                department.label()
            );
            if !task.suspicions.is_empty() {
                println!(
                    "锦衣卫密报 {} 条,`ziyuan flags {}` 查看;修道期间司礼监不代批红。",
                    task.suspicions.len(),
                    edict.id.0
                );
            }
            if session.court().needs_approval(task) {
                println!("待批红:`ziyuan approve {}`。", edict.id.0);
            }
        }
        Command::Templates => {
            for (name, t, builtin) in session.court().templates() {
                let origin = if builtin { "内置" } else { "自定" };
                println!(
                    "「{name}」({origin},{},玉玺 {})",
                    t.department.label(),
                    t.seal
                );
                println!("  {}", t.text);
                for (i, c) in t.criteria.iter().enumerate() {
                    println!("  验收 {}. {c}", i + 1);
                }
            }
            println!(
                "用法:`ziyuan edict --template <名> [补充内容]`;验收标准随诏令附给承办官员,`ziyuan censor` 时都察院逐条核验。"
            );
        }
        Command::SaveTemplate { name, template } => {
            let overrides = session.court().template(&name).is_some();
            session.save_template(&name, template)?;
            let verb = if overrides { "覆盖" } else { "新存" };
            println!("翰林院{verb}模板「{name}」。");
        }
        Command::RemoveTemplate(name) => {
            session.remove_template(&name)?;
            println!("翰林院撤去模板「{name}」。");
        }
        Command::Urgent(task) => {
            session.expedite(task)?;
            println!("诏令 #{} 八百里加急:插队先行,时限加倍。", task.0);
        }
        Command::Exam(agent) => {
            let backend = worker_backend()?;
            let name = session
                .court()
                .agent(agent)
                .map_or("?".to_owned(), |a| a.name.clone());
            println!("礼部开科:#{} {name} 应试。", agent.0);
            let taken = session.exam(
                agent,
                &env::current_dir()?,
                backend.as_ref(),
                |paper, score| {
                    let mark = if score >= 60 { "及格" } else { "不及格" };
                    println!("  「{}」{score} 分({mark})", paper.name);
                },
            )?;
            let record = session.court().service_record(agent);
            println!(
                "考毕 {taken} 题;履历:科举及格 {}/{}。成绩供吏部荐举参考,任命仍由皇帝决定。",
                record.exams_passed, record.exams
            );
        }
        Command::Palace(question) => {
            let backend = worker_backend()?;
            println!("殿试,天子亲策:{question}");
            let stopped = session.palace_exam(&question, backend.as_ref(), |agent, answer| {
                println!(
                    "【#{} {}{}·{}】{}",
                    agent.id.0,
                    answer.office.label(),
                    agent.name,
                    Persona::of(agent.id).label(),
                    answer.text
                );
                let _ = io::stdout().flush();
            })?;
            if let Some(reason) = stopped {
                println!("殿试中止:{reason};已交的答卷照记。");
            }
            println!("请 `ziyuan crown <官员ID>` 钦点状元。");
        }
        Command::Crown(agent) => println!("{}", session.crown(agent)?),
        Command::Flags(only) => {
            let court = session.court();
            let mut any = false;
            for task in court
                .tasks()
                .filter(|t| only.is_none_or(|id| t.edict.id == id))
            {
                for (i, s) in task.suspicions.iter().enumerate() {
                    any = true;
                    let source = s.origin();
                    println!(
                        "诏令 #{} 第 {} 处 {}({source}):{}「{}」{}",
                        task.edict.id.0,
                        i + 1,
                        s.bureau(),
                        s.threat.label(),
                        s.excerpt,
                        suspicion_status(s)
                    );
                }
            }
            if !any {
                println!("刑部与锦衣卫无所奏报。");
            } else {
                println!(
                    "(关键词机械检出,可能误报;玉玺不因此改变。可 `ziyuan recheck <诏令ID>` 请刑部复勘,\
                     `ziyuan acquit <诏令ID> [序号]` 平反误报。)"
                );
            }
        }
        Command::GitHub(action) => github(session, action)?,
        Command::Mcp => {
            let servers =
                ziyuan_runtime::mcp::survey(&env::current_dir()?).map_err(|e| e.to_string())?;
            if servers.is_empty() {
                println!(
                    "外藩名册为空:在 {} 登记 MCP 服务,下诏时以 `--mcp <服务>` 授权。",
                    ziyuan_runtime::mcp::CONFIG
                );
            }
            for (name, tools) in servers {
                match tools {
                    Ok(tools) => {
                        println!("外藩「{name}」:{} 件工具", tools.len());
                        for t in tools {
                            let line = t.description.lines().next().unwrap_or_default();
                            println!("  {name}/{}  {line}", t.name);
                            let schema = &t.input_schema;
                            let required: Vec<_> = schema["required"]
                                .as_array()
                                .into_iter()
                                .flatten()
                                .filter_map(|r| r.as_str())
                                .collect();
                            for (param, spec) in
                                schema["properties"].as_object().into_iter().flatten()
                            {
                                let kind = spec["type"].as_str().unwrap_or("任意");
                                let must = if required.contains(&param.as_str()) {
                                    ",必填"
                                } else {
                                    ""
                                };
                                let doc = spec["description"].as_str().unwrap_or_default();
                                let doc = doc.lines().next().unwrap_or_default();
                                println!("      {param}({kind}{must}){doc}");
                            }
                        }
                    }
                    Err(e) => println!("外藩「{name}」:未能朝贡({e})"),
                }
            }
        }
        Command::Changelog { version, since } => {
            let (range, commits) = ziyuan_app::changelog_commits(&env::current_dir()?, since)?;
            let edict = session.draft_changelog(&version, &commits)?;
            println!(
                "诏令 #{} 已入队:礼部修 CHANGELOG「{version}」,收提交 {} 条({range})。玉玺只授 read_file、write_file,范围只限 {}。",
                edict.id.0,
                commits.len(),
                ziyuan_core::CHANGELOG
            );
            if session
                .court()
                .needs_approval(session.court().task(edict.id).expect("刚入队"))
            {
                println!("待批红:`ziyuan approve {}`。", edict.id.0);
            }
            println!(
                "执行 `ziyuan run` 后,`ziyuan diff {0}` 审阅,`ziyuan apply {0}` 准奏落盘。",
                edict.id.0
            );
            println!("{}", ziyuan_app::CHANGELOG_NOTE);
        }
        Command::Recheck(only) => {
            let tasks: Vec<TaskId> = match only {
                Some(task) => vec![task],
                None => session
                    .court()
                    .tasks()
                    .filter(|t| {
                        t.suspicions
                            .iter()
                            .any(|s| s.review.is_none() && !s.acquitted)
                    })
                    .map(|t| t.edict.id)
                    .collect(),
            };
            if tasks.is_empty() {
                println!("没有待复勘的检出。");
            } else {
                let backend = worker_backend()?;
                for task in tasks {
                    session.recheck(task, backend.as_ref())?;
                    let court = session.court();
                    let entry = court.task(task).expect("刚复勘");
                    for (i, s) in entry.suspicions.iter().enumerate() {
                        let Some(r) = &s.review else { continue };
                        let name = court.agent(r.reviewer).map_or("?", |a| a.name.as_str());
                        println!(
                            "诏令 #{} 第 {} 处 {}「{}」:刑部{name}复勘为{}——{}",
                            task.0,
                            i + 1,
                            s.threat.label(),
                            s.excerpt,
                            if r.upheld { "维持" } else { "误报" },
                            r.note
                        );
                    }
                }
                println!(
                    "复勘只是意见:平反请 `ziyuan acquit <诏令ID>`(平反刑部判为误报的各处)。"
                );
            }
        }
        Command::Acquit(task, indices) => {
            let indices = match indices {
                Some(list) if list.is_empty() => {
                    let entry = session
                        .court()
                        .task(task)
                        .ok_or(format!("诏令 #{} 不存在", task.0))?;
                    Some(
                        (0..entry.suspicions.len() as u32)
                            .filter(|&i| !entry.suspicions[i as usize].acquitted)
                            .collect(),
                    )
                }
                other => other,
            };
            let (done, note) = session.acquit(task, indices)?;
            let list: Vec<String> = done.iter().map(|i| (i + 1).to_string()).collect();
            println!(
                "诏令已颁:平反诏令 #{} 第 {} 处检出,不再妨碍司礼监代批。",
                task.0,
                list.join("、")
            );
            println!("{note}");
        }
        Command::Budget(None) => {
            let default = resolved_backend().map(|m| m.model_label);
            println!(
                "{}",
                duzhi_report(session.court(), default.as_deref(), workspace_price_for)
            );
        }
        Command::Budget(Some((scope, tokens))) => {
            session.set_budget(scope, tokens)?;
            match tokens {
                Some(t) => println!("诏令已颁:户部度支 · {}:限 {t} tokens。", scope.label()),
                None => println!("诏令已颁:户部度支 · {}:取消限额。", scope.label()),
            }
        }
        Command::BudgetExport {
            output,
            format,
            bom,
        } => {
            let default = resolved_backend().map(|m| m.model_label);
            let exported =
                ziyuan_app::duzhi_export(session.court(), default.as_deref(), workspace_price_for);
            let content = match format {
                BudgetExportFormat::Csv => ziyuan_app::duzhi_export_csv(&exported, bom),
                BudgetExportFormat::Json => {
                    serde_json::to_string_pretty(&ziyuan_app::duzhi_export_json(&exported))? + "\n"
                }
            };
            if let Some(parent) = output.parent()
                && !parent.as_os_str().is_empty()
            {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&output, content.as_bytes())?;
            let label = match format {
                BudgetExportFormat::Csv if bom => "CSV(UTF-8 BOM)",
                BudgetExportFormat::Csv => "CSV",
                BudgetExportFormat::Json => "JSON",
            };
            println!(
                "户部度支报表已导出至 {}({label},共 {} 行明细,总计 {} tokens)。",
                output.display(),
                exported.rows.len(),
                exported.total_tokens
            );
        }
        Command::Debate(task, members, rounds) => {
            let backend = worker_backend()?;
            println!("诏令 #{} 廷议:", task.0);
            let stopped =
                session.debate(task, &members, rounds, backend.as_ref(), |agent, speech| {
                    println!(
                        "【{}{}·{}】{}",
                        speech.office.label(),
                        agent.name,
                        Persona::of(agent.id).label(),
                        speech.text
                    );
                    let _ = io::stdout().flush();
                })?;
            if let Some(reason) = stopped {
                println!("廷议中止:{reason};已有发言照记。");
            }
            println!("纪要已记入事件簿,票拟与承办时附上,供参考;派工与玉玺不变。");
        }
        Command::Split {
            task,
            plan,
            file,
            parallel_writes,
        } => {
            let root = env::current_dir()?;
            let subtasks = if let Some(file) = file {
                let json = std::fs::read_to_string(&file)
                    .map_err(|e| format!("无法读取排程方案 {file}:{e}"))?;
                let schedule: Vec<ziyuan_app::ScheduledSubtask> = serde_json::from_str(&json)
                    .map_err(|e| format!("无效的排程方案 {file}:{e}"))?;
                session.split_scheduled_with_options(
                    task,
                    schedule,
                    parallel_writes,
                    Some(&root),
                )?
            } else if plan.is_empty() {
                session.plan_split_with_options(
                    task,
                    worker_backend()?.as_ref(),
                    parallel_writes,
                    Some(&root),
                )?
            } else {
                session.split_with_options(task, plan, parallel_writes, Some(&root))?
            };
            let court = session.court();
            let note = court
                .task(task)
                .and_then(|t| t.split.as_ref())
                .map_or("", |s| s.note.as_str());
            println!("诏令 #{} 分办({note}):", task.0);
            let mut chained = false;
            for id in subtasks {
                let sub = court.task(id).expect("刚分办");
                let worker = sub.assignee.and_then(|a| court.agent(a));
                let name = worker.map_or("?", |a| a.name.as_str());
                let deps = sub
                    .dag
                    .as_ref()
                    .map(|d| d.dependencies.as_slice())
                    .unwrap_or_default();
                let order = if deps.is_empty() {
                    String::new()
                } else {
                    chained = true;
                    format!(
                        "(先办 {})",
                        deps.iter()
                            .map(|d| format!("#{}", d.0))
                            .collect::<Vec<_>>()
                            .join("、")
                    )
                };
                println!("  #{} → {name}:{}{order}", id.0, sub.edict.text);
            }
            if parallel_writes {
                println!(
                    "已启用并行写:执行时各写子诏令自动获独立 jj 工作副本,落盘仍须逐件准奏。"
                );
            } else if chained {
                println!("写子诏令查阅范围重叠,已按上述次序自动串行;上游失败则下游受阻。");
            }
            println!("`ziyuan run` 执行;子诏令全部结束后由尚书汇总回奏。");
        }
        Command::DagAdd { parent, subtask } => {
            let new_id = session.dag_add_subtask(parent, subtask)?;
            let court = session.court();
            let sub = court.task(new_id).expect("刚追加子诏令");
            let name = sub
                .assignee
                .and_then(|a| court.agent(a))
                .map_or("?", |a| a.name.as_str());
            let deps = sub
                .dag
                .as_ref()
                .map(|d| d.dependencies.as_slice())
                .unwrap_or_default();
            let order = if deps.is_empty() {
                String::new()
            } else {
                format!(
                    "(先办 {})",
                    deps.iter()
                        .map(|d| format!("#{}", d.0))
                        .collect::<Vec<_>>()
                        .join("、")
                )
            };
            println!(
                "已向诏令 #{} 追加子诏令 #{} → {name}:{}{order}",
                parent.0, new_id.0, sub.edict.text
            );
        }
        Command::DagDeps {
            subtask,
            dependencies,
        } => {
            session.dag_update_deps(subtask, dependencies.clone())?;
            if dependencies.is_empty() {
                println!("已清除子诏令 #{} 的前置依赖。", subtask.0);
            } else {
                let list = dependencies
                    .iter()
                    .map(|d| format!("#{}", d.0))
                    .collect::<Vec<_>>()
                    .join("、");
                println!("已调整子诏令 #{} 的前置依赖:先办 {list}。", subtask.0);
            }
        }
        Command::Redraft(task, worker, note) => {
            session.redraft(task, worker, note)?;
            print_draft(session, task);
        }
        Command::Approve(task) => {
            let tasks = match task {
                Some(task) => vec![task],
                None => {
                    let court = session.court();
                    court
                        .tasks()
                        .filter(|t| court.needs_approval(t))
                        .map(|t| t.edict.id)
                        .collect()
                }
            };
            if tasks.is_empty() {
                println!("没有待批红的诏令。");
            }
            for task in tasks {
                session.approve(task)?;
                println!("诏令 #{} 已批红。", task.0);
            }
        }
        Command::Dismiss(id) => {
            session.dismiss(id)?;
            println!("诏令已颁:官员 #{} 已罢免现职(身份与履历保留)。", id.0);
        }
        Command::Appoint(id, office) => {
            let note = session.appoint(id, office)?;
            println!("诏令已颁:任命官员 #{} 为{}。", id.0, office.label());
            if let Some(note) = note {
                println!("{note}");
            }
        }
        Command::Nominate { office, lots: true } => {
            let (agent, note) = session.draw_lots(office)?;
            println!("诏令已颁:枚卜得官员 #{},任{}。", agent.0, office.label());
            println!("{note}");
        }
        Command::Nominate {
            office,
            lots: false,
        } => {
            let backend = worker_backend()?;
            println!("吏部会同九卿,廷推{}:", office.label());
            let mut lines = Vec::new();
            let votes = session.nominate(office, backend.as_ref(), |voter, vote| {
                lines.push((voter.name.clone(), vote.candidate, vote.note.clone()));
            })?;
            let names = |id: AgentId| {
                session
                    .court()
                    .agent(id)
                    .map_or("?".to_owned(), |a| format!("#{} {}", id.0, a.name))
            };
            for (voter, candidate, note) in lines {
                let note = if note.is_empty() {
                    String::new()
                } else {
                    format!("——{note}")
                };
                println!("  {voter} 推 {}{note}", names(candidate));
            }
            let tally: Vec<String> = session
                .court()
                .nomination_tally(office)
                .into_iter()
                .map(|(id, n)| format!("{} {n} 票", names(id)))
                .collect();
            println!("得票:{}(共 {} 票)", tally.join("、"), votes.len());
            println!(
                "廷推只是建议:`ziyuan appoint <官员ID> {}` 任命(被推者现任他职的径直擢升),或 `ziyuan nominate {} --lots` 枚卜。",
                office.code(),
                office.code()
            );
        }
        Command::Cane(id) => println!("{}", session.cane(id)?),
        Command::Pardon(id) => println!("{}", session.pardon(id)?),
        Command::Examine(id) => {
            let court = session.court();
            let agent = court.agent(id).ok_or("官员不存在")?;
            let r = court.service_record(id);
            println!("吏部考绩:{}(#{})", agent.name, id.0);
            println!("  {};考成:{}", describe_record(&r), kaocheng_grade(&r));
            println!(
                "  工具调用 {} 次,其中失败 {} 次(含越出玉玺的尝试)",
                r.tool_calls, r.tool_failures
            );
            let handled = court.tasks().filter(|t| t.handler() == Some(id));
            println!("  模型用量:{}{}", r.usage, cost_note(handled));
            if let Some(office) = court.office_of(id) {
                println!(
                    "  承办模型:{}",
                    court.office_model(office).unwrap_or(&model_label())
                );
                if let Some(ceiling) = court.office_ceiling(office) {
                    println!("  {}玉玺上限:{ceiling}", office.label());
                }
            }
            if r.unreviewed > 0 {
                println!(
                    "  另有 {} 件回奏未经评定,不计入考绩。可用 `ziyuan review <诏令ID> accept|reject` 评定。",
                    r.unreviewed
                );
            }
        }
        Command::Review(task, verdict, note) => {
            session.review(task, verdict, note)?;
            println!("诏令 #{} 评定为{}。", task.0, verdict.label());
        }
        Command::Recommend(office) => {
            let court = session.court();
            let candidates = court.recommend(office)?;
            if candidates.is_empty() {
                println!("无人可任{}。可先 `ziyuan recruit`。", office.label());
                return Ok(());
            }
            println!(
                "吏部荐举{}(按 采纳−驳回、失败、工具失败 排序):",
                office.label()
            );
            for c in &candidates {
                let current = c.current.map_or("未任官职".into(), |o| o.label());
                println!(
                    "#{:<3} {:<8} {:<12} {}",
                    c.agent.id.0,
                    c.agent.name,
                    current,
                    describe_record(&c.record)
                );
            }
            println!("仅为建议:任命须由皇帝 `ziyuan appoint`(如有现职须先 dismiss)。");
        }
        Command::Records(query) => {
            let records = session.court().records();
            let found = ziyuan_core::find_records(&records, &query);
            if found.is_empty() {
                println!(
                    "{}",
                    if records.is_empty() {
                        "翰林院尚无实录:诏令完成后自动归档。"
                    } else {
                        "实录中无相关前例。"
                    }
                );
            }
            for r in found {
                println!(
                    "#{} {} · #{} {} · {}",
                    r.task.0,
                    r.department.label(),
                    r.worker.0,
                    r.handler,
                    r.verdict
                );
                println!("    诏令:{}", r.edict);
                let summary = r
                    .summary
                    .lines()
                    .find(|l| !l.trim().is_empty())
                    .unwrap_or("");
                let short: String = summary.trim().chars().take(80).collect();
                let more = if short.len() < summary.trim().len() {
                    "…"
                } else {
                    ""
                };
                println!("    回奏:{short}{more}");
            }
        }
        Command::History(filter) => {
            let offset = tz_offset();
            for entry in history_entries(session.history()?, &filter)? {
                let at = entry.at.map_or("—".repeat(16), |t| format_time(t, offset));
                println!("{:>3}: {at}  {}", entry.seq, entry.text);
            }
        }
    }
    Ok(())
}