diff --git a/docs/roadmap/library-upgrades.md b/docs/roadmap/library-upgrades.md new file mode 100644 index 0000000..75b9012 --- /dev/null +++ b/docs/roadmap/library-upgrades.md @@ -0,0 +1,397 @@ +# ConfigKit, PromptKit, And CommandKit Upgrades + +## Status And Recommendation + +Proposed, reviewed 2026-11-23 against Scriptorium commit +`857c0bae201bb5f9b5ffdcb20c4f5a0bddb00114`. This is an upgrade recommendation, +not an implementation plan or a record of implemented behavior. + +Adopt the latest released versions together, using ConfigKit's completed result +as the handoff to PromptKit and CommandKit's native integrations for operator +interfaces. Prefer a clean configuration migration over retaining the separate +framework-loading architecture. Expose native token/cost reporting and preserve +new definition features without building parallel application machinery. + +The main approval decision is the configuration cutover described below. It +changes the application format and inspection boundary, not just dependencies. +The recommended HTTP reporting additions are a smaller, separable decision. + +## Reviewed Releases And Sources + +Published tags were checked directly against each repository's `origin` using +`git ls-remote --tags`. The adjacent clean checkouts supplied release notes, +consumer contracts, public APIs, and change history. The newly published +ckprompt v0.12.0 tag was fetched and its released module metadata checked; +recommendations do not rely on the older checkout's draft dependency selection. +The web reader could not access the forge; Git supplied the release evidence. + +| Module | Current | Recommended | Full released source commit | +| --- | --- | --- | --- | +| `go.maximumdirect.net/configkit` | v1.2.1 | v1.4.0 | `4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3` | +| `go.maximumdirect.net/promptkit` | v0.23.3 | v0.25.0 | `207677e9948dc5699073a4d6620d21139033c72d` | +| `go.maximumdirect.net/commandkit` | v0.7.0 | v0.8.0 | `0b53a63648c536afe50c46f948159116f776adae` | +| `go.maximumdirect.net/ckconfig` | v0.9.0 | v0.11.0 | `cd5cf483a46caeff7ca0a91fb4747d57188a3888` | +| `go.maximumdirect.net/ckprompt` | v0.10.0 | v0.12.0 | `2422ccf02d6b55756b07f21e66a581202a09fc3f` | + +Review covers both intervening ConfigKit releases (v1.3.0 and v1.4.0), both +PromptKit releases (v0.24.0 and v0.25.0), CommandKit v0.8.0, and the corresponding +integration changes. Released ckprompt v0.12.0 already requires the four other +recommended versions. No unpublished API or local replacement is needed. +All retain Go 1.27.0 as their consumer minimum; Scriptorium's selected release +toolchain need not change solely for these upgrades. + +Primary release records: + +- ConfigKit [v1.3.0][ck130] and [v1.4.0][ck140]. +- PromptKit [v0.24.0][pk240] and [v0.25.0][pk250]. +- CommandKit [v0.8.0][cmd080], ckconfig [v0.10.0][cc100] and + [v0.11.0][cc110], and ckprompt [v0.11.0][cp110] and [v0.12.0][cp120]. + +## Current Baseline + +`internal/config` loads a strict application document through ConfigKit. Its +`promptkit` section currently selects an external `configuration` file and a +cwd-relative `schema_dir`; it does not contain PromptKit definitions. Runtime +conversion produces application settings, and the CLI adapter constructs an +engine through a second, PromptKit-owned load. Bundled OpenRouter definitions +are enabled by that constructor. + +Native `config` commands expose the application result and the separate engine +inspection. The CLI maintains application-acquisition evidence and decorators +to distinguish those two loads. Application-only inspection currently avoids +framework acquisition. Each comparison side loads independently. + +CLI execution submits one native `RunResult` to CommandKit; text writes exact +artifact bytes, structured output exposes upstream results, and an optional +separate report uses independent native formatting. HTTP uses application DTOs +and an opt-in terminal-event projection in `internal/report`. Those projections +currently omit the new reasoning and cost fields. The server constructs one +engine and shares its backend capacity accounting across requests. + +The accepted [definition-support boundary](../adr/0004-definition-boundary.md), +[ConfigKit boundary](../adr/0005-configkit-boundary.md), and +[native operator-interface decision](../adr/0006-adopt-commandkit-native-operator-interfaces.md) +support this upgrade direction. They do not require adopting workflow APIs or +every public library capability. + +## Upstream Changes And Adoption Assessment + +### ConfigKit + +v1.3.0 adds explicit secrets-directory startup helpers, main-file +`config.secrets_dir` / `config.secrets_overwrite`, and overwrite options. +Configured bootstrap returns a captured main source for the subsequent load, +preserving its filesystem context. It writes process environment variables; +partial writes survive a later failure. Ordinary loading consumes the controls +but never performs bootstrap itself. This is optional application startup work, +not a new automatic credential lifecycle. + +v1.4.0 supplies the key integration enablers: + +- `Result.Value(path)` returns current typed values without root-type knowledge, + conversion, or revalidation. Maps, slices, and pointers can alias the result. +- `Result.InspectSubtree(path)` exposes non-generic, frozen inspection with + redaction, historical paths, explanations, source catalogs, and resource + contexts. It can represent an absent scope. +- `Inspection.Diff` compares matching scopes, including across different root + types, using native snapshot comparison and paired redaction. Ancestor + differences remain possible; sequences remain atomic. + +These are additive APIs. Use them through PromptKit and ckconfig rather than +creating a Scriptorium configuration projection or provenance merger. Keep +resolved settings consistent with frozen evidence until engine handoff; this +requires ordinary ownership discipline, not a new generic deep-copy layer. + +Recommendation: adopt v1.4.0 now; defer explicit secrets bootstrap unless wanted +as a separate startup capability. PromptKit still resolves `api_key_env` at its +native preparation/execution lifecycle. Converting those names to ConfigKit +`Secret` fields would change that lifecycle and is not needed for this upgrade. + +### PromptKit + +v0.24.0 changes the configuration and schema boundary: + +- Public `Settings` can be embedded at application YAML key `promptkit`. + `Configure` composes native rules with application callbacks, defaults, + sensitivity, version policy, and sequence registrations. `NewFromConfig` + captures resources from the whole completed ConfigKit result without loading + again. Bundled defaults must be selected before that application load. +- Complete documents move resources and `schema_root` under `promptkit`. + `SettingsInput` and `CollectionInput` mount wrapperless fragments at their + native destinations. Discovery helpers themselves remain root-mounted. +- Output contracts support inline `schema`, source-relative `schema_file`, and + explicit-root `schema_path`; collections can own schema roots. Global + `Config.SchemaDir`, `WithSchemaFS`, and `WithSchemaFile` are removed. Schemas + are read during preparation and retained by prepared execution. +- `RunRequest.Validation` uses `*OutputContractInput`, whose pointer repair + budget distinguishes omission from zero. Enabled validation defaults to one + repair; `none` defaults to zero. Inspection returns a resolved integer budget. +- Prepared reports add opaque `message_content_hash` for ordered message roles + and exact text, independent of session/cache metadata. The existing + rendered-prompt hash is unchanged. +- Native configuration inspection focuses on `/promptkit` and exposes + `HistoricalPaths`, while retaining whole-load evidence and explicit queries. +- PromptKit no longer imposes resource-version policy. It retains extension + fields at settings, collection, backend, profile, and prompt boundaries; + nested PromptKit-owned objects remain strict. Input requirements inherited + from application defaults are now retained correctly. Capture and schema + handling also avoid unnecessary copying and provenance expansion. + +v0.25.0 adds execution and provider capabilities: + +- `WithExecutionObserver` carries invocation-scoped observation in context, + composing with explicit request observers. Prepared execution selects + contextual observers when executed, not when prepared. +- Backend `provider` explicitly selects `openai-compatible`, `openrouter`, or + `vllm`; blank/omitted uses the generic provider. IDs and endpoints do not + select conventions. Declared `zero_cost: true` is an optional fallback, + never an inferred property of local endpoints. +- Usage includes reasoning tokens and provider-specific cache fields, with + native presence-aware cache-hit ratios. Reasoning is included in completion + tokens; cache activity does not add to total tokens. +- `RunResult.CostUSD` and observations retain available USD subtotals, + completeness, and provider/configured-zero/mixed source information. Costs + include dispatched retries and repairs; result usage still sums successful + generation responses. Failure observations can retain cost without a result. +- Authentication diagnostics can use provider defaults, including `vllm_models`. + An endpoint-only authentication object is now valid; `kind: none` disables + authentication testing. Probes remain explicitly requested operations. + +Recommendation: adopt both releases' definition semantics and shared-load API. +Use native results/inspection for the new fields; do not write a local schema +resolver, cost estimator, repair controller, or provider-name heuristic. + +### CommandKit And Integrations + +Core v0.8.0 adds captured invocation features: application-wide flags, context +decoration, and final diagnostic reports. Features start after successful input +checks and finish after deferred messages, including on returned failure or +cancellation. Help, version, completion, and input failures skip startup. +`ErrHelpRequested` also supports help-only input checks. Registry validation +accounts for feature flag/alias collisions; invocation flag processing avoids +repeated owner partitioning and duplicated lookup maps. + +ckconfig v0.10.0 adds `FromConfigKitSubtree` and native path discovery through +`View.Paths`. v0.11.0 adopts core's help-only exemption for bare `config explain`. +Loading and validation cover the whole result even when rendering is focused. + +ckprompt v0.11.0 adopts shared loading, focused inspection, schema selections, +repair inputs, and message hashes. v0.12.0 installs native `--show-tokens` through +ordinary nonempty `Command` / `Declarations` assembly. It observes the invocation +context and produces a text token/cost summary on diagnostics, independently of +main `--format`; quiet suppresses it. It also forwards provider declarations, +reasoning/cache evidence, and changes automatic smoke output to a native text +template. Explicit JSON/YAML remain structured; smoke usage is separate from +ordinary run observation and its report does not acquire a cost field. + +Recommendation: retain existing native assembly and expose this capability +without wrapping `App.Execute`, installing a second accounting observer, or +adding a duplicate application flag. Preserve invocation context in PromptKit +calls. No selected-main-format accessor is needed for current output delivery. + +## Recommended Target State And Required Changes + +### One Application-Owned Configuration Load + +Replace the acquisition-only `PromptKitDocument` with public +`promptkit.Settings` at `Document.PromptKit`. Compose the existing application +definition with `promptkit.Configure`. Load through `configkit.LoadLayered` +using the existing selected file/search source as main, imports and overlay +selection, existing override records, and `promptkit.BundledOpenRouterUnderlay()` +as the lowest-priority underlay. Defaults-only startup remains supported. + +Pass the successful whole result to `promptkit.NewFromConfig`, supplying the +existing optional transient-retry setting through `RuntimeConfig` and the HTTP +artifact reader through its existing public option. Engine construction remains +the point where message-file content is captured; configuration inspection need +not construct an engine or read those messages. + +Retire `promptkit.configuration`, `promptkit.schema_dir`, the schema-directory +default, and their cwd-path normalization and runtime fields. External definition +files remain supported through native ConfigKit imports, with declared +destinations/placement for wrapperless fragments. This removes a special +Scriptorium source-selection mechanism; it does not require putting every +definition inline or flattening collection checkouts. + +Preserve source-relative context for imported message/schema references. Do not +rebase native resource references against cwd, widen filesystem roots, or copy +imports into generated temporary files. Preserve server-setting normalization, +HTTP limits, artifact-reader policy, namespace behavior, and shared engine pools. + +Apply a hard cutover with migration guidance, not dual loading or format aliases. +Because PromptKit retains extension fields, make retired acquisition selectors +clearly diagnosable during migration rather than silently claiming they still +load resources. Keep any such check narrowly about those retired selectors. +Retain ordinary upstream extension fields and existing credential restrictions; +do not introduce a blanket unknown-field ban within PromptKit's extension points. +In particular, `api_key` in a backend/profile extension is not an upstream +credential field and is not automatically protected: preserve Scriptorium's +existing raw-key boundary through application validation using public settings. +Do not redact `extra_params` as a whole or invent a new version requirement. + +### Native Views Of The Same Result + +Keep `config`'s `app` scope as the complete application result using +`FromConfigKit`. Expose the `promptkit` scope with `FromConfigKitSubtree` at +`configkit.Keys("promptkit")`, using the same loader, without requiring an +engine. Continue to use native ckprompt resource/preparation commands for +engine-derived information. Native `--set` may then address embedded PromptKit +settings wherever the scope's existing override capability permits it; do not +reintroduce application-specific inspection selector flags. + +Remove acquisition evidence transport/decorators that exist only to reconcile +the former two loads. Preserve native typed errors, findings, source catalogs, +and left/right comparison context. Emit diagnostics once for their real load, +not as independently generated application and framework evidence. + +The intentional operator change is that `app` inspection includes PromptKit +settings and validates the whole document. Invalid PromptKit settings can fail +an application inspection. The focused scope retains whole-load diagnostics and +explicit native queries, including outside `/promptkit`; ancestor differences +can survive focused comparison. Neither scope promises isolation. Each reached +comparison side still loads independently from its own selection, without +sharing mutable results or inheriting the other side's options. + +### Definition, Example, And Repair Migration + +Migrate maintained complete framework documents to `/promptkit`; adapt import +destinations for wrapperless fragments and collection entrypoints. Audit +`examples/`, test fixtures, preview scripts, overlays, and consumer guidance +together. Existing IDs, references, inheritance, and namespace selections keep +their upstream meanings; mounting does not rewrite references. + +Replace the old application schema base with explicit definition-owned roots or +source-relative files; prefer `schema_file` for independently portable prompts, +inline schemas when appropriate, and `schema_path` for deliberately shared roots. +All three modes and collection-specific roots must work through Scriptorium. +Do not install an implicit cwd root or local fallback search. Update any Go +request/fixture using the changed output-contract input type and use keyed +upstream struct literals where expanded structs affect compilation. + +Adopt upstream repair defaults rather than silently injecting zero. Explicit +`repair_attempts: 0` in existing maintained definitions continues to mean no +repair. Explain that omitted/null enabled budgets can add a generation, latency, +and cost and still return invalid output. Request replacements, where already +exposed upstream, resolve their own defaults. Existing CLI domain outcome versus +operational failure and HTTP completed-validation semantics remain distinct. + +Migrate application-defined OpenRouter backends to `provider: openrouter` when +those conventions are intended; do not infer that choice from endpoints. +Allow native `zero_cost` and vLLM declarations without app-side defaults or +provider allowlists. Update inspection paths to include `/promptkit` and allow +the native prepared message hash/schema evidence through unchanged. + +### Native Usage And HTTP Result Visibility + +Adopt ckprompt's `--show-tokens` with its native defaults, ordering, quiet and +help behavior. Preserve artifact-only CLI text output, native structured results, +and the independently formatted separate report; structured results acquire +native reasoning/cost fields without a Scriptorium report wrapper. Document the +changed automatic smoke representation and explicit structured alternatives. + +For HTTP, recommend adding `reasoning_tokens` to result usage and the opt-in +terminal usage projection, plus native-shaped `cost_usd` to success metadata and +terminal execution reports. Expose the terminal cache-hit ratio as a nullable +fraction derived by `ObservedTokenUsage.CacheHitRatio()`, not by guessing from +result zeros. Keep existing integer result usage distinct from presence-aware +terminal accounting. Retain cost `value`, `known`, `complete`, and `source` on +both success and failure paths where native evidence exists. + +The existing request-scoped observer can remain; contextual observation is not +mandatory for HTTP. Do not attach a server-global mutable group or aggregate +unrelated requests. Do not sum terminal and attempt totals, add reasoning/cache +counts to token totals, interpret unknown as zero, estimate prices, or claim +invoice accuracy. No HTTP request controls or broader HTTP redesign are needed +to expose these result facts. + +### Documentation, Licensing, And Verification + +Update the canonical configuration, CLI, HTTP (if selected), operations, +subprocess/migration, contributor, and internal documents with the implemented +changes. Update the architecture policy's current integration description and +versioned upstream links; accepted ADR decision text remains unchanged. Mark the +embedded-configuration direction in [future work](future.md) as delivered only +when its implementation lands. Other deferred directions remain separate. + +The five selected components' COPYRIGHT and LICENSE texts are unchanged from +their adopted baselines and remain LGPL-3.0-or-later. During implementation, +update their entries in `docs/oss/attribution.md` to the exact released commits +above and recheck the resolved runtime dependency graph. Reuse applicable local +license texts; graph-only maintainer tools do not become runtime dependencies +merely because they occur in upstream module metadata. This review adds no +copied third-party implementation or new licensing requirement. + +Validate the assembled integration, not upstream internals. Focus coverage on +shared-load imports/overlays and independent comparisons, native provenance and +redaction, all schema selection forms and collection roots, omitted versus zero +repair budgets, provider declarations, and request-scoped accounting on success, +failure, cancellation, retries, and repairs. Protect stream separation, quiet and +help-only behavior, independent report delivery, HTTP limits/reader containment, +and shared backend capacity using representative real-library integration tests +with controlled providers. Reuse existing coverage rather than duplicate upstream +format/accounting matrices. + +Run normal repository code validation and affected maintained examples during +implementation; default tests remain offline and credential-free. This review +did not upgrade modules or compile/test the proposed combination. A green build +against the old baseline would not establish upgrade compatibility. No new +release gates, live provider checks, tags, or publication are part of this work. +The proposed public configuration changes warrant a new Scriptorium minor +release under the existing pre-v1 policy; choose its number during release +preparation, not in this roadmap. + +## Open Decisions + +### Shared-Load Configuration Cutover + +**Recommendation:** approve the embedded-settings, single-load target above, +including whole-document application inspection and native imports in place of +`promptkit.configuration`. It realizes the previously deferred integration, +reduces custom evidence handling, and follows the adopted ownership boundaries. +Provide migration guidance without a legacy loader. + +**Alternative:** adopt the released dependencies using standalone `NewEngine`, +retain a separate external-file selector, and migrate only that file's format +and schema handling. This is viable and narrows the immediate application change, +but retains two resolution lifecycles and diagnostic plumbing while postponing +the most useful new integration API. It still requires the upstream breaking +format/default changes; it is not a dependency-only patch. + +### HTTP Accounting Additions + +**Recommendation:** include the additive reasoning/cost/cache visibility above. +The existing result and terminal-report projections otherwise discard useful +upstream evidence, especially known cost on failure. Keep the HTTP work limited +to those facts and update its canonical contract and strict-consumer guidance. + +**Alternative:** preserve the current HTTP response schema for this sprint and +deliver accounting only through native CLI reports. This reduces wire-surface +work and cleanly separates the deferred HTTP review, at the cost of knowingly +omitting newly available evidence for HTTP consumers. Definition support does +not itself require these response additions. + +### Configured Secrets Bootstrap + +**Recommendation:** defer explicit bootstrap for now. Existing deployments +supply environment variables, and native PromptKit credential timing remains +appropriate. Global environment writes require a deliberate startup policy, +particularly for inspection/comparison invocations; adopting the library alone +does not select one. + +**Alternative:** expose ConfigKit's configured-main bootstrap as an opt-in +startup capability. Use its returned captured source for the same subsequent +load, honor native overwrite controls, and handle partial failures without +logging contents. This helps file-provisioned deployments but needs a separately +agreed process-wide startup boundary so one comparison side's environment writes +cannot be mistaken for independent configuration resolution. Neither option +requires adding raw-key settings or changing PromptKit to typed ConfigKit secrets. + +[ck130]: https://forge.maximumdirect.net/base-layer/configkit/src/commit/652ddb649c60208dbba964f0ef919e36725c12c0/docs/releases/v1.3.0.md +[ck140]: https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/docs/releases/v1.4.0.md +[pk240]: https://forge.maximumdirect.net/base-layer/promptkit/src/commit/5ea60e9b96651fd7dfcbc7d05b6f43d131df358f/docs/releases/v0.24.0.md +[pk250]: https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/docs/releases/v0.25.0.md +[cmd080]: https://forge.maximumdirect.net/base-layer/commandkit/src/commit/0b53a63648c536afe50c46f948159116f776adae/docs/releases/v0.8.0.md +[cc100]: https://forge.maximumdirect.net/base-layer/commandkit/src/commit/eedbd83e7ea7be6a626755a63595f512ccd6fd15/integrations/ckconfig/docs/releases/v0.10.0.md +[cc110]: https://forge.maximumdirect.net/base-layer/commandkit/src/commit/cd5cf483a46caeff7ca0a91fb4747d57188a3888/integrations/ckconfig/docs/releases/v0.11.0.md +[cp110]: https://forge.maximumdirect.net/base-layer/commandkit/src/commit/54e951e38a404b4338c7967ac39c6c01159bf76d/integrations/ckprompt/docs/releases/v0.11.0.md +[cp120]: https://forge.maximumdirect.net/base-layer/commandkit/src/commit/2422ccf02d6b55756b07f21e66a581202a09fc3f/integrations/ckprompt/docs/releases/v0.12.0.md