kcode-session-history 0.1.4

Kennedy's durable session history, lifecycle, and reconstructed context
Documentation
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
# API

`kcode-session-history` is Kennedy's private durable session library. It owns
the active `.session-log` files supplied by `kcode-session-log`, lifecycle and
command control journals, staged objects, reconstructed Chatend state, and the
append-only completed-session receipt list.

Private raw `.session-control` record encoding, SHA-256 integrity, complete
record validation, incomplete-final-tail repair, synchronized append, and
atomic replacement are supplied by `kcode-session-control-journal`. Session
History retains ownership of lifecycle, command, and stop projections plus
domain compaction selection and ordering.

The crate is not an HTTP component. It has no Axum types, routes, status codes,
multipart parsing, Kweb transaction API, or KennedyServer dependency.

## Dependency and opening

The current managed source version is 0.1.4 for Kennedy component dependencies:

```toml
[dependencies]
kcode-session-history = "0.1.4"
```

Open one long-lived, cheaply cloneable `SessionHistory` for a persistence root:

```rust,no_run
use kcode_session_history::{Config, SessionHistory};

let history = SessionHistory::open(Config {
    directory: "data/sessions/in-progress".into(),
    completed_list: "data/session-history.txt".into(),
    provider_cost_compatibility: None,
})?;
# Ok::<(), anyhow::Error>(())
```

`SessionHistory::open` creates private directories and the completed-list file
when absent, verifies and compacts active control journals, and preserves the
authoritative session logs and pending objects. The library owns the files it
derives beneath `Config::directory` and the exact file at
`Config::completed_list`.

## Public store types

```rust
pub struct Config {
    pub directory: std::path::PathBuf,
    pub completed_list: std::path::PathBuf,
    pub provider_cost_compatibility: Option<ProviderCostCompatibility>,
}

pub struct ProviderCostCompatibility {
    pub session_model: fn(&serde_json::Value) -> Option<String>,
    pub estimator: chatend::ProviderCostEstimator,
}

impl SessionHistory {
    pub fn legacy_provider_cost_summary_for_archive(
        &self,
        archive: &serde_json::Value,
        session_state: Option<&serde_json::Value>,
    ) -> anyhow::Result<Option<chatend::ProviderCostSummary>>;
}

pub struct NewSession {
    pub kind: chatend::SessionKind,
    pub created_at: String,
    pub effective_context_tokens: u64,
    pub channel: serde_json::Value,
}

pub struct RegisterSession {
    pub id: String,
    pub started_at: String,
    pub state: serde_json::Value,
}

pub struct StartSession {
    pub idempotency_id: String,
    pub started_at: String,
    pub session_type: String,
    pub duration_minutes: Option<f64>,
    pub custom_prompt: Option<String>,
}

pub struct NewIngressSession {
    pub idempotency_id: String,
    pub started_at: String,
    pub source_session_type: String,
    pub kind: chatend::SessionKind,
    pub effective_context_tokens: u64,
    pub text: String,
    pub metadata: serde_json::Value,
}

pub struct SessionRecord {
    pub id: String,
    pub phase: String,
    pub started_at: String,
    pub updated_at: String,
    pub state: serde_json::Value,
    pub provenance_id: Option<String>,
    pub version: i64,
    pub last_user_message_at: Option<String>,
    pub ended_at: Option<String>,
    pub ingress_failure_count: i64,
    pub ingress_failures: serde_json::Value,
    pub ingress_next_attempt_at: Option<String>,
    pub summary: bool,
}

pub struct Created<T> {
    pub value: T,
    pub created: bool,
}
```

`SessionHistory::legacy_provider_cost_summary_for_archive` replays an immutable
Kweb session archive with the configured compatibility callbacks and returns
only the two cost status fields. HTTP adapters can overlay those fields on the
response's `context.status`; the archive bytes and checksummed events remain
unchanged. It returns `None` when compatibility is disabled or when the object
is a valid metadata-free `kcode-session-log` archive from before Session
History began attaching Chatend replay metadata.

`created` distinguishes a new idempotent operation from a replay that returned
the existing value. Active record phases are `active`, `ingress_pending`,
`ingress_in_progress`, and `ingress_failed`; completed-list records materialize
as `complete`. `version` is the optimistic-concurrency value required by
checkpoint and transition inputs.

## Session creation and discovery

```rust
impl SessionHistory {
    pub fn open(config: Config) -> anyhow::Result<SessionHistory>;
    pub fn health(&self) -> Result<(), Error>;

    pub fn create_session(&self, input: NewSession)
        -> anyhow::Result<Session>;
    pub fn open_session(&self, metadata: chatend::SessionMetadata)
        -> anyhow::Result<Session>;
    pub fn open_session_with_provider_model(
        &self,
        metadata: chatend::SessionMetadata,
        provider_model: Option<&str>,
    ) -> anyhow::Result<Session>;

    pub async fn register(&self, input: RegisterSession)
        -> Result<SessionRecord, Error>;
    pub async fn start(&self, input: StartSession)
        -> Result<Created<SessionRecord>, Error>;
    pub async fn enqueue_ingress(&self, input: NewIngressSession)
        -> Result<Created<SessionRecord>, Error>;
    pub async fn list(&self) -> Result<Vec<SessionRecord>, Error>;
    pub async fn get(&self, id: &str) -> Result<SessionRecord, Error>;
}
```

There are two intentional creation flows:

- `create_session` assigns a UUID and returns a mutable `Session` for a
  Kennedy execution. After the caller has built its initial application state,
  `register` attaches the lifecycle journal to that same durable log.
- `start` is the idempotent lifecycle-first path used for backend-managed work.
  It assigns the session ID and creates the transcript and control journal
  together.
- `enqueue_ingress` durably creates a prepared source session and exposes it
  directly as `ingress_pending`. Repeated calls with the same idempotency ID
  return the active or completed record. Source text is stored in the session
  log; its small source descriptor remains available in the completion receipt.

`open_session` reconstructs the mutable Chatend projection from an existing
session log. The supplied `SessionMetadata` identity and creation time must
match the durable header. No public operation accepts or returns an individual
session-log path.

When `provider_cost_compatibility` is configured, replay preserves every
durable event while pricing legacy provider receipts that omitted a stored
cost. Chatend uses an already-recorded provider model first, then the model on
the active model-backed tool or subagent-start record, and finally the exact
session model supplied by `open_session_with_provider_model` or the configured
`session_model` callback. The application-owned `estimator` remains the only
price catalog. Receipts with insufficient model or metering evidence stay
unpriced, and replay never rewrites the session log.

`list` returns active sessions plus immutable completion receipts, newest
updated first. Active entries are summary projections. Completion synchronizes
its receipt before removing active files, so a list or command-head scan that
observed a journal immediately before its removal skips that stale path rather
than surfacing a storage failure. `get` returns the full active projection or a
completed receipt selected by its canonical archive object ID. Active control
checkpoints retain the small `chatendMetadata` value, not duplicated context
text. On a full read, Session History replays the canonical log through
Chatend's Rust projection and materializes `boxes`, `context`, and
`chatendText`; that text is the exact UTF-8 model input for the current state.
If an older record lacks replay metadata, Session History leaves
`chatendText` absent rather than labeling a reconstructed transcript as model
context.

## Commands and staged objects

```rust
pub struct NewCommand {
    pub idempotency_id: String,
    pub kind: String,
    pub payload: serde_json::Value,
}

pub struct SessionCommand {
    pub id: String,
    pub conversation_id: String,
    pub sequence: i64,
    pub kind: String,
    pub payload: serde_json::Value,
    pub status: String,
    pub cancel_requested: bool,
    pub outcome: Option<serde_json::Value>,
    pub created_at: String,
    pub processing_started_at: Option<String>,
    pub completed_at: Option<String>,
    pub idempotency_id: String,
}

pub struct CommandOutcome {
    pub outcome: serde_json::Value,
}

pub struct NewStopRequest {
    pub idempotency_id: String,
    pub scope: String,
}

pub struct StopOutcome {
    pub outcome: serde_json::Value,
}

pub struct NewObject {
    pub file_name: Option<String>,
    pub media_type: String,
    pub bytes: Vec<u8>,
}

pub struct StoredObject {
    pub file_name: String,
    pub media_type: String,
    pub bytes: Vec<u8>,
}

impl SessionHistory {
    pub async fn enqueue(
        &self,
        id: &str,
        input: NewCommand,
    ) -> Result<Created<SessionCommand>, Error>;

    pub async fn command_heads(&self)
        -> Result<Vec<SessionCommand>, Error>;
    pub async fn claim_command(&self, id: &str)
        -> Result<SessionCommand, Error>;
    pub async fn complete_command(
        &self,
        id: &str,
        outcome: CommandOutcome,
    ) -> Result<SessionCommand, Error>;

    pub async fn request_stop(
        &self,
        id: &str,
        input: NewStopRequest,
    ) -> Result<Created<SessionStopRequest>, Error>;
    pub async fn request_current_work_stop(
        &self,
        id: &str,
        input: NewCurrentWorkStop,
    ) -> Result<Created<SessionStopRequest>, Error>;
    pub fn listen_for_stop(&self, id: &str)
        -> Result<StopListener, Error>;
    pub async fn stop_heads(&self)
        -> Result<Vec<SessionStopRequest>, Error>;
    pub async fn complete_stop(
        &self,
        id: &str,
        outcome: StopOutcome,
    ) -> Result<SessionStopRequest, Error>;

    pub async fn stage_object(
        &self,
        id: &str,
        object: NewObject,
    ) -> Result<String, Error>;
    pub fn object(
        &self,
        id: &str,
        pending_id: &str,
    ) -> Result<StoredObject, Error>;
}
```

Commands are ordered per active session. Only the earliest unfinished command
is claimable. Enqueue is idempotent by `idempotency_id`; command states are
`pending`, `processing`, and `complete`.

Stop requests are durable orchestration sidebands with `turn`, `session`, or
`self-time-run` scope. They do not advance the lifecycle version or select an
ingress phase. Requesting a turn stop also marks the current browser message or
retry command for cancellation. `request_current_work_stop` is the normal
application boundary: it derives the scope from the durable phase and typed
Chatend session kind, records or reuses the request, and signals any
same-process `StopListener` before returning. `listen_for_stop` also observes a
request recorded before listener registration, so recovery does not depend on
an ephemeral notification. The orchestrator owns cancellation and completes a
turn request after the session has been made ready for input; terminal session
completion removes autonomous stop state with the rest of the active journal.

`stage_object` takes ownership of complete bytes and returns the durable
event-derived ID `pending:N`. Object staging is rejected while a command is
unfinished so independent handles cannot race allocation. `object` verifies
the pending object and returns a safe filename, usable media type, and owned
bytes.

## Lifecycle and completion

```rust
pub struct Checkpoint {
    pub expected_version: i64,
    pub state: serde_json::Value,
    pub user_activity: bool,
}

pub struct ExpectedVersion {
    pub expected_version: i64,
}

pub struct StartIngress {
    pub expected_version: i64,
    pub provenance_id: String,
}

pub struct IngressFailure {
    pub expected_version: i64,
    pub stage: String,
    pub code: Option<String>,
    pub message: String,
    pub rounds_used: Option<u64>,
    pub context_tokens: Option<u64>,
    pub context_window_tokens: Option<u64>,
}

pub struct RetryIngress {
    pub expected_version: i64,
    pub state: serde_json::Value,
}

impl SessionHistory {
    pub async fn checkpoint(
        &self,
        id: &str,
        input: Checkpoint,
    ) -> Result<SessionRecord, Error>;
    pub async fn request_ingress(
        &self,
        id: &str,
        input: Checkpoint,
    ) -> Result<SessionRecord, Error>;
    pub async fn start_ingress(
        &self,
        id: &str,
        input: StartIngress,
    ) -> Result<SessionRecord, Error>;
    pub async fn complete_ingress(
        &self,
        id: &str,
        input: ExpectedVersion,
    ) -> Result<SessionRecord, Error>;
    pub async fn fail_ingress(
        &self,
        id: &str,
        input: IngressFailure,
    ) -> Result<SessionRecord, Error>;
    pub async fn retry_ingress(
        &self,
        id: &str,
        input: RetryIngress,
    ) -> Result<SessionRecord, Error>;
    pub async fn release_interrupted_ingress(&self)
        -> Result<Vec<String>, Error>;
    pub async fn complete(
        &self,
        id: &str,
        input: Checkpoint,
    ) -> Result<SessionRecord, Error>;
}
```

All mutation inputs carrying `expected_version` use optimistic concurrency and
return `Conflict` when stale. `checkpoint` retains a new application snapshot
without changing phase. `request_ingress` moves active work to
`ingress_pending`; `start_ingress` claims it and records provenance. Stop
requests are intentionally separate from these lifecycle mutations.

`fail_ingress` applies the fixed retry policy. Retryable failures below the
five-attempt budget return to `ingress_pending` with a short delay. The fifth
failure, or a non-retryable failure, enters `ingress_failed`. Only the five
latest concise failures are embedded in the lifecycle record.
`retry_ingress` manually grants a fresh attempt budget while retaining the
failure count. `release_interrupted_ingress` requeues claims left in progress
by process interruption.

`complete` commits a final state directly. `complete_ingress` commits the
current state after ingress. These lifecycle operations do not themselves
write Kweb data or remove local session data.

Completion receipts are recorded separately after the embedding application
has committed Kweb:

```rust
pub struct RecordCompletion {
    pub session_object_id: String,
    pub commit_receipt: Option<CompletionReceipt>,
    pub session_id: Option<String>,
    pub session_type: Option<String>,
    pub created_at: Option<String>,
}

pub struct CompletionReceipt {
    pub transaction_id: Option<String>,
    pub session_object_id: String,
    pub session_id: Option<String>,
    pub session_type: Option<String>,
    pub created_at: Option<String>,
    pub committed_at: Option<String>,
    pub ingress_source: Option<serde_json::Value>,
    pub node_ids: std::collections::BTreeMap<String, String>,
    pub object_ids: std::collections::BTreeMap<String, String>,
}

impl SessionHistory {
    pub async fn record_completion(
        &self,
        input: RecordCompletion,
    ) -> Result<(), Error>;
}
```

`record_completion` synchronizes an idempotent JSON-lines receipt to the
completed list. When `session_id` is supplied, success then removes the exact
committed session log, its pending objects, and its control journal. Historical
completed-list lines containing only an object ID remain readable.

## Mutable session and Chatend

`Session` is an opaque handle to one ordered session history. Construct it only
through `SessionHistory::create_session` or
`SessionHistory::open_session`. It exposes durable mutations without exposing
`kcode-session-log` or a storage path.

```rust
impl Session {
    pub fn id(&self) -> &str;
    pub fn state(&self) -> &chatend::Chatend;
    pub fn objects(
        &self,
    ) -> &std::collections::BTreeMap<
        chatend::PendingId,
        chatend::ObjectLocation,
    >;
    pub fn archive_bytes(&self) -> anyhow::Result<Vec<u8>>;
    pub fn is_sealed(&self) -> bool;
    pub fn seal(&mut self) -> anyhow::Result<()>;
    pub fn repair_unfinished_tools(
        &mut self,
        recorded_at: impl Into<String>,
    ) -> anyhow::Result<Vec<chatend::EventId>>;
    pub fn mark_completed(&mut self, session_object_id: String);
    pub fn configure_context(
        &mut self,
        kind: chatend::SessionKind,
        effective_context_tokens: u64,
    );

    pub fn create_box(
        &mut self,
        recorded_at: impl Into<String>,
        name: impl Into<String>,
        owner: chatend::BoxOwner,
        content: chatend::BoxContent,
    ) -> anyhow::Result<chatend::BoxId>;
    pub fn update_box(
        &mut self,
        recorded_at: impl Into<String>,
        box_id: chatend::BoxId,
        content: chatend::BoxContent,
    ) -> anyhow::Result<Option<chatend::EventId>>;
    pub fn dehydrate_boxes(
        &mut self,
        recorded_at: impl Into<String>,
        box_ids: &[chatend::BoxId],
    ) -> anyhow::Result<Vec<chatend::EventId>>;
    pub fn summarize_box(
        &mut self,
        recorded_at: impl Into<String>,
        box_id: chatend::BoxId,
        text: impl Into<String>,
    ) -> anyhow::Result<chatend::EventId>;
    pub fn rehydrate_box(
        &mut self,
        recorded_at: impl Into<String>,
        box_id: chatend::BoxId,
    ) -> anyhow::Result<chatend::EventId>;
    pub fn retire_box(
        &mut self,
        recorded_at: impl Into<String>,
        box_id: chatend::BoxId,
    ) -> anyhow::Result<chatend::EventId>;

    pub fn allocate_pending_node(
        &mut self,
        recorded_at: impl Into<String>,
    ) -> anyhow::Result<chatend::PendingId>;
    pub fn stage_object(
        &mut self,
        recorded_at: impl Into<String>,
        media_type: impl Into<String>,
        file_name: Option<String>,
        transport: serde_json::Value,
        bytes: &[u8],
    ) -> anyhow::Result<chatend::PendingId>;
    pub fn read_object(
        &mut self,
        id: &chatend::PendingId,
    ) -> anyhow::Result<Vec<u8>>;

    pub fn record(
        &mut self,
        recorded_at: impl Into<String>,
        kind: chatend::EventKind,
    ) -> anyhow::Result<chatend::EventId>;
    pub fn commit_events(
        &mut self,
        recorded_at: impl Into<String>,
        events: Vec<chatend::Event>,
    ) -> anyhow::Result<()>;
    pub fn apply_tool_slots(
        &mut self,
        recorded_at: impl Into<String>,
        tool_instance: impl Into<String>,
        slots: Vec<chatend::ToolSlotInput>,
    ) -> anyhow::Result<Vec<chatend::EventId>>;
    pub fn apply_tool_slots_with_layout(
        &mut self,
        recorded_at: impl Into<String>,
        tool_instance: impl Into<String>,
        slots: Vec<chatend::ToolSlotInput>,
        layout_slots: &[String],
    ) -> anyhow::Result<Vec<chatend::EventId>>;
    pub fn apply_box_representations(
        &mut self,
        recorded_at: impl Into<String>,
        desired: &std::collections::BTreeMap<
            chatend::BoxId,
            chatend::BoxRepresentation,
        >,
    ) -> anyhow::Result<Vec<chatend::EventId>>;
}
```

Every event-producing mutation and object-staging operation appends and
synchronizes its durable representation before updating the in-memory
projection. `seal` is idempotent and rejects unfinished tool invocations.
`repair_unfinished_tools` writes explicit recovery completions before a
recovered session is sealed.

The `chatend` module contains the provider-independent logical model:

- identity types `EventId`, `BoxId`, and validated `PendingId`;
- `SessionKind`, `SessionMetadata`, `BoxOwner`, `BoxContent`, `BoxState`,
  `Representation`, and `BoxRepresentation`;
- `EventKind`, `Event`, and `Transition`;
- pending-object metadata and location types;
- `ToolSlotInput`, `ToolSlot`, and `ToolState`; and
- `Chatend`, `ContextProjection`, and `ProjectionItem`.

Its small value helpers are:

```rust
impl chatend::PendingId {
    pub fn from_event(id: chatend::EventId) -> Self;
    pub fn parse(value: impl Into<String>) -> anyhow::Result<Self>;
    pub fn number(&self) -> u64;
}

impl chatend::BoxContent {
    pub fn text(value: impl Into<String>) -> Self;
    pub fn use_concise_header(&mut self);
}

impl chatend::BoxState {
    pub fn stale(&self) -> bool;
}
```

`EventKind` represents configuration, box creation/update/representation,
pending resource allocation, tool invocation/completion/layout, inference
submission and provider receipts, capacity failures, source termination,
history-ingress lifecycle, Kweb planning/commit, completion, and arbitrary
labeled notes. Legacy history-event inspection markers remain readable for
old-log replay but have no current context-control command. It serializes as a
tagged snake-case enum; the concrete Rust variants in `chatend::EventKind` are
the authoritative schema.

`Chatend` exposes event/box lookup, active-box iteration, fixed context-limit
calculations, current projection, and nonmutating projection previews:

```rust
impl chatend::Chatend {
    pub fn event(&self, id: chatend::EventId)
        -> Option<&chatend::Event>;
    pub fn box_state(&self, id: chatend::BoxId)
        -> Option<&chatend::BoxState>;
    pub fn active_boxes(&self)
        -> impl Iterator<Item = &chatend::BoxState>;
    pub fn live_context_limit(&self) -> u64;
    pub fn forced_ingress_context_limit(&self) -> u64;
    pub fn ingress_initial_context_limit(&self) -> u64;
    pub fn ingress_context_limit(&self) -> u64;
    pub fn active_context_limit(&self) -> u64;
    pub fn projection_with_new_boxes(
        &self,
        boxes: &[(String, chatend::BoxOwner, chatend::BoxContent)],
    ) -> anyhow::Result<chatend::ContextProjection>;
    pub fn projection_with_new_boxes_at(
        &self,
        recorded_at: &str,
        boxes: &[(String, chatend::BoxOwner, chatend::BoxContent)],
    ) -> anyhow::Result<chatend::ContextProjection>;
    pub fn projection_with_new_boxes_and_updates(
        &self,
        boxes: &[(String, chatend::BoxOwner, chatend::BoxContent)],
        updates: &std::collections::BTreeMap<
            chatend::BoxId,
            chatend::BoxContent,
        >,
    ) -> anyhow::Result<chatend::ContextProjection>;
    pub fn projection_with_new_boxes_and_updates_at(
        &self,
        recorded_at: &str,
        boxes: &[(String, chatend::BoxOwner, chatend::BoxContent)],
        updates: &std::collections::BTreeMap<
            chatend::BoxId,
            chatend::BoxContent,
        >,
    ) -> anyhow::Result<chatend::ContextProjection>;
    pub fn projection_with_box_representations(
        &self,
        desired: &std::collections::BTreeMap<
            chatend::BoxId,
            chatend::BoxRepresentation,
        >,
    ) -> anyhow::Result<chatend::ContextProjection>;
    pub fn projection(&self) -> chatend::ContextProjection;
}

impl chatend::ContextProjection {
    pub fn render(&self) -> String;
}

pub fn estimate_tokens(text: &str) -> u64;
```

Projected box headers never include Chatend's internal owner.
`BoxContent::use_concise_header` remains as a source-compatible no-op for
callers that previously selected the now-universal concise header. User
messages and user-visible Kennedy messages include their recorded RFC 3339
timestamp in the header. When a later box occurrence supersedes an earlier
occurrence, the earlier position projects exactly
`[box updated]` so tool-call/result continuity remains visible without
duplicating stale content.

The projection footer lists stale box IDs first and the current RFC 3339 UTC
time including the year next. Its final line contains only
`[current context size: N | max context size: M]`, where `N` is the calibrated
current estimate and `M` is the active capacity limit. It does not expose the
larger provider window as usable capacity. Journal events do not otherwise
become independent model-context blocks; their box effects drive the
projection.

The current format constant is `chatend::FORMAT_VERSION`. Objects are bounded
by `chatend::MAX_OBJECT_BYTES` per object and in aggregate per session.
Token estimation uses `chatend::ESTIMATED_CHARACTERS_PER_TOKEN`.

## Errors, concurrency, and recovery

Lifecycle methods return:

```rust
pub enum ErrorKind {
    InvalidInput,
    NotFound,
    Conflict,
    Storage,
}

pub struct Error {
    pub kind: ErrorKind,
    pub message: String,
}

impl ErrorKind {
    pub fn code(self) -> &'static str;
}
```

`ErrorKind::code` returns `invalid_request`, `not_found`, `state_conflict`, or
`internal_error`. Storage diagnostics are logged with `tracing`; the public
storage message is intentionally generic. `Session` and opening operations use
`anyhow::Error` for internal integration failures.

Mutations through handles opened in one process are serialized per session;
completed-list changes use a catalog lock. The package does not coordinate
independent processes writing the same persistence root.

Checksummed complete control records are authoritative. The private
`kcode-session-control-journal` leaf repairs only an incomplete trailing
record, rejects other complete corruption, and atomically replaces a selected
record sequence. Session History chooses and orders the retained lifecycle,
command, stop, and other domain records during compaction, then replays the
`.session-log` to reconstruct Chatend. No presentation snapshot is required.
See `Specification.md` for the full persistence, retry, and cleanup contract.