Skip to main content

memstead_base/
binding.rs

1//! Binding format **v2** — one record per pipeline.
2//!
3//! This is the **live** binding shape: [`crate::pipeline_store::load_pipeline_configs`]
4//! reads it (version-gated), the `projection` CLI tree writes it, and the
5//! resolve / brief / status / advance paths consume it. A v2 [`Binding`]
6//! alone fully defines a pipeline: intent, **inline sources** (each carrying
7//! what the retired standalone medium + facet records carried), reference
8//! mems, destination, deny paths, coverage semantics, and operations. The
9//! 2026-07 consolidation (operator directive, 2026-07-18) removed the
10//! three-file store: the engine reads only this format; `memstead projection
11//! migrate` converts prior generations, and there is no compatibility layer.
12//!
13//! Three things live here:
14//!
15//! 1. [`Binding`] — the versioned record: one file per pipeline, collapsing
16//!    the medium / facet / binding split into a single record with inline
17//!    [`Source`] entries and an `operations { build, sync, verify }` block.
18//! 2. [`hash_binding`] — `hash(D)`: the lowercase-hex SHA-256 of the
19//!    canonical JSON of the binding's *content-defining* projection.
20//!    Scheduling knobs (`trigger` / `batch_size` / `post_actions`, the
21//!    sync/verify blocks, prune) are excluded by construction; a source's
22//!    selection pattern or pointer changing — now inputs *inside* the one
23//!    record — changes the hash.
24//! 3. [`medium_capabilities`] + [`validate_binding`] — the medium-capability
25//!    matrix (the medium *half* of a source description keeps the medium
26//!    vocabulary) and the validation entry point: capability refusals,
27//!    in-record source validation (empty / duplicate source names), and the
28//!    preparation-registry check (a declared `preparation` must be one
29//!    [`crate::preparation`] knows, over a medium it can apply to).
30//!
31//! The findings store (`memstead_projection::findings`, the maintenance-loop crate above this one) keys on `hash(D)`, so the
32//! consolidation's shape change invalidates prior findings by construction —
33//! accepted and disclosed (findings are re-derivable measurements).
34
35use serde::{Deserialize, Serialize};
36use sha2::{Digest as _, Sha256};
37
38use crate::pipeline::{IngestTrigger, MediumType, PatternEntry, Source};
39
40/// The current binding format version. A v2 binding carries `version: 2`.
41pub const BINDING_VERSION: u32 = 2;
42
43/// The engine's current preparation-implementation version — the single
44/// source of truth for "which preparation implementation is live".
45///
46/// `3` since the code-map flavour (`code-map`, touchpoint A on path grains)
47/// landed; `2` was the delivery flavour (`dated-entries`, touchpoint B); `1`
48/// the first registered preparation (`entity-load-bearing`, see
49/// [`crate::preparation`]); `0` meant "none". It participates in
50/// [`hash_binding`] for every source: because the declared identifier and
51/// this version are both hashed, landing or changing an implementation
52/// invalidates every prior finding keyed on the old `hash(D)` by
53/// construction — the findings store keys on `hash(D)` alone, so the old
54/// batch is segregated as superseded and never mixed into the current view
55/// (pinned by `ingest::findings`'s
56/// `impl_version_bump_invalidates_findings_by_construction`). Bump it once
57/// per landed or changed implementation, never per registry entry that
58/// merely exists.
59pub const PREPARATION_IMPL_VERSION: u32 = 4;
60
61// ---------------------------------------------------------------------------
62// The v2 record
63// ---------------------------------------------------------------------------
64
65/// Coverage semantics — whether the binding claims to cover *everything* in
66/// its declared scope (`exhaustive`) or a deliberately partial slice
67/// (`curated`).
68///
69/// On the [`Binding`] record the field is **optional**: absent means "not
70/// stated", which is a different fact from "stated as exhaustive". The
71/// effective value is resolved per medium by
72/// [`effective_coverage_semantics`] — there is deliberately no `Default`
73/// impl, because a default is exactly the silence-as-assertion this
74/// design retired.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "lowercase")]
77pub enum CoverageSemantics {
78    /// Every artifact in scope is expected to be accounted for.
79    Exhaustive,
80    /// A deliberately partial selection — an unaccounted artifact is
81    /// information, not a defect.
82    Curated,
83}
84
85/// How a [`BuildOperation`] engages its binding. **`refinement` is deleted
86/// from the vocabulary** — it is neither a variant here nor migrated, so
87/// deserializing `"mode": "refinement"` fails as an unknown value.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "kebab-case")]
90pub enum BuildMode {
91    /// Build out new coverage.
92    Discovery,
93    /// A single bounded pass.
94    OneShot,
95}
96
97/// The **build** operation — the only operation carrying a mode. Grows new
98/// coverage (or runs a one-shot lens). `trigger` / `batch_size` /
99/// `post_actions` are scheduling attributes, excluded from [`hash_binding`].
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101pub struct BuildOperation {
102    /// Discovery / one-shot. The one operation with a mode.
103    pub mode: BuildMode,
104    /// What sets this operation running (loop / manual / on-event).
105    pub trigger: IngestTrigger,
106    /// How many artifacts a single run processes.
107    pub batch_size: u32,
108    /// Free-form post-run actions (e.g. a one-shot `archive_source` flag).
109    /// Opaque to the engine — consumed only by the one-shot brief renderer.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub post_actions: Option<serde_json::Value>,
112}
113
114/// The **sync** operation — the (future) sole maintenance writer. Optional: an
115/// absent `sync` block makes that *mutating* operation refuse at run time.
116/// Carries no mode.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118pub struct SyncOperation {
119    /// What sets a sync running.
120    pub trigger: IngestTrigger,
121    /// How many artifacts a single run processes.
122    pub batch_size: u32,
123}
124
125/// Default per-run tier-3 adjudication cap. Tuned against this project's own
126/// live `engine/graph` binding (524 source
127/// artifacts): a fully-drifted mem of that scale clears its adjudication backlog
128/// in ~11 verify runs while each run's asserted-drift work stays bounded and its
129/// token cost predictable. `0` disables the cap (adjudicate every candidate).
130pub const DEFAULT_ADJUDICATION_CAP: u32 = 50;
131
132/// Default `full_resync_every`:
133/// fire a guaranteed full-enumeration coverage sweep every N verify runs.
134/// Tuned against this project's own `engine/graph` (524 artifacts, sample batch 20 → a
135/// rotation completes in ~27 runs): a sweep every 20 runs guarantees a complete
136/// coverage picture without waiting on the rotation to happen to finish. `0`
137/// disables scheduled full walks (rotating sample only).
138pub const DEFAULT_FULL_RESYNC_EVERY: u32 = 20;
139
140fn default_adjudication_cap() -> u32 {
141    DEFAULT_ADJUDICATION_CAP
142}
143
144fn default_full_resync_every() -> u32 {
145    DEFAULT_FULL_RESYNC_EVERY
146}
147
148/// The **verify** operation — measurement. Optional: an absent `verify`
149/// block means engine defaults, never a refusal (verify has no mutating
150/// operation to gate). Mutates no entity, but records findings, backfills
151/// observed anchor hashes and writes a `#verified` baseline. Carries no mode.
152///
153/// `adjudication_cap` and `full_resync_every` are the tier-3 operations knobs:
154/// scheduling attributes on the
155/// measurement side only — like `trigger` / `batch_size`, they never change what
156/// the mem claims, so they are excluded from [`hash_binding`] (the whole
157/// `verify` block is). Both are additive: an older `verify` block without them
158/// deserializes to the defaults above.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct VerifyOperation {
161    /// What sets a verify running.
162    pub trigger: IngestTrigger,
163    /// How many artifacts a single run processes.
164    pub batch_size: u32,
165    /// Per-run tier-3 adjudication cap: the maximum number of hash-drift
166    /// adjudications a single verify run asserts. Once the cap is reached the
167    /// run **stops adjudicating** and queues the remaining drift candidates as
168    /// `queued-for-adjudication` findings (the tier-3 backlog the fidelity
169    /// report renders). Combined with the rotating sample, successive runs
170    /// adjudicate different windows, so the whole anchor set is covered over a
171    /// full rotation. `0` disables the cap. Defaults to
172    /// [`DEFAULT_ADJUDICATION_CAP`].
173    #[serde(default = "default_adjudication_cap")]
174    pub adjudication_cap: u32,
175    /// Scheduled full-enumeration walk cadence: every N verify runs, a full
176    /// coverage sweep enumerates the whole source set (`S(D)`) for **enumerable**
177    /// mediums, guaranteeing eventual complete coverage rather than relying on
178    /// the rotating sample to finish. For a medium the capability matrix marks
179    /// **non-enumerable**, the scheduled walk refuses with a typed signal — never
180    /// a silent skip, never a fabricated full-coverage claim. `0` disables
181    /// scheduled full walks. Defaults to [`DEFAULT_FULL_RESYNC_EVERY`].
182    #[serde(default = "default_full_resync_every")]
183    pub full_resync_every: u32,
184}
185
186/// The **prune** configuration of a [`Binding`] — additive, optional. An
187/// absent `prune` block means prune is not enabled for the binding (no deletion
188/// proposals are produced); a present block enables it. Prune produces
189/// **proposals** only: the source no longer holds the artifacts an entity
190/// describes, both sides are shown in the sync brief, and the agent acting on
191/// the brief decides. Prune has no independent schedule: it rides the sync
192/// brief (the sole maintenance-writer channel), so it carries no `trigger` /
193/// `batch_size`, and it carries no guarantee level either: a source artifact
194/// and the agent-authored entity about it share no common ancestor a merge
195/// could compare, so there is nothing for the engine to decide on the
196/// entity's behalf (see the prune module docs). Like the `sync` / `verify`
197/// blocks it is **excluded from [`hash_binding`]**: a maintenance policy never
198/// changes what the mem claims. The retired `guarantee` key of earlier
199/// records is ignored on read; every binding behaves as `conflict-flag`
200/// always did.
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
202pub struct PruneConfig {}
203
204/// The operations block of a [`Binding`]: every operation is **optional**.
205/// An absent `build` / `sync` block makes that *mutating* operation
206/// refuse at run time with a `projection enable <op>` remedy; an absent
207/// `verify` block means engine defaults (verify has no mutating operation to
208/// gate — never a refusal). `build` is optional in serde so an absent block yields the
209/// remedy-bearing refusal rather than a generic "missing field" parse error.
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211pub struct Operations {
212    /// The build operation (optional — absent = mutating op refuses with the
213    /// `projection enable build` remedy at run time).
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub build: Option<BuildOperation>,
216    /// The sync operation (optional — absent = mutating op refuses with the
217    /// `projection enable sync` remedy at run time).
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub sync: Option<SyncOperation>,
220    /// The verify operation (optional — absent = engine defaults, never a refusal).
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub verify: Option<VerifyOperation>,
223}
224
225/// Default `deny_paths` scaffolded onto a fresh enumerable
226/// (`codebase` / `filesystem`) binding: ordinary platform/tooling
227/// debris that would otherwise flood a first denominator. A default,
228/// not an invariant — the scaffold materialises the list into the
229/// binding record, so an author who wants one of these in scope
230/// deletes the entry and gets the files back; bindings created before
231/// the default existed keep their recorded (empty) list. Engine state
232/// (`.memstead/`, `.memstead.cache/`, mount storage) is NOT on this
233/// list — its exclusion is unconditional in the strategy layer, never
234/// a deletable record entry.
235pub const DEFAULT_SCAFFOLD_DENY_PATHS: &[&str] = &[
236    "**/.DS_Store",
237    "**/.git/**",
238    "**/node_modules/**",
239    "**/Thumbs.db",
240];
241
242/// A **binding**, format version 2 — one record per pipeline. The single
243/// versioned file at `projections/<mem>/<name>.json` that alone fully defines
244/// the obligation: `intent`, inline [`Source`] entries (each carrying the
245/// medium and facet halves the retired standalone records held),
246/// `reference_mems`, `destination_mem`, `deny_paths`, `coverage_semantics`,
247/// `rules`, `prune`, and the `operations { build, sync, verify }` block.
248///
249/// This is the live store record — [`crate::pipeline_store::load_pipeline_configs`]
250/// reads it version-gated and the `projection` CLI tree writes it.
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct Binding {
253    /// Format version — required. v2 is [`BINDING_VERSION`]. A projection file
254    /// without it (or with a prior version) is refused by the loader with a
255    /// typed error (`PROJECTION_STORE_LEGACY`).
256    pub version: u32,
257    /// What the binding is trying to accomplish — prose for the agent.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub intent: Option<String>,
260    /// The inline sources the binding consumes, in declaration order.
261    /// Each `name` is unique within the record and keys per-source state.
262    #[serde(default)]
263    pub sources: Vec<Source>,
264    /// Read-only reference mems that supply cross-mem context.
265    #[serde(default)]
266    pub reference_mems: Vec<String>,
267    /// The mem this binding writes into.
268    pub destination_mem: String,
269    /// Paths excluded from the binding's scope (workspace-relative globs).
270    #[serde(default)]
271    pub deny_paths: Vec<String>,
272    /// Whether the binding claims exhaustive or curated coverage.
273    /// Optional: `None` means **not stated** — a different fact from
274    /// "stated as exhaustive". Consumers never read this raw; they read
275    /// [`effective_coverage_semantics`], which resolves `None` per
276    /// medium (all sources enumerable → exhaustive; any non-enumerable
277    /// source → curated). An explicit `exhaustive` over a
278    /// non-enumerable source is refused by [`validate_binding`].
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub coverage_semantics: Option<CoverageSemantics>,
281    /// Free-form binding rules (e.g. a one-shot lens `routing` string).
282    /// Opaque to the engine — consumed only by the one-shot brief renderer.
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub rules: Option<serde_json::Value>,
285    /// The **prune** policy — additive, optional. Absent = prune disabled (no
286    /// deletion proposals). Present = prune produces deletion proposals in the
287    /// sync brief; see [`PruneConfig`]. Excluded from [`hash_binding`] (a
288    /// maintenance policy, not content-defining).
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub prune: Option<PruneConfig>,
291    /// The operations this binding declares (build required; sync/verify optional).
292    pub operations: Operations,
293}
294
295// ---------------------------------------------------------------------------
296// hash(D)
297// ---------------------------------------------------------------------------
298
299/// One source's content-defining projection, in a fixed serde shape so
300/// [`hash_binding`] hashes every content input. Private — the hash is the
301/// only consumer.
302#[derive(Serialize)]
303struct HashSource<'a> {
304    source: &'a str,
305    patterns: &'a [PatternEntry],
306    preparation: &'a Option<String>,
307    preparation_impl_version: u32,
308    medium_type: MediumType,
309    pointer: &'a str,
310    change_detection: &'a Option<String>,
311}
312
313/// The content-defining projection of a binding, in a fixed serde shape.
314/// Private — serialized to canonical JSON for hashing. Excludes `trigger`,
315/// `batch_size`, `post_actions`, and the `sync` / `verify` / `prune` blocks:
316/// scheduling and maintenance policy never change what the mem claims. The
317/// `engagement` slot is likewise excluded (an engagement contract shapes how
318/// an agent works, not what the mem claims — the pre-consolidation exclusion
319/// carried forward).
320#[derive(Serialize)]
321struct HashInput<'a> {
322    version: u32,
323    intent: &'a Option<String>,
324    sources: Vec<HashSource<'a>>,
325    reference_mems: &'a [String],
326    destination_mem: &'a str,
327    deny_paths: &'a [String],
328    coverage_semantics: CoverageSemantics,
329    rules: &'a Option<serde_json::Value>,
330    /// The build mode participates in `hash(D)`; an absent build block simply
331    /// does not contribute it (skipped from the canonical JSON).
332    #[serde(skip_serializing_if = "Option::is_none")]
333    build_mode: Option<BuildMode>,
334}
335
336/// Serialize a JSON value with **recursively sorted object keys** and no
337/// insignificant whitespace — the canonical form. serde_json's map is a
338/// sorted `BTreeMap` today; this rebuild makes the canonicalization explicit
339/// and robust even if the `preserve_order` feature is ever enabled build-wide.
340fn canonical_json(value: &serde_json::Value) -> String {
341    fn sorted(v: &serde_json::Value) -> serde_json::Value {
342        match v {
343            serde_json::Value::Object(map) => {
344                let mut keys: Vec<&String> = map.keys().collect();
345                keys.sort();
346                let mut out = serde_json::Map::new();
347                for k in keys {
348                    out.insert(k.clone(), sorted(&map[k]));
349                }
350                serde_json::Value::Object(out)
351            }
352            serde_json::Value::Array(items) => {
353                serde_json::Value::Array(items.iter().map(sorted).collect())
354            }
355            other => other.clone(),
356        }
357    }
358    serde_json::to_string(&sorted(value)).expect("canonical JSON serializes")
359}
360
361/// Compute `hash(D)` — the lowercase-hex SHA-256 of the canonical JSON of a
362/// binding's content-defining projection.
363///
364/// Hashed: `version`, `intent`, `sources` (per source: its name, selection
365/// patterns, preparation identifier + [`PREPARATION_IMPL_VERSION`], and its
366/// medium half's `type` / `pointer` / `change_detection`), `reference_mems`,
367/// `destination_mem`, `deny_paths`, `coverage_semantics`, `rules`, and
368/// `operations.build.mode`.
369///
370/// **Excluded:** `trigger`, `batch_size`, `post_actions`, the `sync` /
371/// `verify` / `prune` blocks, and each source's `engagement` contract —
372/// scheduling, maintenance policy, and engagement style never change what
373/// the mem claims. The v2 record needs no external resolution: every content
374/// input lives inside the one record, so a selection or pointer edit
375/// invalidates the hash — and thus any findings keyed on it — directly.
376pub fn hash_binding(binding: &Binding) -> String {
377    hash_binding_at_impl_version(binding, PREPARATION_IMPL_VERSION)
378}
379
380/// [`hash_binding`] under an explicit preparation-implementation version.
381/// The live hash is always [`PREPARATION_IMPL_VERSION`]'s; this exists so a
382/// caller can name the hash a prior engine generation keyed its findings on
383/// (the invalidation-by-construction pin, a migration report) without
384/// re-deriving the canonical projection.
385pub fn hash_binding_at_impl_version(binding: &Binding, preparation_impl_version: u32) -> String {
386    let sources: Vec<HashSource<'_>> = binding
387        .sources
388        .iter()
389        .map(|s| HashSource {
390            source: &s.name,
391            patterns: &s.scope,
392            preparation: &s.preparation,
393            preparation_impl_version,
394            medium_type: s.medium_type,
395            pointer: &s.pointer,
396            change_detection: &s.change_detection,
397        })
398        .collect();
399
400    let input = HashInput {
401        version: binding.version,
402        intent: &binding.intent,
403        sources,
404        reference_mems: &binding.reference_mems,
405        destination_mem: &binding.destination_mem,
406        deny_paths: &binding.deny_paths,
407        // The RESOLVED effective value, never the `Option`: a binding
408        // over enumerable sources that never declared the field keeps
409        // its pre-optionality hash byte-for-byte (resolved
410        // `exhaustive` == the old default), so its findings survive. A
411        // non-enumerable-source binding that declared nothing rehashes
412        // exactly once — correct, its asserted coverage genuinely
413        // changed.
414        coverage_semantics: effective_coverage_semantics(binding).value,
415        rules: &binding.rules,
416        build_mode: binding.operations.build.as_ref().map(|b| b.mode),
417    };
418
419    let value = serde_json::to_value(&input).expect("hash input serializes to a JSON value");
420    let canonical = canonical_json(&value);
421    let digest = Sha256::digest(canonical.as_bytes());
422    crate::hex_lower(&digest)
423}
424
425// ---------------------------------------------------------------------------
426// Medium-capability matrix + validation
427// ---------------------------------------------------------------------------
428
429/// What a medium can support — the row of the capability matrix for a
430/// [`MediumType`] (the medium *half* of a source description). Pure data;
431/// [`validate_binding`] reads it to refuse operations a medium cannot support.
432#[derive(Debug, Clone, Copy, PartialEq, Eq)]
433pub struct MediumCapabilities {
434    /// Can the medium's scope be enumerated (`S(D)` computable)?
435    pub enumerable: bool,
436    /// Does the medium provide a change signal?
437    pub change_signal: bool,
438    /// Can a base version be retrieved (for three-way merge)?
439    pub base_version_retrievable: bool,
440    /// The medium's anchor namespace (`path`, `path+commit`, `entity`, `url`).
441    pub anchor_namespace: &'static str,
442    /// Is a glob `deny_paths` list legal (i.e. is the namespace path-shaped)?
443    pub glob_deny_legal: bool,
444}
445
446/// The capability-matrix row for a medium type. The single source of
447/// truth the fidelity report also renders.
448pub fn medium_capabilities(medium_type: MediumType) -> MediumCapabilities {
449    match medium_type {
450        MediumType::Codebase => MediumCapabilities {
451            enumerable: true,
452            change_signal: true,
453            base_version_retrievable: true,
454            anchor_namespace: "path",
455            glob_deny_legal: true,
456        },
457        MediumType::Filesystem => MediumCapabilities {
458            enumerable: true,
459            change_signal: true,
460            base_version_retrievable: true,
461            anchor_namespace: "path",
462            glob_deny_legal: true,
463        },
464        MediumType::Git => MediumCapabilities {
465            enumerable: true,
466            change_signal: true,
467            base_version_retrievable: true,
468            anchor_namespace: "path+commit",
469            glob_deny_legal: true,
470        },
471        MediumType::Graph => MediumCapabilities {
472            enumerable: true,
473            change_signal: true,
474            base_version_retrievable: true,
475            anchor_namespace: "entity",
476            glob_deny_legal: false,
477        },
478        MediumType::Web => MediumCapabilities {
479            // Web enumeration / change detection / base retrieval are all
480            // not supported: a web source has no change signal.
481            enumerable: false,
482            change_signal: false,
483            base_version_retrievable: false,
484            anchor_namespace: "url",
485            glob_deny_legal: false,
486        },
487    }
488}
489
490/// The effective coverage of a binding plus its provenance — whether the
491/// value was declared by the author or resolved from the sources' media.
492/// The fidelity report renders the distinction; every other consumer
493/// reads only [`Self::value`].
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub struct EffectiveCoverage {
496    /// The coverage every consumer acts on.
497    pub value: CoverageSemantics,
498    /// `true` when the binding declared the field; `false` when the
499    /// value was resolved from the medium capabilities.
500    pub declared: bool,
501}
502
503/// Resolve a binding's **effective** coverage semantics. A declared value
504/// wins (validation has already refused an illegal `exhaustive`). An
505/// undeclared value resolves per binding, not per source: all sources on
506/// enumerable media → `exhaustive`; at least one non-enumerable source →
507/// `curated` — a mixed binding can only honestly claim the weaker of its
508/// parts, because coverage is an obligation of the binding as a whole
509/// (the artifact that is measured, reported, and keyed).
510pub fn effective_coverage_semantics(binding: &Binding) -> EffectiveCoverage {
511    if let Some(declared) = binding.coverage_semantics {
512        return EffectiveCoverage {
513            value: declared,
514            declared: true,
515        };
516    }
517    let all_enumerable = binding
518        .sources
519        .iter()
520        .all(|s| medium_capabilities(s.medium_type).enumerable);
521    EffectiveCoverage {
522        value: if all_enumerable {
523            CoverageSemantics::Exhaustive
524        } else {
525            CoverageSemantics::Curated
526        },
527        declared: false,
528    }
529}
530
531/// A binding operation subject to capability validation.
532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub enum Operation {
534    /// The sync (maintenance-write) operation.
535    Sync,
536    /// The verify (measurement) operation.
537    Verify,
538}
539
540impl Operation {
541    /// The lowercase name used in refusal messages.
542    fn name(self) -> &'static str {
543        match self {
544            Operation::Sync => "sync",
545            Operation::Verify => "verify",
546        }
547    }
548}
549
550/// A validation-time refusal: a capability the source's medium half cannot
551/// support, or a malformed in-record source declaration. Every refusal names
552/// the offending source so it is diagnosable without re-reading the store.
553#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
554pub enum CapabilityError {
555    /// A source has an empty `name` — the name keys per-source sync/verify
556    /// state, so it must be present.
557    #[error("a source has an empty name: every source names itself (the name keys its state)")]
558    EmptySourceName,
559    /// A scope pattern is not a compilable glob. Refused at validation so a
560    /// malformed pattern never reaches the enumerator, where an all-or-nothing
561    /// glob set turned one bad allow into an empty denominator and one bad
562    /// deny into no denies at all — both silently.
563    #[error(
564        "source '{source_name}' declares a scope pattern that is not a valid glob: \
565         '{pattern}' ({reason})"
566    )]
567    MalformedScopePattern {
568        /// The source declaring it.
569        source_name: String,
570        /// The pattern as written.
571        pattern: String,
572        /// The glob compiler's own reason.
573        reason: String,
574    },
575    /// Two sources in the record share a name — per-source state keys would
576    /// collide.
577    #[error(
578        "duplicate source name '{name}': source names are unique within a binding \
579         (they key per-source sync/verify state)"
580    )]
581    DuplicateSourceName {
582        /// The colliding name.
583        name: String,
584    },
585    /// A `sync` / `verify` operation is declared over a medium that cannot
586    /// support it (a `web` source has no change signal). The
587    /// out-of-scope statement is said out loud, never a silent mtime-over-URL.
588    #[error(
589        "operation '{operation}' is out of scope for source '{source_name}' over a '{medium_type}' \
590         medium: this medium has no change signal"
591    )]
592    OperationOutOfScope {
593        /// The offending operation.
594        operation: &'static str,
595        /// The source declaring it.
596        source_name: String,
597        /// The medium type that cannot support the operation.
598        medium_type: String,
599    },
600    /// A `graph` source's scope carries a pattern the entity-namespace
601    /// vocabulary does not define. Refused at declaration rather than
602    /// silently selecting nothing: a scope that looks like selection but
603    /// reaches nothing is the defect this rule exists to prevent.
604    #[error(
605        "scope pattern '{pattern}' on source '{source_name}' is not a legal entity selector: a \
606         graph medium selects entities, not paths — write '*' for the whole mem, \
607         'type:<entity_type>', or 'id:<glob>'"
608    )]
609    GraphScopeNotEntitySelector {
610        /// The source declaring it.
611        source_name: String,
612        /// The offending pattern, verbatim.
613        pattern: String,
614    },
615    /// A source's scope carries a pattern its medium has no vocabulary to
616    /// express at all, so nothing anywhere can interpret it. Distinct from
617    /// [`Self::GraphScopeNotEntitySelector`], which names the legal forms
618    /// because a legal form exists; here there is none, so the only honest
619    /// scope is no scope.
620    #[error(
621        "scope pattern '{pattern}' on source '{source_name}' cannot be interpreted: a \
622         '{medium_type}' medium has no scope vocabulary, so the pattern would select \
623         nothing while looking like selection — remove the scope rule"
624    )]
625    ScopeNotInterpretable {
626        /// The source declaring it.
627        source_name: String,
628        /// The offending pattern, verbatim.
629        pattern: String,
630        /// The medium with no scope vocabulary.
631        medium_type: String,
632    },
633    /// Glob `deny_paths` are declared over a medium whose namespace is not
634    /// path-shaped (`graph`, `web`) — a glob cannot select in that namespace.
635    #[error(
636        "glob deny_paths are illegal for source '{source_name}' over a '{medium_type}' medium: its \
637         '{anchor_namespace}' namespace is not path-shaped"
638    )]
639    GlobDenyIllegal {
640        /// The offending source.
641        source_name: String,
642        /// The medium type whose namespace is not path-shaped.
643        medium_type: String,
644        /// That medium's anchor namespace.
645        anchor_namespace: &'static str,
646    },
647    /// A source declares a preparation identifier the engine's preparation
648    /// registry ([`crate::preparation`]) does not know. The refusal is
649    /// exactly "not in this engine's registry": a registered identifier
650    /// validates clean, an unknown one refuses, and the message names the
651    /// registered set.
652    ///
653    /// Raised by [`validate_binding`], which the edit/validate paths call —
654    /// NOT `projection init` (which has no `--preparation` flag). The brief
655    /// renderer mirrors the same rule for a record that acquired an unknown
656    /// identifier by hand (accepted at rest, reported unsupported and
657    /// skipped at run time with exit 0; see `GLOSSARY.md` and
658    /// `crate::pipeline::Source::preparation`), so both refusal paths carry
659    /// one semantics and move together.
660    #[error(
661        "source '{source_name}' declares preparation '{preparation}', which is not in this \
662         engine's preparation registry (registered: {}; preparation impl version {impl_version})",
663        crate::preparation::registered_identifiers().join(", ")
664    )]
665    PreparationUnsupported {
666        /// The offending source.
667        source_name: String,
668        /// The declared preparation identifier.
669        preparation: String,
670        /// The current preparation-implementation version.
671        impl_version: u32,
672    },
673    /// A registered preparation is declared over a medium whose anchor
674    /// namespace admits none of the grains it prepares (`entity-load-bearing`
675    /// over a `codebase` source). It would never meet an anchor it applies
676    /// to, so the declaration is refused at validation rather than accepted
677    /// and silently never applying.
678    #[error(
679        "source '{source_name}' declares preparation '{preparation}' over a '{medium_type}' \
680         medium whose '{anchor_namespace}' anchor namespace admits none of the grains it \
681         prepares"
682    )]
683    PreparationGrainMismatch {
684        /// The offending source.
685        source_name: String,
686        /// The declared (registered) preparation identifier.
687        preparation: String,
688        /// The medium type it was declared over.
689        medium_type: String,
690        /// That medium's anchor namespace.
691        anchor_namespace: &'static str,
692    },
693    /// The binding declares `coverage_semantics: exhaustive` while at least
694    /// one source sits on a medium whose scope the engine cannot enumerate
695    /// (`web`) — `S(D)` is not computable, so exhaustive coverage cannot be
696    /// asserted over it. Refused at binding-validation time with `curated`
697    /// as the remedy. An *undeclared* field never trips this: it resolves
698    /// per medium via [`effective_coverage_semantics`].
699    #[error(
700        "coverage_semantics 'exhaustive' is unsupported for source '{source_name}' over a \
701         '{medium_type}' medium: its scope is not enumerable (S(D) is not computable), so \
702         exhaustive coverage cannot be asserted — declare 'curated', or omit the field to \
703         resolve per medium"
704    )]
705    CoverageExhaustiveUnsupported {
706        /// The offending source.
707        source_name: String,
708        /// The medium type whose scope is not enumerable.
709        medium_type: String,
710    },
711}
712
713/// Validate a binding against the medium-capability matrix and the in-record
714/// source rules, returning **every** refusal (empty `Err` never returned —
715/// `Ok` means clean). The v2 record needs no external resolution: everything
716/// validated lives inside the one record.
717///
718/// Refuses:
719/// - an empty or duplicate source `name`
720///   ([`CapabilityError::EmptySourceName`] /
721///   [`CapabilityError::DuplicateSourceName`]) — names key per-source state;
722/// - a declared `sync` / `verify` operation over a `web` source
723///   ([`CapabilityError::OperationOutOfScope`]);
724/// - a glob `deny_paths` list over a non-path-namespace medium
725///   ([`CapabilityError::GlobDenyIllegal`]);
726/// - a source preparation the engine's registry does not know
727///   ([`CapabilityError::PreparationUnsupported`]), or a registered one
728///   over a medium whose anchor namespace admits none of its grains
729///   ([`CapabilityError::PreparationGrainMismatch`]);
730/// - a declared `coverage_semantics: exhaustive` over a non-enumerable
731///   medium ([`CapabilityError::CoverageExhaustiveUnsupported`]).
732pub fn validate_binding(binding: &Binding) -> Result<(), Vec<CapabilityError>> {
733    let mut refusals = Vec::new();
734    let has_deny = !binding.deny_paths.is_empty();
735    let sync_declared = binding.operations.sync.is_some();
736    let verify_declared = binding.operations.verify.is_some();
737    let mut seen_names: Vec<&str> = Vec::new();
738    for source in &binding.sources {
739        if source.name.is_empty() {
740            refusals.push(CapabilityError::EmptySourceName);
741        } else if seen_names.contains(&source.name.as_str()) {
742            refusals.push(CapabilityError::DuplicateSourceName {
743                name: source.name.clone(),
744            });
745        } else {
746            seen_names.push(&source.name);
747        }
748
749        // A scope pattern must compile. Path-shaped mediums only: a graph
750        // source's scope entries are entity selectors, a different grammar
751        // with its own parser.
752        if !matches!(source.medium_type, MediumType::Graph | MediumType::Web) {
753            for rule in &source.scope {
754                if let Err(e) = globset::Glob::new(&rule.path) {
755                    refusals.push(CapabilityError::MalformedScopePattern {
756                        source_name: source.name.clone(),
757                        pattern: rule.path.clone(),
758                        reason: e.to_string(),
759                    });
760                }
761            }
762        }
763
764        let caps = medium_capabilities(source.medium_type);
765        let medium_type = serde_json::to_value(source.medium_type)
766            .ok()
767            .and_then(|v| v.as_str().map(str::to_string))
768            .unwrap_or_default();
769
770        // A declared preparation must be one the registry knows — the
771        // touchpoints consult the registry by identifier, so an unknown one
772        // could never be applied — and one that can apply over this medium's
773        // anchor namespace.
774        if let Some(prep) = &source.preparation {
775            match crate::preparation::lookup(prep) {
776                None => refusals.push(CapabilityError::PreparationUnsupported {
777                    source_name: source.name.clone(),
778                    preparation: prep.clone(),
779                    impl_version: PREPARATION_IMPL_VERSION,
780                }),
781                Some(registered)
782                    if !crate::preparation::applies_to_namespace(
783                        registered,
784                        caps.anchor_namespace,
785                    ) =>
786                {
787                    refusals.push(CapabilityError::PreparationGrainMismatch {
788                        source_name: source.name.clone(),
789                        preparation: prep.clone(),
790                        medium_type: medium_type.clone(),
791                        anchor_namespace: caps.anchor_namespace,
792                    });
793                }
794                Some(_) => {}
795            }
796        }
797
798        // sync / verify over a medium with no change signal (web) is out of scope.
799        if !caps.change_signal {
800            for (declared, op) in [
801                (sync_declared, Operation::Sync),
802                (verify_declared, Operation::Verify),
803            ] {
804                if declared {
805                    refusals.push(CapabilityError::OperationOutOfScope {
806                        operation: op.name(),
807                        source_name: source.name.clone(),
808                        medium_type: medium_type.clone(),
809                    });
810                }
811            }
812        }
813
814        // A scope rule must be one its medium's namespace can express. The
815        // engine used to accept any string here and interpret none of them,
816        // so `**/*` scaffolded onto a graph facet looked like scope and
817        // selected nothing. Refuse the undefined form at declaration.
818        //
819        // Checked for every medium whose namespace is not path-shaped, not for
820        // graph alone: `web` has no selector vocabulary either, and gating on
821        // one medium is how the class survived a round — fixed where it had
822        // been demonstrated and left standing one row over.
823        match source.medium_type {
824            MediumType::Graph => {
825                for rule in &source.scope {
826                    if crate::source_scope::parse_entity_selector(&rule.path).is_none() {
827                        refusals.push(CapabilityError::GraphScopeNotEntitySelector {
828                            source_name: source.name.clone(),
829                            pattern: rule.path.clone(),
830                        });
831                    }
832                }
833            }
834            MediumType::Web => {
835                for rule in &source.scope {
836                    refusals.push(CapabilityError::ScopeNotInterpretable {
837                        source_name: source.name.clone(),
838                        pattern: rule.path.clone(),
839                        medium_type: medium_type.clone(),
840                    });
841                }
842            }
843            MediumType::Codebase | MediumType::Filesystem | MediumType::Git => {}
844        }
845
846        // Glob deny_paths over a non-path-shaped namespace is illegal.
847        if has_deny && !caps.glob_deny_legal {
848            refusals.push(CapabilityError::GlobDenyIllegal {
849                source_name: source.name.clone(),
850                medium_type: medium_type.clone(),
851                anchor_namespace: caps.anchor_namespace,
852            });
853        }
854
855        // A declared `exhaustive` over a non-enumerable medium is refused —
856        // the engine cannot compute S(D) there, so the claim is unassertable.
857        // Fires only on what the author actually wrote (`Some(Exhaustive)`);
858        // an undeclared field resolves per medium instead of refusing.
859        if binding.coverage_semantics == Some(CoverageSemantics::Exhaustive) && !caps.enumerable {
860            refusals.push(CapabilityError::CoverageExhaustiveUnsupported {
861                source_name: source.name.clone(),
862                medium_type: medium_type.clone(),
863            });
864        }
865    }
866
867    if refusals.is_empty() {
868        Ok(())
869    } else {
870        Err(refusals)
871    }
872}
873
874/// What a caller wants scaffolded: one binding over one source. Everything
875/// else — deny defaults, the capability-matrix filter, the prune block — is
876/// the engine's to decide, so that every front door that scaffolds a binding
877/// scaffolds the same one.
878#[derive(Debug, Clone)]
879pub struct ScaffoldParams<'a> {
880    /// The mem the binding writes into — the `<mem>` half of the binding id.
881    pub destination_mem: &'a str,
882    /// The single source's `name` (unique within the record; keys per-source
883    /// state). Conventionally the binding stem.
884    pub source_name: &'a str,
885    /// The medium pointer — workspace-relative path, mem id, or URL.
886    pub pointer: &'a str,
887    /// The medium type, which decides the capability matrix.
888    pub medium_type: MediumType,
889    /// Intent prose for the agent, or `None`.
890    pub intent: Option<String>,
891    /// Deny globs to add beyond [`DEFAULT_SCAFFOLD_DENY_PATHS`], for a caller
892    /// that knows something about the tree the engine cannot infer. Materialised
893    /// into the record exactly like the defaults — visible, editable, deletable.
894    /// Engine state and mount storage locations never belong here: their
895    /// exclusion is unconditional in the strategy layer.
896    pub additional_deny_paths: Vec<String>,
897}
898
899/// A scaffolded binding, ready to write: the record, the operations it ended
900/// up declaring, and the warnings the caller must surface.
901#[derive(Debug, Clone)]
902pub struct ScaffoldedBinding {
903    /// The record to write.
904    pub binding: Binding,
905    /// The operation names the record declares, in `build, sync, verify` order
906    /// — the matrix may have stripped some.
907    pub operations: Vec<&'static str>,
908    /// Capability refusals the scaffold resolved by stripping an operation,
909    /// rendered for the caller's output. Never a failure: a scaffold that
910    /// declares less than asked says so rather than refusing.
911    pub warnings: Vec<String>,
912}
913
914/// Scaffold the default binding record for one source — the single
915/// definition of "a fresh binding", shared by every front door that creates
916/// one (`memstead projection init`, the guided `memstead quickstart` path,
917/// any embedder).
918///
919/// The record: one inline [`Source`] scoped `**/*` (a scoped default — an
920/// unscoped source refuses at run time), the enumerable-medium deny defaults
921/// materialised into the record (see [`DEFAULT_SCAFFOLD_DENY_PATHS`] for why
922/// they are recorded rather than injected), unstated `coverage_semantics`
923/// (the scaffold asserts nothing), and `build` + `sync` + `verify` filtered
924/// through the capability matrix — a `web` source loses sync/verify and the
925/// deferral rides `warnings`. Prune is scaffolded wherever sync survived.
926pub fn scaffold_binding(params: ScaffoldParams<'_>) -> ScaffoldedBinding {
927    let ScaffoldParams {
928        destination_mem,
929        source_name,
930        pointer,
931        medium_type,
932        intent,
933        additional_deny_paths,
934    } = params;
935
936    let source = Source {
937        name: source_name.to_string(),
938        medium_type,
939        pointer: pointer.to_string(),
940        change_detection: None,
941        // Scope is medium-shaped. A path glob over a graph source is not a
942        // narrower scope — it is an uninterpreted string: nothing anywhere
943        // matches globs against entity ids, so `**/*` scaffolded a facet that
944        // looked scoped and selected nothing. The graph namespace gets its own
945        // whole-mem selector; every path medium keeps `**/*` byte-for-byte.
946        //
947        // `web` gets no scope rule at all. Its namespace is `url`, nothing
948        // enumerates it, and no selector vocabulary exists for it — so any
949        // pattern scaffolded here would be decorative in exactly the way the
950        // graph glob was, and the brief would print it at an agent as
951        // selection. An absent scope is the honest scaffold: it renders as
952        // unmonitored rather than as a scope that reaches nothing.
953        scope: match medium_type {
954            MediumType::Graph => vec![PatternEntry {
955                path: "*".to_string(),
956                mode: crate::pipeline::PatternMode::Allow,
957            }],
958            MediumType::Web => Vec::new(),
959            _ => vec![PatternEntry {
960                path: "**/*".to_string(),
961                mode: crate::pipeline::PatternMode::Allow,
962            }],
963        },
964        engagement: None,
965        preparation: None,
966    };
967
968    let mut deny_paths: Vec<String> =
969        if matches!(medium_type, MediumType::Codebase | MediumType::Filesystem) {
970            DEFAULT_SCAFFOLD_DENY_PATHS
971                .iter()
972                .map(|s| s.to_string())
973                .collect()
974        } else {
975            Vec::new()
976        };
977    for extra in additional_deny_paths {
978        if !deny_paths.contains(&extra) {
979            deny_paths.push(extra);
980        }
981    }
982
983    let mut binding = Binding {
984        version: BINDING_VERSION,
985        intent,
986        sources: vec![source],
987        reference_mems: Vec::new(),
988        destination_mem: destination_mem.to_string(),
989        deny_paths,
990        coverage_semantics: None,
991        rules: None,
992        prune: None,
993        operations: Operations {
994            build: Some(BuildOperation {
995                mode: BuildMode::Discovery,
996                trigger: IngestTrigger::Loop,
997                batch_size: 20,
998                post_actions: None,
999            }),
1000            sync: Some(SyncOperation {
1001                trigger: IngestTrigger::Manual,
1002                batch_size: 20,
1003            }),
1004            verify: Some(VerifyOperation {
1005                trigger: IngestTrigger::Manual,
1006                batch_size: 20,
1007                adjudication_cap: DEFAULT_ADJUDICATION_CAP,
1008                full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
1009            }),
1010        },
1011    };
1012
1013    let mut warnings: Vec<String> = Vec::new();
1014    if let Err(refusals) = validate_binding(&binding) {
1015        for r in &refusals {
1016            if let CapabilityError::OperationOutOfScope { operation, .. } = r {
1017                match *operation {
1018                    "sync" => binding.operations.sync = None,
1019                    "verify" => binding.operations.verify = None,
1020                    _ => {}
1021                }
1022            }
1023            warnings.push(r.to_string());
1024        }
1025    }
1026
1027    if binding.operations.sync.is_some() {
1028        binding.prune = Some(PruneConfig::default());
1029    }
1030
1031    let mut operations: Vec<&'static str> = vec!["build"];
1032    if binding.operations.sync.is_some() {
1033        operations.push("sync");
1034    }
1035    if binding.operations.verify.is_some() {
1036        operations.push("verify");
1037    }
1038
1039    ScaffoldedBinding {
1040        binding,
1041        operations,
1042        warnings,
1043    }
1044}
1045
1046#[cfg(test)]
1047mod scaffold_tests;
1048#[cfg(test)]
1049mod tests;