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
//! `MemoryPrefix` — assembled tier blocks + splice rendering.
use std::fmt::Write as _;
use std::path::PathBuf;
/// Where a [`TierFile`] originated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TierFileSource {
/// Operator-global CLAUDE.md.
Global,
/// Discovered via the project-tier ancestor walk.
Walk,
/// Inlined via an `@`-import inside another tier file.
Import,
/// Added on-demand after the model touched a file in this subtree.
Nested,
/// Path-glob-matched rule from `.caliban/rules/`.
Rule,
/// Per-workspace auto-memory `MEMORY.md`.
Auto,
/// Legacy single-file project tier (regression escape).
LegacyProject,
}
impl TierFileSource {
/// Splice attribute value.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Global => "global",
Self::Walk => "walk",
Self::Import => "import",
Self::Nested => "nested",
Self::Rule => "rule",
Self::Auto => "auto",
Self::LegacyProject => "legacy",
}
}
}
/// One loaded tier file with provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TierFile {
/// Absolute path of the file on disk.
pub path: PathBuf,
/// File contents (UTF-8 lossy; may have a truncation suffix when over-budget).
pub body: String,
/// Estimated tokens (`body.len() / 4`).
pub estimated_tokens: usize,
/// Bytes shed by budget truncation; `0` when the file fit.
pub truncated_bytes: usize,
}
/// Tier identifiers used by the splice output and the `/memory` summary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TierKind {
/// Operator-global `CLAUDE.md` (XDG config).
Global,
/// Project `CLAUDE.md` at the workspace root.
Project,
/// Per-workspace auto-memory `MEMORY.md`.
Auto,
}
impl TierKind {
/// XML tag name written into the system-prompt prefix.
#[must_use]
pub const fn tag(self) -> &'static str {
match self {
Self::Global => "global-claude-md",
Self::Project => "project-claude-md",
Self::Auto => "auto-memory-index",
}
}
/// Short label used by `/memory` summary lines.
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Global => "global",
Self::Project => "project",
Self::Auto => "auto",
}
}
}
/// Rich project tier with all sub-collections preserved. Useful for the
/// `/memory` overlay and the ancestry-addendum subsystem.
#[derive(Debug, Clone, Default)]
pub struct ProjectTier {
/// Files discovered by the ancestor walk (broad → narrow order).
pub base_files: Vec<TierFile>,
/// Imports resolved from any walk / rule / nested file — surfaced for
/// provenance display; the bodies are already inlined in their owning
/// tier file via `<!-- imported from … -->` markers.
pub imports: Vec<TierFile>,
/// Path-glob-matched rules (loaded lazily on first matching path touch).
pub active_rules: Vec<TierFile>,
/// Files added on-demand mid-session by `Read`/`Edit`/`Glob` hooks.
pub nested: Vec<TierFile>,
}
impl ProjectTier {
/// Total estimated tokens across every collection.
#[must_use]
pub fn estimated_tokens(&self) -> usize {
self.base_files
.iter()
.map(|t| t.estimated_tokens)
.sum::<usize>()
+ self
.imports
.iter()
.map(|t| t.estimated_tokens)
.sum::<usize>()
+ self
.active_rules
.iter()
.map(|t| t.estimated_tokens)
.sum::<usize>()
+ self
.nested
.iter()
.map(|t| t.estimated_tokens)
.sum::<usize>()
}
/// Concatenate all base files + always-active rules into a single body for
/// the legacy `project: Option<TierFile>` slot used by `splice_into`.
/// The first file's path is used as the slot's `path` for provenance.
#[must_use]
pub fn to_legacy_tier(&self) -> Option<TierFile> {
if self.base_files.is_empty() && self.active_rules.is_empty() {
return None;
}
let mut body = String::new();
let mut tokens = 0usize;
for f in &self.base_files {
let _ = writeln!(
body,
"<project-claude-md path=\"{}\" source=\"walk\">",
f.path.display(),
);
body.push_str(&f.body);
if !body.ends_with('\n') {
body.push('\n');
}
body.push_str("</project-claude-md>\n\n");
tokens = tokens.saturating_add(f.estimated_tokens);
}
for r in &self.active_rules {
let _ = writeln!(
body,
"<project-rule path=\"{}\" source=\"rule\">",
r.path.display(),
);
body.push_str(&r.body);
if !body.ends_with('\n') {
body.push('\n');
}
body.push_str("</project-rule>\n\n");
tokens = tokens.saturating_add(r.estimated_tokens);
}
let path = self
.base_files
.first()
.or_else(|| self.active_rules.first())
.map(|t| t.path.clone())
.unwrap_or_default();
Some(TierFile {
path,
body,
estimated_tokens: tokens,
truncated_bytes: 0,
})
}
}
/// Assembled memory prefix.
///
/// Tiers are present when the corresponding file existed and read successfully.
/// `estimated_tokens` is the *combined* token estimate across all present tiers.
#[derive(Debug, Clone, Default)]
pub struct MemoryPrefix {
/// Operator-global `CLAUDE.md`, if any.
pub global: Option<TierFile>,
/// Workspace `CLAUDE.md`, if any. This is the **flattened** view of
/// [`Self::project_tier`] used by `splice_into` for backward compat; the
/// rich view is in `project_tier`.
pub project: Option<TierFile>,
/// Rich project-tier collections (walk + imports + rules + nested).
pub project_tier: Option<ProjectTier>,
/// Per-workspace auto-memory `MEMORY.md`, if any.
pub auto: Option<TierFile>,
/// Sum of `estimated_tokens` across present tiers.
pub estimated_tokens: usize,
/// `true` if any tier was truncated by budget enforcement.
pub truncated: bool,
}
impl MemoryPrefix {
/// Render the memory prefix and append the operator's default-body system
/// prompt. Tier order is global → project → auto; missing tiers contribute
/// zero bytes. When all tiers are missing, returns `default_body` as-is.
#[must_use]
pub fn splice_into(&self, default_body: &str) -> String {
let mut out = String::new();
for (kind, tier) in [
(TierKind::Global, self.global.as_ref()),
(TierKind::Project, self.project.as_ref()),
(TierKind::Auto, self.auto.as_ref()),
] {
let Some(tier) = tier else { continue };
out.push('<');
out.push_str(kind.tag());
out.push_str(" path=\"");
out.push_str(&tier.path.display().to_string());
out.push_str("\">\n");
out.push_str(&tier.body);
if !tier.body.ends_with('\n') {
out.push('\n');
}
out.push_str("</");
out.push_str(kind.tag());
out.push_str(">\n\n");
}
out.push_str(default_body);
out
}
/// Human-readable summary lines for the `/memory` slash command.
#[must_use]
pub fn summary_lines(&self) -> Vec<String> {
let mut out = Vec::with_capacity(6);
for (kind, tier) in [
(TierKind::Global, self.global.as_ref()),
(TierKind::Project, self.project.as_ref()),
(TierKind::Auto, self.auto.as_ref()),
] {
match tier {
Some(t) => out.push(format!(
" {:<8} {} ({} tokens{})",
kind.label(),
t.path.display(),
t.estimated_tokens,
if t.truncated_bytes > 0 {
format!(", truncated {} bytes", t.truncated_bytes)
} else {
String::new()
},
)),
None => out.push(format!(" {:<8} (missing)", kind.label())),
}
}
if let Some(pt) = self.project_tier.as_ref() {
for f in &pt.base_files {
out.push(format!(
" walk {} ({} tokens)",
f.path.display(),
f.estimated_tokens,
));
}
for f in &pt.imports {
out.push(format!(
" import {} ({} tokens)",
f.path.display(),
f.estimated_tokens,
));
}
for f in &pt.active_rules {
out.push(format!(
" rule {} ({} tokens)",
f.path.display(),
f.estimated_tokens,
));
}
for f in &pt.nested {
out.push(format!(
" nested {} ({} tokens)",
f.path.display(),
f.estimated_tokens,
));
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tier(label: TierKind, body: &str) -> TierFile {
TierFile {
path: PathBuf::from(format!("/tmp/{}.md", label.label())),
estimated_tokens: body.len() / 4,
body: body.to_string(),
truncated_bytes: 0,
}
}
fn raw_tier(path: &str, body: &str) -> TierFile {
TierFile {
path: PathBuf::from(path),
estimated_tokens: body.len() / 4,
body: body.to_string(),
truncated_bytes: 0,
}
}
#[test]
fn splice_into_orders_tiers_correctly() {
let p = MemoryPrefix {
global: Some(tier(TierKind::Global, "GLOBAL")),
project: Some(tier(TierKind::Project, "PROJECT")),
auto: Some(tier(TierKind::Auto, "AUTO")),
..MemoryPrefix::default()
};
let out = p.splice_into("BODY");
let g = out.find("GLOBAL").expect("global present");
let pj = out.find("PROJECT").expect("project present");
let a = out.find("AUTO").expect("auto present");
let b = out.find("BODY").expect("body present");
assert!(g < pj && pj < a && a < b, "wrong order: {out}");
}
#[test]
fn splice_into_omits_missing_tiers() {
let p = MemoryPrefix {
global: None,
project: Some(tier(TierKind::Project, "PROJECT")),
auto: None,
..MemoryPrefix::default()
};
let out = p.splice_into("BODY");
assert!(!out.contains("global-claude-md"));
assert!(!out.contains("auto-memory-index"));
assert!(out.contains("project-claude-md"));
assert!(out.contains("BODY"));
}
#[test]
fn splice_into_preserves_default_body() {
let p = MemoryPrefix::default();
let out = p.splice_into("the default body verbatim");
assert_eq!(out, "the default body verbatim");
}
#[test]
fn summary_lines_show_missing_tiers() {
let p = MemoryPrefix {
global: None,
project: Some(tier(TierKind::Project, "x")),
auto: None,
..MemoryPrefix::default()
};
let lines = p.summary_lines();
assert_eq!(lines.len(), 3);
assert!(lines[0].contains("(missing)"));
assert!(lines[1].contains("project"));
assert!(lines[2].contains("(missing)"));
}
#[test]
fn project_tier_flattens_walk_and_rules_into_legacy_tier() {
let pt = ProjectTier {
base_files: vec![
raw_tier("/tmp/root/CLAUDE.md", "ROOT-BODY"),
raw_tier("/tmp/root/sub/CLAUDE.md", "SUB-BODY"),
],
active_rules: vec![raw_tier("/tmp/root/.caliban/rules/x.md", "RULE-BODY")],
..ProjectTier::default()
};
let flat = pt.to_legacy_tier().expect("flat tier built");
assert!(flat.body.contains("ROOT-BODY"));
assert!(flat.body.contains("SUB-BODY"));
assert!(flat.body.contains("RULE-BODY"));
assert!(flat.body.contains("project-claude-md"));
assert!(flat.body.contains("project-rule"));
// ROOT should come before SUB (broad → narrow).
assert!(flat.body.find("ROOT-BODY").unwrap() < flat.body.find("SUB-BODY").unwrap(),);
}
#[test]
fn project_tier_empty_returns_none_legacy_tier() {
let pt = ProjectTier::default();
assert!(pt.to_legacy_tier().is_none());
}
}