Repository navigation
Expand file tree
/
Copy pathcodex.rs
More file actions
2331 lines (2094 loc) · 92.7 KB
/
Copy pathcodex.rs
File metadata and controls
2331 lines (2094 loc) · 92.7 KB
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
//! Codex agent: hook install/uninstall helpers.
use super::*;
use crate::core::user_dirs;
use crate::hooks::constants::{CODEX_DIR, CODEX_HOOK_COMMAND, HOOKS_JSON, PRE_TOOL_USE_KEY};
use std::path::Component;
/// The line that says an `RTK.md` is RTK's to rewrite and to remove.
///
/// `--codex` is the one mode whose `RTK.md` sits at the project root, next to the user's own
/// files and under a name RTK does not own, so it has to be able to tell the two apart. It
/// says so in the file rather than by comparing content: the payload changes between releases,
/// and a check against the running build's copy stops recognising RTK's own file the moment it
/// does -- leaving it orphaned on uninstall and backed up on every upgrade.
const RTK_MD_OWNED_MARKER: &str = "<!-- rtk-owned:";
/// The header [`RTK_MD_OWNED_MARKER`] appears in, written above the awareness payload.
const RTK_MD_OWNED_HEADER: &str =
"<!-- rtk-owned: written by `rtk init --codex`, removed by `rtk init --codex --uninstall` -->";
/// The `RTK.md` the Codex mode writes: RTK's ownership line, then the awareness payload.
pub(super) fn codex_rtk_md_content(level: AwarenessLevel) -> String {
format!("{RTK_MD_OWNED_HEADER}\n\n{}", awareness_content(level))
}
/// The heading every `--codex` release up to v0.48.0 wrote at the top of the `RTK.md` it
/// owned, before the ownership line existed. Nothing writes it any more, so it is frozen, and
/// it names both RTK and the mode, so a file starting with it is RTK's. The headings that
/// replaced it (`# RTK`, `# Command output`) are left out on purpose: a user's own notes may
/// legitimately open with either, and taking their file would be the worse mistake.
const RTK_MD_LEGACY_CODEX_HEADING: &str = "# RTK - Rust Token Killer (Codex CLI)";
/// SHA-256 of the three awareness payloads RTK wrote as `RTK.md` between the legacy heading
/// and the ownership line -- v0.49.0 and the builds after it, which wrote the shared text with
/// nothing on top claiming it. Their headings (`# RTK`, `# Command output`) name neither RTK
/// nor the mode and a user's notes may open with either, so only the whole file identifies
/// them. Digests rather than the payload constants: these name bytes that shipped, and
/// rewording the awareness text today must not change which files uninstall recognises.
const RTK_MD_UNMARKED_PAYLOAD_DIGESTS: [&str; 3] = [
"dc37dc6afdf513200c2aae1931496e433d323f313877a49b0d5ba11992c33ac7",
"d124b2926b0cd506680f785ab98ef64c211854549da4a85ec544fb803aaea812",
"278274ef3d08c858d4247cc91419c4d74ef922b95719e987b22e896aef10e1fc",
];
/// The digest [`RTK_MD_UNMARKED_PAYLOAD_DIGESTS`] is compared against. Carriage returns are
/// dropped first: a checkout or an editor may have rewritten the line endings of a file RTK
/// wrote, which does not make it the user's.
fn rtk_md_payload_digest(content: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(content.replace('\r', "").as_bytes());
format!("{:x}", hasher.finalize())
}
/// Whether `content` is an RTK.md that RTK itself wrote.
///
/// The ownership line and the legacy heading are read on the first non-blank line only: RTK
/// writes its claim at the top of a file it wrote whole, and a user who pasted either -- or
/// an RTK-written block -- somewhere inside their own notes has not handed the rest of the
/// file over with it. A payload from the releases that claimed nothing is matched whole.
fn is_rtk_authored_md(content: &str) -> bool {
// A BOM is what an editor adds, not a change of authorship, and Windows editors add one.
let content = strip_leading_bom(content);
let claimed = content
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.is_some_and(|line| {
line.starts_with(RTK_MD_OWNED_MARKER) || line == RTK_MD_LEGACY_CODEX_HEADING
});
claimed || RTK_MD_UNMARKED_PAYLOAD_DIGESTS.contains(&rtk_md_payload_digest(content).as_str())
}
/// [`is_rtk_authored_md`] for a path. An unreadable file is not provably RTK's, so it is
/// treated as the user's and left alone.
fn rtk_md_is_rtk_authored(path: &Path) -> bool {
fs::read_to_string(path).is_ok_and(|content| is_rtk_authored_md(&content))
}
/// Which directory a Codex `RTK.md` sits in, which is what decides who owns it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum RtkMdScope {
/// `--global`: the Codex home. RTK created the file there, nothing else claims the name,
/// and every release before the ownership marker wrote it there unmarked -- reading the
/// marker in this scope would strand all of those files on uninstall.
CodexHome,
/// Project scope: the project root, shared with the user's own files. Only the marker
/// tells RTK's `RTK.md` from one the user wrote under the same name.
ProjectRoot,
}
impl RtkMdScope {
fn for_global(global: bool) -> Self {
if global {
Self::CodexHome
} else {
Self::ProjectRoot
}
}
/// Whether RTK may overwrite or remove the `RTK.md` at `path` without asking.
fn owns(self, path: &Path) -> bool {
match self {
Self::CodexHome => true,
Self::ProjectRoot => rtk_md_is_rtk_authored(path),
}
}
}
/// How many numbered backups may sit beside a file before RTK refuses to make another.
///
/// High enough that no ordinary sequence of installs reaches it, and bounded so a file that
/// keeps producing distinct backups cannot quietly fill its directory: at the ceiling RTK
/// stops and says so rather than choosing one to overwrite.
const MAX_BACKUP_ATTEMPTS: usize = 99;
/// A slot to preserve a file's current content in, and what is known about that content.
///
/// Reading the source is only ever needed to answer "is this already preserved?", which is
/// why the unreadable case is its own arm rather than a refusal: a caller that copies cannot
/// proceed without that answer, while a caller that renames never needed it, since a rename
/// carries the content whether or not RTK can read it.
#[derive(Debug)]
enum BackupSlot {
/// Free, and the source differs from every backup already present.
Free(PathBuf),
/// Identical content already sits here, so a copy would be redundant. A rename still has
/// the original to move, and moving it here is what discards the duplicate.
AlreadyPreserved(PathBuf),
/// Free, but the source could not be read, so whether it is already preserved is unknown.
SourceUnreadable(PathBuf),
}
impl BackupSlot {
/// The slot to move the original onto, for a caller that preserves content by renaming.
///
/// Every arm gives the same answer: a rename carries content RTK could not read, and
/// renaming onto a byte-identical backup discards the duplicate instead of burning a slot.
fn for_rename(self) -> PathBuf {
match self {
BackupSlot::Free(path)
| BackupSlot::AlreadyPreserved(path)
| BackupSlot::SourceUnreadable(path) => path,
}
}
}
/// `path.bak` for the first slot, `path.bak.N` after that.
///
/// Built by appending to the `OsString` rather than through `with_extension`, which replaces
/// an extension instead of extending it, and rather than through `display()`, which is lossy:
/// on a path that is not valid UTF-8 the probe and the write would disagree.
fn numbered_backup_path(path: &Path, attempt: usize) -> PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(".bak");
if attempt > 0 {
name.push(format!(".{attempt}"));
}
PathBuf::from(name)
}
/// Pick a `.bak` sibling for `path`, numbered when earlier backups are still there so a second
/// run cannot overwrite the first one's rescue copy.
fn free_backup_slot(path: &Path) -> Result<BackupSlot> {
let source = fs::read(path).ok();
for attempt in 0..=MAX_BACKUP_ATTEMPTS {
let candidate = numbered_backup_path(path, attempt);
match fs::read(&candidate) {
// A provisioning loop that reapplies the same local change would otherwise
// consume a slot on every run.
Ok(existing) if source.as_deref() == Some(existing.as_slice()) => {
return Ok(BackupSlot::AlreadyPreserved(candidate));
}
Ok(_) => continue,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(match source {
Some(_) => BackupSlot::Free(candidate),
None => BackupSlot::SourceUnreadable(candidate),
});
}
// Occupied by something unreadable -- a directory, or a file this user cannot
// read. Its content cannot be compared, so treat the slot as taken rather than
// overwriting it.
Err(_) => continue,
}
}
anyhow::bail!(
"Cannot back up {}: {} existing backups are already present. \
Remove or archive them first.",
path.display(),
MAX_BACKUP_ATTEMPTS + 1
)
}
/// How many hops one path's symlink chain is followed before the walk gives up.
///
/// The bound is per component, not per walk: [`resolve_symlink_components_within`] spends a
/// fresh budget on the descent into each target it jumps to. It sits below the kernel's own
/// limit on purpose -- RTK has to be able to say where a write lands, and a chain this deep
/// under a path RTK joins itself is not one a user maintains.
const MAX_SYMLINK_HOPS: usize = 16;
/// What one `readlink` established.
///
/// [`Unreadable`](Self::Unreadable) is not [`NotALink`](Self::NotALink): `lstat` already said
/// this is a symlink, so reporting the read failure as "no link here" would hand a caller a
/// path nothing resolved and let it compare that as if it had.
enum SymlinkHop {
NotALink,
To(PathBuf),
Unreadable,
}
/// What following one path's symlink chain established.
enum SymlinkChain {
/// The path is not a symlink.
Settled,
/// Followed to a target that is not itself a symlink.
Target(PathBuf),
/// Still a symlink after [`MAX_SYMLINK_HOPS`]: a cycle, or a chain too deep to vouch for.
Exhausted,
/// A link on the chain could not be read, so where it leads is unknown.
Unreadable,
}
/// How far a component walk got, and whether it can be trusted as an answer.
enum Resolution {
/// Every symlink along the path was followed to a target that is not a link.
Fully(PathBuf),
/// The walk gave up: a cycle, a chain too deep, or a link it could not read. The path is
/// as far as it got, which a caller that only acts may still use -- the kernel finishes
/// the resolution -- but which says nothing about where the write lands.
Unresolved(PathBuf),
}
/// Read one symlink hop, resolving a relative link against the link's own directory.
fn symlink_hop(path: &Path) -> SymlinkHop {
if !fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
return SymlinkHop::NotALink;
}
let Ok(target) = fs::read_link(path) else {
return SymlinkHop::Unreadable;
};
if target.is_absolute() {
return SymlinkHop::To(target);
}
match path.parent() {
Some(parent) => SymlinkHop::To(parent.join(target)),
None => SymlinkHop::Unreadable,
}
}
/// Follow a chain of symlinks whose final target does not exist yet, stopping at the first
/// entry that is not a symlink. `canonicalize` reports `ELOOP` for a cycle, so the hop limit
/// is the only terminator available here.
fn follow_symlink_chain(path: &Path) -> SymlinkChain {
let mut current = match symlink_hop(path) {
SymlinkHop::NotALink => return SymlinkChain::Settled,
SymlinkHop::Unreadable => return SymlinkChain::Unreadable,
SymlinkHop::To(target) => target,
};
// Inclusive: the bound counts hops followed, and an exclusive range would stop one short
// of the chain length the documentation promises.
for _ in 1..=MAX_SYMLINK_HOPS {
match symlink_hop(¤t) {
SymlinkHop::NotALink => return SymlinkChain::Target(current),
SymlinkHop::Unreadable => return SymlinkChain::Unreadable,
SymlinkHop::To(next) => current = next,
}
}
SymlinkChain::Exhausted
}
/// Jumping to a link's target abandons the components walked so far, and that target may
/// itself sit behind symlinked ancestors this walk never visited, so it is resolved from the
/// top. `budget` bounds that descent: the paths involved can form a cycle that
/// [`follow_symlink_chain`]'s own hop limit does not see, because each jump hands it a
/// different path.
fn resolve_symlink_components_within(path: &Path, budget: usize) -> Resolution {
let mut resolved = PathBuf::new();
let mut settled = true;
for component in path.components() {
resolved.push(component);
match follow_symlink_chain(&resolved) {
SymlinkChain::Settled => {}
SymlinkChain::Exhausted | SymlinkChain::Unreadable => settled = false,
SymlinkChain::Target(target) => match budget.checked_sub(1) {
Some(remaining) => match resolve_symlink_components_within(&target, remaining) {
Resolution::Fully(path) => resolved = path,
Resolution::Unresolved(path) => {
resolved = path;
settled = false;
}
},
None => {
resolved = target;
settled = false;
}
},
}
}
if settled {
Resolution::Fully(resolved)
} else {
Resolution::Unresolved(resolved)
}
}
/// Refuse a project-scoped write whose path leaves the project.
///
/// `.codex/hooks.json` and its backup sibling are relative names RTK joins itself, so a
/// symlinked component is the only way they can resolve elsewhere -- and then `rtk init
/// --codex` would register a hook, which runs shell commands, in a directory the user never
/// named. The global mode exists for writing outside the project.
///
/// This answers for the tree as it stands when asked. A process rewriting these paths while
/// init runs can still move the write afterwards; the case it is built for is a repository
/// that ships the links, which is settled before init starts.
fn ensure_inside_project(path: &Path) -> Result<()> {
let root = user_dirs::current_dir().context("Failed to resolve the current directory")?;
ensure_inside_root(&root, path)
}
/// [`ensure_inside_project`] against an explicit root.
fn ensure_inside_root(root: &Path, path: &Path) -> Result<()> {
let root = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
// Anchored to the root before resolving: these paths are relative, and
// `canonicalize_path_for_comparison` hands a relative path straight back when none of its
// components exist yet, which no absolute root can ever contain.
let site = root.join(path);
ensure_chain_sits_inside(&root, path, &site)?;
match resolve_symlink_components_within(&site, MAX_SYMLINK_HOPS) {
// A walk that gave up cannot say where the write lands, and a path RTK cannot place
// is one it must not write to.
Resolution::Unresolved(_) => anyhow::bail!(
"{} passes through a symlink RTK cannot follow to an end, \
so RTK cannot say where a write to it would land.\n\
Remove the symlink, or use --global to configure Codex outside the project.",
path.display()
),
Resolution::Fully(resolved) => {
let resolved = canonicalize_path_for_comparison(&lexically_normalized(&resolved));
if !resolved.starts_with(&root) {
anyhow::bail!(
"{} resolves to {}, outside the project at {}.\n\
Remove the symlink, or use --global to configure Codex outside the project.",
path.display(),
resolved.display(),
root.display()
);
}
Ok(())
}
}
}
/// Every link the write site itself passes through has to *sit* inside the project, not only
/// end up pointing back into it.
///
/// `atomic_write` cannot canonicalize a chain whose end does not exist, and then writes at the
/// path as the filesystem reads it, replacing the last link rather than following it. A link
/// anywhere along that chain is therefore a place the write can land, and one the project does
/// not contain is one an attacker may own: pointing it back inside passes a check that only
/// looked at the far end, while leaving the middle free to be re-aimed afterwards.
///
/// Only the chain of the site itself is judged this way. Links on *ancestor* components are
/// traversed, never sited -- whole directory trees hang off one on macOS, so refusing those
/// would refuse every absolute target under `/var` or `/tmp`.
fn ensure_chain_sits_inside(root: &Path, named: &Path, site: &Path) -> Result<()> {
let mut hop = site.to_path_buf();
for _ in 0..=MAX_SYMLINK_HOPS {
match symlink_hop(&hop) {
SymlinkHop::NotALink => return Ok(()),
SymlinkHop::Unreadable => anyhow::bail!(
"{} passes through a symlink at {} that RTK cannot read, \
so RTK cannot say where a write to it would land.\n\
Remove the symlink, or use --global to configure Codex outside the project.",
named.display(),
hop.display()
),
SymlinkHop::To(next) => {
let at = link_site(&hop);
if !at.starts_with(root) {
anyhow::bail!(
"{} is a symlink at {}, outside the project at {}.\n\
Remove the symlink, or use --global to configure Codex outside the project.",
named.display(),
at.display(),
root.display()
);
}
hop = next;
}
}
}
anyhow::bail!(
"{} passes through more symlinks than RTK follows, \
so RTK cannot say where a write to it would land.\n\
Remove the symlink, or use --global to configure Codex outside the project.",
named.display()
)
}
/// Where a symlink sits, as a path free of `.` and `..`.
///
/// Resolving the parent and re-attaching the name gives the link's own location rather than
/// its target's, whether or not the parent itself holds links.
fn link_site(link: &Path) -> PathBuf {
match (link.parent(), link.file_name()) {
(Some(parent), Some(name)) => canonicalize_path_for_comparison(parent).join(name),
_ => lexically_normalized(link),
}
}
/// `path` with `.` dropped and `..` folded into the component before it.
///
/// Only sound once the path holds no symlink, which is where the containment walk uses it:
/// `link/..` is the parent of the link's target, not of the link. Comparing without it would
/// mean comparing a path nothing resolved, because `canonicalize`'s fallback gives up and
/// returns its argument untouched as soon as a missing component is followed by `..`.
fn lexically_normalized(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
// Only a named component can be folded away: `..` after a root, or after another
// `..` on a relative path, names somewhere else and has to survive.
Component::ParentDir
if matches!(
normalized.components().next_back(),
Some(Component::Normal(_))
) =>
{
normalized.pop();
}
kept => normalized.push(kept),
}
}
normalized
}
pub(super) fn uninstall_codex(global: bool, ctx: InitContext) -> Result<()> {
let InitContext { dry_run, .. } = ctx;
let mut hook_left_in_place = None;
let removed = if global {
let codex_dir = resolve_codex_dir()?;
uninstall_codex_at(&codex_dir, ctx)?
} else {
// Only the hook path is guarded, and only it is given up when the guard trips:
// `AGENTS.md` and `RTK.md` are project-root names RTK joins itself, they are
// demonstrably where uninstall left them, and refusing to clean them because some
// other path is a symlink leaves the user with artifacts and no command to remove
// them -- `--global` acts on `~/.codex`, which is not where these are.
let hooks_json_path = user_dirs::in_working_dir(CODEX_DIR).join(HOOKS_JSON);
let hooks_json_path = match ensure_inside_project(&hooks_json_path)
.and_then(|()| ensure_inside_project(&backup_path_for(&hooks_json_path)))
{
Ok(()) => Some(hooks_json_path.as_path()),
Err(error) => {
hook_left_in_place = Some(error);
None
}
};
uninstall_codex_with_paths(
&user_dirs::in_working_dir(AGENTS_MD),
&user_dirs::in_working_dir(RTK_MD),
RtkMdScope::ProjectRoot,
hooks_json_path,
&[RTK_MD_REF],
ctx,
)?
};
println!(
"{}",
codex_uninstall_report(&removed, hook_left_in_place.as_ref(), dry_run)
);
Ok(())
}
/// Everything `rtk init --codex --uninstall` says it did, as one block.
///
/// Built rather than printed line by line so a hook the guard refused to touch cannot be
/// dropped from the summary without the tests noticing: read on its own, a list of what was
/// removed reads as a complete uninstall.
fn codex_uninstall_report(
removed: &[String],
unchecked_hook: Option<&anyhow::Error>,
dry_run: bool,
) -> String {
let mut report = if removed.is_empty() {
"RTK was not installed for Codex CLI (nothing to remove)".to_string()
} else {
let header = if dry_run {
"[dry-run] would uninstall RTK for Codex CLI:"
} else {
"RTK uninstalled for Codex CLI:"
};
std::iter::once(header.to_string())
.chain(removed.iter().map(|item| format!(" - {item}")))
.collect::<Vec<_>>()
.join("\n")
};
// Not a claim that the hook is registered: the guard refuses before anything reads the
// file, so RTK does not know -- only that it did not look.
if let Some(error) = unchecked_hook {
report.push_str(&format!(
"\n Not checked: the Codex hook in {}, which may still be registered:",
user_dirs::in_working_dir(CODEX_DIR)
.join(HOOKS_JSON)
.display()
));
for line in error.to_string().lines() {
report.push_str(&format!("\n {line}"));
}
}
report
}
fn uninstall_codex_at(codex_dir: &Path, ctx: InitContext) -> Result<Vec<String>> {
let absolute_rtk_md_ref = codex_rtk_md_ref(codex_dir);
uninstall_codex_with_paths(
&codex_dir.join(AGENTS_MD),
&codex_dir.join(RTK_MD),
RtkMdScope::CodexHome,
Some(&codex_dir.join(HOOKS_JSON)),
&[RTK_MD_REF, absolute_rtk_md_ref.as_str()],
ctx,
)
}
pub(super) fn run_codex_mode(global: bool, ctx: InitContext) -> Result<()> {
let (agents_md_path, rtk_md_path, hooks_json_path) = if global {
let codex_dir = resolve_codex_dir()?;
(
codex_dir.join(AGENTS_MD),
codex_dir.join(RTK_MD),
codex_dir.join(HOOKS_JSON),
)
} else {
let paths = (
user_dirs::in_working_dir(AGENTS_MD),
user_dirs::in_working_dir(RTK_MD),
user_dirs::in_working_dir(CODEX_DIR).join(HOOKS_JSON),
);
// Only the hook path. A symlinked `AGENTS.md` or `RTK.md` may be the user's own
// arrangement, which `atomic_write` preserves deliberately, or may have come with a
// clone -- git stores symlinks -- in which case init appends its `@RTK.md` line to
// whatever the link names, outside the project. That is accepted: the line is inert
// text, where `.codex/hooks.json` is a hook that runs shell commands, and RTK creates
// `.codex` itself rather than following something the user put there.
//
// Its backup sibling is vouched for as well: `fs::copy` follows a symlink at the
// destination, so a planted `hooks.json.bak` carried the existing hooks.json out of
// the project even when `.codex` itself was a real directory.
ensure_inside_project(&paths.2)?;
ensure_inside_project(&backup_path_for(&paths.2))?;
paths
};
run_codex_mode_with_paths(agents_md_path, rtk_md_path, hooks_json_path, global, ctx)
}
/// Move a user-authored `RTK.md` aside before init writes RTK's own over it, returning where
/// it went, or `None` when [`RtkMdScope`] says the file is RTK's to replace in place.
/// `--codex` is the one mode that writes `RTK.md` outside a directory RTK owns, so it is the
/// one mode whose existing file may be the user's.
fn back_up_foreign_rtk_md(
path: &Path,
scope: RtkMdScope,
ctx: InitContext,
) -> Result<Option<PathBuf>> {
if !path.exists() || scope.owns(path) {
return Ok(None);
}
let backup = free_backup_slot(path)?.for_rename();
if ctx.dry_run {
println!(
"[dry-run] would move your RTK.md aside: {} -> {}",
path.display(),
backup.display()
);
return Ok(None);
}
fs::rename(path, &backup).with_context(|| {
format!(
"Failed to move {} aside to {}",
path.display(),
backup.display()
)
})?;
// Now, not in the closing summary: the steps after this one can fail, and the user's
// text has already moved. Where it went is the one thing they must be told either way.
println!("Your existing RTK.md was saved to {}", backup.display());
Ok(Some(backup))
}
pub(super) fn run_codex_mode_with_paths(
agents_md_path: PathBuf,
rtk_md_path: PathBuf,
hooks_json_path: PathBuf,
global: bool,
ctx: InitContext,
) -> Result<()> {
let InitContext { dry_run, .. } = ctx;
if global
&& !dry_run
&& let Some(parent) = agents_md_path.parent()
{
fs::create_dir_all(parent).with_context(|| {
format!(
"Failed to create Codex config directory: {}",
parent.display()
)
})?;
}
// ISSUE #892: In global mode, use absolute path so @RTK.md resolves
// from any CWD (worktrees, nested projects). Codex resolves @ references
// relative to CWD, not the AGENTS.md file location.
let rtk_md_ref = if global {
codex_rtk_md_ref(
rtk_md_path
.parent()
.context("RTK.md path missing parent directory")?,
)
} else {
RTK_MD_REF.to_string()
};
back_up_foreign_rtk_md(&rtk_md_path, RtkMdScope::for_global(global), ctx)?;
write_if_changed(
&rtk_md_path,
&codex_rtk_md_content(ctx.awareness),
RTK_MD,
ctx,
)?;
let added_ref = patch_agents_md(&agents_md_path, &rtk_md_ref, ctx)?;
let hook_added = patch_codex_hooks_json(&hooks_json_path, ctx)?;
if !dry_run {
println!("\nRTK configured for Codex CLI.\n");
println!(" RTK.md: {}", rtk_md_path.display());
println!(
" Hook: {} ({})",
hooks_json_path.display(),
if hook_added {
"registered"
} else {
"already present"
}
);
if added_ref {
println!(" AGENTS.md: {} reference added", rtk_md_ref);
} else {
println!(" AGENTS.md: {} reference already present", rtk_md_ref);
}
if global {
println!(
"\n Codex global instructions path: {}",
agents_md_path.display()
);
} else {
println!(
"\n Codex project instructions path: {}",
agents_md_path.display()
);
}
println!(
"\n Restart Codex. For a project hook, approve it when Codex asks you to trust it."
);
match crate::core::tracking::get_db_path().and_then(|path| codex_tracking_config(&path)) {
Ok(config) => {
println!("\n Optional: if history recording fails with SQLITE_CANTOPEN in the");
println!(
" workspace-write sandbox, grant write access to the tracking directory:"
);
println!("\n{config}");
println!(
" Merge this into Codex config.toml only if you want persistent history."
);
println!(" Keep existing writable_roots; do not add a duplicate table.");
println!(" This grants access to the directory, including SQLite sidecar files.");
println!(" No Codex permission settings have been changed.");
}
Err(error) => eprintln!("rtk: warning: could not prepare tracking guidance: {error:#}"),
}
}
Ok(())
}
fn resolve_codex_dir() -> Result<PathBuf> {
resolve_codex_dir_from(
user_dirs::env_path("CODEX_HOME").map(PathBuf::from),
user_dirs::home(),
)
}
fn resolve_codex_dir_from(
codex_home: Option<PathBuf>,
home_dir: Option<PathBuf>,
) -> Result<PathBuf> {
resolve_config_dir(
codex_home.map(PathBuf::into_os_string),
home_dir,
CODEX_DIR,
"Cannot determine Codex config directory. Set $CODEX_HOME or $HOME.",
)
}
fn codex_rtk_md_ref(codex_dir: &Path) -> String {
format!("@{}", codex_dir.join(RTK_MD).display())
}
pub(super) fn show_codex_config() -> Result<()> {
let codex_dir = resolve_codex_dir()?;
let global_agents_md = codex_dir.join(AGENTS_MD);
let global_rtk_md = codex_dir.join(RTK_MD);
let global_hooks_json = codex_dir.join(HOOKS_JSON);
let global_rtk_md_ref = codex_rtk_md_ref(&codex_dir);
let local_agents_md = user_dirs::in_working_dir(AGENTS_MD);
let local_rtk_md = user_dirs::in_working_dir(RTK_MD);
let local_hooks_json = user_dirs::in_working_dir(CODEX_DIR).join(HOOKS_JSON);
println!("rtk Configuration (Codex CLI):\n");
if global_rtk_md.exists() {
println!("[ok] Global RTK.md: {}", global_rtk_md.display());
} else {
println!("[--] Global RTK.md: not found");
}
print_codex_hook_status("Global", &global_hooks_json)?;
if global_agents_md.exists() {
let content = fs::read_to_string(&global_agents_md).with_context(|| {
format!(
"Failed to read global Codex instructions: {}",
global_agents_md.display()
)
})?;
if has_rtk_reference(&content, &[RTK_MD_REF, global_rtk_md_ref.as_str()]) {
println!("[ok] Global AGENTS.md: RTK.md reference");
} else if content.contains(RTK_BLOCK_START) {
println!("[!!] Global AGENTS.md: old inline RTK block");
} else {
println!("[--] Global AGENTS.md: exists but rtk not configured");
}
} else {
println!("[--] Global AGENTS.md: not found");
}
if local_rtk_md.exists() {
if rtk_md_is_rtk_authored(&local_rtk_md) {
println!("[ok] Local RTK.md: {}", local_rtk_md.display());
} else {
// The project root is not a name RTK owns, and uninstall will say the same.
println!(
"[--] Local RTK.md: {} exists but RTK did not write it",
local_rtk_md.display()
);
}
} else {
println!("[--] Local RTK.md: not found");
}
print_codex_hook_status("Local", &local_hooks_json)?;
if local_agents_md.exists() {
let content = fs::read_to_string(&local_agents_md).with_context(|| {
format!(
"Failed to read local Codex instructions: {}",
local_agents_md.display()
)
})?;
if has_rtk_reference(&content, &[RTK_MD_REF]) {
println!("[ok] Local AGENTS.md: @RTK.md reference");
} else if content.contains(RTK_BLOCK_START) {
println!("[!!] Local AGENTS.md: old inline RTK block");
} else {
println!("[--] Local AGENTS.md: exists but rtk not configured");
}
} else {
println!("[--] Local AGENTS.md: not found");
}
println!("\nUsage:");
println!(" rtk init --codex # Configure local AGENTS.md + RTK.md + hooks.json");
println!(" rtk init -g --codex # Configure global AGENTS.md + RTK.md + hooks.json");
println!(" rtk init --codex --uninstall # Remove local Codex RTK artifacts");
println!(" rtk init -g --codex --uninstall # Remove global Codex RTK artifacts");
Ok(())
}
fn print_codex_hook_status(label: &str, path: &Path) -> Result<()> {
match read_json_file(path) {
Ok(Some(root)) if codex_hook_already_present(&root) => {
println!("[ok] {label} hook: {}", path.display())
}
Ok(Some(_)) => println!("[--] {label} hooks.json exists but RTK hook is not configured"),
Ok(None) => println!("[--] {label} hook: not found"),
Err(error) if error.downcast_ref::<serde_json::Error>().is_some() => {
println!("[!!] {label} hooks.json is invalid JSON")
}
Err(error) => return Err(error),
}
Ok(())
}
fn uninstall_codex_with_paths(
agents_md_path: &Path,
rtk_md_path: &Path,
rtk_md_scope: RtkMdScope,
hooks_json_path: Option<&Path>,
rtk_md_refs: &[&str],
ctx: InitContext,
) -> Result<Vec<String>> {
let InitContext {
verbose, dry_run, ..
} = ctx;
let mut removed = Vec::new();
if let Some(hooks_json_path) = hooks_json_path
&& remove_codex_hook_from_file(hooks_json_path, ctx)?
{
removed.push(format!("hooks.json: removed {} entry", CODEX_HOOK_COMMAND));
}
if rtk_md_path.exists() {
if !rtk_md_scope.owns(rtk_md_path) {
// Uninstall removes RTK's artifacts, not a file that merely shares their name.
println!(
"{}Kept RTK.md: {} (RTK did not write it; remove it yourself if you want it gone)",
if dry_run { "[dry-run] " } else { "" },
rtk_md_path.display()
);
} else if dry_run {
println!("[dry-run] would remove RTK.md: {}", rtk_md_path.display());
removed.push(format!("RTK.md: {}", rtk_md_path.display()));
} else {
// nosemgrep: filesystem-deletion
fs::remove_file(rtk_md_path)
.with_context(|| format!("Failed to remove RTK.md: {}", rtk_md_path.display()))?;
if verbose > 0 {
eprintln!("Removed RTK.md: {}", rtk_md_path.display());
}
removed.push(format!("RTK.md: {}", rtk_md_path.display()));
}
}
if agents_md_path.exists() {
let content = fs::read_to_string(agents_md_path)
.with_context(|| format!("Failed to read AGENTS.md: {}", agents_md_path.display()))?;
let mut working_content = content.clone();
let mut agents_changed = false;
if working_content.contains(RTK_BLOCK_START) {
let (cleaned, did_remove) = remove_rtk_block(&working_content);
if did_remove {
working_content = cleaned;
agents_changed = true;
removed.push("AGENTS.md: removed rtk-instructions block".to_string());
}
}
if agents_changed {
atomic_write(agents_md_path, &working_content).with_context(|| {
format!("Failed to write AGENTS.md: {}", agents_md_path.display())
})?;
}
}
if remove_rtk_reference_from_agents(agents_md_path, rtk_md_refs, ctx)? {
removed.push("AGENTS.md: removed @RTK.md reference".to_string());
}
Ok(removed)
}
fn codex_tracking_config(db_path: &Path) -> Result<String> {
let absolute = std::path::absolute(db_path).context("Failed to resolve RTK database path")?;
let parent = absolute
.parent()
.context("RTK database path has no parent")?;
let directory = fs::canonicalize(parent).unwrap_or_else(|_| parent.to_path_buf());
let directory = directory
.to_str()
.context("RTK database directory is not valid UTF-8")?;
let quoted = toml::Value::String(directory.to_string());
Ok(format!(
"sandbox_mode = \"workspace-write\"\n\n[sandbox_workspace_write]\nwritable_roots = [{quoted}]\n"
))
}
pub(super) fn codex_hook_already_present(root: &serde_json::Value) -> bool {
hook_present(
root,
PRE_TOOL_USE_KEY,
HookEntries::Grouped,
|group| group_covers_tool(group, "Bash"),
|hook| is_command_hook(hook, is_codex_hook_command),
)
}
fn patch_codex_hooks_json(path: &Path, ctx: InitContext) -> Result<bool> {
let InitContext { dry_run, .. } = ctx;
let mut root = read_json_file(path)?.unwrap_or_else(|| serde_json::json!({}));
if codex_hook_already_present(&root) {
return Ok(false);
}
insert_hook_entry(&mut root, CODEX_HOOK_COMMAND)?;
if !dry_run && let Some(parent) = path.parent() {
fs::create_dir_all(parent).with_context(|| {
format!(
"Failed to create Codex config directory: {}",
parent.display()
)
})?;
}
update_json_file(
path,
&root,
ctx,
"Codex hooks.json",
&format!("[dry-run] would patch Codex hooks: {}", path.display()),
true,
Written::Line(format!("Patched Codex hooks: {}", path.display())),
)?;
Ok(true)
}
pub(super) fn remove_codex_hook_from_json(root: &mut serde_json::Value) -> bool {
remove_hook_entries(root, PRE_TOOL_USE_KEY, HookEntries::Grouped, |hook| {
is_command_hook(hook, is_codex_hook_command)
})
}
fn remove_codex_hook_from_file(path: &Path, ctx: InitContext) -> Result<bool> {
let Some(mut root) = read_json_file(path)? else {
return Ok(false);
};
if !remove_codex_hook_from_json(&mut root) {
return Ok(false);
}
update_json_file(
path,
&root,
ctx,
"Codex hooks.json",
&format!(
"[dry-run] would remove RTK hook entry from {}",
path.display()
),
true,
Written::Line(format!("Removed Codex RTK hook: {}", path.display())),
)?;
Ok(true)
}
/// Matches this agent's RTK hook command: `rtk hook codex` from a bare, absolute or
/// Windows `rtk` path, and nothing else.
fn is_codex_hook_command(command: &str) -> bool {
crate::hooks::is_rtk_hook_command(command, "codex")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::test_isolation;
use tempfile::TempDir;
#[test]
fn codex_hook_command_matches_bare_absolute_and_windows_rtk() {
assert!(is_codex_hook_command("rtk hook codex"));
assert!(is_codex_hook_command("/opt/homebrew/bin/rtk hook codex"));
assert!(is_codex_hook_command(
"\"C:\\Program Files\\rtk.exe\" hook codex"
));
}
#[test]
fn codex_hook_command_rejects_other_commands() {
assert!(!is_codex_hook_command("rtk hook claude"));
assert!(!is_codex_hook_command("echo rtk hook codex"));