Files
configkit/docs/roadmap/implementation.md

485 lines
28 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Implementation plan: absolute and parent-relative imports
Status: ready for implementation.
Planning baseline: `8c04dfd`; runtime baseline: `a441347`.
## Scope and execution
Implement the agreed end state in [absolute-imports.md](absolute-imports.md).
Read [development guidance](../development.md), [agents](../policy/agents.md),
[architecture](../policy/architecture.md), [testing](../policy/testing.md),
[documentation](../policy/documentation.md), and the release policy's
[compatibility definition](../policy/release.md#versioning-and-compatibility).
Use [the import contract](../config.md#explicit-imports) and
[import internals](../internal/imports.md) for behavior retained from the baseline.
Execute stages in order in one end-to-end sprint. Each stage is sized as one
focused Luna prompt. Intermediate stages need not compile; defer a focused
command until its dependencies are integrated rather than adding transitional
adapters or preserving two implementations. Private helper names are flexible;
the behavior and ownership choices below are settled.
This is an additive minor-release feature. Existing valid configurations,
explicit roots, resource coordinates and public signatures continue to work.
The relaxed implicit import boundary is intentional and must be documented.
Keep composition, precedence, version checks, source admission, budgets and
safe inspection on their existing owners. No new dependency, public switch,
automatic search, network provider, numeric budget, performance threshold or
release gate is required. Do not publish, push or tag a release during the
implementation sprint unless separately instructed.
## Concrete design and acceptance rules
### Separate import scope from the context's other roots
Extend the private resolved context with an optional import-containment root.
Keep the current `rootPath` meaning as the legacy resource/overlay/bootstrap
anchor, and `basePath` as the lookup base. An empty host import root denotes
unrestricted host imports; it is not a path to canonicalize or open. Native
imports retain the selected namespace root, including `.` for the full namespace.
Do not infer explicit containment merely because a resource root was resolved.
Persist the import policy with a captured main and copy it through derived
contexts. No additional public context fields are needed.
The following table defines host context resolution. Directory values are
canonical existing directories, with the baseline absolute-path validation
retained where applicable. A selected host file still rejects a supplied BaseDir.
| Input/context | Lookup base | Resource/legacy anchor | Import boundary |
| --- | --- | --- | --- |
| Selected host file, Root omitted | Canonical file directory | Same directory | None |
| Selected host file, explicit Root R | Canonical file directory | R | R |
| Bytes/reader/mapping, BaseDir B only | B | B | None |
| Bytes/reader/mapping, BaseDir B and Root R | B | R | R |
| NoSource or optional search exhaustion, BaseDir B only | B | B | None |
| Absent main, Root R only | R | R | R |
| Absent main, BaseDir B and Root R | B | R | R |
Synthetic host inputs still require BaseDir even for absolute-only declarations.
A supplied empty absent-main context establishes no working-directory default;
contextless NoSource remains valid under its existing lifecycle. An explicit
root must contain the selected file and base as today. A search that selects a
file follows the selected-file row; an invalid selected context is terminal.
Keep native Go context arguments and their validation unchanged, including the
existing synthetic-native base/root requirements.
For unrestricted host acquisition, use an unbounded mode in the existing
filesystem-access owner, dispatching to ordinary host filesystem operations.
Explicitly bounded host access continues to use its contained root handle;
native access continues borrowing its fs.FS. Do not open `/` as a new default
resource root, manufacture a boundary at the selected file's directory, or
retain a root handle per imported file. Overlay access must explicitly use the
legacy anchor, independently of the import mode.
### Selector resolution
- Host absolute selectors start at their host path; relative selectors start at
the declaring source's canonical directory. Synthetic and absent host contexts
use their selected base. Test absoluteness before joining; ordinary Join does
not provide the required selector dispatch.
- In YAML native selectors, leading `/` means the selected fs.FS namespace root.
Translate it to namespace-relative coordinates before filesystem calls.
Relative parent traversal uses the declaring source's namespace directory.
Paths must be addressable in that namespace and satisfy its selected root;
there is no host fallback. Existing Go constructor/context path syntax stays
slash-relative and follows fs.ValidPath.
- Share this distinction across path, directory and glob selection. Keep the
existing scheme/URL rejection and pattern grammar except for recognizing path
roots. Parse supported host volume roots before treating a colon as a scheme.
Preserve literal backslashes and wildcard escapes according to the existing
host/native conventions; do not turn every selector into a host filepath.
- Absolute glob roots and their longest literal prefix establish the starting
location before wildcard discovery. For Root `/etc/myapp`, the pattern
`/etc/myapp/fragments/*.yml` starts in the contained fragments directory;
`/` and `/etc` are resolution prefixes, not wildcard discovery targets.
The same distinction applies to native roots. Explicit-root containment still
governs the actual discovery directory and every subsequent traversal target.
- Keep segments after the first wildcard in traversal order. Expand `*` before
processing a following `..`; retain separate namespace spelling and physical
access coordinates under the current candidate model. Do not clean the whole
glob, skip matched-directory inspection, or suppress access errors through
premature normalization. A glob without wildcards follows named-target
requiredness/type behavior already used by glob selection.
- Preserve existing canonical host identity, normalized native namespace
identity, alias handling, candidate unions, admission and dependency scheduling.
Newly accepted absolute and relative spellings normalize into those existing
identities. Native link-target identities retain their current traversal role;
do not introduce inode identity or a new native alias contract.
- The new leading-slash interpretation is for YAML selectors. Preserve supplied
filesystem symlink-target interpretation, fs.ReadLinkFS capability handling,
discovered-link follow rules and native absolute-link rejection as currently
implemented. Host links can reach outside the old default directory when
imports are unbounded; explicit containment still applies to their targets.
### Resources and captured-policy compatibility
For a host source inside its context's legacy resource anchor, keep the same
rooted FS and relative BaseDir. For an unbounded external host import, use its
own canonical directory as its passive resource root and `.` as BaseDir. Imports
are still resolved using the load's import policy: the new per-source resource
root must not become a boundary on that source's transitive imports.
Synthetic/absent BaseDir-only sources use that base as their resource anchor.
Main-relative inputs inherit the main resource anchor and base coordinates.
Explicitly bounded host and native resource views retain baseline behavior.
Returned contexts remain passive and require no new close operation.
For an actual captured host main, retain canonical main path, base, resource
anchor and import boundary separately. Compatibility is:
| Capture | Later context | Result |
| --- | --- | --- |
| Unbounded, resource anchor D | None, or host context with Root omitted | Keep unbounded imports and D |
| Unbounded, resource anchor D | Root canonically equal to D | Apply explicit containment at D |
| Bounded at R | None, or host context with Root omitted | Keep containment at R |
| Bounded at R | Root canonically equal to R | Keep containment at R |
| Either capture | Different resource root, native FS, or supplied BaseDir | Existing incompatible-context option error |
Canonical aliases for an otherwise compatible root remain compatible. Do not
reopen or reselect the main to decide compatibility. Preserve existing behavior
after deletion or retargeting of its original filename. Absence does not create
a captured document or a new context-retention API.
Configured secrets bootstrap continues using the legacy anchor and its existing
relative-only directory declaration. Ordinary/layered overlay selection and
containment likewise continue using their established context anchors and lookup
locations. Import widening does not widen either facility.
## Stage 1 — Record the selected architectural change
Completed: recorded in [ADR 0026](../adr/0026-optional-host-import-containment.md)
and linked from ADR 0022's status.
Write ADR 0026 (or the next available number) as Accepted, recording optional
host import containment, namespace-root YAML selectors, and the separation of
import policy from resource/overlay/bootstrap anchors. Include the additive
compatibility intent and preserve the complete-on-return lifecycle.
Reference ADRs 0008, 0015, 0016, 0019, 0022 and 0023 as relevant. Describe selected
behavior directly; put rejected alternatives only in Alternatives Considered.
The inherited containment provision in ADR 0022 is revised by this decision:
update its status with a link explaining the partial supersession, preserving
the accepted decision text and its continuing context-selection rules. Leave
the configured-bootstrap decision intact.
Acceptance: the record states the agreed policy without adding a public
permission switch, sandbox promise, execution sequence or new approval gate.
## Stage 2 — Represent and validate independent context facts
Completed: resolved contexts now retain a separate import boundary; host
BaseDir-only contexts are accepted without changing native requirements or
selected-file base ownership. Focused context, filesystem and discovery tests pass.
Read `filesystem_context.go`, `filesystem.go`, `options.go`, `load_input.go` and
the context tables above. Add the private import-boundary state while retaining
the legacy anchor/base meanings. Update host selected, synthetic, absent and
search-exhaustion context resolution plus option validation to implement the
table. Separate host and native synthetic checks before allowing Root omission.
Audit directory validation and nil-context branches so an absent import bound
never reaches canonicalExistingPath or os.OpenRoot as an empty string. Continue
validating supplied contexts even when imports are disabled where baseline
contracts require it. Keep selected-file BaseDir rejection and native namespace
validation. Do not resolve a working directory for an empty context.
Add focused context cases in the existing filesystem/discovery owners for
BaseDir-only host synthetic and absent inputs, root-only absence, a base outside
an explicit root, and a search selecting a file versus exhausting with BaseDir.
Acceptance: the table is expressible without changing public signatures or
native Go context syntax. Runtime wiring can remain incomplete until later stages.
## Stage 3 — Add unbounded host filesystem access
Completed: the existing access owner dispatches unbounded host operations to the
OS, preserves namespace tokens and bounded/native access, and validates actual
anchor/base directories. The focused access, directory-read and cleanup test passes.
In `filesystem_access.go` and the access-opening path in
`filesystem_context.go`, add unbounded host operation dispatch to the existing
access object. Keep absolute host access names and namespace tokens; bounded
access translates contained names relative to its live root, native access
uses namespace-relative names, and unbounded access uses ordinary OS calls.
Update contains/stat/open/close and any root-relative assumptions needed for
regular file and directory reads. An unbounded context owns no root handle;
opened files and directories retain their normal cleanup. Retain the distinction
between missing initial directory opens and enumeration/close failures.
Keep nonregular preflight and post-open file checks in their existing owner.
Add narrow access/cleanup coverage using existing seams. Check the access
initialization in `acquireImportedWithAccess`: it must validate real base/anchor
directories, not stat an absent import-boundary path. Preserve tier host tokens.
Acceptance: host operations outside the legacy anchor are representable without
weakening explicit-root access or retaining handles in published metadata.
## Stage 4 — Integrate host link inspection with both access modes
Read `filesystem_links.go`, `filesystem_links_test.go`, `directory_walk.go` and
the regular-file tests. Update host import-entry inspection and link operations
to use the selected bounded/unbounded mode. Retain the shared iterative link
frame algorithm, active-cycle tracking and completed-target reuse. Extend its
coordinate handling only as needed to express host absolute roots; unbounded
resolution must not accidentally start from the process working directory.
Use ordinary host Lstat/Readlink operations for unbounded access. Resolve
absolute host link targets as host paths, including intermediate directory
links, while preserving follow behavior for the final discovered entry. Bounded
links retain canonical containment. Keep the native binding's existing link
target policy and capability-dependent behavior.
Cover contained and external host links, intermediate absolute links, final-link
follow=false, explicit-root rejection and active link cycles. Reuse FIFO and
cleanup coverage; no concurrent-filesystem attacker guarantees are added.
Acceptance: link and regular-file checks work in both host modes without a
second link-resolution framework or host fallback from a native namespace.
## Stage 5 — Parse selector roots and share literal path resolution
Read `directives.go`, `import_spec.go`, `import_selection.go` and `glob.go`.
Separate path spelling validation from selected-filesystem interpretation.
Accept new absolute spellings while preserving existing nonempty/string-set,
scheme rejection, declaration-site and selector-option validation. Keep root
information alongside glob segments instead of treating its leading slash as
an invalid empty segment.
Provide a shared private literal-selector resolution helper taking the selected
access/base. Absolute host paths bypass base joining; native leading-slash
selectors anchor at the namespace root; relative paths use the declared base.
Normalize native results into fs.ValidPath coordinates and retain outside-root
diagnostics for unaddressable or out-of-bound results. Recognize platform path
roots without introducing unrelated host spelling restrictions or changing Go
Source constructors. Leave wildcard segments uncleaned for stages 7–8.
Cover host absolute/parent-relative and native root/parent-relative spellings,
including explicit bounds, escaped literal names and the existing invalid input
classes. Acceptance: path and directory selectors can share one resolution rule;
native Go argument validation and native symlink target parsing remain separate.
## Stage 6 — Route named and directory imports through the shared resolver
Update `selectNamedImportCandidates` and `selectDirectoryImportCandidates` to
resolve each authored selector before candidate normalization. Preserve source
sites for list elements, candidate union/exclusion order, lexical selection
ordering, and canonical access identity separate from display spelling. Reuse
`validateNamedImportTarget`, directory traversal and shared admission rather
than constructing a parallel absolute-import acquisition path.
Trace `import_acquisition.go` and `acquisition.go` through transitive imports:
each acquired file uses its own directory as base while retaining its load's
import boundary and namespace. Avoid charging a source twice or creating a
fresh host token when paths cross directories.
Add behavioral path/list/directory cases outside the main directory and inside
an explicit root. Include optional missing versus required missing, unchanged
selection exclusions, transitive relative imports and absolute/relative repeats
and cycles. Native tests use a supplied filesystem; host path/link tests use real
temporary files. Acceptance: path and directory imports follow the target policy
end to end with existing diagnostics, version processing and accounting.
## Stage 7 — Establish glob roots and literal starting locations
Implement rooted glob initialization in `glob.go` using stage 5's root parsing
and literal resolution. Establish the longest literal starting directory before
the first wildcard, decoding literal escapes through the existing glob helpers.
If there is no wildcard, resolve and validate the complete named target through
the existing glob path. Preserve current grammar, including recursive-star
rules, and do not implicitly add recursive traversal.
Apply containment to the actual starting directory after resolving the literal
prefix. Absolute path ancestors preceding a contained explicit root are not
selected discovery directories. This does not authorize wildcard enumeration
outside an explicit root merely because a later match might reenter it.
Keep missing/required and inaccessible-prefix behavior consistent with existing
selection rules; no unrelated directories should be enumerated to reach a
literal prefix. Preserve component inspection within that prefix, including a
literal directory before `..`: a previously missing or inaccessible component
must not disappear through whole-prefix cleaning. Resolution prefixes may be
ancestors of the explicit root; that permission does not turn them into selected
discovery directories or suppress filesystem errors.
Cover host and native absolute globs whose literal prefix enters a multi-part
explicit root, an outside-root discovery directory, optional/required missing
prefixes, a missing literal component before `..`, and fully literal glob targets.
Acceptance: an explicitly bounded `/allowed/fragments/*.yml` reaches its contained
starting directory successfully.
## Stage 8 — Preserve wildcard traversal before parent normalization
Continue segment-by-segment traversal from stage 7's starting candidates.
Update literal-segment handling and `explicitGlobCandidate` so a `..` after
a wildcard advances from each inspected matched directory. Keep namespace
candidate spelling and physical access paths distinct, particularly for links.
Preserve `prepareGlobEntry` ownership of wildcard matching, hidden/follow policy,
link inspection and intermediate-directory eligibility.
Do not clean away wildcard/parent segments before inspection. Retain the
existing union, filtering and source-admission rules and directory-entry budget.
Reuse their sorting and traversal instead of duplicating them for absolute forms.
Containment remains enforced at the actual discovery/traversal targets, and
exclusions continue to leave discovery/access errors visible.
Add a focused wildcard-then-parent fixture with irrelevant/missing branches,
a matched directory inspection failure using an existing deterministic seam,
and representative link/boundary cases. Reuse existing glob grammar and policy
tests. Acceptance: `services/*/../shared/*.yml` preserves traversal and error
behavior rather than behaving like a prematurely cleaned literal path.
## Stage 9 — Produce passive contexts for external imported sources
Update `contextsForResolvedSources` in `source_context.go` to select a passive
root per source under the rules above. Keep the context anchor unchanged for
existing contained sources. External unbounded host imports use their own
canonical directory; synthetic/absent BaseDir-only contexts use their base;
native and explicit-root contexts retain their baseline roots.
Use existing rootedHostFS/rootedNativeFS wrappers. Returning a context performs
no resource read and retains no loading handle. Keep slash-relative BaseDir
coordinates and apply this behavior to contexts available during resolution,
successful results and supported failure inspection. The per-source passive
root must not constrain transitive import acquisition.
Cover a main and contained fragment retaining their old coordinates, an external
fragment reading its neighboring resource, a synthetic source's own context,
and an external fragment importing beyond its resource directory. Follow actual
origins to select contexts; do not infer ownership from the final YAML location.
Acceptance: admitted external imports no longer fail context construction.
## Stage 10 — Preserve main-relative binding and overlay behavior
Audit `acquireUnderlayGroupScopes`, `nativeTokenForLoadInput`,
`completeAcquisitionContexts`, `resolveOrdinaryOverlayFilesystem` and
`openSelectedOverlayAccess`. Derived inputs copy the selected namespace, import
boundary, resource anchor and base; only tier identity/main-source bookkeeping
changes as before. Explicit input contexts still override binding. BaseDir-only
fallbacks are usable after absence; optional contextless imports and RequireBase
retain their established behavior.
Overlay access must use a bounded view at the legacy context anchor. Ordinary
and explicit overlay lookup remain root-relative; derived/fallback layered
lookup retains its existing base-relative choice. Never substitute an unbounded
import root for an overlay lookup or access root. Preserve terminal selected-main
failures and inactive-overlay behavior.
Extend existing main-relative and overlay tests for unbounded main imports,
BaseDir-only fallback/optional exhaustion, root-only absent contexts, explicit
override and inherited resource coordinates. Reuse native and selected-overlay
repetition tests. Acceptance: broader imports work with discovered mains while
overlay paths and containment remain unchanged for existing valid loads.
## Stage 11 — Retain captured import policy without widening secrets bootstrap
Extend `capturedHostSource` and `captureHostMain` in `prepared_source.go` to
retain the separated policy. Implement the captured compatibility table in
`resolveCapturedFilesystemContext`. Preserve canonical main identity, captured
bytes/nodes and live later imports; preparation must not pre-acquire imports or
reselect the main. A later omitted Root keeps captured explicit containment,
while compatible explicit narrowing of an unbounded capture is applied.
Trace `loadSecretsFromConfig` and `secrets_from_config.go`: configured directory
bootstrap continues using the captured legacy anchor, not the optional import
boundary. Keep its relative-only YAML paths, overwrite precedence, separate
report, failure handling and explicit environment mutation. Absent preparation
retains existing NoSource behavior rather than inventing a captured document.
Test the capture table, including canonical root aliases, nil and empty later
host contexts, narrowing, incompatible roots, and original-main removal or link
retargeting. Add one public bootstrap-then-load case where imports can reach an
external file while bootstrap still obeys its original default/explicit root.
Restore environment changes and keep process-mutating tests nonparallel.
Acceptance: preparation preserves authored import intent, compatible old calls,
and the existing secrets contract.
## Stage 12 — Verify public lifecycle integration and minor compatibility
Use public facade tests for a representative externally imported fragment that
is mounted into a mapping or identified sequence, contributes an inherited
value, and supplies a relative resource reference. Reuse current lifecycle
fixtures instead of combining every optional feature in every case.
Check final values, source-local provenance, placement and history; obtain the
resource context through origins. Repeat one configuration with semantic
validation rejection and verify its frozen inspection reports the same retained
source values safely. Include a source-version case to establish that absolute
imports still go through normal version processing and source catalogs.
Keep existing valid configurations working across ordinary/layered loading,
discovery, native filesystems, explicit roots, synthetic contexts, overlays and
prepared sources. Move old tests that enforce implicit containment to explicit
roots where they still protect that contract; add positive default-scope cases
rather than deleting meaningful failure coverage. Preserve tests for unchanged
budgets, regular-file checks, namespaces, link capabilities and cleanup.
Acceptance: existing public signatures and boundary tests pass, old valid
fixtures remain accepted, and new path spellings use the normal lifecycle.
## Stage 13 — Demonstrate the feature with a maintained consumer example
Add a small example under `examples/consumers` showing a main file importing a
shared external file using an absolute path, plus a relative import declared by
that external file. Build the host paths from temporary fixture directories in
its test; do not depend on `/etc` contents, credentials or network access.
Demonstrate explicitly retaining containment with Root and using SourceContext
for a resource supplied by the external source. Use the existing consumer
example conventions and one representative behavioral test. Link a short YAML
illustration from consumer guidance rather than copying a whole application.
Acceptance: the example uses existing public APIs, loads once and proves both
the unrestricted default and intentional boundary without a new wrapper API.
## Stage 14 — Update canonical documentation and release handoff
Update Go declaration comments for FilesystemContext and affected import-facing
APIs without redefining the unchanged Go native-path format. Update
`docs/config.md` for selector roots, optional host import containment, synthetic
and absent contexts, prepared compatibility, passive resources and symlink
scope. Update `docs/internal/imports.md` and the component overview for actual
access/context responsibilities. Link the ADR and example from development and
consumer guidance. Adjust architecture policy only where its existing wording
needs the new distinction; preserve adopted upstream provenance.
Review stale blanket statements about imports staying beneath the main root,
absolute selectors being invalid, and synthetic host Root being mandatory.
Retain the separate current secrets and overlay contracts. Keep historical
release notes and accepted ADR decision text intact, apart from status links.
Include a release handoff in the final sprint report describing: an additive
minor release; new absolute and parent-relative selector support; the deliberately broader default import
scope; Root as the way to preserve containment; and compatibility of existing
valid configurations/resource coordinates. Version selection and writing the
version-matched note occur during the documented release preparation, not by
inventing a version or publication step here. Do not add release machinery.
Acceptance: current documents describe implemented behavior accurately and the
roadmap points to canonical owners after completion.
## Stage 15 — Validate and finish the sprint
Use installed compatible Go and explicitly acquired dependencies as described
in development guidance. Run focused commands as relevant after dependent
stages compile:
```sh
go test ./internal/engine -run 'Import|Glob|Filesystem|Captured|MainRelative|Resource|SecretsFromConfig'
go test . -run 'Import|Glob|Filesystem|Search|MainRelative|SourceContext|Secrets|Failure'
go test ./examples/consumers
```
Finish with `./scripts/check.sh` and `go test -race ./...` for the completed
ownership/context changes. Reuse successful checks on unchanged code; rerun
affected validation after later edits. No benchmarks, allocation thresholds,
additional platform gates, CI waiting or real-service checks are required.
Review the diff against the context/capture tables and every roadmap target.
Check changed local Markdown links, examples, terminal failure paths, handle
cleanup and public/dependency boundaries. Ensure only intended feature changes
are staged. Mark the plan and roadmap complete only after the integrated result
is validated; commit completed nonempty units with plain-English messages.
Report tests, remaining limitations and workspace status. Do not publish a
release or update downstream consumers as part of this sprint.
## Open Questions
None required for this scope. The adopted roadmap decisions and the mechanical
context/access/capture choices above settle the implementation direction.
Helper names, small private file splits and test organization remain normal
implementation choices, subject to the existing ownership and testing policies.