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
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
mod config;
mod outbox;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use miette::{Context, IntoDiagnostic, Result, bail, miette};
use serde::Serialize;
use tracing::{error, info, warn};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
const DOCKERFILE: &str = include_str!("../assets/Dockerfile");
const RAMEKIN_PROMPT: &str = include_str!("../assets/ramekin-prompt.md");
const VERSION: &str = env!("RAMEKIN_VERSION");
/// Tag of the base image. One image carries both agents — the generated
/// compose config picks the entrypoint per session — so concurrent sessions
/// of different agents build the same idempotent tag.
const BASE_IMAGE: &str = "ramekin-agent";
/// Container path of the rendered per-session system prompt.
const PROMPT_TARGET: &str = "/root/.ramekin/ramekin-prompt.md";
/// The `~/.claude` subdirectories that are caches and scratch, bound to
/// fresh session-scoped dirs so they don't accumulate in the persistent
/// claude state. A best-current-guess denylist; everything else persists
/// (worst case: rot) rather than vanishing (worst case: lost auth).
const CLAUDE_EPHEMERAL: &[&str] = &["statsig", "todos", "shell-snapshots", "debug"];
/// The files in pi's agent dir that are runtime state rather than config,
/// bound individually from `$XDG_DATA_HOME/ramekin/agents/pi/` so they
/// survive the otherwise-ephemeral agent dir: credentials and the model
/// catalog cache. Kept to files pi is known to write — anything else it
/// writes shows up in the teardown report as a candidate for this list.
const PI_PERSISTENT_FILES: &[&str] = &["auth.json", "models-store.json"];
/// Where pi clones the git packages named in its `settings.json`. Persisted
/// because re-cloning every package on every session start is pure latency.
const PI_PACKAGES_DIR: &str = "git";
#[derive(Parser)]
#[command(about = "Run a coding agent (pi or Claude Code) in a containerized environment", version = VERSION)]
struct Cli {
/// Workspace directory to mount (defaults to current directory)
#[arg(global = true, default_value = ".")]
workspace: PathBuf,
/// Profile to run (a named agent + provider bundle)
#[arg(short, long, global = true)]
profile: Option<String>,
#[command(subcommand)]
command: Option<Cmd>,
/// Extra arguments forwarded to the agent inside the container (after --)
#[arg(last = true, global = true)]
agent_args: Vec<String>,
}
#[derive(Subcommand)]
enum Cmd {
/// Start a containerized agent session
Run {
/// Force a full image rebuild (ignores Docker layer cache)
#[arg(long)]
rebuild: bool,
},
/// Show resolved paths and mount configuration
Config,
/// Review config changes proposed by agents
Outbox {
#[command(subcommand)]
command: OutboxCmd,
},
/// Generate shell completions
Completions {
/// Shell to generate completions for
shell: Shell,
},
}
#[derive(Subcommand)]
enum OutboxCmd {
/// List pending proposals across all repos and sessions
List,
/// Diff proposals against the host config they were mounted from
Diff {
/// A single proposal (`<slug>/<session>/<path>`) or session
/// (`<slug>/<session>`); all proposals when omitted
entry: Option<String>,
},
/// Copy a proposal over its host source, after confirmation
Apply {
/// The proposal to apply (`<slug>/<session>/<path>`)
entry: String,
/// Destination for proposals that don't map back to an allowlisted
/// agent-config entry
#[arg(long)]
to: Option<PathBuf>,
},
/// Drop proposals without applying them
Discard {
/// A single proposal (`<slug>/<session>/<path>`) or a whole session
/// (`<slug>/<session>`)
entry: String,
},
}
fn main() -> Result<()> {
miette::set_hook(Box::new(|_| {
Box::new(miette::MietteHandlerOpts::new().build())
}))?;
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
let cli = Cli::parse();
let command = cli.command.unwrap_or(Cmd::Run { rebuild: false });
// Completions doesn't need workspace resolution.
if let Cmd::Completions { shell } = command {
clap_complete::generate(
shell,
&mut Cli::command(),
"ramekin",
&mut std::io::stdout(),
);
return Ok(());
}
// Outbox review is host-global: it spans repos and needs no workspace,
// profile, or agent resolution.
if let Cmd::Outbox { command } = command {
return run_outbox(command);
}
let ramekin = Ramekin::resolve(cli.workspace, cli.profile.as_deref())?;
match command {
Cmd::Run { rebuild } => ramekin.run(rebuild, &cli.agent_args),
Cmd::Config => ramekin.config(),
Cmd::Completions { .. } | Cmd::Outbox { .. } => unreachable!(),
}
}
// ---------------------------------------------------------------------------
// Outbox commands
// ---------------------------------------------------------------------------
fn run_outbox(command: OutboxCmd) -> Result<()> {
let data_home = xdg::BaseDirectories::with_prefix("ramekin")
.get_data_home()
.ok_or_else(|| miette!("could not determine XDG data home"))?;
match command {
OutboxCmd::List => {
let proposals = outbox::scan(&data_home)?;
if proposals.is_empty() {
println!("no pending proposals");
return Ok(());
}
for p in proposals {
match p.host_target() {
Some(target) => println!("{} → {}", p.entry(), target.display()),
None => println!("{} (no mapped target; apply needs --to)", p.entry()),
}
}
}
OutboxCmd::Diff { entry } => {
let proposals = match entry {
Some(entry) => outbox::find(&data_home, &entry)?,
None => outbox::scan(&data_home)?,
};
for p in proposals {
diff_proposal(&p, p.host_target().as_deref())?;
}
}
OutboxCmd::Apply { entry, to } => {
let proposals = outbox::find(&data_home, &entry)?;
let [proposal] = proposals.as_slice() else {
bail!(
"`{entry}` matches {} proposals; apply one file at a time",
proposals.len()
);
};
let target = to.or_else(|| proposal.host_target()).ok_or_else(|| {
miette!(
"`{entry}` doesn't map back to an allowlisted agent-config entry; \
pass an explicit destination with --to"
)
})?;
diff_proposal(proposal, Some(&target))?;
if !confirm(&format!("apply to {}?", target.display()))? {
println!("not applied");
return Ok(());
}
// Write through a symlinked host source (dotfiles), so the
// change lands in the dotfiles working copy, not over the link.
let dest = if target.exists() {
target.canonicalize().into_diagnostic()?
} else {
if let Some(parent) = target.parent() {
fs_err::create_dir_all(parent).into_diagnostic()?;
}
target
};
fs_err::copy(&proposal.file, &dest).into_diagnostic()?;
outbox::remove(&data_home, proposal)?;
println!("applied to {}", dest.display());
}
OutboxCmd::Discard { entry } => {
for proposal in outbox::find(&data_home, &entry)? {
outbox::remove(&data_home, &proposal)?;
println!("discarded {}", proposal.entry());
}
}
}
Ok(())
}
/// Show a proposal's diff against its host source (difftastic when
/// available, `diff -u` otherwise). A missing host source diffs against
/// /dev/null, i.e. shows the whole proposal as new.
fn diff_proposal(proposal: &outbox::Proposal, target: Option<&Path>) -> Result<()> {
println!("--- {}", proposal.entry());
let host: &Path = match target {
Some(t) if t.exists() => t,
_ => Path::new("/dev/null"),
};
let difft = Command::new("difft").arg(host).arg(&proposal.file).status();
if difft.is_err() {
// difftastic not installed; plain diff. Exit code 1 just means the
// files differ.
Command::new("diff")
.arg("-u")
.arg(host)
.arg(&proposal.file)
.status()
.into_diagnostic()
.wrap_err("failed to run diff")?;
}
Ok(())
}
/// Ask the user to confirm on stdin. Anything but `y`/`yes` is a no.
fn confirm(prompt: &str) -> Result<bool> {
print!("{prompt} [y/N] ");
std::io::stdout().flush().into_diagnostic()?;
let mut answer = String::new();
std::io::stdin().read_line(&mut answer).into_diagnostic()?;
let answer = answer.trim().to_ascii_lowercase();
Ok(answer == "y" || answer == "yes")
}
// ---------------------------------------------------------------------------
// AgentState
// ---------------------------------------------------------------------------
/// Host-side persistent state for the active agent, and how it mounts.
///
/// The two agents get opposite persistence policies, chosen by failure mode:
/// pi is ephemeral by default with an allowlist of what persists (its
/// persistent surface is small and stable); claude persists by default with
/// a denylist of known junk (an unclassified new state file should rot, not
/// vanish along with auth or onboarding state).
enum AgentState {
Pi {
/// `$XDG_DATA_HOME/ramekin/agents/pi/`; holds the global state that
/// survives across sessions — `PI_PERSISTENT_FILES` and the package
/// checkouts under `PI_PACKAGES_DIR`.
state_dir: PathBuf,
/// `$XDG_DATA_HOME/ramekin/repos/<slug>/sessions/`.
repo_sessions_dir: PathBuf,
},
Claude {
/// `$XDG_DATA_HOME/ramekin/agents/claude/` → `/root/.claude`.
/// Global across repos so OAuth tokens, account identity, and
/// onboarding state survive switching workspaces.
data_dir: PathBuf,
/// `$XDG_DATA_HOME/ramekin/agents/claude.json` → `/root/.claude.json`
/// (sibling to `~/.claude/`, not inside it). Its cwd-keyed `projects`
/// map partitions per repo via the `/workspace/<slug>` mount, so the
/// file itself stays global.
state_file: PathBuf,
},
}
impl AgentState {
fn for_agent(agent: config::Agent, data_home: &Path, repo_slug: &str) -> Self {
match agent {
config::Agent::Pi => Self::Pi {
state_dir: data_home.join("agents/pi"),
repo_sessions_dir: data_home.join(format!("repos/{repo_slug}/sessions")),
},
config::Agent::Claude => Self::Claude {
data_dir: data_home.join("agents/claude"),
state_file: data_home.join("agents/claude.json"),
},
}
}
/// Materialize persistent host-side state. Idempotent.
fn prepare(&self, xdg: &xdg::BaseDirectories) -> Result<()> {
match self {
Self::Pi {
state_dir,
repo_sessions_dir,
} => {
fs_err::create_dir_all(state_dir).into_diagnostic()?;
fs_err::create_dir_all(repo_sessions_dir).into_diagnostic()?;
fs_err::create_dir_all(state_dir.join(PI_PACKAGES_DIR)).into_diagnostic()?;
// Migrate auth from the pre-redesign location
// (~/.config/ramekin/agent/auth.json) before the init below
// would claim the path with an empty file.
let auth_file = state_dir.join("auth.json");
if !auth_file.exists()
&& let Some(old) = xdg
.get_config_home()
.map(|config_home| config_home.join("agent/auth.json"))
.filter(|p| p.exists())
{
info!(from = %old.display(), to = %auth_file.display(), "migrating pi auth");
fs_err::copy(&old, &auth_file).into_diagnostic()?;
}
// These bind-mount as files, so they have to exist before the
// container starts.
for name in PI_PERSISTENT_FILES {
init_json_file(&state_dir.join(name))?;
}
}
Self::Claude {
data_dir,
state_file,
} => {
fs_err::create_dir_all(data_dir).into_diagnostic()?;
init_json_file(state_file)?;
}
}
Ok(())
}
/// Create the session-scoped directories this agent's mounts need.
fn prepare_session(&self, session_dir: &Path) -> Result<()> {
match self {
Self::Pi { .. } => {
fs_err::create_dir_all(session_dir.join("agent")).into_diagnostic()?;
}
Self::Claude { .. } => {
for name in CLAUDE_EPHEMERAL {
fs_err::create_dir_all(session_dir.join("claude").join(name))
.into_diagnostic()?;
}
}
}
Ok(())
}
/// Agent-state mounts for one session. Read-only host-config mounts
/// from the binary layer sit above these.
fn mounts(&self, session_dir: &Path) -> Vec<config::ResolvedMount> {
let rw = |source: PathBuf, target: String| config::ResolvedMount {
source,
target,
writable: true,
};
match self {
// Fresh empty writable dir per session, with the allowlisted
// persistent pieces bound on top.
Self::Pi {
state_dir,
repo_sessions_dir,
} => {
let mut mounts = vec![rw(session_dir.join("agent"), config::PI_AGENT_DIR.into())];
mounts.extend(PI_PERSISTENT_FILES.iter().map(|name| {
rw(
state_dir.join(name),
format!("{}/{name}", config::PI_AGENT_DIR),
)
}));
mounts.push(rw(
state_dir.join(PI_PACKAGES_DIR),
format!("{}/{PI_PACKAGES_DIR}", config::PI_AGENT_DIR),
));
mounts.push(rw(
repo_sessions_dir.clone(),
format!("{}/sessions", config::PI_AGENT_DIR),
));
mounts
}
// Persistent state dir and state file, with fresh session-scoped
// dirs bound over the known ephemeral subdirs.
Self::Claude {
data_dir,
state_file,
} => {
let mut mounts = vec![
rw(data_dir.clone(), "/root/.claude".into()),
rw(state_file.clone(), "/root/.claude.json".into()),
];
mounts.extend(CLAUDE_EPHEMERAL.iter().map(|name| {
rw(
session_dir.join("claude").join(name),
format!("/root/.claude/{name}"),
)
}));
mounts
}
}
}
/// The session-scoped dir whose discarded writes the teardown report
/// inspects. Only pi has one: its whole agent dir is ephemeral, so a
/// novel write there is a candidate for the persistent allowlist.
/// Claude's session-scoped dirs are the ephemeral denylist — already
/// classified junk, not worth reporting every run.
fn report_dir(&self, session_dir: &Path) -> Option<PathBuf> {
match self {
Self::Pi { .. } => Some(session_dir.join("agent")),
Self::Claude { .. } => None,
}
}
/// Labelled host paths for `ramekin config` output.
fn state_labels(&self) -> Vec<(&'static str, &Path)> {
match self {
Self::Pi {
state_dir,
repo_sessions_dir,
} => vec![("pi state", state_dir), ("sessions", repo_sessions_dir)],
Self::Claude {
data_dir,
state_file,
} => vec![("claude ", data_dir), ("state ", state_file)],
}
}
}
/// Create a file containing `{}\n` unless it already exists. `create_new`
/// is race-safe: two concurrent first runs can't clobber each other, and
/// losing the race is fine — the file exists.
fn init_json_file(file: &Path) -> Result<()> {
match fs_err::OpenOptions::new()
.write(true)
.create_new(true)
.open(file)
{
Ok(mut f) => f.write_all(b"{}\n").into_diagnostic()?,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e).into_diagnostic(),
}
Ok(())
}
// ---------------------------------------------------------------------------
// Ramekin
// ---------------------------------------------------------------------------
struct Ramekin {
workspace: PathBuf,
/// Container path of the workspace mount: `/workspace/<slug>`. Per-repo
/// so anything the agent keys by cwd (pi's session grouping, claude's
/// `projects` map and transcripts) gets a distinct path per repo instead
/// of every repo looking like the same `/workspace` project.
workspace_target: String,
repo_slug: String,
xdg: xdg::BaseDirectories,
data_home: PathBuf,
cache_dir: PathBuf,
custom_dockerfile: Option<PathBuf>,
config: config::ScopedConfig,
agent_state: AgentState,
}
impl Ramekin {
/// Resolve all paths and load config layers. Side-effect free: nothing
/// is created or written until `run` calls `prepare`, so `ramekin
/// config` can inspect state without mutating it.
fn resolve(workspace_arg: PathBuf, cli_profile: Option<&str>) -> Result<Self> {
let workspace = workspace_arg
.canonicalize()
.into_diagnostic()
.wrap_err_with(|| {
format!("workspace path does not exist: {}", workspace_arg.display())
})?;
let xdg = xdg::BaseDirectories::with_prefix("ramekin");
let data_home = xdg
.get_data_home()
.ok_or_else(|| miette!("could not determine XDG data home"))?;
let cache_dir = xdg
.get_cache_home()
.ok_or_else(|| miette!("could not determine XDG cache home"))?;
let repo_slug = repo_slug(&workspace);
let workspace_target = format!("/workspace/{repo_slug}");
let custom_dockerfile_path = workspace.join(".ramekin/Dockerfile");
let custom_dockerfile = custom_dockerfile_path
.is_file()
.then_some(custom_dockerfile_path);
let config = config::ScopedConfig::load(&workspace, &workspace_target, cli_profile)
.wrap_err("failed to load ramekin configuration")?;
let agent_state = AgentState::for_agent(config.agent(), &data_home, &repo_slug);
Ok(Self {
workspace,
workspace_target,
repo_slug,
xdg,
data_home,
cache_dir,
custom_dockerfile,
config,
agent_state,
})
}
/// Host directory backing this repo's caches, one subdirectory per
/// configured `cache`.
fn repo_caches_dir(&self) -> PathBuf {
self.data_home
.join(format!("repos/{}/caches", self.repo_slug))
}
/// Mounts for the configured caches. Forced like the session mounts: the
/// container path comes from config, the host path never does.
fn cache_mounts(&self) -> Result<Vec<config::ResolvedMount>> {
let base = self.repo_caches_dir();
Ok(self
.config
.merged_caches()?
.into_iter()
.map(|sv| config::ResolvedMount {
source: base.join(&sv.value.name),
target: sv.value.target.clone(),
writable: true,
})
.collect())
}
/// Session plumbing mounts shared by both agents: the rendered prompt,
/// the outbox, and the workspace.
fn session_mounts(&self, session_dir: &Path, outbox_dir: &Path) -> Vec<config::ResolvedMount> {
let mut mounts = self.agent_state.mounts(session_dir);
mounts.push(config::ResolvedMount {
source: session_dir.join("ramekin-prompt.md"),
target: PROMPT_TARGET.into(),
writable: false,
});
mounts.push(config::ResolvedMount {
source: outbox_dir.to_path_buf(),
target: outbox::OUTBOX_TARGET.into(),
writable: true,
});
mounts.push(config::ResolvedMount {
source: self.workspace.clone(),
target: self.workspace_target.clone(),
writable: true,
});
mounts
}
/// Host path a mask at `target` hides, when ramekin can name one: a
/// path inside the workspace maps back to the host repo, and anywhere
/// else the mount a lower layer declared is what the mask covers.
/// Neither exists for a path the image alone supplies.
fn hidden_host_path(&self, target: &str) -> Option<PathBuf> {
if let Some(rel) = target
.strip_prefix(&self.workspace_target)
.and_then(|rest| rest.strip_prefix('/'))
{
return Some(self.workspace.join(rel));
}
self.config.overridden_source(target).map(Path::to_path_buf)
}
/// Merge config mounts with the forced ones (session plumbing and
/// caches), ordered lexicographically by target so parents precede
/// children.
fn final_mounts<'a>(
&'a self,
forced: &'a [config::ResolvedMount],
) -> Vec<&'a config::ResolvedMount> {
let mut by_target: BTreeMap<&str, &config::ResolvedMount> = self
.config
.merged_mounts()
.into_iter()
.map(|sv| (sv.value.target.as_str(), sv.value))
.collect();
for mount in forced {
by_target.insert(mount.target.as_str(), mount);
}
by_target.into_values().collect()
}
fn config(&self) -> Result<()> {
println!("Workspace");
println!(" {} → {}", self.workspace.display(), self.workspace_target);
println!();
println!("Profile");
let selected_by = self
.config
.selected_by
.map_or("-p".to_string(), |scope| scope.to_string());
println!(
" {} (agent {}, selected by {selected_by})",
self.config.profile.name,
self.config.agent(),
);
for (name, sv) in &self.config.profiles {
let marker = if *name == self.config.profile.name {
"*"
} else {
" "
};
println!(" {marker} {name} ({}, agent {})", sv.scope, sv.value.agent);
}
println!();
println!("Ramekin directories");
for (label, path) in self.agent_state.state_labels() {
println!(" {label} {}", path.display());
}
println!(" cache {}", self.cache_dir.display());
let merged_mounts = self.config.merged_mounts();
let merged_env = self.config.merged_env();
let scope_label = |scope: config::Scope| -> String {
if scope == config::Scope::Profile {
return format!("profile ({})", self.config.profile.name);
}
self.config
.layers
.iter()
.find(|l| l.scope == scope)
.and_then(|l| l.path.as_ref())
.map(|p| format!("{scope} ({})", p.display()))
.unwrap_or_else(|| scope.to_string())
};
// Mounts
if !merged_mounts.is_empty() {
println!();
println!("Mounts");
let scopes: BTreeSet<_> = merged_mounts.iter().map(|sv| sv.scope).collect();
// Masks over a directory bind a session-scoped empty dir, so show
// that rather than the /dev/null the config file spells.
let empty_placeholder = self.cache_dir.join("sessions/<session>/empty");
for scope in scopes {
println!(" {}", scope_label(scope));
for sv in merged_mounts.iter().filter(|sv| sv.scope == scope) {
let hides_a_dir = sv.value.is_mask()
&& self
.hidden_host_path(&sv.value.target)
.is_some_and(|path| path.is_dir());
let source = if hides_a_dir {
&empty_placeholder
} else {
&sv.value.source
};
println!(" {} → {}", source.display(), sv.value.display_target());
}
}
}
// Session mounts (sources materialize per run; shown with a placeholder)
let placeholder = self.cache_dir.join("sessions/<session>");
let outbox_placeholder = self
.data_home
.join(format!("repos/{}/outbox/<session>", self.repo_slug));
println!();
println!("Session mounts");
for mount in self.session_mounts(&placeholder, &outbox_placeholder) {
println!(
" {} → {}",
mount.source.display(),
mount.display_target()
);
}
// Caches
let caches = self.config.merged_caches()?;
if !caches.is_empty() {
println!();
println!("Caches");
let base = self.repo_caches_dir();
let scopes: BTreeSet<_> = caches.iter().map(|sv| sv.scope).collect();
for scope in scopes {
println!(" {}", scope_label(scope));
for sv in caches.iter().filter(|sv| sv.scope == scope) {
println!(
" {} → {}",
base.join(&sv.value.name).display(),
sv.value.target
);
}
}
}
// Environment
if !merged_env.is_empty() {
println!();
println!("Environment");
let scopes: BTreeSet<_> = merged_env.iter().map(|sv| sv.scope).collect();
for scope in scopes {
println!(" {}", scope_label(scope));
for sv in merged_env.iter().filter(|sv| sv.scope == scope) {
match &sv.value.value {
Some(value) => println!(" {}={value}", sv.value.name),
None => println!(" {} (passed through from host)", sv.value.name),
}
}
}
}
println!();
println!("Dockerfile");
match &self.custom_dockerfile {
Some(path) => println!(" ✓ {} (FROM {BASE_IMAGE})", path.display()),
None => {
println!(" embedded ({BASE_IMAGE})");
println!(
" ✗ {} (not found)",
self.workspace.join(".ramekin/Dockerfile").display()
);
}
}
Ok(())
}
fn run(&self, rebuild: bool, agent_args: &[String]) -> Result<()> {
let agent = self.config.agent();
info!(
profile = %self.config.profile.name,
agent = %agent,
workspace = %self.workspace.display(),
target = %self.workspace_target,
"starting agent"
);
fs_err::create_dir_all(&self.cache_dir).into_diagnostic()?;
self.agent_state.prepare(&self.xdg)?;
// Write the embedded Dockerfile to the cache directory
let base_dockerfile = self.cache_dir.join("Dockerfile");
fs_err::write(&base_dockerfile, DOCKERFILE).into_diagnostic()?;
// The base image fetches release metadata from the GitHub API at
// build time. Pass a host token so the build doesn't get rate-limited.
let gh_token = host_github_token();
if gh_token.is_some() {
info!("authenticated GitHub API for image build");
}
if rebuild {
info!("rebuilding base image (no cache)");
} else {
info!("building base image");
}
let mut build_cmd = Command::new("docker");
build_cmd
.args(["build", "-t", BASE_IMAGE, "-f"])
.arg(&base_dockerfile);
if let Some(token) = &gh_token {
build_cmd
.env("RAMEKIN_GH_TOKEN", token)
.args(["--secret", "id=github-token,env=RAMEKIN_GH_TOKEN"]);
}
if rebuild {
build_cmd.args(["--no-cache", "--pull"]);
}
build_cmd.arg(&self.cache_dir);
let status = build_cmd
.status()
.into_diagnostic()
.wrap_err("failed to build base image")?;
if !status.success() {
bail!("base image build failed ({})", status);
}
// Determine the final dockerfile, build context, and image tag. A
// custom Dockerfile gets a repo-specific tag so it doesn't collide
// with the base image it builds `FROM`; sharing the tag would make
// `docker compose up` reuse the base instead of the project layer.
let (dockerfile, build_context, image) = match &self.custom_dockerfile {
Some(custom) => {
info!("building project image from .ramekin/Dockerfile");
(
custom.clone(),
self.workspace.clone(),
project_image_name(&self.repo_slug),
)
}
None => (
base_dockerfile,
self.cache_dir.clone(),
BASE_IMAGE.to_string(),
),
};
// Session-scoped: compose file, rendered prompt, and fresh agent
// dirs, all under a random session id so concurrent runs don't
// interfere.
let session_id = session_id();
let session_dir = self
.xdg
.create_cache_directory(format!("sessions/{session_id}"))
.into_diagnostic()
.wrap_err("failed to create session directory")?;
self.agent_state.prepare_session(&session_dir)?;
let prompt = RAMEKIN_PROMPT.replace("{{WORKSPACE_PATH}}", &self.workspace_target);
fs_err::write(session_dir.join("ramekin-prompt.md"), prompt).into_diagnostic()?;
let outbox_dir =
outbox::create_session(&self.data_home, &self.repo_slug, &session_id, agent)
.wrap_err("failed to create session outbox")?;
// Caches are created rather than skipped when absent: a cache that
// silently didn't mount would look like nothing but slow builds.
let mut forced_mounts = self.session_mounts(&session_dir, &outbox_dir);
for mount in self.cache_mounts()? {
fs_err::create_dir_all(&mount.source).into_diagnostic()?;
forced_mounts.push(mount);
}
// A mask over a directory needs an empty directory to bind, not
// /dev/null; the dir is session-scoped so nothing can write into it
// and have it outlive the run.
let empty_dir = session_dir.join("empty");
fs_err::create_dir_all(&empty_dir).into_diagnostic()?;
let emitted = elide_directory_masks(&self.final_mounts(&forced_mounts), &empty_dir, |t| {
self.hidden_host_path(t)
});
let all_mounts: Vec<&config::ResolvedMount> = emitted.iter().collect();
let env_vars = self.config.merged_env();
let compose = generate_compose(ComposeParams {
dockerfile: &dockerfile,
build_context: &build_context,
mounts: &all_mounts,
env_vars: &env_vars,
image: &image,
working_dir: &self.workspace_target,
// The image has no ENTRYPOINT; the compose config picks the agent.
entrypoint: agent.name(),
prompt_flag: match agent {
// Pi's --append-system-prompt accepts a file path; Claude's
// takes a literal string, so it needs the -file variant to
// read the file rather than append the literal path.
config::Agent::Pi => "--append-system-prompt",
config::Agent::Claude => "--append-system-prompt-file",
},
profile_args: &self.config.profile.args,
agent_args,
});
let compose_file = session_dir.join("compose.yml");
fs_err::write(&compose_file, &compose).into_diagnostic()?;
// Mount targets inside the agent dir show up on the host as empty
// artifacts Docker creates to serve as mount points; the teardown
// report has to know to skip them.
let agent_dir_mountpoints: BTreeSet<PathBuf> = all_mounts
.iter()
.filter_map(|m| {
m.target
.strip_prefix(&format!("{}/", config::PI_AGENT_DIR))
.map(PathBuf::from)
})
.collect();
let project_name = format!("ramekin-{session_id}");
let docker_compose = |args: &[&str]| -> Result<Command> {
let mut cmd = Command::new("docker");
cmd.args(["compose", "-f"])
.arg(&compose_file)
.args(["--project-name", &project_name])
.args(args);
Ok(cmd)
};
// Build the project image when a custom Dockerfile is present. `up`
// alone only builds when the image is missing, which would serve a stale
// layer after the Dockerfile changes. Layer caching keeps this cheap
// unless `--rebuild` forces a clean build.
if self.custom_dockerfile.is_some() || rebuild {
let mut args = vec!["build"];
if rebuild {
args.push("--no-cache");
}
let status = docker_compose(&args)?
.status()
.into_diagnostic()
.wrap_err("failed to run docker compose build")?;
if !status.success() {
bail!("docker compose build failed ({})", status);
}
}
let status = docker_compose(&["up", "-d"])?
.status()
.into_diagnostic()
.wrap_err("failed to run docker compose up")?;
if !status.success() {
bail!("docker compose up failed ({})", status);
}
let status = docker_compose(&["attach", "agent"])?
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
.into_diagnostic()
.wrap_err("failed to attach to agent")?;
// Always tear down, regardless of attach exit status
let down_status = docker_compose(&["down"])?
.status()
.into_diagnostic()
.wrap_err("failed to run docker compose down")?;
if !down_status.success() {
error!("docker compose down failed ({})", down_status);
}
// Anything the agent wrote to its session-scoped dir is about to be
// discarded; log it so a path that deserves persistence gets noticed
// instead of silently vanishing.
if let Some(report_dir) = self.agent_state.report_dir(&session_dir) {
match discarded_writes(&report_dir, &agent_dir_mountpoints) {
Ok(paths) => {
for path in paths {
warn!(path = %path.display(), "discarding session-scoped agent write");
}
}
Err(e) => error!("failed to inspect session agent dir: {e}"),
}
}
// A non-empty outbox survives teardown as pending proposals.
match outbox::finish_session(&self.data_home, &self.repo_slug, &session_id) {
Ok(0) => {}
Ok(pending) => {
info!("{pending} config proposal(s) pending — review with `ramekin outbox list`");
}
Err(e) => error!("failed to finalize session outbox: {e}"),
}
if let Err(e) = fs_err::remove_dir_all(&session_dir) {
error!("failed to clean up session dir: {e}");
}
if !status.success() {
bail!("agent exited with error ({})", status);
}
Ok(())
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/// Collect every file the agent wrote into its session-scoped agent dir.
///
/// The dir starts empty, so anything found here (other than the empty
/// artifacts Docker created as mount points, listed in `mountpoints` as
/// agent-dir-relative paths) is durable-looking state the agent produced
/// that ramekin is about to throw away. Logging these is the learning loop
/// for promoting a path into the persistent set — or confirming it's junk.
fn discarded_writes(agent_dir: &Path, mountpoints: &BTreeSet<PathBuf>) -> Result<Vec<PathBuf>> {
fn walk(
dir: &Path,
root: &Path,
skip: &BTreeSet<PathBuf>,
found: &mut Vec<PathBuf>,
) -> Result<()> {
for entry in fs_err::read_dir(dir).into_diagnostic()? {
let entry = entry.into_diagnostic()?;
let path = entry.path();
let rel = path
.strip_prefix(root)
.expect("walk stays under root")
.to_path_buf();
// A mount point (and everything a mount put under it) is not an
// agent write; skip the whole subtree.
if skip.contains(&rel) {
continue;
}
if entry.file_type().into_diagnostic()?.is_dir() {
walk(&path, root, skip, found)?;
} else {
found.push(rel);
}
}
Ok(())
}
let mut found = Vec::new();
walk(agent_dir, agent_dir, mountpoints, &mut found)?;
found.sort();
Ok(found)
}
/// Look up a GitHub token from the host environment for build-time API calls.
///
/// Tries env vars first, then falls back to `gh auth token`. Returns `None`
/// if no token is available; the build degrades to anonymous API access.
fn host_github_token() -> Option<String> {
for var in ["RAMEKIN_GH_TOKEN", "GITHUB_TOKEN", "GH_TOKEN"] {
if let Ok(v) = std::env::var(var)
&& !v.is_empty()
{
return Some(v);
}
}
let output = Command::new("gh").args(["auth", "token"]).output().ok()?;
if !output.status.success() {
return None;
}
let token = String::from_utf8(output.stdout).ok()?.trim().to_string();
(!token.is_empty()).then_some(token)
}
/// Generate a random session ID for scoping the compose project and cache dir.
fn session_id() -> String {
format!("{:08x}", fastrand::u32(..))
}
/// FNV-1a 64-bit hash. Deterministic across Rust toolchain versions, unlike DefaultHasher.
fn fnv1a_64(bytes: &[u8]) -> u64 {
const BASIS: u64 = 0xcbf29ce484222325;
const PRIME: u64 = 0x00000100000001B3;
let mut hash = BASIS;
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(PRIME);
}
hash
}
/// Create a slug for a workspace path: `<dirname>-<hash>`.
fn repo_slug(workspace: &Path) -> String {
let name = workspace
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "root".into());
let hash = fnv1a_64(workspace.as_os_str().as_encoded_bytes());
format!("{name}-{hash:08x}")
}
/// Docker image tag for a workspace's project image, built from its
/// `.ramekin/Dockerfile`. Kept distinct from the base tag so `docker compose
/// up` builds the project layer instead of reusing the base image that
/// shares the tag. Lowercased because Docker repository names must be
/// lowercase.
fn project_image_name(repo_slug: &str) -> String {
format!("ramekin-{repo_slug}").to_lowercase()
}
#[derive(Serialize)]
struct ComposeConfig {
services: Services,
}
#[derive(Serialize)]
struct Services {
agent: AgentService,
}
#[derive(Serialize)]
struct AgentService {
build: BuildConfig,
image: String,
stdin_open: bool,
tty: bool,
working_dir: String,
entrypoint: Vec<String>,
environment: Vec<String>,
volumes: Vec<VolumeBind>,
command: Vec<String>,
}
#[derive(Serialize)]
struct BuildConfig {
context: String,
dockerfile: String,
}
/// Long-form compose bind mount. Avoids the `source:target[:ro]` short form,
/// which can't represent paths containing colons.
#[derive(Serialize)]
struct VolumeBind {
#[serde(rename = "type")]
kind: &'static str,
source: String,
target: String,
read_only: bool,
}
/// Inputs for [`generate_compose`], grouped so the container command,
/// mounts, environment, and build context travel together instead of as a
/// long positional argument list.
struct ComposeParams<'a> {
dockerfile: &'a Path,
build_context: &'a Path,
mounts: &'a [&'a config::ResolvedMount],
env_vars: &'a [config::ScopedValue<&'a config::EnvVar>],
image: &'a str,
working_dir: &'a str,
/// The agent binary to run — the image carries both, with no ENTRYPOINT
/// of its own.
entrypoint: &'a str,
prompt_flag: &'a str,
/// CLI flags the active profile pins for the agent binary. Placed before
/// the per-run trailing args so a `ramekin -- ...` flag still wins.
profile_args: &'a [String],
agent_args: &'a [String],
}
/// Bind an empty directory for masks that hide a directory.
///
/// `/dev/null` binds over a file and blanks it, but over a directory Docker
/// refuses the mount and the run dies at startup. An empty directory elides
/// the contents while keeping the target the shape callers expect, so
/// listing it succeeds and comes back empty.
fn elide_directory_masks(
mounts: &[&config::ResolvedMount],
empty_dir: &Path,
hidden_host_path: impl Fn(&str) -> Option<PathBuf>,
) -> Vec<config::ResolvedMount> {
mounts
.iter()
.map(|mount| {
let mut mount = (*mount).clone();
let hides_a_dir = mount.is_mask()
&& hidden_host_path(&mount.target).is_some_and(|path| path.is_dir());
if hides_a_dir {
mount.source = empty_dir.to_path_buf();
}
mount
})
.collect()
}
/// Generate a Docker Compose config with all volume mounts.
fn generate_compose(params: ComposeParams) -> String {
let ComposeParams {
dockerfile,
build_context,
mounts,
env_vars,
image,
working_dir,
entrypoint,
prompt_flag,
profile_args,
agent_args,
} = params;
let volumes: Vec<VolumeBind> = mounts
.iter()
.map(|m| VolumeBind {
kind: "bind",
source: m.source.display().to_string(),
target: m.target.clone(),
read_only: !m.writable,
})
.collect();
// A bare name (no value) is compose's passthrough form: the variable is
// forwarded from the environment ramekin runs in, and stays unset in the
// container when the host doesn't have it either.
let environment: Vec<String> = env_vars
.iter()
.map(|sv| match &sv.value.value {
Some(value) => format!("{}={value}", sv.value.name),
None => sv.value.name.clone(),
})
.collect();
// Always pass the prompt flag for the ramekin container context.
// Profile args come next; user-supplied CLI args come last so they win.
let command: Vec<String> = [prompt_flag.to_string(), PROMPT_TARGET.to_string()]
.into_iter()
.chain(profile_args.iter().cloned())
.chain(agent_args.iter().cloned())
.collect();
let config = ComposeConfig {
services: Services {
agent: AgentService {
build: BuildConfig {
context: build_context.display().to_string(),
dockerfile: dockerfile.display().to_string(),
},
image: image.to_string(),
stdin_open: true,
tty: true,
working_dir: working_dir.to_string(),
entrypoint: vec![entrypoint.to_string()],
environment,
volumes,
command,
},
},
};
serde_yaml::to_string(&config).expect("failed to serialize compose config")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_image_name_is_repo_specific_and_distinct_from_base() {
let name = project_image_name("lit-rs-deadbeef");
// Must not collide with the base image tag, or `docker compose up`
// reuses the base instead of building the project Dockerfile.
assert_ne!(name, BASE_IMAGE);
// Docker repository names must be lowercase.
assert_eq!(name, name.to_lowercase(), "got: {name}");
}
fn compose_params<'a>(
mounts: &'a [&'a config::ResolvedMount],
env_vars: &'a [config::ScopedValue<&'a config::EnvVar>],
) -> ComposeParams<'a> {
ComposeParams {
dockerfile: Path::new("/cache/Dockerfile"),
build_context: Path::new("/cache"),
mounts,
env_vars,
image: BASE_IMAGE,
working_dir: "/workspace/x-1",
entrypoint: "pi",
prompt_flag: "--append-system-prompt",
profile_args: &[],
agent_args: &[],
}
}
#[test]
fn generate_compose_places_profile_args_before_cli_args() {
let profile_args = vec!["--provider".to_string(), "amazon-bedrock".to_string()];
let cli_args = vec!["--model".to_string(), "override".to_string()];
let mut params = compose_params(&[], &[]);
params.profile_args = &profile_args;
params.agent_args = &cli_args;
let yaml = generate_compose(params);
let prompt = yaml.find(PROMPT_TARGET).expect("prompt target missing");
let provider = yaml.find("amazon-bedrock").expect("profile arg missing");
let model = yaml.find("override").expect("cli arg missing");
assert!(
prompt < provider && provider < model,
"expected prompt < profile arg < cli arg, got {yaml}"
);
}
#[test]
fn directory_mask_binds_an_empty_dir() {
let workspace = tempfile::tempdir().unwrap();
fs_err::create_dir_all(workspace.path().join("node_modules")).unwrap();
let mask = config::ResolvedMount {
source: PathBuf::from(config::MASK_SOURCE),
target: "/workspace/slug/node_modules".to_string(),
writable: false,
};
let emitted = elide_directory_masks(&[&mask], Path::new("/session/empty"), |_| {
Some(workspace.path().join("node_modules"))
});
assert_eq!(emitted[0].source, PathBuf::from("/session/empty"));
assert_eq!(emitted[0].target, mask.target);
}
#[test]
fn file_mask_still_binds_dev_null() {
let workspace = tempfile::tempdir().unwrap();
fs_err::write(workspace.path().join(".envrc"), "export FOO=1").unwrap();
let mask = config::ResolvedMount {
source: PathBuf::from(config::MASK_SOURCE),
target: "/workspace/slug/.envrc".to_string(),
writable: false,
};
let emitted = elide_directory_masks(&[&mask], Path::new("/session/empty"), |_| {
Some(workspace.path().join(".envrc"))
});
assert_eq!(emitted[0].source, PathBuf::from(config::MASK_SOURCE));
}
#[test]
fn a_mask_over_nothing_nameable_binds_dev_null() {
let mask = config::ResolvedMount {
source: PathBuf::from(config::MASK_SOURCE),
target: "/root/.config/nowhere".to_string(),
writable: false,
};
let emitted = elide_directory_masks(&[&mask], Path::new("/session/empty"), |_| None);
assert_eq!(emitted[0].source, PathBuf::from(config::MASK_SOURCE));
}
#[test]
fn generate_compose_long_form_binds() {
let mount = config::ResolvedMount {
source: PathBuf::from("/host/.config/git"),
target: "/root/.config/git".into(),
writable: false,
};
let yaml = generate_compose(compose_params(&[&mount], &[]));
assert!(yaml.contains("type: bind"), "{yaml}");
assert!(yaml.contains("source: /host/.config/git"), "{yaml}");
assert!(yaml.contains("target: /root/.config/git"), "{yaml}");
assert!(yaml.contains("read_only: true"), "{yaml}");
assert!(yaml.contains("working_dir: /workspace/x-1"), "{yaml}");
}
#[test]
fn generate_compose_env_passthrough_is_a_bare_name() {
let with_value = config::EnvVar {
name: "FOO".into(),
value: Some("bar".into()),
};
let passthrough = config::EnvVar {
name: "GITHUB_TOKEN".into(),
value: None,
};
let env = [
config::ScopedValue {
scope: config::Scope::User,
value: &with_value,
},
config::ScopedValue {
scope: config::Scope::Profile,
value: &passthrough,
},
];
let yaml = generate_compose(compose_params(&[], &env));
assert!(yaml.contains("- FOO=bar"), "{yaml}");
assert!(yaml.contains("- GITHUB_TOKEN\n"), "{yaml}");
assert!(!yaml.contains("GITHUB_TOKEN="), "{yaml}");
}
#[test]
fn generate_compose_sets_the_agent_entrypoint() {
let mut params = compose_params(&[], &[]);
params.entrypoint = "claude";
params.prompt_flag = "--append-system-prompt-file";
let yaml = generate_compose(params);
// One image carries both agents; the compose entrypoint picks one.
assert!(yaml.contains("entrypoint:\n - claude"), "{yaml}");
// Claude needs the -file variant: the plain flag would append the
// literal path string instead of the prompt contents.
assert!(yaml.contains("--append-system-prompt-file"), "{yaml}");
assert!(yaml.contains(PROMPT_TARGET), "{yaml}");
}
#[test]
fn discarded_writes_skips_mountpoint_artifacts() {
let dir = tempfile::tempdir().unwrap();
// Mount point artifacts docker would leave behind.
fs_err::write(dir.path().join("auth.json"), "").unwrap();
fs_err::create_dir_all(dir.path().join("sessions")).unwrap();
// Genuine agent writes.
fs_err::write(dir.path().join("scratch.txt"), "x").unwrap();
fs_err::create_dir_all(dir.path().join("cache")).unwrap();
fs_err::write(dir.path().join("cache/blob"), "y").unwrap();
let mountpoints: BTreeSet<PathBuf> =
[PathBuf::from("auth.json"), PathBuf::from("sessions")]
.into_iter()
.collect();
let found = discarded_writes(dir.path(), &mountpoints).unwrap();
assert_eq!(
found,
vec![PathBuf::from("cache/blob"), PathBuf::from("scratch.txt")]
);
}
#[test]
fn discarded_writes_empty_dir_reports_nothing() {
let dir = tempfile::tempdir().unwrap();
let found = discarded_writes(dir.path(), &BTreeSet::new()).unwrap();
assert!(found.is_empty());
}
#[test]
fn claude_state_mounts_partition_persistent_and_ephemeral() {
let state = AgentState::Claude {
data_dir: PathBuf::from("/data/agents/claude"),
state_file: PathBuf::from("/data/agents/claude.json"),
};
let mounts = state.mounts(Path::new("/cache/sessions/abc"));
let target = |t: &str| mounts.iter().find(|m| m.target == t);
let data = target("/root/.claude").expect("claude data dir mount");
assert_eq!(data.source, PathBuf::from("/data/agents/claude"));
assert!(data.writable);
let state_file = target("/root/.claude.json").expect("claude state file mount");
assert_eq!(state_file.source, PathBuf::from("/data/agents/claude.json"));
// Ephemeral denylist dirs bind session-scoped dirs over the junk.
for name in CLAUDE_EPHEMERAL {
let m = target(&format!("/root/.claude/{name}"))
.unwrap_or_else(|| panic!("missing ephemeral mount for {name}"));
assert_eq!(m.source, Path::new("/cache/sessions/abc/claude").join(name));
assert!(m.writable);
}
}
#[test]
fn pi_state_mounts_allowlist_persistence() {
let state = AgentState::Pi {
state_dir: PathBuf::from("/data/agents/pi"),
repo_sessions_dir: PathBuf::from("/data/repos/x-1/sessions"),
};
let mounts = state.mounts(Path::new("/cache/sessions/abc"));
let target = |t: &str| mounts.iter().find(|m| m.target == t);
let agent_dir = target("/root/.pi/agent").expect("session agent dir mount");
assert_eq!(agent_dir.source, PathBuf::from("/cache/sessions/abc/agent"));
for name in PI_PERSISTENT_FILES {
let m = target(&format!("/root/.pi/agent/{name}"))
.unwrap_or_else(|| panic!("{name} mount"));
assert_eq!(m.source, PathBuf::from(format!("/data/agents/pi/{name}")));
assert!(m.writable);
}
let packages = target("/root/.pi/agent/git").expect("packages mount");
assert_eq!(packages.source, PathBuf::from("/data/agents/pi/git"));
let sessions = target("/root/.pi/agent/sessions").expect("sessions mount");
assert_eq!(sessions.source, PathBuf::from("/data/repos/x-1/sessions"));
}
}