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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! # Module: main (agent-doc CLI)
//!
//! ## Spec
//! - Entry point for the `agent-doc` binary; parses the command line with `clap` derive.
//! - Top-level struct `Cli` holds a single `Commands` subcommand enum (40+ variants).
//! - `AgentDocMode` enum (`Append`, `Template`, `Stream`) is a `ValueEnum` used by `Convert`
//! and `Mode` subcommands; `Append` maps to inline format, `Template`/`Stream` to CRDT.
//! - On startup, calls `upgrade::warn_if_outdated()` for all subcommands except `Upgrade`.
//! - Loads global config via `config::load()` before dispatching; config is threaded into
//! subcommands that accept an agent backend (`Run`, `Stream`, `Watch`, `Init`).
//! - Each subcommand delegates immediately to its own module (`run::run`, `diff::run`, etc.);
//! `main` contains no business logic beyond argument destructuring and dispatch.
//! - `Route` additionally calls `sync::run_layout_only` when `--col` args are present,
//! logging layout-sync failures to stderr without propagating the error.
//! - `Write` auto-detects the write strategy from frontmatter when no `--template`/`--stream`
//! flag is given; CRDT-mode documents use `write::run_stream`, others use `write::run`.
//! - `Prompt --all` runs `prompt::run_all()`; otherwise `FILE` is required.
//! - `History --restore <commit>` calls `history::restore`; bare `History` calls `history::list`.
//! - `Watch` dispatches to `watch::stop`, `watch::status`, or `watch::start` based on flags.
//! - `Skill install --reload` prints `SKILL_RELOAD=compact` or `SKILL_RELOAD=restart` when the
//! skill was updated, enabling the caller to take the appropriate reload action.
//! - `LibPath` prints the platform-appropriate shared library path (`libagent_doc.so/dylib/dll`)
//! next to the binary, exiting with code 1 if not found.
//! - `ListCommands` emits a JSON array of all available subcommand names for plugin autocomplete.
//!
//! ## Agentic Contracts
//! - `main` returns `anyhow::Result<()>`; any subcommand error propagates and prints to stderr.
//! - Subcommand modules are the single source of truth for their behavior; `main` only routes.
//! - Config is loaded once and passed by reference; subcommands must not reload config.
//! - `Upgrade` bypasses the version check that all other subcommands run on startup.
//!
//! ## Evals
//! - dispatch_run: `agent-doc run <file>` → `run::run` called with correct args
//! - dispatch_write_crdt_autodetect: CRDT frontmatter + no flags → `write::run_stream` selected
//! - dispatch_write_inline_autodetect: inline frontmatter + no flags → `write::run` selected
//! - dispatch_route_with_cols: `--col` args present → `sync::run_layout_only` called after route
//! - dispatch_prompt_all: `--all` → `prompt::run_all`, no FILE required
//! - dispatch_history_restore: `--restore <sha>` → `history::restore` called
//! - dispatch_watch_stop: `--stop` flag → `watch::stop` called
//! - dispatch_skill_install_reload: skill updated + `--reload compact` → prints `SKILL_RELOAD=compact`
//! - dispatch_lib_path_missing: library absent → exits with code 1
mod agent;
mod annotate;
mod audit_docs;
mod autoclaim;
mod boundary;
mod callback;
mod claim;
mod clean;
mod cleanup_cmd;
mod commands;
mod compact;
mod config;
mod convert;
mod pending_cmd;
mod project_config;
mod gc;
mod parallel;
mod preflight;
mod read;
mod dedupe;
mod diff;
mod env;
mod extract;
mod focus;
mod git;
mod history;
mod hook_cmd;
mod hooks;
mod init;
mod install;
mod layout;
mod mode;
mod notify;
mod outline;
mod patch;
mod plugin;
mod prompt;
mod recover;
mod rename;
mod reset;
mod resync;
mod route;
mod session_cmd;
mod sessions;
mod skill;
mod snapshot;
mod start;
mod stream;
mod run;
mod sync;
mod terminal;
pub(crate) use agent_doc::ipc_socket;
mod undo;
mod upgrade;
mod watch;
mod worktree;
mod ops_log;
mod write;
// Re-export library modules so binary-internal modules can use `crate::` paths
pub(crate) use agent_doc::component;
pub(crate) use agent_doc::crdt;
pub(crate) use agent_doc::frontmatter;
pub(crate) use agent_doc::merge;
pub(crate) use agent_doc::template;
use anyhow::Context;
use clap::{Parser, Subcommand, ValueEnum};
use std::path::{Path, PathBuf};
/// Document mode for agent-doc sessions.
#[derive(Clone, Debug, ValueEnum)]
pub enum AgentDocMode {
/// Append-mode: alternating ## User / ## Assistant blocks
Append,
/// Template-mode: in-place component patching
Template,
/// Stream-mode: real-time CRDT write-back (superset of template)
Stream,
}
#[derive(Parser)]
#[command(name = "agent-doc", version, about = "Interactive document sessions with AI agents")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Run a session: diff, send to agent, append response
Run {
/// Path to the session document
file: PathBuf,
/// Auto-create a branch for session commits
#[arg(short = 'b')]
branch: bool,
/// Agent backend to use
#[arg(long)]
agent: Option<String>,
/// Model override
#[arg(long)]
model: Option<String>,
/// Preview what would be sent without submitting
#[arg(long)]
dry_run: bool,
/// Skip git commit after submit
#[arg(long)]
no_git: bool,
},
/// List or restore exchange component versions from git history
History {
/// Path to the session document
file: PathBuf,
/// Restore exchange content from a specific commit (prepend to current)
#[arg(long)]
restore: Option<String>,
},
/// Annotated git log for a session document (shows pre-compact tags)
Log {
/// Path to the session document
file: PathBuf,
},
/// Show document content at a specific point in git history
Show {
/// Path to the session document
file: PathBuf,
/// Show the file N commits back from HEAD (e.g. --back 1 → HEAD~1)
#[arg(long)]
back: Option<usize>,
/// Show the Nth commit in git log order (0 = newest, 1 = next oldest, …)
#[arg(long)]
at: Option<usize>,
/// Show the commit pointed to by this tag
#[arg(long)]
tag: Option<String>,
},
/// Scaffold a new session document (omit file to initialize project)
Init {
/// Path for the new session document (omit to initialize project)
file: Option<PathBuf>,
/// Session title
title: Option<String>,
/// Agent backend to use
#[arg(long)]
agent: Option<String>,
/// Document mode: append (default) or template
#[arg(long)]
mode: Option<String>,
},
/// System-level setup: check prerequisites, install editor plugins
Install {
/// Editor to install plugin for (jetbrains or vscode; auto-detected if omitted)
#[arg(long)]
editor: Option<String>,
/// Skip prerequisite checks
#[arg(long)]
skip_prereqs: bool,
/// Skip plugin installation
#[arg(long)]
skip_plugins: bool,
},
/// Preview the diff that would be sent, or diff between two git refs
Diff {
/// Path to the session document
file: PathBuf,
/// Wait for stable content (truncation detection) before computing diff
#[arg(long)]
wait: bool,
/// Starting git ref for historical diff (e.g. commit hash, tag, HEAD~2)
#[arg(long)]
from: Option<String>,
/// Ending git ref for historical diff (default: HEAD)
#[arg(long)]
to: Option<String>,
},
/// Clear session ID and delete snapshot
Reset {
/// Path to the session document
file: PathBuf,
},
/// Squash session git history into one commit
Clean {
/// Path to the session document
file: PathBuf,
/// Create an archive tag before squashing (preserves full history)
#[arg(long)]
archive: bool,
},
/// Audit instruction files against the codebase
AuditDocs {
/// Project root directory (auto-detected if omitted)
#[arg(long)]
root: Option<PathBuf>,
},
/// Garbage-collect orphaned files in .agent-doc/
Gc {
/// Project root directory (auto-detected if omitted)
#[arg(long)]
root: Option<PathBuf>,
/// Show what would be deleted without deleting
#[arg(long)]
dry_run: bool,
},
/// Start Claude in a tmux pane and register the session
Start {
/// Path to the session document
file: PathBuf,
},
/// Route /agent-doc command to the correct tmux pane
Route {
/// Path to the session document
file: PathBuf,
/// Tmux pane ID for lazy claiming (auto-claims if existing claim is stale)
#[arg(long)]
pane: Option<String>,
/// Editor layout columns (comma-separated files per column, repeatable)
#[arg(long = "col")]
cols: Vec<String>,
/// Focused file in the editor (for tmux pane focus)
#[arg(long)]
focus: Option<String>,
/// Wait for typing to settle before routing (milliseconds, 0 = no debounce)
#[arg(long, default_value_t = 0)]
debounce: u64,
},
/// Detect permission prompts from a Claude Code session
Prompt {
/// Path to the session document (omit with --all)
file: Option<PathBuf>,
/// Answer a prompt by selecting option N (1-based)
#[arg(long)]
answer: Option<usize>,
/// Poll all active sessions instead of a single file
#[arg(long)]
all: bool,
},
/// Commit a session document (git add + commit with timestamp)
Commit {
/// Path to the session document
file: PathBuf,
},
/// Remove consecutive duplicate response blocks
Dedupe {
/// Path to the session document
file: PathBuf,
},
/// Claim a document for the current tmux pane
Claim {
/// Path to the session document
file: PathBuf,
/// Positional hint to select pane by position (left, right, top, bottom)
#[arg(long)]
position: Option<String>,
/// Explicit tmux pane ID (e.g. %42) — overrides position detection
#[arg(long)]
pane: Option<String>,
/// Scope pane resolution to this tmux window (e.g. @1)
#[arg(long)]
window: Option<String>,
/// Force overwrite tmux_session even if already set to a different session
#[arg(long)]
force: bool,
},
/// Focus the tmux pane for a session document
Focus {
/// Path to the session document
file: PathBuf,
/// Explicit tmux pane ID — overrides session lookup
#[arg(long)]
pane: Option<String>,
},
/// Arrange tmux panes to mirror editor split layout
Layout {
/// Session documents to arrange
files: Vec<PathBuf>,
/// Split direction: h (horizontal/side-by-side) or v (vertical/stacked)
#[arg(long, short, default_value = "h")]
split: String,
/// Explicit tmux pane ID — scopes pane selection to this pane's session
#[arg(long)]
pane: Option<String>,
/// Only operate on panes within this tmux window (e.g. @1)
#[arg(long)]
window: Option<String>,
},
/// Sync tmux panes to a 2D columnar layout matching the editor
Sync {
/// Columns of comma-separated file paths (left-to-right). Repeat for each column.
#[arg(long = "col", required = true)]
columns: Vec<String>,
/// Only operate on panes within this tmux window (e.g. @1)
#[arg(long)]
window: Option<String>,
/// Focus this file's pane after arranging (defaults to first file)
#[arg(long)]
focus: Option<String>,
},
/// Replace content in a named component
Patch {
/// Path to the document
file: PathBuf,
/// Component name (e.g. "status", "log")
component: String,
/// Replacement content (reads from stdin if omitted)
content: Option<String>,
},
/// Watch session files for changes and auto-submit
Watch {
/// Stop the running watch daemon
#[arg(long)]
stop: bool,
/// Show watch daemon status
#[arg(long)]
status: bool,
/// Debounce delay in milliseconds
#[arg(long, default_value = "500")]
debounce: u64,
/// Maximum agent-triggered cycles per file
#[arg(long, default_value = "3")]
max_cycles: u32,
},
/// Display markdown outline with section structure and token counts
Outline {
/// Path to the markdown document
file: PathBuf,
/// Output as JSON array
#[arg(long)]
json: bool,
},
/// Validate sessions.json against live tmux panes, remove stale entries
Resync {
/// Actually kill wrong-session panes and deregister stale entries (without this flag, dry-run only)
#[arg(long)]
fix: bool,
/// Relocate WrongSession panes to this tmux session via join-pane instead of killing them.
/// Requires --fix. Example: --session 10
#[arg(long)]
session: Option<String>,
},
/// Manage the Claude Code skill definition
Skill {
#[command(subcommand)]
command: SkillCommands,
},
/// Manage editor plugins
Plugin {
#[command(subcommand)]
action: PluginAction,
},
/// Append an assistant response to a session document (reads from stdin)
Write {
/// Path to the session document
file: PathBuf,
/// Baseline content for 3-way merge (reads from file if omitted)
#[arg(long)]
baseline_file: Option<PathBuf>,
/// Template mode: parse <!-- patch:name --> blocks and apply to components
#[arg(long)]
template: bool,
/// Stream mode: template patches with CRDT merge (conflict-free)
#[arg(long)]
stream: bool,
/// IPC mode: write patch JSON to .agent-doc/patches/ for IDE plugin consumption
#[arg(long)]
ipc: bool,
/// Force direct disk write, skip IPC even when plugin is installed
#[arg(long)]
force_disk: bool,
/// Write origin identifier for tracing (e.g., "skill", "watch", "stream")
#[arg(long)]
origin: Option<String>,
/// Commit the document to git after a successful write (skipped silently if not in a git repo)
#[arg(long)]
commit: bool,
},
/// Stream agent output to document in real-time (CRDT merge)
Stream {
/// Path to the session document
file: PathBuf,
/// Write-back interval in milliseconds
#[arg(long, default_value = "200")]
interval: u64,
/// Agent backend to use
#[arg(long)]
agent: Option<String>,
/// Model override
#[arg(long)]
model: Option<String>,
/// Skip git commit after stream completes
#[arg(long)]
no_git: bool,
},
/// Show template structure of a document (components, modes, content)
TemplateInfo {
/// Path to the document
file: PathBuf,
},
/// Recover an orphaned response (from interrupted write-back after compaction)
Recover {
/// Path to the session document
file: PathBuf,
},
/// Run all pre-agent steps (recover, commit, claims, diff, document HEAD) and output JSON
Preflight {
/// Path to the session document
file: PathBuf,
},
/// Print document content to stdout (full file or a single named component).
Read {
/// Path to the session document
file: PathBuf,
/// Name of a specific component to extract (e.g. "exchange", "pending").
/// If omitted, the full file is printed.
#[arg(long)]
component: Option<String>,
},
/// Archive old exchanges / compact component content
Compact {
/// Path to the session document
file: PathBuf,
/// Number of recent exchanges/topics to keep.
/// Append mode default: 2. Template mode: omit to archive all (full compact),
/// or pass N to keep last N `### Re:` topic sections (partial compact).
#[arg(long)]
keep: Option<usize>,
/// Component to compact (template/stream mode, default: exchange)
#[arg(long)]
component: Option<String>,
/// Summary message to replace content with
#[arg(long)]
message: Option<String>,
/// Git tag name for pre-compact checkpoint (default: auto-generated
/// agent-doc/<doc-name>/pre-compact-N). Use "skip" to disable tagging.
#[arg(long)]
tag: Option<String>,
},
/// Convert a document between append and template modes
Convert {
/// Path to the session document
file: PathBuf,
/// Target mode (deprecated positional — use --agent-doc-format / --agent-doc-write instead)
#[arg(value_enum)]
mode: Option<AgentDocMode>,
/// Set document format (append | template)
#[arg(long, value_enum)]
agent_doc_format: Option<frontmatter::AgentDocFormat>,
/// Set write strategy (merge | crdt)
#[arg(long, value_enum)]
agent_doc_write: Option<frontmatter::AgentDocWrite>,
},
/// Get or set the document mode (format + write strategy)
Mode {
/// Path to the session document
file: PathBuf,
/// Set mode: append or template (deprecated — use --format / --write)
#[arg(long)]
set: Option<String>,
},
/// Print and clear the claims log (.agent-doc/claims.log)
Claims,
/// Fan-out: decompose task into parallel worktree-isolated subagents
Parallel {
/// Path to the session document
file: PathBuf,
/// Explicit subtask descriptions (repeatable)
#[arg(long = "task")]
tasks_explicit: Vec<String>,
/// Model override for subtask agents
#[arg(long)]
model: Option<String>,
/// Skip git commits in worktrees
#[arg(long)]
no_git: bool,
/// Run without worktrees (read-only tasks, shared CWD)
#[arg(long)]
no_worktree: bool,
/// Per-task timeout in seconds
#[arg(long, default_value = "600")]
timeout: u64,
/// Show plan without executing
#[arg(long)]
dry_run: bool,
},
/// Re-establish claims after context compaction (SessionStart hook)
Autoclaim,
/// Check for updates and upgrade to the latest version.
Upgrade,
/// Generate content-source annotation sidecar for a document
Annotate {
/// Path to the session document
file: PathBuf,
/// Force regeneration even if cache is valid
#[arg(long)]
force: bool,
/// Use git blame for full history attribution
#[arg(long)]
history: bool,
},
/// Undo the last agent response (restore pre-response state)
Undo {
/// Path to the session document
file: PathBuf,
},
/// Extract the last exchange entry from source to target document
Extract {
/// Source document
source: PathBuf,
/// Target document
target: PathBuf,
/// Component name to extract from (default: exchange)
#[arg(long)]
component: Option<String>,
},
/// Transfer entire component content from source to target document
Transfer {
/// Source document
source: PathBuf,
/// Target document
target: PathBuf,
/// Component name to transfer
component: String,
},
/// Migrate session state after a document file rename/move
Rename {
/// Original document path (may no longer exist on disk)
old_path: PathBuf,
/// New document path (must exist)
new_path: PathBuf,
},
/// Open an external terminal with tmux attached to the session
Terminal {
/// Path to the session document
file: PathBuf,
/// Tmux session name (overrides frontmatter tmux_session)
#[arg(long)]
session: Option<String>,
},
/// Insert a boundary marker at the end of a component for response ordering
Boundary {
/// Path to the session document
file: PathBuf,
/// Component name (default: exchange)
#[arg(long)]
component: Option<String>,
},
/// Append a blockquote notification to a document's exchange component
Notify {
/// Path to the document
file: PathBuf,
/// Notification message
message: String,
/// Source document or session
#[arg(long)]
source: Option<String>,
/// Sections affected (for re-evaluation directive)
#[arg(long)]
affects: Option<String>,
/// Skip git commit after notification
#[arg(long)]
no_commit: bool,
},
/// Print the path to the shared library (libagent_doc.so/dylib/dll)
LibPath,
/// List all available commands as JSON (for editor plugin autocomplete)
#[command(name = "commands")]
#[allow(clippy::enum_variant_names)]
ListCommands,
/// Hook system for cross-session coordination
Hook {
#[command(subcommand)]
action: HookAction,
},
/// Clean up document: compact, prune pending, apply callback results
Cleanup {
/// Path to the session document
file: PathBuf,
/// Timeout waiting for Claude session response (seconds)
#[arg(long, default_value_t = 120)]
timeout: u64,
/// Polling interval for callback response (milliseconds)
#[arg(long, default_value_t = 1000)]
poll_interval: u64,
/// Model for fallback agent (default: sonnet)
#[arg(long, default_value = "sonnet")]
fallback_model: String,
},
/// Manage the agent:pending component
Pending {
/// Path to the session document
file: PathBuf,
#[command(subcommand)]
action: PendingAction,
},
/// Manage bidirectional IPC callbacks
Callback {
#[command(subcommand)]
action: CallbackAction,
},
/// Show or change the configured tmux session
Session {
#[command(subcommand)]
action: Option<SessionAction>,
},
}
#[derive(Subcommand)]
enum HookAction {
/// Fire a hook event
Fire {
/// Event name (e.g., post_write, post_commit, claim)
event: String,
/// Document file path
file: String,
/// Session ID (auto-read from frontmatter if omitted)
#[arg(long)]
session_id: Option<String>,
/// JSON data to attach to the event
#[arg(long)]
data: Option<String>,
},
/// Poll for hook events
Poll {
/// Event name to poll
event: String,
/// Only return events newer than this timestamp (unix seconds)
#[arg(long, default_value_t = 0)]
since: u64,
/// Project root directory
#[arg(long)]
root: Option<String>,
},
/// Start hook socket listener
Listen {
/// Project root directory
#[arg(long)]
root: Option<String>,
},
/// Clean up expired events
Gc {
/// Project root directory
#[arg(long)]
root: Option<String>,
},
/// Check for pending callback requests (called by PostToolUse hooks)
CheckCallbacks {
/// Project root directory
#[arg(long)]
root: Option<String>,
},
}
#[derive(Subcommand)]
enum PendingAction {
/// Add an item to the pending component
Add {
/// The pending item description
item: String,
},
/// Remove an item from the pending component
Remove {
/// Content to match
target: String,
/// Treat target as a substring match
#[arg(long, short)]
contains: bool,
},
/// Remove completed items
Prune,
/// List current pending items
List,
}
#[derive(Subcommand)]
enum CallbackAction {
/// Create a callback request for a document
Request {
/// Path to the session document
file: PathBuf,
/// Operations requested (comma-separated: compact,prune-pending,summary)
operations: String,
/// Optional additional context
#[arg(long)]
context: Option<String>,
/// TTL in seconds before the request expires
#[arg(long, default_value_t = 300)]
ttl: u64,
},
/// Read the pending callback request for a document
Read {
/// Path to the session document
file: PathBuf,
},
/// Write a callback response for a document
Respond {
/// Path to the session document
file: PathBuf,
/// The request_id to respond to (must match the pending request)
#[arg(long)]
request_id: String,
/// Response status: "success" or "error"
#[arg(long, default_value = "success")]
status: String,
/// Summary text
#[arg(long)]
summary: String,
},
/// Clean up expired callback requests
Gc {
/// Project root directory
#[arg(long)]
root: Option<String>,
},
}
#[derive(Subcommand)]
enum SessionAction {
/// Set the configured tmux session and migrate panes
Set {
/// Target tmux session name (e.g., "5")
name: String,
},
}
#[derive(Subcommand)]
enum PluginAction {
/// Download and install an editor plugin
Install {
/// Editor: jetbrains, vscode
editor: String,
/// Install from local build instead of GitHub Releases
#[clap(long)]
local: bool,
},
/// Update an installed plugin to the latest version
Update {
/// Editor: jetbrains, vscode
editor: String,
},
/// List installed editor plugins
List,
}
#[derive(Subcommand)]
enum SkillCommands {
/// Install the skill definition for the detected (or specified) agent harness
Install {
/// After install, output reload instructions: compact (default) or restart
#[arg(long)]
reload: Option<String>,
/// Target harness: claude, opencode, codex, cursor, generic (auto-detected if omitted)
#[arg(long)]
harness: Option<String>,
/// Install for all supported harnesses
#[arg(long)]
all: bool,
},
/// Check if the installed skill matches the binary version
Check,
}
/// Initialize structured logging. When `AGENT_DOC_LOG` is set (e.g., "debug"),
/// logs are written to `.agent-doc/logs/debug.log`. When unset, this is a no-op.
fn init_tracing() {
let filter = match std::env::var("AGENT_DOC_LOG") {
Ok(val) => val,
Err(_) => return, // No logging configured — zero overhead
};
// Find .agent-doc/logs/ directory (walk up from CWD)
let log_dir = {
let mut dir = std::env::current_dir().unwrap_or_default();
loop {
let candidate = dir.join(".agent-doc/logs");
if candidate.is_dir() {
break Some(candidate);
}
if !dir.pop() {
break None;
}
}
};
let Some(log_dir) = log_dir else {
eprintln!("[tracing] AGENT_DOC_LOG set but no .agent-doc/logs/ found — logging disabled");
return;
};
let file_appender = tracing_appender::rolling::daily(&log_dir, "debug.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
// Leak the guard so it lives for the program lifetime
std::mem::forget(_guard);
use tracing_subscriber::EnvFilter;
let env_filter = EnvFilter::try_new(&filter)
.unwrap_or_else(|_| EnvFilter::new("debug"));
tracing_subscriber::fmt()
.with_env_filter(env_filter)
.with_writer(non_blocking)
.with_ansi(false)
.with_target(true)
.with_thread_ids(true)
.init();
tracing::debug!("agent-doc tracing initialized (filter: {})", filter);
}
fn main() -> anyhow::Result<()> {
// Initialize structured logging via AGENT_DOC_LOG env var.
// Examples: AGENT_DOC_LOG=debug, AGENT_DOC_LOG=agent_doc::preflight=debug
// When set, logs to .agent-doc/logs/debug.log (auto-rotated).
// When unset, no file logging (zero overhead).
init_tracing();
let cli = Cli::parse();
// Warn about newer versions on startup, but skip if running the upgrade command itself.
if !matches!(cli.command, Commands::Upgrade) {
upgrade::warn_if_outdated();
}
let config = config::load()?;
match cli.command {
Commands::Run {
file,
branch,
agent,
model,
dry_run,
no_git,
} => run::run(&file, branch, agent.as_deref(), model.as_deref(), dry_run, no_git, &config),
Commands::History { file, restore } => match restore {
Some(commit) => history::restore(&file, &commit),
None => history::list(&file),
},
Commands::Log { file } => history::log(&file),
Commands::Show { file, back, at, tag } => {
history::show(&file, back, at, tag.as_deref())
}
Commands::Init { file, title, agent, mode } => {
init::run(file.as_deref(), title.as_deref(), agent.as_deref(), mode.as_deref(), &config)
}
Commands::Install { editor, skip_prereqs, skip_plugins } => {
install::run(editor.as_deref(), skip_prereqs, skip_plugins)
}
Commands::Diff { file, wait, from, to } => {
if let Some(from_ref) = from {
let to_ref = to.as_deref().unwrap_or("HEAD");
history::git_diff(&file, &from_ref, to_ref)
} else {
diff::run(&file, wait)
}
}
Commands::Reset { file } => reset::run(&file),
Commands::Clean { file, archive } => clean::run(&file, archive),
Commands::AuditDocs { root } => audit_docs::run(root.as_deref()),
Commands::Gc { root, dry_run } => {
let result = gc::run(root.as_deref(), dry_run)?;
if dry_run {
eprintln!("[gc] Dry run: {} files would be deleted, {} kept", result.deleted, result.skipped);
}
Ok(())
}
Commands::Start { file } => start::run(&file),
Commands::Route { file, pane, cols, focus: _focus, debounce } => {
// NOTE: sync::run_layout_only was previously called here after route when
// --col args were provided. Removed because the JB plugin calls `agent-doc sync`
// separately with the correct --window arg. Running sync from both route AND
// the plugin created a double-sync glitch (panes bouncing between stash and
// agent-doc window). The plugin's sync is authoritative for layout.
route::run(&file, pane.as_deref(), debounce, &cols)
}
Commands::Prompt { file, answer, all } => {
if all {
return prompt::run_all();
}
let file = file.context("FILE required when not using --all")?;
match answer {
Some(option) => prompt::answer(&file, option),
None => prompt::run(&file),
}
}
Commands::Commit { file } => git::commit(&file),
Commands::Dedupe { file } => dedupe::run(&file),
Commands::Claim { file, position, pane, window, force } => claim::run(&file, position.as_deref(), pane.as_deref(), window.as_deref(), force),
Commands::Focus { file, pane } => focus::run(&file, pane.as_deref()),
Commands::Layout { files, split, pane, window } => {
let split = match split.as_str() {
"v" | "vertical" => layout::Split::Vertical,
_ => layout::Split::Horizontal,
};
let paths: Vec<&Path> = files.iter().map(|f| f.as_path()).collect();
layout::run(&paths, split, pane.as_deref(), window.as_deref())
}
Commands::Sync {
columns,
window,
focus,
} => sync::run(&columns, window.as_deref(), focus.as_deref()),
Commands::Patch {
file,
component,
content,
} => patch::run(&file, &component, content.as_deref()),
Commands::Watch {
stop,
status,
debounce,
max_cycles,
} => {
if stop {
watch::stop()
} else if status {
watch::status()
} else {
watch::start(
&config,
watch::WatchConfig {
debounce_ms: debounce,
max_cycles,
},
)
}
}
Commands::Outline { file, json } => outline::run(&file, json),
Commands::Resync { fix, session } => resync::run(fix, session.as_deref()),
Commands::Skill { command } => match command {
SkillCommands::Install { reload, harness, all } => {
if all {
skill::install_all()?;
} else if let Some(ref h) = harness {
let env = agent_kit::detect::Environment::from_name(h)
.ok_or_else(|| anyhow::anyhow!(
"unknown harness '{}'. Valid: claude, opencode, codex, cursor, generic", h
))?;
skill::install_for(env)?;
} else {
let updated = skill::install_and_check_updated()?;
if updated
&& let Some(ref mode) = reload
{
match mode.as_str() {
"restart" => {
println!("SKILL_RELOAD=restart");
println!("Skill updated. Please restart this session with --resume to reload the skill.");
}
_ => {
println!("SKILL_RELOAD=compact");
println!("Skill updated. Please run /compact to reload the updated skill instructions.");
}
}
}
}
Ok(())
}
SkillCommands::Check => skill::check(),
},
Commands::Plugin { action } => match action {
PluginAction::Install { editor, local } => {
if local {
plugin::install_local(&editor)
} else {
plugin::install(&editor)
}
}
PluginAction::Update { editor } => plugin::update(&editor),
PluginAction::List => plugin::list(),
},
Commands::Write { file, baseline_file, template: is_template, stream: is_stream, ipc: is_ipc, force_disk, origin, commit: do_commit } => {
// Log write origin for tracing
if let Some(ref orig) = origin {
crate::ops_log::log_op(&file, &format!("write_origin file={} origin={}", file.display(), orig));
}
let baseline = baseline_file
.as_ref()
.map(std::fs::read_to_string)
.transpose()
.context("failed to read baseline file")?;
let result = if is_ipc {
write::run_ipc(&file, baseline.as_deref())
} else if is_stream {
write::run_stream(&file, baseline.as_deref(), force_disk)
} else if is_template {
write::run_template(&file, baseline.as_deref())
} else {
// Auto-detect write strategy from frontmatter
let content = std::fs::read_to_string(&file)
.context("failed to read document for mode detection")?;
let (fm, _) = frontmatter::parse(&content)?;
if fm.resolve_mode().is_crdt() {
write::run_stream(&file, baseline.as_deref(), force_disk)
} else {
write::run(&file, baseline.as_deref())
}
};
// Fix 2: attempt commit even when run_stream returns Err — a partial write
// may have already saved the snapshot, and we want it tracked before
// propagating the error.
if do_commit {
if git::is_in_git_repo(&file) {
if let Err(e) = git::commit(&file) {
eprintln!("[commit] warning: {}", e);
}
} else {
eprintln!("[commit] skipped (not in git repo)");
}
}
result?;
Ok(())
}
Commands::Stream { file, interval, agent, model, no_git } => {
stream::run(&file, interval, agent.as_deref(), model.as_deref(), no_git, &config)
}
Commands::TemplateInfo { file } => {
let info = template::template_info(&file)?;
println!("{}", serde_json::to_string_pretty(&info)?);
Ok(())
}
Commands::Recover { file } => {
let recovered = recover::run(&file)?;
if !recovered {
eprintln!("[recover] No pending response found for {}", file.display());
}
Ok(())
}
Commands::Preflight { file } => preflight::run(&file),
Commands::Read { file, component } => read::run(&file, component.as_deref()),
Commands::Compact {
file,
keep,
component,
message,
tag,
} => compact::run(&file, keep, component.as_deref(), message.as_deref(), tag.as_deref()),
Commands::Convert { file, mode, agent_doc_format, agent_doc_write } => {
convert::run(&file, mode.as_ref(), agent_doc_format, agent_doc_write)
}
Commands::Mode { file, set } => mode::run(&file, set.as_deref()),
Commands::Annotate { file, force, history } => annotate::run(&file, force, history),
Commands::Undo { file } => undo::run(&file),
Commands::Extract { source, target, component } => extract::run(&source, &target, component.as_deref()),
Commands::Transfer { source, target, component } => extract::transfer(&source, &target, &component),
Commands::Rename { old_path, new_path } => rename::run(&old_path, &new_path),
Commands::Claims => {
let cwd = std::env::current_dir()?;
if let Some(root) = snapshot::find_project_root(&cwd) {
let log_path = root.join(".agent-doc/claims.log");
if let Ok(contents) = std::fs::read_to_string(&log_path)
&& !contents.is_empty()
{
print!("{}", contents);
std::fs::write(&log_path, "")?;
}
}
Ok(())
}
Commands::Parallel { file, tasks_explicit, model, no_git, no_worktree, timeout, dry_run } => {
parallel::run(&file, parallel::ParallelConfig {
tasks: tasks_explicit,
model,
no_git,
no_worktree,
timeout_secs: timeout,
dry_run,
})
}
Commands::Notify { file, message, source, affects, no_commit } => {
notify::run(&file, &message, source.as_deref(), affects.as_deref(), !no_commit)
}
Commands::Boundary { file, component } => boundary::run(&file, component.as_deref()),
Commands::Terminal { file, session } => terminal::run(&file, session.as_deref()),
Commands::Autoclaim => autoclaim::run(),
Commands::Upgrade => upgrade::run(),
Commands::LibPath => {
// Print the path to the shared library built alongside this binary.
// The cdylib is in the same target directory as the binary.
let exe = std::env::current_exe()?;
let dir = exe.parent().unwrap();
#[cfg(target_os = "linux")]
let lib_name = "libagent_doc.so";
#[cfg(target_os = "macos")]
let lib_name = "libagent_doc.dylib";
#[cfg(target_os = "windows")]
let lib_name = "agent_doc.dll";
let lib_path = dir.join(lib_name);
if lib_path.exists() {
println!("{}", lib_path.display());
} else {
eprintln!("[lib-path] library not found at {}", lib_path.display());
eprintln!("[lib-path] build with: cargo build --release");
std::process::exit(1);
}
Ok(())
}
Commands::ListCommands => commands::run(),
Commands::Session { action } => match action {
Some(SessionAction::Set { name }) => session_cmd::set(&name),
None => session_cmd::show(),
},
Commands::Hook { action } => match action {
HookAction::Fire { event, file, session_id, data } => {
hook_cmd::fire(&event, &file, session_id.as_deref(), data.as_deref())
}
HookAction::Poll { event, since, root } => {
hook_cmd::poll(&event, since, root.as_deref())
}
HookAction::Listen { root } => {
hook_cmd::listen(root.as_deref())
}
HookAction::Gc { root } => {
hook_cmd::gc(root.as_deref())
}
HookAction::CheckCallbacks { root } => {
let pending = callback::scan_pending_callbacks(root.as_deref())?;
let json = serde_json::to_string_pretty(
&serde_json::json!({"pending_callbacks": pending})
)?;
println!("{}", json);
Ok(())
}
},
Commands::Cleanup { file, timeout, poll_interval, fallback_model } => {
cleanup_cmd::run(&file, timeout, poll_interval, &fallback_model)
}
Commands::Pending { file, action } => match action {
PendingAction::Add { item } => pending_cmd::add(&file, &item),
PendingAction::Remove { target, contains } => pending_cmd::remove(&file, &target, contains),
PendingAction::Prune => pending_cmd::prune(&file),
PendingAction::List => pending_cmd::list(&file),
},
Commands::Callback { action } => match action {
CallbackAction::Request { file, operations, context, ttl } => {
let ops: Vec<&str> = operations.split(',').map(|s| s.trim()).collect();
let request = callback::create_request(&file, &ops, context.as_deref(), ttl)?;
println!("{}", serde_json::to_string_pretty(&request)?);
Ok(())
}
CallbackAction::Read { file } => {
match callback::read_request(&file)? {
Some(request) => {
println!("{}", serde_json::to_string_pretty(&request)?);
}
None => {
println!("{{}}");
eprintln!("[callback] no pending request for {}", file.display());
}
}
Ok(())
}
CallbackAction::Respond { file, request_id, status, summary } => {
callback::write_response(&file, &request_id, &status, &summary, None)?;
eprintln!("[callback] response written for request {}", request_id);
Ok(())
}
CallbackAction::Gc { root } => {
let cwd = std::env::current_dir()?;
let root_path = root.map(PathBuf::from)
.or_else(|| snapshot::find_project_root(&cwd))
.context("could not find project root")?;
callback::cleanup_expired(&root_path, 300)
}
},
}
}