rusty_agent_runtime/registry.rs
1//! The prompt/configuration registry (R0.11 Extension Plane, wave 1):
2//! named artifacts with an owner and a commit history, plus the diff
3//! views between committed versions.
4//!
5//! The governing decision, from the design: the registry is the R0.8
6//! candidate pipeline turned toward human-authored configuration. A
7//! commit **is** a [`Candidate`] — content-addressed, immutable, authored
8//! (`human:{id}` attribution, the correction loop's discipline applied to
9//! configuration) — and everything that makes a candidate governable
10//! (the lifecycle, the envelope gate, the version pointer, the journaled
11//! transitions) is reused unchanged from [`crate::learn`]. What this
12//! module adds is exactly the two things the pipeline never had:
13//!
14//! - [`ArtifactRecord`] — the named, owned index over candidates. One
15//! artifact per production surface (`prompt:system`,
16//! `model_settings:primary`, …): the record carries the family, the
17//! owner, and the ordered commit sequence, and nothing else. It is an
18//! index over the candidate store, never a fork of it — a commit
19//! changes nothing about the candidate it names, and the candidate's
20//! own lifecycle (created → evaluated → promoted) journals through the
21//! learn plane exactly as before. Ownership is review routing and
22//! attribution, not an ACL: tenant isolation stays API keys, and
23//! fine-grained RBAC stays post-R1.0.
24//! - [`diff_candidates`] — the derived view between two committed
25//! versions: a line diff for the prompt text, a structural diff over
26//! the canonical-JSON form for the JSON families (added / removed /
27//! changed leaves). Computed on read, **never stored**: the store
28//! holds immutable versions, and a stored diff would be a second,
29//! divergent account of the same change. Diffing over
30//! `canonicalize_value` inherits its determinism — a reordering of
31//! canonical JSON object keys is not a change (array order stays
32//! significant: a middleware composition's layer order *is* the
33//! artifact).
34//!
35//! Environment tags and promotion per tag compose the learn plane's
36//! pointer machinery directly ([`SurfaceKey::tagged`]); they are not
37//! re-implemented here.
38//!
39//! Wave 2 (admission resolution and pinning) adds the read half of that
40//! machinery: [`ConfigResolution`], the journaled payload of a
41//! [`RunEventKind::ConfigResolved`](crate::record::RunEventKind::ConfigResolved)
42//! event, plus the two pure functions the server's admission path is
43//! built from — [`pointer_admission`] (which candidate a pointer binds
44//! for this run: the canary when the seeded draw admits, else the active
45//! version) and [`resolution_pin`] (what the run's manifest pins for the
46//! resolved candidate). The manifest pin itself is unchanged — digests,
47//! recorded by the R0.7 `pin_prompt` / `pin_tool_schema` / `pin_model`
48//! exactly as before; this event is the digest ↔ version join the
49//! manifest alone cannot express, so the manifest's wire shape stays
50//! frozen and pre-R0.11 manifests keep deserializing.
51
52use chrono::{DateTime, Utc};
53use serde::{Deserialize, Serialize};
54use serde_json::Value;
55use thiserror::Error;
56
57use crate::learn::{
58 canary_admits, surface_for_kind, Candidate, CandidateId, CandidateKind, EnvironmentTag,
59 SurfaceKey, VersionPointer,
60};
61use crate::memory::ProvenanceAuthor;
62use crate::record::{canonicalize_value, sha256_hex};
63
64// --------------------------------------------------------------------- //
65// The artifact record
66// --------------------------------------------------------------------- //
67
68/// The longest an artifact name may be. Names live inside surface keys —
69/// which ride in pointer files, receipts, and journaled payloads — so a
70/// bound keeps a configuration typo from minting an unbounded key.
71pub const MAX_ARTIFACT_NAME_LEN: usize = 128;
72
73/// One entry in an artifact's commit sequence: a candidate id and the
74/// instant it joined the history. Authorship is deliberately *not*
75/// repeated here — the candidate carries its own `distilled_by`, and
76/// repeating it would give one fact two homes. The sequence is
77/// append-only: a commit, like the candidate it names, is immutable.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct ArtifactCommit {
80 /// The committed candidate (its content address).
81 pub candidate_id: CandidateId,
82
83 /// When the commit joined this artifact's history — which may be
84 /// later than the candidate's own `created_at` (distillation and
85 /// registry authorship are separate acts).
86 pub committed_at: DateTime<Utc>,
87}
88
89/// A named, owned artifact: the registry's only new persisted entity.
90///
91/// The key is the untagged production surface — [`Candidate::surface`]
92/// for any candidate of this family and name — so the artifact ↔
93/// candidate join is structural, not conventional: a candidate can only
94/// ever commit to the artifact its own surface names. Environment-tagged
95/// pointers (`prompt:system@prod`) hang off the base surface through the
96/// learn plane's pointer machinery; the artifact itself is never tagged,
97/// because a tag names a promotion target, and history is shared across
98/// targets.
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
100pub struct ArtifactRecord {
101 /// The registry key: the untagged surface (`prompt:system`,
102 /// `policy:retry`, `memory:agent:support-1`, …).
103 pub surface: SurfaceKey,
104
105 /// The registry family — the candidate kind this artifact indexes.
106 pub family: CandidateKind,
107
108 /// Who owns the artifact: review routing and attribution, not an
109 /// ACL. `human:{id}` is the registry's native attribution (operator-
110 /// authored configuration), but any [`ProvenanceAuthor`] is legal —
111 /// a distiller-owned artifact is how a learned family keeps its
112 /// pipeline attribution.
113 pub owner: ProvenanceAuthor,
114
115 /// The commit sequence, oldest first, append-only. Absent from the
116 /// wire when empty: a declared-but-uncommitted artifact carries no
117 /// placeholder.
118 #[serde(default, skip_serializing_if = "Vec::is_empty")]
119 pub commits: Vec<ArtifactCommit>,
120
121 /// When the artifact was declared.
122 pub created_at: DateTime<Utc>,
123}
124
125impl ArtifactRecord {
126 /// Declare an artifact for `family` under `name`, owned by `owner`.
127 /// The name is validated (see the module docs and
128 /// [`RegistryError::InvalidName`]); the surface key derives from
129 /// `(family, name)` by the same rule [`Candidate::surface`] applies,
130 /// so the artifact and its candidates can never disagree about which
131 /// surface they govern.
132 pub fn new(
133 family: CandidateKind,
134 name: impl Into<String>,
135 owner: ProvenanceAuthor,
136 created_at: DateTime<Utc>,
137 ) -> Result<Self, RegistryError> {
138 let name = name.into();
139 validate_artifact_name(&name)?;
140 Ok(Self {
141 surface: surface_for_kind(family, &name),
142 family,
143 owner,
144 commits: Vec::new(),
145 created_at,
146 })
147 }
148
149 /// The artifact's name — the surface minus its family prefix
150 /// (`prompt:system` → `system`; `memory:agent:support-1` →
151 /// `agent:support-1`).
152 pub fn name(&self) -> &str {
153 let prefix = surface_for_kind(self.family, "");
154 self.surface
155 .as_str()
156 .strip_prefix(prefix.as_str())
157 .unwrap_or_else(|| self.surface.as_str())
158 }
159
160 /// The latest commit (`None` before the first).
161 pub fn latest(&self) -> Option<&ArtifactCommit> {
162 self.commits.last()
163 }
164
165 /// The commit naming `candidate_id`, when this artifact's history
166 /// contains it.
167 pub fn find_commit(&self, candidate_id: &CandidateId) -> Option<&ArtifactCommit> {
168 self.commits
169 .iter()
170 .find(|commit| &commit.candidate_id == candidate_id)
171 }
172
173 /// Admit a candidate into the history: build the commit, checking the
174 /// three rules that keep the index honest. The candidate's kind must
175 /// be the artifact's family and its surface must be the artifact's —
176 /// a `prompt:other` candidate has no business in `prompt:system`'s
177 /// history — and the candidate must not already be committed (a
178 /// re-committed candidate is the same fact, answered by the route as
179 /// a convergence, so reaching this guard means a genuinely duplicate
180 /// append).
181 ///
182 /// This is the check, not the write: the store appends under its
183 /// compare-and-swap guard, so two concurrent commits cannot lose one
184 /// another.
185 pub fn admit_commit(
186 &self,
187 candidate: &Candidate,
188 committed_at: DateTime<Utc>,
189 ) -> Result<ArtifactCommit, RegistryError> {
190 if candidate.kind() != self.family {
191 return Err(RegistryError::FamilyMismatch {
192 artifact: self.family,
193 candidate: candidate.kind(),
194 });
195 }
196 if candidate.surface() != self.surface {
197 return Err(RegistryError::SurfaceMismatch {
198 artifact: self.surface.clone(),
199 candidate: candidate.surface(),
200 });
201 }
202 if self.find_commit(&candidate.candidate_id).is_some() {
203 return Err(RegistryError::DuplicateCommit {
204 candidate_id: candidate.candidate_id.clone(),
205 });
206 }
207 Ok(ArtifactCommit {
208 candidate_id: candidate.candidate_id.clone(),
209 committed_at,
210 })
211 }
212}
213
214/// The artifact naming rules, enforced at declaration: non-empty, bounded
215/// ([`MAX_ARTIFACT_NAME_LEN`]), no leading or trailing whitespace, no
216/// control characters, no `@` (the environment-tag separator — a name
217/// carrying it would make tagged and untagged surfaces ambiguous), and no
218/// `/` (the tenant id-prefix separator — a name carrying it would escape
219/// the store's path-keyed tenancy and the default tenant's id grammar).
220/// `:` is legal: memory-scope addresses (`agent:support-1`) are names.
221fn validate_artifact_name(name: &str) -> Result<(), RegistryError> {
222 let refuse = |reason: &'static str| RegistryError::InvalidName {
223 name: name.to_owned(),
224 reason,
225 };
226 if name.is_empty() {
227 return Err(refuse("empty — an artifact exists to be named"));
228 }
229 if name.len() > MAX_ARTIFACT_NAME_LEN {
230 return Err(refuse("over 128 bytes"));
231 }
232 if name != name.trim() {
233 return Err(refuse(
234 "leading or trailing whitespace — visually identical names would be distinct \
235 artifacts, which is a misreview waiting to happen",
236 ));
237 }
238 if name.chars().any(|c| c.is_control() || c == '@' || c == '/') {
239 return Err(refuse(
240 "carries a control character, `@`, or `/` — the tag separator and the tenant \
241 separator are structural, and control characters have no business in a key",
242 ));
243 }
244 Ok(())
245}
246
247// --------------------------------------------------------------------- //
248// Diff views — computed on read, never stored
249// --------------------------------------------------------------------- //
250
251/// The derived view between two committed versions of one artifact. A
252/// line diff for the prompt text ([`RegistryDiff::Text`]); a structural
253/// diff over the canonical-JSON content for every JSON family
254/// ([`RegistryDiff::Structural`]). The wire shape is pinned under
255/// `tests/golden/`, like every contract in the release.
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257#[serde(tag = "view", rename_all = "snake_case")]
258pub enum RegistryDiff {
259 /// Line diff of two prompt texts, oldest change hunks first.
260 Text {
261 /// Every line of the view, in order: context lines carried once,
262 /// removed lines (from the base) before their added replacements.
263 lines: Vec<TextDiffLine>,
264 },
265 /// Structural diff over the canonical-JSON content: added, removed,
266 /// and changed leaves, each sorted by path. A leaf is a scalar, or a
267 /// whole subtree where one side lacks the path — a removed object
268 /// reports as one removed leaf, not a forest of scalars.
269 Structural {
270 /// Leaves present in the target and absent in the base.
271 added: Vec<LeafChange>,
272 /// Leaves present in the base and absent in the target.
273 removed: Vec<LeafChange>,
274 /// Leaves present in both with different values (including type
275 /// changes, reported whole).
276 changed: Vec<LeafModification>,
277 },
278}
279
280impl RegistryDiff {
281 /// `true` when the two versions are content-equal — the honest answer
282 /// for a no-op diff, with no placeholder hunks invented.
283 pub fn is_empty(&self) -> bool {
284 match self {
285 RegistryDiff::Text { lines } => lines
286 .iter()
287 .all(|line| matches!(line, TextDiffLine::Context(_))),
288 RegistryDiff::Structural {
289 added,
290 removed,
291 changed,
292 } => added.is_empty() && removed.is_empty() && changed.is_empty(),
293 }
294 }
295}
296
297/// One line of a [`RegistryDiff::Text`] view.
298#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
299#[serde(tag = "op", content = "line", rename_all = "snake_case")]
300pub enum TextDiffLine {
301 /// A line both versions carry.
302 Context(String),
303 /// A line the base carries and the target does not.
304 Removed(String),
305 /// A line the target carries and the base does not.
306 Added(String),
307}
308
309/// One added or removed leaf of a [`RegistryDiff::Structural`] view.
310#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
311pub struct LeafChange {
312 /// The leaf's path (`/parameters/temperature`, `/layers/0/config`;
313 /// `/`-joined segments, array indices as numbers — diagnostic, not a
314 /// parseable pointer).
315 pub path: String,
316
317 /// The leaf's value on the side that carries it.
318 pub value: Value,
319}
320
321/// One changed leaf of a [`RegistryDiff::Structural`] view.
322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
323pub struct LeafModification {
324 /// The leaf's path (same convention as [`LeafChange::path`]).
325 pub path: String,
326
327 /// The base version's value.
328 pub from: Value,
329
330 /// The target version's value.
331 pub to: Value,
332}
333
334/// Compute the diff view from `from` (the base) to `to` (the target).
335///
336/// Both candidates must be the same kind — a diff across kinds compares
337/// two different contracts, which is not a view but a category error.
338/// Within one kind the function is lenient about surfaces: the artifact
339/// route enforces membership (both versions committed to *this*
340/// artifact); the pure function answers for any same-kind pair.
341///
342/// The prompt family diffs its text line by line (an LCS walk — removed
343/// lines before their added replacements, deterministic by construction;
344/// prompt texts are operator-scale, so the quadratic table is never the
345/// bottleneck). Every other family diffs structurally over the
346/// canonical-JSON serialization of its content: equal canonical forms
347/// diff empty, so a reordered object is not a change and equal content
348/// addresses are visibly equal.
349pub fn diff_candidates(from: &Candidate, to: &Candidate) -> Result<RegistryDiff, RegistryError> {
350 if from.kind() != to.kind() {
351 return Err(RegistryError::DiffAcrossKinds {
352 from: from.kind(),
353 to: to.kind(),
354 });
355 }
356 if let (
357 crate::learn::CandidateContent::Prompt { prompt: base, .. },
358 crate::learn::CandidateContent::Prompt { prompt: target, .. },
359 ) = (&from.content, &to.content)
360 {
361 return Ok(RegistryDiff::Text {
362 lines: diff_lines(base, target),
363 });
364 }
365 let base = canonicalize_value(
366 &serde_json::to_value(&from.content)
367 .map_err(|e| RegistryError::UndiffableContent(e.to_string()))?,
368 );
369 let target = canonicalize_value(
370 &serde_json::to_value(&to.content)
371 .map_err(|e| RegistryError::UndiffableContent(e.to_string()))?,
372 );
373 let mut added = Vec::new();
374 let mut removed = Vec::new();
375 let mut changed = Vec::new();
376 diff_values("", &base, &target, &mut added, &mut removed, &mut changed);
377 Ok(RegistryDiff::Structural {
378 added,
379 removed,
380 changed,
381 })
382}
383
384/// The recursive walk behind the structural diff. Objects merge-walk by
385/// key (the canonical form sorts keys, so the walk order — and therefore
386/// the emitted leaf order — is deterministic); arrays pair by position
387/// (order is significant: a middleware layer order *is* the artifact);
388/// anything else compares whole.
389fn diff_values(
390 path: &str,
391 base: &Value,
392 target: &Value,
393 added: &mut Vec<LeafChange>,
394 removed: &mut Vec<LeafChange>,
395 changed: &mut Vec<LeafModification>,
396) {
397 match (base, target) {
398 (Value::Object(base_map), Value::Object(target_map)) => {
399 for (key, base_value) in base_map {
400 let child = format!("{path}/{key}");
401 match target_map.get(key) {
402 Some(target_value) => {
403 diff_values(&child, base_value, target_value, added, removed, changed)
404 }
405 None => removed.push(LeafChange {
406 path: child,
407 value: base_value.clone(),
408 }),
409 }
410 }
411 for (key, target_value) in target_map {
412 if !base_map.contains_key(key) {
413 added.push(LeafChange {
414 path: format!("{path}/{key}"),
415 value: target_value.clone(),
416 });
417 }
418 }
419 }
420 (Value::Array(base_items), Value::Array(target_items)) => {
421 let shared = base_items.len().min(target_items.len());
422 for (index, (base_value, target_value)) in base_items
423 .iter()
424 .zip(target_items.iter())
425 .enumerate()
426 .take(shared)
427 {
428 diff_values(
429 &format!("{path}/{index}"),
430 base_value,
431 target_value,
432 added,
433 removed,
434 changed,
435 );
436 }
437 for (index, base_value) in base_items.iter().enumerate().skip(shared) {
438 removed.push(LeafChange {
439 path: format!("{path}/{index}"),
440 value: base_value.clone(),
441 });
442 }
443 for (index, target_value) in target_items.iter().enumerate().skip(shared) {
444 added.push(LeafChange {
445 path: format!("{path}/{index}"),
446 value: target_value.clone(),
447 });
448 }
449 }
450 _ => {
451 if base != target {
452 changed.push(LeafModification {
453 path: path.to_owned(),
454 from: base.clone(),
455 to: target.clone(),
456 });
457 }
458 }
459 }
460}
461
462/// The line diff behind the prompt view: a longest-common-subsequence
463/// walk over `base` and `target`, emitting context lines once and, at
464/// each change, the removed lines before the added ones. Ties break
465/// toward removal, which keeps a changed block reading as "these lines
466/// out, those lines in" rather than interleaving the two.
467fn diff_lines(base: &str, target: &str) -> Vec<TextDiffLine> {
468 let base: Vec<&str> = base.lines().collect();
469 let target: Vec<&str> = target.lines().collect();
470 // lcs[i][j] = the common-subsequence length of base[i..] and
471 // target[j..], filled bottom-up.
472 let mut lcs = vec![vec![0usize; target.len() + 1]; base.len() + 1];
473 for i in (0..base.len()).rev() {
474 for j in (0..target.len()).rev() {
475 lcs[i][j] = if base[i] == target[j] {
476 lcs[i + 1][j + 1] + 1
477 } else {
478 lcs[i + 1][j].max(lcs[i][j + 1])
479 };
480 }
481 }
482 let mut lines = Vec::new();
483 let (mut i, mut j) = (0, 0);
484 while i < base.len() && j < target.len() {
485 if base[i] == target[j] {
486 lines.push(TextDiffLine::Context(base[i].to_owned()));
487 i += 1;
488 j += 1;
489 } else if lcs[i + 1][j] >= lcs[i][j + 1] {
490 lines.push(TextDiffLine::Removed(base[i].to_owned()));
491 i += 1;
492 } else {
493 lines.push(TextDiffLine::Added(target[j].to_owned()));
494 j += 1;
495 }
496 }
497 lines.extend(
498 base[i..]
499 .iter()
500 .map(|line| TextDiffLine::Removed((*line).to_owned())),
501 );
502 lines.extend(
503 target[j..]
504 .iter()
505 .map(|line| TextDiffLine::Added((*line).to_owned())),
506 );
507 lines
508}
509
510// --------------------------------------------------------------------- //
511// Admission resolution (R0.11 Extension Plane, wave 2)
512// --------------------------------------------------------------------- //
513
514/// Which pointer slot admitted the candidate at resolution: the
515/// full-traffic `active` version, or the `canary` when the seeded draw
516/// ([`canary_admits`]) admitted this run. Journaled on every
517/// [`ConfigResolution`] — the difference between "the run served the
518/// promoted version" and "the run served the experiment" is exactly the
519/// evidence an audit of a canary's blast radius reads.
520#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
521#[serde(rename_all = "snake_case")]
522pub enum PointerBinding {
523 /// The pointer's full-traffic candidate.
524 Active,
525 /// The pointer's canary candidate, admitted by this run's seeded draw.
526 Canary,
527}
528
529/// A journaled admission resolution (R0.11 wave 2): the answer to one
530/// named registry artifact a run declared at submission, recorded as the
531/// output of a
532/// [`RunEventKind::ConfigResolved`](crate::record::RunEventKind::ConfigResolved)
533/// event at admission. This is the link that lets a manifest's content
534/// *digest* pin reach the *version* it resolved from — the
535/// [`CapsuleResolution`](crate::capsule::CapsuleResolution) precedent
536/// (version string → content address) applied to configuration
537/// (content digest → candidate).
538///
539/// The walk it closes: the run's signed receipt commits the manifest
540/// digest; the manifest pins `digest`; this event names the `surface`,
541/// `tag`, and `candidate_id` the digest resolved from; the candidate
542/// carries its author, evaluation, and promotion approver. Every hop is
543/// signature-covered — the resolution event sits inside the journal the
544/// receipt's head signs.
545#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
546pub struct ConfigResolution {
547 /// The artifact resolved: its registry key, the **untagged** surface
548 /// (`prompt:system`). The tag travels separately so the two facts —
549 /// which artifact, which environment — read without string surgery.
550 pub surface: SurfaceKey,
551
552 /// The environment tag the run resolved under (`prompt:system@prod`).
553 /// Absent when the run resolved the untagged surface — either it
554 /// declared no environment and the deployment declares no default
555 /// tag, or (deliberately) the artifact is governed untagged. Absent
556 /// is a fact, never a guess: the deployment's declared default tag is
557 /// configuration, not something the run invents.
558 #[serde(default, skip_serializing_if = "Option::is_none")]
559 pub tag: Option<EnvironmentTag>,
560
561 /// The candidate the pointer bound — the exact version the run
562 /// pinned, reproducible at audit from this id alone (candidates are
563 /// content-addressed: the id *is* the integrity check).
564 pub candidate_id: CandidateId,
565
566 /// Which pointer slot admitted the candidate.
567 pub pointer: PointerBinding,
568
569 /// The content digest the run's manifest pins for this artifact —
570 /// exactly what `RunManifest::pin_prompt` (SHA-256 of the prompt
571 /// text), `pin_tool_schema` (canonical-JSON digest of the schema),
572 /// or `pin_model` (canonical-JSON digest of the parameters) records.
573 /// The digest ↔ version join, journaled: equal digests under
574 /// different candidate ids cannot exist (content addressing), so
575 /// this field is the receipt walk's hinge.
576 pub digest: String,
577
578 /// The model identifier the manifest pins alongside the parameters
579 /// digest — present exactly for `model_settings` resolutions (the
580 /// manifest's `model` slot is an identifier, not a digest, and the
581 /// walk is incomplete without it).
582 #[serde(default, skip_serializing_if = "Option::is_none")]
583 pub model: Option<String>,
584
585 /// The resolved layer order — present exactly for
586 /// `middleware_composition` resolutions (R0.11 wave 4): the layer
587 /// names in the order the run's chain instantiated them. Ordering is
588 /// registry-aware in both directions — the artifact declares the
589 /// order, and this is the journaled evidence of the order that
590 /// actually served.
591 #[serde(default, skip_serializing_if = "Option::is_none")]
592 pub layers: Option<Vec<String>>,
593}
594
595/// The candidate a pointer binds for `run_id`: the canary when this
596/// run's seeded draw admits, else the full-traffic version. `None` when
597/// the pointer serves nothing — for registry artifacts there is no
598/// static fallback (that floor belongs to learned policy, where the
599/// pre-registry behavior is defined); an artifact with nothing promoted
600/// is unresolvable, and admission refuses the run rather than guessing.
601///
602/// The draw reads `pointer.surface` — the *tagged* key when the
603/// promotion was tagged — so the environment is part of the draw's seed
604/// material: a canary at `staging` and a canary at `prod` are
605/// independent draws over the same run id, and a recorded run
606/// re-derives its assignment from the journaled resolution alone.
607pub fn pointer_admission(
608 pointer: &VersionPointer,
609 run_id: &str,
610) -> Option<(CandidateId, PointerBinding)> {
611 if let Some(binding) = &pointer.canary {
612 if canary_admits(binding, &pointer.surface, run_id) {
613 return Some((binding.candidate_id.clone(), PointerBinding::Canary));
614 }
615 }
616 pointer
617 .active
618 .clone()
619 .map(|candidate_id| (candidate_id, PointerBinding::Active))
620}
621
622/// What the run's manifest pins for a resolved candidate: the content
623/// digest (and, for model settings, the model identifier) the R0.7 pin
624/// slots record. Computed from the candidate's content by the same rules
625/// `RunManifest`'s pin functions apply, so the journaled `digest` and
626/// the manifest's pin can never diverge — one derivation, two homes
627/// (the header and the journal).
628///
629/// Four families resolve: prompts, tool contracts, and model settings
630/// (the R0.7 digest slots), plus middleware compositions (R0.11 wave 4 —
631/// the release's one additive manifest field, the `middleware` digest).
632/// Every other kind is refused ([`RegistryError::UnresolvableKind`]) —
633/// executor policies bind through the checkpoint header's
634/// `policy_version`, tool permissions through the capsule machinery, and
635/// memory configuration pins in its own wave; pretending otherwise would
636/// fake coverage the manifest cannot express.
637pub fn resolution_pin(candidate: &Candidate) -> Result<(String, Option<String>), RegistryError> {
638 match &candidate.content {
639 crate::learn::CandidateContent::Prompt { prompt, .. } => {
640 Ok((sha256_hex(prompt.as_bytes()), None))
641 }
642 crate::learn::CandidateContent::ToolContract { schema, .. } => {
643 let bytes = serde_json::to_vec(&canonicalize_value(schema))
644 .map_err(|e| RegistryError::UndiffableContent(e.to_string()))?;
645 Ok((sha256_hex(&bytes), None))
646 }
647 crate::learn::CandidateContent::ModelSettings {
648 model, parameters, ..
649 } => {
650 let bytes = serde_json::to_vec(&canonicalize_value(parameters))
651 .map_err(|e| RegistryError::UndiffableContent(e.to_string()))?;
652 Ok((sha256_hex(&bytes), Some(model.clone())))
653 }
654 // The composition's pin is the canonical-JSON digest of its
655 // ordered layer list — the same rule `RunManifest::pin_middleware`
656 // applies, so the journaled digest and the header pin are one
657 // derivation. Array order is significant: a middleware layer
658 // order *is* the artifact, so the canonical form sorts object
659 // keys but never arrays.
660 crate::learn::CandidateContent::MiddlewareComposition { layers, .. } => {
661 let value = serde_json::to_value(layers)
662 .map_err(|e| RegistryError::UndiffableContent(e.to_string()))?;
663 let bytes = serde_json::to_vec(&canonicalize_value(&value))
664 .map_err(|e| RegistryError::UndiffableContent(e.to_string()))?;
665 Ok((sha256_hex(&bytes), None))
666 }
667 _ => Err(RegistryError::UnresolvableKind {
668 kind: candidate.kind(),
669 }),
670 }
671}
672
673// --------------------------------------------------------------------- //
674// Errors
675// --------------------------------------------------------------------- //
676
677/// The registry's typed refusals. A refused declaration, commit, or diff
678/// changes nothing — the [`crate::learn::LearnError`] discipline: refused
679/// operations are contract outcomes surfaced to the caller, never silent
680/// no-ops.
681#[derive(Debug, Clone, PartialEq, Error)]
682pub enum RegistryError {
683 /// An artifact name outside the naming rules (see
684 /// [`ArtifactRecord::new`]).
685 #[error("invalid artifact name {name:?}: {reason}")]
686 InvalidName {
687 /// The refused name.
688 name: String,
689 /// The rule it broke.
690 reason: &'static str,
691 },
692
693 /// A commit whose candidate is not the artifact's family.
694 #[error(
695 "candidate is `{candidate}` but artifact is `{artifact}` — a commit joins the \
696 artifact of its own family, never another's"
697 )]
698 FamilyMismatch {
699 /// The artifact's family.
700 artifact: CandidateKind,
701 /// The candidate's kind.
702 candidate: CandidateKind,
703 },
704
705 /// A commit whose candidate surfaces somewhere else.
706 #[error(
707 "candidate surfaces at `{candidate}` but the artifact is `{artifact}` — a commit \
708 joins the artifact its own surface names"
709 )]
710 SurfaceMismatch {
711 /// The artifact's surface.
712 artifact: SurfaceKey,
713 /// The candidate's surface.
714 candidate: SurfaceKey,
715 },
716
717 /// The candidate is already in this artifact's history.
718 #[error(
719 "candidate `{candidate_id}` is already committed to this artifact — a re-commit is \
720 the same fact, converged at the route; a second distinct commit needs a distinct \
721 candidate"
722 )]
723 DuplicateCommit {
724 /// The doubly committed candidate.
725 candidate_id: CandidateId,
726 },
727
728 /// A diff was requested against a candidate this artifact's history
729 /// does not contain.
730 #[error(
731 "candidate `{candidate_id}` is not committed to this artifact — a diff views two \
732 committed versions of one artifact, nothing wider"
733 )]
734 NotCommitted {
735 /// The candidate outside the history.
736 candidate_id: CandidateId,
737 },
738
739 /// A diff across kinds: two different contracts, not a view.
740 #[error(
741 "cannot diff `{from}` against `{to}` — a diff compares two versions of one \
742 contract; across kinds it compares two different contracts"
743 )]
744 DiffAcrossKinds {
745 /// The base candidate's kind.
746 from: CandidateKind,
747 /// The target candidate's kind.
748 to: CandidateKind,
749 },
750
751 /// An admission resolution was requested for a kind with no
752 /// content-digest slot in the run manifest (R0.11): prompts, tool
753 /// contracts, model settings, and middleware compositions (wave 4)
754 /// resolve; executor policies bind through the checkpoint header's
755 /// `policy_version`, tool permissions through the capsule machinery,
756 /// and memory configuration pins in its own wave.
757 #[error(
758 "`{kind}` candidates do not resolve into a run manifest at admission — prompts, tool \
759 contracts, model settings, and middleware compositions bind; the other families pin \
760 through their own surfaces (the checkpoint header, capsule manifests) or their own waves"
761 )]
762 UnresolvableKind {
763 /// The kind refused.
764 kind: CandidateKind,
765 },
766
767 /// A candidate's content could not be serialized for the structural
768 /// diff — unreachable for well-formed content, surfaced rather than
769 /// panicked (the `UnaddressableContent` precedent).
770 #[error("candidate content could not be diffed: {0}")]
771 UndiffableContent(String),
772}