//! The instruction head of a transcript is durable state, not a live read of its sources.
//!
//! The claims these tests hold, in the order the rules are applied: the head of a request is the
//! text this transcript pinned; a change is observed where it happened and carried as verified
//! patches; a change with no actor here is reported honestly instead of attributed to a guess;
//! and a fold is the one moment the head moves.
use klbr_core::prompt_header::{
apply_source_patches, change_between, header_digest, join_sources, plan_header, read_revision,
HeaderChange, HeaderPin, HeaderPlan, HeaderRecord, HeaderRevision, HeaderSnapshot,
HeaderSource, PinReason, RevisionActor, RevisionOrigin, HEADER_PIN_EVENT,
HEADER_REVISION_EVENT,
};
use klbr_runtime::store::{Event, Store};
use serde_json::json;
/// A contract with enough lines that a patch's size is visibly its own, not the document's.
const LONG_CONTRACT: &str = "paragraph 0 of instructions that nobody edited\nparagraph 1 of instructions that nobody edited\nparagraph 2 of instructions that nobody edited\nparagraph 3 of instructions that nobody edited\nparagraph 4 of instructions that nobody edited\nparagraph 5 of instructions that nobody edited\nparagraph 6 of instructions that nobody edited\nparagraph 7 of instructions that nobody edited\nparagraph 8 of instructions that nobody edited\nparagraph 9 of instructions that nobody edited\nparagraph 10 of instructions that nobody edited\nparagraph 11 of instructions that nobody edited\nparagraph 12 of instructions that nobody edited\nparagraph 13 of instructions that nobody edited\nparagraph 14 of instructions that nobody edited\nparagraph 15 of instructions that nobody edited\nparagraph 16 of instructions that nobody edited\nparagraph 17 of instructions that nobody edited\nparagraph 18 of instructions that nobody edited\nparagraph 19 of instructions that nobody edited\n";
const LONG_EDITED: &str = "paragraph 0 of instructions that nobody edited\nparagraph 1 of instructions that nobody edited\nparagraph 2 of instructions that nobody edited\nparagraph 3 of instructions that nobody edited\nparagraph 4 of instructions that nobody edited\nparagraph 5 of instructions that nobody edited\nparagraph 6 of instructions that nobody edited\nparagraph 7 of instructions that nobody edited\nparagraph 8 of instructions that nobody edited\nparagraph 9 of instructions that nobody edited\nparagraph 10 of instructions that nobody edited\nparagraph 11 of instructions that nobody edited\nparagraph 12 of instructions that nobody edited\nparagraph 13 of instructions that nobody edited\nparagraph 14 of instructions that nobody edited\nparagraph 15 of instructions that somebody edited\nparagraph 16 of instructions that nobody edited\nparagraph 17 of instructions that nobody edited\nparagraph 18 of instructions that nobody edited\nparagraph 19 of instructions that nobody edited\n";
fn sources(soul: &str, contract: &str) -> Vec<HeaderSource> {
vec![
HeaderSource::new("soul", soul),
HeaderSource::new("contract", contract),
]
}
fn event(id: i64, kind: &str, payload: serde_json::Value) -> Event {
Event {
id,
kind: kind.into(),
payload,
created_ms: 1_789_325_940_000,
}
}
fn session_revision(base: &HeaderSnapshot, soul: &str, contract: &str) -> serde_json::Value {
let current = sources(soul, contract);
let text = join_sources(¤t);
HeaderRevision::new(
&text,
current,
change_between(base, &sources(soul, contract)),
RevisionActor::session("exec-9", Some(1), "contract"),
1_789_325_941_000,
)
.payload()
}
fn plan(events: &[Event], current: &[HeaderSource], drained_through: i64) -> HeaderPlan {
plan_header(
events
.iter()
.map(|event| (event.id, event.kind.as_str(), &event.payload)),
current,
drained_through,
)
}
fn pin_reason(plan: &HeaderPlan) -> Option<PinReason> {
match plan.record.as_ref() {
Some(HeaderRecord::Pin(pin)) => pin.reason_kind(),
_ => None,
}
}
fn record_revision(plan: &HeaderPlan) -> &HeaderRevision {
match plan.record.as_ref() {
Some(HeaderRecord::Revision(revision)) => revision,
other => panic!("expected an observation, got {other:?}"),
}
}
#[test]
fn a_first_request_pins_the_head_it_runs_under() {
let plan = plan(&[], &sources("soul v1", "contract v1"), 0);
assert_eq!(plan.state.head_text, "soul v1\n\ncontract v1");
assert_eq!(pin_reason(&plan), Some(PinReason::SessionStart));
let Some(HeaderRecord::Pin(pin)) = plan.record.as_ref() else {
panic!("expected a pin");
};
assert_eq!(
pin.sources.len(),
2,
"the parts are kept so a later patch can name one"
);
}
#[test]
fn a_second_request_reuses_the_pinned_bytes_and_records_nothing() {
let events = vec![event(
5,
HEADER_PIN_EVENT,
HeaderPin::of(
&sources("soul v1", "contract v1"),
PinReason::SessionStart,
7,
)
.payload(),
)];
let plan = plan(&events, &sources("soul v1", "contract v1"), 0);
assert_eq!(plan.state.head_text, "soul v1\n\ncontract v1");
assert!(
plan.state.pinned,
"the head is the pinned revision, not a live read"
);
assert!(plan.record.is_none());
}
#[test]
fn a_revision_is_carried_as_a_patch_and_the_head_keeps_its_bytes() {
let pinned = sources("soul v1", LONG_CONTRACT);
let base = HeaderSnapshot::new(pinned.clone());
let events = vec![
event(
5,
HEADER_PIN_EVENT,
HeaderPin::of(&pinned, PinReason::SessionStart, 7).payload(),
),
event(
21,
HEADER_REVISION_EVENT,
session_revision(&base, "soul v1", LONG_EDITED),
),
];
let plan = plan(&events, &sources("soul v1", LONG_EDITED), 0);
assert_eq!(
plan.state.head_text,
join_sources(&pinned),
"the head stays pinned"
);
assert!(
plan.record.is_none(),
"an observation this transcript already carries needs no record"
);
let (_, revision) = &plan.state.revisions[0];
assert_eq!(
revision.form(),
"diff",
"a small change is carried as a patch"
);
let rendered = revision.render();
assert!(
rendered.contains("the patch below is current from here on"),
"{rendered}"
);
assert!(rendered.contains("@@ contract · lines"), "{rendered}");
assert!(
rendered.contains("-paragraph 15 of instructions that nobody edited"),
"{rendered}"
);
assert!(
rendered.contains("+paragraph 15 of instructions that somebody edited"),
"{rendered}"
);
assert!(
revision.change.body_len() < join_sources(&pinned).len(),
"the patch costs less than a second copy of the instructions"
);
}
#[test]
fn a_change_with_no_actor_here_is_reported_not_attributed() {
let pinned = sources("soul v1", "contract v1");
let base = HeaderSnapshot::new(pinned.clone());
let events = vec![event(
5,
HEADER_PIN_EVENT,
HeaderPin::of(&pinned, PinReason::SessionStart, 7).payload(),
)];
let plan = plan(&events, &sources("soul v1", "contract v2"), 0);
assert_eq!(
plan.state.head_text,
join_sources(&pinned),
"the head keeps its bytes"
);
assert!(plan.state.pinned);
let revision = record_revision(&plan);
assert_eq!(revision.actor.origin, RevisionOrigin::Host);
assert_eq!(revision.form(), "diff");
assert_eq!(
revision.digest,
header_digest(&join_sources(&sources("soul v1", "contract v2")))
);
// And the patch is against the pinned revision, which is the text this transcript knows.
let HeaderChange::Diff {
base_digest,
patches,
} = &revision.change
else {
panic!("expected patches");
};
assert_eq!(base_digest, &base.digest);
let applied = apply_source_patches(&base.sources, patches).expect("patches fit");
assert_eq!(
join_sources(&applied),
join_sources(&sources("soul v1", "contract v2"))
);
let rendered = revision.render();
assert!(
rendered.contains("instructions changed for this runtime"),
"{rendered}"
);
assert!(!rendered.contains("by this session"), "{rendered}");
}
#[test]
fn a_patch_that_does_not_reconstruct_is_replaced_by_the_whole_text() {
let base = HeaderSnapshot::new(sources("soul v1", "contract v1"));
// A change with nothing in common is still expressible; what must never happen is a patch
// that claims a transformation it does not perform.
let current = sources("soul v2", "something else entirely\nwith two lines\n");
let change = change_between(&base, ¤t);
let text = join_sources(¤t);
match &change {
HeaderChange::Diff { patches, .. } => {
let applied = apply_source_patches(&base.sources, patches).expect("patches fit");
assert_eq!(
join_sources(&applied),
text,
"a stored patch must reconstruct exactly"
);
}
HeaderChange::Full { text: full } => assert_eq!(full, &text),
}
}
#[test]
fn a_chain_that_breaks_falls_back_to_the_last_text_this_transcript_knows() {
let pinned = sources("soul v1", "contract v1");
let base = HeaderSnapshot::new(pinned.clone());
let first = session_revision(&base, "soul v1", "contract v2");
// A revision whose patches cannot be applied: the chain to it is broken, and the next change
// must patch against the last text that still reconstructs rather than against a guess.
let broken = json!({
"type": "header_revision",
"digest": "0".repeat(64),
"change": {"form": "diff", "base_digest": header_digest(&join_sources(&sources("soul v1", "contract v2"))), "patches": [
{"source": "contract", "start_line": 1, "old_lines": ["a line that is not there\n"], "new_lines": ["x\n"]}
]},
"sources": [],
"actor": {"origin": "host", "reason": "test"},
"observed_at_ms": 1,
});
let events = vec![
event(
5,
HEADER_PIN_EVENT,
HeaderPin::of(&pinned, PinReason::SessionStart, 7).payload(),
),
event(21, HEADER_REVISION_EVENT, first),
event(22, HEADER_REVISION_EVENT, broken),
];
let plan = plan(&events, &sources("soul v1", "contract v3"), 0);
let revision = record_revision(&plan);
let HeaderChange::Diff {
base_digest,
patches,
} = &revision.change
else {
panic!("expected patches against the last reconstructible text");
};
// The last text that resolved is "contract v2", so that is the base a new patch names.
assert_eq!(
base_digest,
&header_digest(&join_sources(&sources("soul v1", "contract v2")))
);
let resolvable = HeaderSnapshot::new(sources("soul v1", "contract v2"));
let applied = apply_source_patches(&resolvable.sources, patches).expect("patches fit");
assert_eq!(
join_sources(&applied),
join_sources(&sources("soul v1", "contract v3"))
);
}
#[test]
fn a_revision_written_before_patches_existed_still_renders_its_text() {
// History is immutable; the reader tolerates the older payload instead of the writer
// pretending it never happened.
let legacy = json!({
"type": "header_revision",
"digest": header_digest("soul v1\n\ncontract v2"),
"text": "soul v1\n\ncontract v2",
"actor": {"origin": "host", "reason": "changed outside this transcript"},
"observed_at_ms": 1_789_325_941_000i64,
});
let revision = read_revision(&legacy).expect("legacy payload is readable");
assert_eq!(revision.form(), "full");
let rendered = revision.render();
assert!(
rendered.contains("the text below is current from here on"),
"{rendered}"
);
assert!(rendered.ends_with("soul v1\n\ncontract v2"), "{rendered}");
}
#[test]
fn a_fold_pins_the_current_text_and_retires_the_observations_behind_it() {
let pinned = sources("soul v1", "contract v1");
let base = HeaderSnapshot::new(pinned.clone());
let events = vec![
event(
5,
HEADER_PIN_EVENT,
HeaderPin::of(&pinned, PinReason::SessionStart, 7).payload(),
),
event(
21,
HEADER_REVISION_EVENT,
session_revision(&base, "soul v1", "contract v2"),
),
event(
40,
HEADER_PIN_EVENT,
HeaderPin::of(&sources("soul v1", "contract v2"), PinReason::Fold, 8).payload(),
),
];
let plan = plan(&events, &sources("soul v1", "contract v2"), 40);
assert_eq!(
plan.state.head_text,
join_sources(&sources("soul v1", "contract v2"))
);
assert!(plan.state.is_current());
assert!(
plan.state.revisions.is_empty(),
"the folded observation is behind the new head"
);
assert!(plan.record.is_none());
}
#[test]
fn an_observation_the_frontier_swallowed_moves_the_head_instead_of_vanishing() {
let pinned = sources("soul v1", "contract v1");
let base = HeaderSnapshot::new(pinned.clone());
let events = vec![
event(
5,
HEADER_PIN_EVENT,
HeaderPin::of(&pinned, PinReason::SessionStart, 7).payload(),
),
event(
21,
HEADER_REVISION_EVENT,
session_revision(&base, "soul v1", "contract v2"),
),
];
let plan = plan(&events, &sources("soul v1", "contract v2"), 40);
assert_eq!(
plan.state.head_text,
join_sources(&sources("soul v1", "contract v2"))
);
assert!(plan.state.revisions.is_empty());
assert_eq!(pin_reason(&plan), Some(PinReason::FoldCoveredRevision));
}
#[test]
fn the_head_is_one_text_so_the_prefix_is_one_block() {
assert_eq!(
klbr_daemon::daemon::header_text("soul v1", "contract v1"),
"soul v1\n\ncontract v1"
);
assert_eq!(
klbr_daemon::daemon::header_text("", "contract v1"),
"contract v1"
);
let named = klbr_daemon::daemon::header_sources("soul v1", "contract v1");
assert_eq!(named[0].name, "soul");
assert_eq!(named[1].name, "contract");
}
#[tokio::test]
async fn resolving_a_head_records_it_so_the_next_request_agrees() {
let temp = tempfile::tempdir().expect("tempdir");
let path = temp.path().join("runtime.sqlite");
let store = Store::open(&path).expect("open store");
let session: klbr_runtime::protocol::SessionId = "header-pin-test".parse().expect("session id");
store.ensure_session(&session).await.expect("session");
let first = klbr_daemon::daemon::resolve_prompt_header(
&store,
&session,
&sources("soul v1", "contract v1"),
&[],
0,
)
.await
.expect("resolve");
assert_eq!(first.state.head_text, "soul v1\n\ncontract v1");
let events = store.history(&session, 0, 1024).await.expect("history");
let pins: Vec<&Event> = events
.iter()
.filter(|event| event.kind == HEADER_PIN_EVENT)
.collect();
assert_eq!(
pins.len(),
1,
"the first request pins the head exactly once"
);
assert_eq!(pins[0].payload["reason"], json!("session_start"));
assert_eq!(pins[0].payload["sources"][0]["name"], json!("soul"));
// Second request, same text: nothing new is recorded and the digest is unchanged.
let second = klbr_daemon::daemon::resolve_prompt_header(
&store,
&session,
&sources("soul v1", "contract v1"),
&events,
0,
)
.await
.expect("resolve");
assert_eq!(second.state.head_digest, first.state.head_digest);
let after = store.history(&session, 0, 1024).await.expect("history");
assert_eq!(
after
.iter()
.filter(|event| event.kind == HEADER_PIN_EVENT)
.count(),
1,
"an unchanged head writes no second pin"
);
// A change nobody in this transcript caused is recorded as an observation, and the head
// stays where it was.
let changed = sources("soul v1", "contract v1\n\nplus one paragraph\n");
let third = klbr_daemon::daemon::resolve_prompt_header(&store, &session, &changed, &after, 0)
.await
.expect("resolve");
assert_eq!(third.state.head_text, "soul v1\n\ncontract v1");
let appended = third.appended.as_ref().expect("the change is recorded");
assert_eq!(appended.kind, HEADER_REVISION_EVENT);
assert_eq!(appended.payload["change"]["form"], json!("diff"));
let rendered = third
.rendered
.as_deref()
.expect("the change reads in this request");
assert!(rendered.contains("+plus one paragraph"), "{rendered}");
assert!(
rendered.contains("the patch below is current from here on"),
"{rendered}"
);
let final_events = store.history(&session, 0, 1024).await.expect("history");
assert_eq!(
final_events
.iter()
.filter(|event| event.kind == HEADER_PIN_EVENT)
.count(),
1,
"an observed change does not move the pin"
);
// And the observation is not written twice: the next request sees it as history.
let fourth =
klbr_daemon::daemon::resolve_prompt_header(&store, &session, &changed, &final_events, 0)
.await
.expect("resolve");
assert!(fourth.appended.is_none(), "the observation is written once");
assert!(fourth.rendered.is_none());
assert_eq!(
fourth.state.revisions.len(),
1,
"and renders in place from now on"
);
}