From 0778cfcfd1f395c6daa4d11f955f80ec1c48ec63 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sat, 5 Dec 2026 15:35:35 +0000 Subject: [PATCH] Plan inspection across configuration failures --- docs/roadmap/failed-load-inspection.md | 10 +- docs/roadmap/implementation.md | 328 ++++++++++++++++++ ...o-validation-inspection-feature-request.md | 38 ++ 3 files changed, 371 insertions(+), 5 deletions(-) create mode 100644 docs/roadmap/implementation.md create mode 100644 docs/roadmap/narratio-validation-inspection-feature-request.md diff --git a/docs/roadmap/failed-load-inspection.md b/docs/roadmap/failed-load-inspection.md index 7a8715f..253f449 100644 --- a/docs/roadmap/failed-load-inspection.md +++ b/docs/roadmap/failed-load-inspection.md @@ -113,9 +113,9 @@ alongside the acquired Inspection. This can include an earlier decoded candidate when a later CLI assignment fails, or a resolver's entry candidate when resolution fails. Availability follows the actual processing completed in that invocation. -During implementation planning, inventory failure exits and specify availability -at each existing checkpoint. Earlier acquisition and parsing failures may have -diagnostics/source evidence alone. This approach reuses existing checkpoints; +The [implementation plan](implementation.md) specifies the checkpoint inventory, +public stage representation, failure-exit selection and execution order. Earlier +acquisition and parsing failures may have diagnostics/source evidence alone. This approach reuses existing checkpoints; it does not require snapshots after every phase or a new partial-decoding or recovery framework. Do not label an earlier or incomplete snapshot as fully resolved, or fabricate omitted values and history. Absence of an inspection view @@ -174,5 +174,5 @@ protect unchanged behavior; avoid private-call-count or performance thresholds. Completion means a consumer can investigate rejected resolved settings through the ordinary inspection interface, see the stage and limits of any earlier -snapshot, and continue to receive the original failure diagnostics. Detailed -sequencing belongs in a subsequent implementation plan. +snapshot, and continue to receive the original failure diagnostics. The +[implementation plan](implementation.md) owns sequencing and verification. diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md new file mode 100644 index 0000000..ab545bf --- /dev/null +++ b/docs/roadmap/implementation.md @@ -0,0 +1,328 @@ +# Implementation plan: inspect failed configuration loads + +Status: ready for implementation; no stages implemented by this document. +Baseline: `5e0f406`, with runtime behavior at `4a7ae66`. + +## Scope and execution + +Implement [failed-load-inspection.md](failed-load-inspection.md). Invalid +configuration has the same inspection interface as valid configuration; the +error remains authoritative about processing/validation outcome. Implement stages +in order as one end-to-end sprint for a Luna coding agent. Intermediate stages +need not compile. No temporary compatibility framework is needed. + +Read [development guidance](../development.md), [agents](../policy/agents.md), +[architecture](../policy/architecture.md), [testing](../policy/testing.md), and +[documentation](../policy/documentation.md). Follow current contracts for +[inspection](../config.md#layered-metadata), [failures](../config.md#results-and-failures), +and [ownership](../config.md#completion-and-resource-lifetime). +The original Narratio request is background; the roadmap incorporates the user's +subsequent decisions. This plan does not change composition, callback contracts, +source-version policy, the public load signatures, or nil Result returns on error. + +Keep exported types root-owned. Share engine history, classification, rendering, +comparison and source conversion mechanisms. No new dependencies, global caches, +background work, load mode, reload, callback retry, permissive decoding, or +publication gate is needed. Existing error messages/codes and diagnostic ordering +continue to apply. Inspection is reporting access; this addition does not expose +typed Config through errors or establish a general prohibition on doing so. + +## Selected API and checkpoint semantics + +Add these root declarations (engine equivalents remain private to consumers): + +```go +func (e *LoadError) InspectSubtree(path Path) (Inspection, bool) +type InspectionStage string +func (i Inspection) Stage() InspectionStage +``` + +Use named constants `InspectionStageMain`, `InspectionStageComposed`, +`InspectionStageInherited`, `InspectionStageDecoded`, `InspectionStageOverridden`, +`InspectionStageResolved`, and `InspectionStageValidated`, with string values +`"main"`, `"composed"`, `"inherited"`, `"decoded"`, `"overridden"`, `"resolved"`, +and `"validated"`. The zero stage is `""` for an unavailable/zero view. Stage +identifies the represented checkpoint, not the error location or a substitute +for handling the load error. All scopes of one snapshot have the same stage. +Successful Result views report Validated. A resolved snapshot does not assert +successful secret lookup, final identity checking or validation. + +InspectSubtree mirrors the existing Result method: nil/zero errors, unavailable +snapshot or invalid Path return false; a valid absent scope succeeds. Preserve +canonical scope equivalence and all existing explicit-query behavior. Use the +existing Inspection methods for output, history, sources, SourceContext and Diff. +Comparison operates on represented frozen values at matching scopes regardless +of stage or load outcome; it does not compare diagnostic status. Preserve atomic +sequence/ancestor differences, paired redaction and cross-root-type support. + +Implement the following checkpoint selection for both Load and LoadLayered: + +| Failure or return point | Snapshot represented | +| --- | --- | +| Options, source acquisition/parsing, unsupported schema, or main strict-composition failure before a coherent main tier and schema exist | No configuration view; retain ordinary diagnostics/source evidence. | +| Main-only version rejection after successful main composition | Main. | +| Later underlay/tier/selected-overlay assembly failure | Last completed main tier (Main); do not present partially assembled peers as a completed tier. | +| Resource-context completion or sibling-inheritance failure after full tier composition | Composed. Context queries expose only contexts actually established. | +| Override preflight or typed-default/decode failure after successful inheritance | Inherited. No partial typed decode is presented. | +| CLI type/decode/assignment failure after a successful typed decode | Decoded; the original pre-CLI candidate, not a partially applied override batch. | +| Resolver error, unrecorded mutation, projection or auditing failure after successful CLI application | Overridden; the resolver-entry candidate, without failed callback edits. | +| Successful resolution followed by detachment, secret lookup, final identity, final validator or publication-detachment failure | Resolved, with completed recorded resolution evidence. | +| Successful load | Validated; existing successful snapshot behavior. | + +Advance to the next checkpoint on successful completion of that phase, even when +it has no selected work (for example, no inheritance or resolver). Main/Composed/ +Inherited describe source trees before typed defaults. Decoded and later describe +typed projections. With NoSource and no contributed document there is no raw-tree +checkpoint; successful defaults/decoding can still produce a typed snapshot, +including a null root. Preserve absence rather than invent an empty source tree. + +Only existing coherent candidates are eligible. A failed phase's partial state is +not substituted for its input checkpoint. The earlier source candidates above +require the established schema bindings for classification; this plan does not +add a second permissive schema parser for unsupported schemas. All errors retain +whatever source/diagnostic evidence the current API already returns. + +For every error during final Validate, including value, sensitivity and Secret +mutation, show the candidate supplied to that validator. Do not project mutated +callback data into the error view, invent its origins, or withhold the existing +snapshot merely because mutation was reported. Callback panics keep their current +behavior; this feature does not introduce panic recovery. + +Retained-history admission and existing source/projection limits still apply. +Count all roots retained by a returned inspection using the existing counter. +If a newer candidate cannot be retained, use an available earlier admissible +checkpoint where possible, with its actual stage; otherwise return no view. +Keep the original failure diagnostics, including any existing limit error. A +failure to prepare optional error inspection must not replace those diagnostics +or cause another load. No new numeric budgets or benchmark thresholds are added. + +## Stage 1 — Record the inspection-on-failure decision + +Write ADR 0025 (use the next unused number if another ADR has landed) recording +inspection independent of validation outcome, the error accessor, reuse of the +existing Inspection interface, and identified existing checkpoints. Record the +already approved decisions as Accepted. Keep discussion focused on ConfigKit; +alternatives belong in Alternatives Considered. Reference ADRs 0003, 0005, 0008, +0010 and 0024 as relevant. The comparison addition extends successful-load-only +eligibility without changing equality or redaction. Do not rewrite accepted ADR +decision text; the new record explains the extension. + +Acceptance: the decision describes selected behavior and rationale without +requiring approval again, execution sequencing, or unrelated safety guarantees. + +## Stage 2 — Add checkpoint state and share inspection finalization + +Read `internal/engine/load.go`, `load_result.go`, `diagnostic.go`, `secret.go`, +`inspection_view.go`, and the retained-node counter in `history.go`. + +Add engine checkpoint stage/state and optional frozen inspection ownership on +engine LoadError. Keep checkpoint acquisition separate from diagnostic collection +so ordinary early errors remain cheap. Add Stage to engine views; preserve the +existing root facade conversion boundary for Stage until stage 7 exposes it. + +Extract the non-generic inspection finishing work from publishLoadResult: +classification, source records, passive contexts, diagnostics and known +secret-reference reporting. Reuse it for successful and failed candidates. +Success must still detach validated typed data as today. Failure needs no typed +execution result and must not discard a frozen candidate if final detachment +fails. Classification must finish before any view becomes observable. + +Preserve existing conservative source-version sanitization on error catalogs. +Use the same error source catalog for LoadError.Sources/Source and its inspection +view; do not let incomplete candidate coverage unmask evidence from other acquired +sources. Preserve all source IDs, including sources whose data is not in the +selected checkpoint. Effective origins/history describe only the checkpoint. +Include only passive contexts actually acquired and established. + +Acceptance: shared finalization can produce a fully classified immutable engine +inspection independently of successful result publication. Nil/zero error and +view behavior stays safe. No raw credential values are retained. + +## Stage 3 — Support source-tree inspection history + +Read `load_input.go`, `history_model.go`, `history_source.go`, +`history_inheritance.go`, `load_metadata.go`, `metadata.go` and `explain.go`. +Extract the source/inheritance prefix construction currently embedded in +preparePostDecodeOverrideContext into reusable helpers. + +Build Main, Composed and Inherited error views from their actual document, +source applications, origins, overlay/sequence contribution evidence and, only +when completed, inheritance operations. Reuse existing producers and replay. +Set effective metadata from the represented tree, its real explicit contributions +and origins. The source-stage baseline is absent: do not run Defaults or invent +default-origin values. Source-version evidence follows existing consumption and +sanitization rules, not new configuration values inserted into the tree. + +Generalize history sealing so these prefixes can freeze without fabricating +pre/post-CLI or resolution checkpoints. Keep successful-load history ordering +unchanged. An unexpanded extends declaration can appear in a source-stage report; +its stage explains that inheritance is unfinished. Do not interpret controls +again while querying or rendering it. + +Ensure the shared classification sees represented paths, retained historical +shapes, tag-based sensitivity from the valid schema, the application predicate, +source-version evidence and completed inheritance dependencies. Final document +lookup indexes and historical path inventories must cover the represented tree. +Use the existing retained-node budget for these error histories too. + +Add focused engine tests for a source-stage view after inheritance/decode failure, +including raw input type mismatch, historical overlay displacement and tagged +container sensitivity. Verify no invented defaults, inheritance or decoding. + +## Stage 4 — Support decoded and resolver-entry history prefixes + +Refactor preparePostDecodeOverrideContext so a successful decoded candidate can +be inspected even when a later override batch fails. Reuse metadataFromDecoded, +source/inheritance prefix observation and the pre-CLI checkpoint. Do not add CLI +applications from a batch that failed assignment, even if some earlier loop +iterations assigned working values. Sources/diagnostics may still describe the +attempted flags under their current contracts. + +The completed post-CLI prefix is the Overridden checkpoint. Resolver errors use +its frozen entry evidence, not the partially modified typed object. Avoid +freezing or sharing a builder that successful resolution continues to mutate: +seal on the error path, or create a properly owned prefix using existing retained +payloads. The callback's own fixed entry metadata remains independent as today. + +Add engine tests for invalid CLI assignment after valid decoding, a resolver that +mutates then returns an error, and a resolver that fails the recorded-change audit. +Assert represented values, stage, CLI/source origins, history and absence of failed +callback edits. Keep successful resolution correspondence/history tests passing. + +## Stage 5 — Retain resolved candidates on final failures + +Wire the already prepared resolved history into error handling after resolution. +Complete classification through the Stage 2 owner before returning it on secret +lookup errors, final registered-identity failures, semantic rejection and +validator-mutation errors. Retain known successful SecretReferenceInfo only for +references actually resolved in this invocation, under existing semantics; +unresolved reference names remain configuration input, not resolved credentials. + +Validator errors, including invalid diagnostic paths and mutations to values, +dynamic classification or secret state, retain the pre-validator candidate. Do +not rerun the validator or use its mutated object to rebuild the snapshot. A +successful load retains its existing detached Config and Validated inspection. + +Add representative engine tests for each final-failure boundary and the successful +counterpart. Check existing diagnostic codes and nil Loaded return. Include +mutation combined with an ordinary semantic error to prove neither suppresses the +report. Reuse the normal success/error source handling rather than cloning it. + +## Stage 6 — Wire the earlier failure exits and enforce ownership/admission + +Walk executeLoadRequest and its ordinary/layered helpers against the table above. +Carry small checkpoint descriptors referencing existing candidate documents and +evidence. Preserve the last completed main tier across later tier/overlay errors, +and the composed tree across inheritance failure. Helpers returning an empty or +partially updated assembledInput must not overwrite the last coherent candidate. + +Materialize an error view only when returning the failure. Successful loads need +not build and retain full historical models for every earlier phase. Retain only +necessary existing candidate evidence; do not add a full tree copy per checkpoint +or a generic tracing/event framework. If a helper mutates a borrowed candidate, +provide the ownership separation needed to preserve that candidate before the +mutation; do not assume an input passed by value owns its node pointers. + +Keep classification/payloads consistent with the selected checkpoint. Existing +budget exhaustion can prevent a view or cause fallback to an earlier admitted +candidate; original diagnostics survive. Before returning, release library-owned +handles normally, drop working typed values and mutable builders from LoadError, +and retain only frozen reporting state and passive contexts. + +Add a table-driven engine lifecycle test covering the matrix's distinct boundaries +for ordinary and layered loads, including malformed early input with no view, +main-version rejection, layer failure, absent NoSource input, and budget failure. +Use existing narrow limit seams for deterministic admission cases. Preserve the +prior history-limit boundary before secret lookup and validation on success; +optional failure inspection must not execute hooks skipped by the original error. + +## Stage 7 — Expose the shared public inspection interface + +Add LoadError.InspectSubtree and the root InspectionStage declarations/Stage method +specified above. Convert stage values explicitly across the private boundary. +Reuse engine.NewInspectionView and existing root conversions; do not embed an +engine type publicly or construct a fake Result with no typed configuration. + +Document nil/zero errors, absent scopes and stage meanings beside declarations. +Result.InspectSubtree and LoadError.InspectSubtree must satisfy the same small +consumer-owned interface. Metadata, Sources, Source, SourceContext, Explain, +WriteExplanation, WriteEffective, HistoricalPaths and Diff retain their existing +view behavior. No separate reduced failure-view type or comparison mode is added. + +Add public tests for root/nested/absent/numeric scopes, nil/zero/no-snapshot errors, +Stage on successful and failed views, native queries outside a focus, and zero +view behavior. Verify errors.As still discovers LoadError with unchanged +Error/Diagnostics behavior and every failed load still returns a nil Result. + +## Stage 8 — Verify redaction and evidence parity across outcomes + +Use focused public fixtures to verify rendered values, metadata and history agree +for the same candidate accepted versus rejected by final validation. Exercise +representative underlay/import/overlay, inheritance, CLI and recorded-resolution +contributions without duplicating every existing combination test. + +Cover tagged and predicate-sensitive values, dynamic struct tags after resolution, +secret lookup failures and successful references, removed historical values and +source-version evidence. Use disposable canaries to prove no credential or +classified value appears in effective/historical/explanation/diff reports. Include +a sensitive pre-validator candidate whose validator removes classification or +changes secret state; inspection must retain the original classification. + +Compare accepted/rejected snapshots at equal scopes, including different root Go +types and different stages; structural values govern differences, not validation +status. Preserve existing paired sensitivity and ancestor/sequence behavior. +Mutate returned query records and callback-retained objects after return; reports +must stay detached/frozen. Check independent loads and passive source contexts +through failure, without keeping loading handles open or re-reading inputs. + +Run focused tests plus `go test -race ./...` when the ownership changes are complete. +Do not add timing, allocation thresholds, snapshots of incidental messages or +new security policy under the guise of tests. + +## Stage 9 — Demonstrate one-invocation diagnostic reporting + +Add a maintained example under examples/consumers and a small behavioral test. +Let an application validator reject an unsupported backend from an imported or +overlaid source. The example handles the error, obtains root/focused inspection, +and forwards show/explain through one reporting helper also accepting Result. +It displays the checkpoint stage and retains the diagnostics and failure status. + +The test verifies the rejected value and original source are inspectable, no +second load is needed, and later source/environment changes do not change the +saved report. Include an earlier-failure example showing the stage of the retained +candidate, or explaining absent inspection with the existing diagnostics. Keep +CommandKit/ckconfig and Narratio changes outside this repository and add no +consumer dependencies or copied downstream CLI infrastructure. + +## Stage 10 — Update owning documents and complete validation + +Update declaration comments and docs/config.md for failure inspection, +checkpoint availability/stages, source evidence and comparison eligibility. +Replace the architecture policy's categorical failure/no-usable-result wording +with the selected distinction between error status and inspectable evidence. +Preserve the synchronous cleanup and successful-result contracts. Link ADR 0025 +from development guidance and relevant architecture/inspection documents without +rewriting accepted ADR decisions. Update docs/internal/overview.md to describe +actual shared finalization and prefix ownership; link the maintained example +from docs/consumers/README.md and add a short README orientation link if useful. + +Remove stale successful-load-only descriptions where they contradict this +feature, including Inspection and Difference documentation; keep generic Diff[T] +restricted to successful Results with its existing signature. The new view Diff +compares snapshots independent of outcome/stage. Leave prior immutable release +notes unchanged. Mark the roadmap and this plan complete only after validation. +Do not publish a release or add new release gates during this sprint. + +Run `./scripts/check.sh` and reuse the successful full race run for unchanged +code, rerunning affected validation after subsequent production changes. Confirm +consumer examples and public/dependency boundaries pass. Review changed Markdown +links, stage descriptions, the checkpoint table and all nil-result error paths. +Audit the full diff for extra contracts, duplicate processing, unbounded retained +state, skipped redaction and hidden reloads. Commit validated nonempty units with +plain-English messages and report the final workspace state. + +## Open Questions + +None required for this scope. The public Stage representation and checkpoint +matrix above resolve the mechanical details left to implementation planning. +Private helper names and file boundaries remain implementation choices. diff --git a/docs/roadmap/narratio-validation-inspection-feature-request.md b/docs/roadmap/narratio-validation-inspection-feature-request.md new file mode 100644 index 0000000..70a79eb --- /dev/null +++ b/docs/roadmap/narratio-validation-inspection-feature-request.md @@ -0,0 +1,38 @@ +# Feature request from Narratio for inspection after failed validation + +## Consumer rationale + +When `narratio config validate` reports a problem, operators use `config show` +and `config explain` to see the resolved value and where it came from. For +example, a validator can report that `storage.backend` must be `local` or `s3`, +while the operator still needs to see the rejected value and find the import or +overlay that supplied it. Today, a semantic validation failure exposes +diagnostics and source records, but the inspection commands have no resolved +view to display. [ConfigKit results and failures](../config.md#results-and-failures) + +Narratio uses CommandKit’s `ckconfig` integration for configuration inspection. +Access to the failed load’s native inspection evidence would let that integration +answer these questions using the same values, provenance, and redaction rules +that apply to successful loads. Operators could investigate the exact selection +that failed in a single invocation. + +## Requested public API and behavior + +Preserve the failed-load contract. When an application’s `Definition.Validate` +rejects resolved settings, the load still returns a nil result and a +`*configkit.LoadError` with its diagnostics and source evidence. Make a +read-only inspection view of the resolved settings available alongside that +evidence. An optional accessor on `LoadError` would give consumers a way to +retrieve the view and distinguish its absence. + +- The view describes the configuration evaluated by the validator in that same + load, including applicable defaults, imports, overlays, overrides, and + recorded resolution. Reading the view is passive and requires no reload. +- Consumers can render the whole resolved document and inspect individual paths + with their values, origins, and available history. Use the existing inspection + path and presence semantics and apply the same redaction to current and + historical values. The view carries reporting data only. + [ConfigKit inspection and metadata](../config.md#layered-metadata) +- When loading stops before a safe resolved view is available, the accessor + reports its absence. Diagnostics and any source evidence remain available + through the existing error API.