Files
notarius/docs/roadmap/promptkit-architecture-discussion.md

406 lines
22 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.
# PromptKit Architecture Discussion
## Purpose And Status
Working notepad for reviewing the ownership boundaries in the
[PromptKit v0.23.2 adoption roadmap](promptkit.md). Work through the topics
below in order, recording questions, evidence, decisions, and follow-up work.
Items 1 and 2 record selected architectural directions. Detailed design,
read-only filesystem and schema decisions, and the remaining topics are still
under discussion.
Item 7 records the completed Audita comparison and its implications for the
remaining decisions.
The goal is to make Notarius fully PromptKit-native and adopt modern PromptKit
capabilities as fully as practical. Application ownership of a policy does not
necessarily require application ownership of its implementation. Evaluate
remaining machinery against this goal, including opportunities for upstream
features where PromptKit does not yet meet an application need.
No application changes have been implemented through this notepad. The adoption
roadmap still needs reconciliation with the selected direction; its adapter
preservation language is subject to this review. Significant changes to accepted
architecture need successor ADRs under the
[documentation policy](../policy/documentation.md#architecture-decision-records).
Current boundaries are described in [Architecture](../policy/architecture.md)
and [LLM Runtime Internals](../internal/llm.md).
## 1. LLM API And Diagnostic Boundary
**Discussion / decision:** Direction selected: remove the Notarius PromptKit
adapter and make the application fully PromptKit-native. Detailed design and
migration consequences remain to be worked through.
### Background And Intent
Notarius and related applications, including Audita, originally developed their
own LLM interfaces or used the OpenAI SDK directly. PromptKit emerged by
extracting their duplicated mechanics into a shared library. Notarius adopted
an early version and predates many of the library's modern capabilities.
The maintainer clarified that duplication of PromptKit capabilities, including
slight behavioral differences, does not reflect an intentional requirement for
an independent Notarius implementation. Existing wrappers, tests, and historical
decisions are migration evidence, not sufficient reasons to preserve that
duplication. Identify actual application needs before choosing what to retain.
Missing reusable capabilities may justify upstream feature requests. The
discussion is not constrained to what v0.23.2 can replace immediately; any
resulting change to the adoption target remains to be selected.
### Design Consequences To Work Through
- Use native PromptKit APIs and contracts for LLM execution instead of preserving
a parallel provider-neutral completion API or rebuilding the adapter under
another name.
- Review copied request, result, error, inspection, observation, and debug types
for removal. Keep application-owned representations only where they serve a
concrete application need, with compatibility decisions made explicitly.
- Let PromptKit provide reusable execution mechanics. Determine how Notarius
supplies domain inputs, interprets typed outputs, and expresses its acceptance
decisions through the resulting design.
- Review application composition, test seams, diagnostic storage, and disclosure
handling without assuming they require an LLM abstraction layer.
- Evaluate each upstream gap as a requirement to understand and potentially
address in PromptKit, rather than automatically preserving local machinery.
Open questions:
- What application collaborators and helpers remain after the adapter is removed?
- Which durable output or diagnostic contracts need deliberate migration?
- Which existing behavioral differences should disappear through native adoption,
and which reflect an application need that should be supplied to PromptKit?
**Follow-up:** Apply this direction to items 2–6, compare Audita under item 7,
and reconcile the adoption roadmap. Record the significant boundary change in
a successor ADR and update architecture and implementation documentation when
the change lands. Do not treat the remaining topics as decided by this direction.
## 2. Prompt Assets And Schema Assembly
**Discussion / decision:** Direction agreed: use native PromptKit declarations
as the sole prompt assembly mechanism and remove the duplicate application
assembly plumbing. Resolution of the custom read-only filesystem and schemas
is explicitly deferred; the next topic may clarify those choices.
**Selected direction:** Keep the embedded content tree and load its prompt and
profile definitions as native PromptKit configuration in the application
collection. Use native filesystem contexts and imports to reference shared
content directly. Application composition assembles the embedded and operator
sources once; modules select prompt IDs, supply domain inputs, and interpret
typed results.
The spell extractor illustrates the current duplication: its prompt YAML
declares ordered messages and a schema, while a separate Go asset manifest
lists files, mounts shared fragments, registers filesystems, and hashes them.
The selected direction makes native declarations the sole prompt assembly source.
Candidates for removal:
- Prompt and fallback-profile registration plumbing in `AssetRegistry` and
individual modules; schema responsibilities remain under review.
- `ModulePromptFS`, `PromptAssetManifest`, shared-name lookup tables, synthetic
`sharedassets` mounts.
- Manual prompt-file enumeration for fingerprints, replaced by captured native
prompt identities subject to the broader identity design in item 5.
Keep prompt prose, ordered messages, cache controls, workload profiles, private
response schema documents, and domain interpretation. Durable artifact schemas
remain separate. Content ownership does not require runtime asset registration.
Native schema paths resolve against the configured schema root, separately from
message-file source contexts. PromptKit v0.23.2 loads schemas during preparation
and requires self-contained schema documents. A captured prompt hash alone does
not establish schema equality. Existing schema metadata in manifests and
checkpoint inputs must be deliberately replaced or retired; its presence does
not require preserving the complete wrapper system.
Deferred decisions:
- Whether the custom read-only filesystem can be removed after reviewing its
remaining responsibilities.
- Schema assembly, root/path selection, wrapper removal, and schema metadata.
Supplying the embedded filesystem as a native schema root remains a candidate,
not a selected design.
- How schema identity contributes to manifests and checkpoint reuse.
Implementation questions:
- Can native sources represent the existing shared fragments and module assets?
- Which registry, remounting, and hashing helpers could disappear?
- What private schema identity is still needed for checkpoint reuse?
- How do we preserve message ordering and cache controls while simplifying
assembly?
**Follow-up:** Continue with item 3, then revisit the deferred filesystem and
schema decisions with any new clarity. Confirm native source contexts for shared
fragments and operator replacements. Resolve metadata and reuse identity with
items 5–6. Verify the resulting definitions through native preparation and
fake-provider execution; filesystem remounting tests can retire with the removed
implementation. The agreed direction has not yet been implemented.
## 3. Retry And Semantic Correction Ownership
Consider narrowing outer stage retries once PromptKit has exhausted its own
transport and structural-repair budgets. Notarius would retain application
assessment, semantic correction, fallback, and acceptance decisions.
Questions:
- Which operational failures justify repeating an entire stage?
- Should semantic correction preserve only the latest response or accumulate
conversation history?
- How should retries for non-LLM operations differ from LLM execution retries?
- Would a native orchestration API reduce machinery without obscuring typed
validation and terminal disposition?
**Discussion / decision:** Pending.
**Follow-up:** Evaluate behavior changes against
[ADR-0014](../adr/0014-feedback-aware-validation-retries.md) and
[ADR-0016](../adr/0016-feedback-aware-module-requested-retries.md).
PromptKit v0.23.2's `Coordinate` continues an exchange; it is not a direct
replacement for the existing latest-response-only policy or full stage loop.
The Audita review in item 7 demonstrates application-owned validation inside
native continuation coordination. Evaluate adopting that model on its merits;
the existing Notarius history policy is subject to reconsideration under item 1.
## 4. Global Scheduling And Admission
Consider whether backend capacity limits and pipeline worker bounds meet the
operational need, or whether a separate cross-backend ceiling remains useful.
If it remains useful, consider implementing that reusable mechanism upstream.
Questions:
- What resource or operational budget does each limit protect?
- Should a global permit remain occupied during backend queueing and repair?
- Can the Notarius scheduler be removed, or should PromptKit gain engine-wide
admission support?
**Discussion / decision:** Pending.
**Follow-up:** Account for the existing global-limit contract. PromptKit
v0.23.2's per-backend limits do not directly replace it.
## 5. Execution Identity And Checkpoint Reuse
Consider moving identity for PromptKit-owned execution semantics upstream.
Notarius would combine opaque upstream identities with its source, module,
reference, schema, and policy identities and retain checkpoint eligibility and
storage decisions.
Questions:
- Which identity can be computed before a stage runs, and which needs a concrete
prepared request?
- Which changes should invalidate reuse, and at what granularity?
- Should a conservative application fingerprint be an interim implementation
rather than the architectural destination?
- Does this justify upstream work and a later adoption target?
**Discussion / decision:** Pending.
**Follow-up:** Review PromptKit's deferred semantic execution-target fingerprint
proposal. This capability is not supplied by the v0.23.2 adoption target.
## 6. Inspection And Execution Bookkeeping
Extend the roadmap's use of native inspection, `Run`, `OnPrepared`, observations,
and `ExecutionGroup` to reconsider surrounding wrappers and copied report types.
Notarius retains stage correlation, artifact provenance, storage, and disclosure
policy; CommandKit is the planned owner of standardized operator presentation.
Questions:
- Which reports and accounting mechanisms can use upstream results directly?
- Which application projections remain necessary for durable contracts?
- Can the PromptKit migration avoid building temporary machinery that the
CommandKit adoption would immediately replace?
**Discussion / decision:** Pending.
**Follow-up:** Coordinate this topic with item 1 and the roadmap's CommandKit
follow-up so report and adapter decisions are made once.
## 7. Compare Audita's PromptKit Workflow
**Review status:** Completed on 2026-11-18 against the clean sibling checkout
`../audita`, revision `da5b8913d1206a8e8f0a784b2322760385548a60`.
Audita uses PromptKit v0.23.2, ConfigKit v1.2.1, CommandKit v0.7.0,
ckconfig v0.9.0, and ckprompt v0.10.0. These are observations of that revision,
not new Notarius contracts. The source links below assume the sibling checkout.
### Embedded Defaults And Operator Replacement
- One captured engine is assembled from PromptKit's default catalog, the
embedded Audita underlay, and a higher-priority operator underlay.
`FilesystemInputs` supplies eleven native prompt definitions in
`collections.audita`: four proposal prompts, four repair prompts, and three
validator prompts.
- Operator sources are optional `prompts.yml` and recursively selected YAML
under `prompts/`, anchored to the application main source's recorded context.
Both locations feed one operator underlay and are peers; conflicting peer
definitions fail rather than receiving filename-based precedence.
- Replacement is by resource identity, not filename. For example, a complete
prompt record with local ID `modules.grammar.repair` under
`collections.audita.prompts` replaces `audita/modules.grammar.repair` while
other embedded definitions remain available. Native same-ID replacement is
whole-record replacement, not recursive merging of individual prompt fields.
- Native imports and message-file context are retained. Tests show that an
existing engine retains captured message content after a file edit and a new
engine sees the edit. They also verify inherited message-file resolution,
main-relative discovery independent of the working directory, and peer
conflict rejection.
- A diagnostic embedded-only construction can classify a loading error; it
does not silently fall back to defaults after an operator-source failure.
Evidence: [runtime assembly](../../../audita/internal/framework/llm/runtime.go),
[source tests](../../../audita/internal/framework/llm/engine_sources_test.go),
and [assembly failure tests](../../../audita/internal/framework/llm/runtime_assembly_test.go).
### Prompt Content And Schema Ownership Are Separate
Audita uses ordinary embedded filesystems for prompt and schema assets. Its
small prompt registry records IDs and embedded paths; it does not reconstruct
Notarius-style per-module virtual prompt trees. Shared instruction fragments are
supplied as template variables. Processing supplies the application-owned values
for those shared names, but an operator replacement decides whether its template
references them at all. They are not forcibly appended to replacement messages.
The processing request independently supplies a complete native output contract:
JSON Schema validation, the schema path selected for that operation, and its
structural-repair budget. The three schemas describe a correction set, a repair
decision, and validator decisions. PromptKit receives their canonical embedded
filesystem via `WithSchemaFS`. Thus operator control of prompt wording does not
change the processing code's expected response shape. A test replaces a prompt
with a text/no-validation declaration and still exercises the processing
request's JSON-schema repair contract.
Audita still keeps a response-schema key/metadata/hash registry and application
decoding checks. Its use of native loading does not prove that every schema
wrapper is necessary, nor decide Notarius's deferred schema design. It supplies
a concrete option: module-owned response requirements expressed directly through
native per-request contracts. Standalone native preview/preparation can use the
prompt declaration's contract; processing supplies its own override.
Evidence: [prompt registry](../../../audita/internal/prompts/registry.go),
[schema registry](../../../audita/internal/framework/responseschema/registry.go),
`prepareCall` and `OutputContract` in the
[processing adapter](../../../audita/internal/framework/llm/adapter.go), and
`TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText` in
[adapter tests](../../../audita/internal/framework/llm/adapter_test.go).
### Native Continuation With Application Assessment
The implemented flow is:
1. Generate a section's proposal set, capturing a native immutable exchange when
correction repair is enabled. This retains the actual proposal messages and
response; it does not require debug recording.
2. Apply application validation. An actionable rejected proposal starts its own
branch from the original proposal exchange. Unavailable-only findings and
no-effect corrections do not start repair. Existing approvals remain separate.
3. Call `Engine.Coordinate` with that exchange and an additional-turn budget.
Each follow-up selects a distinct repair prompt, repair profile, and repair
response schema. The request carries the original proposal reference, current
correction, ordered findings, and available before/after text previews.
4. PromptKit assembles history and progresses the conversation. A second turn
retains the first repair instruction and response. A sibling branch starts
from the original exchange and does not inherit another branch's repairs.
Audita does not rerender the original proposal or manually replay messages.
5. Audita decodes each delivered decision. Withdrawal ends the branch without
applying that correction. A revision undergoes the full application validation
chain again, including validators that approved its earlier version. Approval
stops the branch; actionable rejection can request another turn.
6. The final permitted response is assessed before exhaustion is determined.
Requesting another turn at that boundary does not allocate another logical
call. Recoverable provider/invalid-output failures finish the branch as
unavailable; fatal errors or parent cancellation interrupt processing.
Canceled, undelivered responses are diagnostic evidence only, never approvals.
Transport retries and structural repair operate inside each PromptKit execution;
they are separate from the semantic branch's additional-turn budget. Tests show
one semantic repair turn containing multiple provider attempts for structural
repair. The application retains acceptance, withdrawal, application ordering,
and reporting; PromptKit retains conversation and execution mechanics.
Audita's prompt roles support this model deliberately: system instructions carry
durable principles, the initial user message carries the initial module task,
and the repair prompt supplies a new user assignment. Adopting continuation in
Notarius would require reviewing the complete conversation and response-format
transitions, rather than mechanically appending to prompts written for fresh
replacement requests.
Evidence: [native coordination bridge](../../../audita/internal/framework/llm/coordinate.go),
[domain repair flow](../../../audita/internal/framework/runner/repair.go),
[wire-level conversation tests](../../../audita/internal/framework/llm/conversation_test.go),
[runner repair tests](../../../audita/internal/framework/runner/repair_test.go),
and [prompt guidance](../../../audita/docs/internal/prompts.md).
### Other Boundaries And Limits Of The Comparison
- Audita still has `RoleClient`, a structured-call interface, an opaque exchange
wrapper, and application diagnostic types. Adopt the demonstrated native
mechanisms without assuming Notarius should copy those wrappers; item 1's
adapter-removal direction remains in force.
- Proposal, validator, and repair roles share one engine and its per-backend
admission. The runner separately bounds section work. This demonstrates useful
separation of application work scheduling and provider capacity, but does not
supply Notarius's independent cross-backend ceiling.
- Ordinary calls use `Run`, `OperationTimeout`, and `OnPrepared`. Observations
feed a native `ExecutionGroup`; application records add logical-call and
stage/section/proposal attribution. Nested validator executions enroll
explicitly. Counts preserve terminal coverage and token-usage completeness.
- CommandKit's ckconfig and ckprompt integrations supply configuration and prompt
commands using Audita's engine construction, including request preparation,
validation, and smoke diagnostics.
- Audita edits independently assessable transcript corrections; Notarius accepts
typed stage artifacts and has cross-stage dependencies. Audita branches at an
individual correction within a proposal response. Notarius must deliberately
choose its correction unit rather than assume per-entity branching.
- Audita has no resume/checkpoint/manifest system. It cannot settle Notarius's
reuse identity or persisted validation-provenance requirements.
Evidence: [LLM runtime](../../../audita/docs/internal/llm-runtime.md),
[observations](../../../audita/internal/framework/llm/observations.go),
[CLI integrations](../../../audita/internal/cli/app_wiring.go), and
[component scope](../../../audita/docs/internal/overview.md).
### Implications For The Remaining Discussion
Item 2's native underlay direction has a working application precedent. Audita
also offers evidence for ordinary embedded filesystems and per-request schema
selection, while our filesystem and schema decisions remain open.
For item 3, native continuation is a practical alternative to the current
latest-response-only protocol. Keeping domain validation local does not require
keeping conversation assembly or the turn loop local. Decide whether Notarius
should adopt accumulated branch history, separate repair prompts, and revised
response contracts; none has been selected merely by this comparison.
Items 4 and 6 can draw on Audita's native admission, observations, and CommandKit
integration. Item 5 remains independent upstream/application identity work.
The two requested capabilities already work with v0.23.2; no new PromptKit
feature is needed merely to provide replaceable defaults or domain-directed
continuation. Any remaining upstream request should identify the specific unmet
requirement after reconsidering Notarius's historical behavior.
### Verification
Read the production composition, adapter, coordinator, domain repair callbacks,
prompt/schema definitions, and focused behavior tests. The following checks
passed from the Audita checkout:
```sh
go test ./internal/framework/llm ./internal/prompts ./internal/framework/responseschema ./internal/framework/runner ./internal/framework/proposal_generation
go test ./cmd/audita -run '^TestSubprocess(CorrectionRepairConversation|CancellationDuringCorrectionRepair|RepairDisabledAndOutputSelections)$' -count=1
```
The subprocess checks exercise assembled configuration, real native continuation
messages, operator replacement, final-turn assessment, sibling isolation,
repair-disabled behavior, and cancellation using a local fake provider. These
checks establish implementation behavior, not live-model quality. No live model
calls or application source changes were made. Broader migration decisions and
changes to the adoption roadmap remain for discussion.