Plan audit remediation implementation

This commit is contained in:
2026-11-25 17:21:45 +00:00
parent e67633b9f4
commit 6beddde313
2 changed files with 466 additions and 214 deletions

View File

@@ -1,12 +1,13 @@
# Audit Remediation Roadmap
Prepared 2026-11-25. Status: planned; implementation has not started.
Baseline: `f040f6906ca14cdfea4162ae31f9dfb18e7667e1`.
Reviewed baseline: `e67633b9f48b42c5b0d14782c6e8e1d4c78fcdd5`.
This roadmap implements the accepted [audit discussion](audit/discussion.md).
The [catalog](audit/catalog.md) and original reports retain the detailed evidence
and reproductions. This document owns the target state, work sequence, and
implementation status; it does not introduce new runtime contracts.
This roadmap captures the target state and scope selected in the accepted
[audit discussion](audit/discussion.md). The [catalog](audit/catalog.md) and
original reports retain the detailed evidence and reproductions.
[implementation.md](implementation.md) owns execution steps and implementation
status. This document does not introduce new runtime contracts.
## Baseline And Target
@@ -25,237 +26,125 @@ ConfigKit, PromptKit, and CommandKit retain the responsibilities established by
HTTP stays in maintenance mode, suitable only for exposure to trusted hosts on
a trusted network. The rest of the application remains actively developed.
Maintenance work includes the accepted report relocation because it makes that
boundary clearer; it does not expand HTTP reporting or deployment capabilities.
The accepted report relocation makes that boundary clearer without expanding
HTTP reporting or deployment capabilities.
At completion of the local work:
## HTTP Input Handling
- Provider parameters reach PromptKit without numeric precision loss, and file
references retain their pathname identity.
- Restricted acquisition uses ordinary regular-file semantics, cooperatively
observes cancellation, and preserves the existing lexical and byte limits.
- Tests detect the demonstrated application regressions without pinning
incidental representations or error prose.
- HTTP terminal reporting and its focused tests live within the HTTP adapter;
CLI reporting continues to use native upstream results and presentation.
- Listener failures carry useful native explanations. Framework capture
diagnostics follow the supported upstream route or remain explicitly tracked
pending upstream support, as specified in stage 4.
- Current contracts and internal documentation reflect the delivered changes,
and deferred HTTP work remains visible in [future.md](future.md).
Provider parameters reach PromptKit without numeric precision loss, and file
references retain their pathname identity. Strict unknown-field handling,
typed numeric validation, and trailing-token rejection remain unchanged.
## Scope And Disposition
Restricted acquisition uses ordinary regular-file semantics: unsupported
non-regular inputs are rejected before opening, opened files are checked, and
cancellation is observed cooperatively during acquisition and before success.
Lexical containment and configured byte limits remain enforced during reading.
Errors retain their identities through existing PromptKit/HTTP mappings.
Numbers refer to the [audit catalog](audit/catalog.md). Status for every stage
below is **not started**.
This does not introduce streaming input support, immediate interruption of
synchronous filesystem operations, abandoned-read goroutines, or a symlink
sandbox. Existing OS-followed symlinks to regular files remain supported.
Ordinary CLI artifact loading remains upstream-owned.
| Catalog entries | Disposition | Stage |
| --- | --- | --- |
| 1–3 | Correct cancellation/non-regular acquisition, numeric precision, and pathname identity. | 1 |
| 9 | Replace self-referential artifact-hash expectations alongside reader work. | 1 |
| 4, 7, 11–13 | Strengthen server lifetime/failure coverage, test cleanup, removed-flag rejection, and error assertions. | 2 |
| 10, 16 | Move HTTP report implementation and tests into the adapter; strengthen accounting assertions. | 3 |
| 8 | Improve listener explanations; verify native capture-diagnostic support and integrate or prepare an upstream request. | 4 |
| 15 | Consolidate the small CLI diagnostic bridge where it reduces maintenance effort. | 4 |
| 5, 6 | Retain existing transport and capacity controls; document limitations and defer additional controls. | 5 |
| 14 | Defer standalone handler decomposition; permit a small useful extraction beside corrective work. | 1, 5 |
| 17 | Permit the nil-aware mapping simplification beside request changes; leaving current correct behavior is acceptable. | 1, 5 |
## Effective Behavioral Protection
## Stage 1: Correct HTTP Input Handling
Tests protect demonstrated failure modes at their application-owned boundaries
rather than incidental representations or error prose:
Work primarily in
[artifact_reader.go](../../internal/adapter/http/artifact_reader.go),
[handler.go](../../internal/adapter/http/handler.go), and their existing tests.
- Lossless provider values, whitespace-significant file identity, post-start
cancellation, unsupported file types, and independently checked hashes.
- Shared engine admission at actual server composition, with reliable test
cancellation, release, and joining on failure paths.
- Engine-construction failures after successful configuration resolution and
before listening, retaining typed causes and nonzero outcomes.
- Specific rejection of removed flags on otherwise-valid invocations.
- HTTP status/code/precedence, usable messages, and cause privacy without
freezing noncontractual error sentences.
- Distinct cache-accounting fields and their required value/known/complete
members, including zero versus unknown and incomplete-count semantics.
1. Enable the request decoder's `UseNumber` capability. Preserve strict unknown
field handling, typed numeric validation, and trailing-token rejection.
Replace the concrete-float64 test expectation with lossless behavior checks.
Use a representative HTTP-to-real-engine-to-loopback-provider case with a
large integer and nested values; do not decode expected and actual values
through float64. Consolidate the old mapping scenario only after retaining
its meaningful JSON-shape protection.
2. Remove request-path whitespace trimming while retaining lexical cleaning
and containment. Keep configured artifact-root normalization separate.
Verify padded and unpadded filenames with distinct contents and preserve
body and metadata identity checks.
3. Pass context through file acquisition. Reject unsupported non-regular input
before opening; align opened-file checks with ordinary upstream semantics.
Check cancellation during reading and before successful return. Preserve
the configured byte limit during acquisition, including oversize detection,
and retain causes through the existing artifact-error mapping.
4. Replace hash expectations derived from the production helper with independent
expected digests for fixed, differing contents. A suitable public upstream
comparison is an alternative when checking interoperability.
Existing behavior owners are extended or consolidated, preserving meaningful
protection before duplicate cases are removed. No coverage quota, exhaustive
upstream matrix, mandatory mutation-testing platform, or new release gate is
selected.
Cover cancellation after acquisition starts and unsupported non-regular input
with deterministic, bounded, platform-appropriate tests and reliable cleanup.
Retain a representative real-engine or HTTP path. A small controlled read seam
may be used where needed; no general fault-injection framework is required.
## HTTP Report Ownership
These changes do not add streaming input support, resolve symlinks for
containment, promise immediate interruption of synchronous filesystem calls,
or abandon blocked reads in background goroutines. Existing symlink behavior
remains unchanged. Ordinary CLI artifact loading remains upstream-owned.
The terminal collector, HTTP projection, and their focused tests belong within
`internal/adapter/http`; the obsolete `internal/report` package is removed.
Implementation names are private where practical. Package reduction is a
consequence, not the goal.
If request mapping is touched, calling the existing nil-aware model converter
unconditionally is permitted. Preserve omitted/null versus explicit-empty
objects and numeric presence. Do not turn this into a standalone cleanup task
or a broad handler rewrite.
Existing wire shapes, opt-in and absence semantics, success/error attachment,
terminal-only observation, detached snapshots, unknown/incomplete counts,
request isolation, and response limits remain unchanged. CLI reporting remains
on native upstream results and presentation. Additional accounting fields and
a shared reporting framework are outside this remediation.
**Completion evidence:** focused regressions establish lossless provider values,
correct file identity, cooperative cancellation and non-regular handling, and
independently checked hashes while existing containment and size tests pass.
## Startup Diagnostics And CLI Maintenance
## Stage 2: Protect Server Composition And Failure Boundaries
Application-owned listener failures provide the selected address and a useful
failure category through native CommandKit explanations, preserving the cause
and existing status. Short, genuinely shared application configuration
diagnostic adaptation is consolidated where it improves maintainability;
native evidence selection, headings, bootstrap reporting, and failure precedence
remain intact. Small cleanup does not justify additional abstraction machinery.
Use the existing CLI server harness in
[lifecycle_test.go](../../internal/adapter/cli/lifecycle_test.go) and the relevant
HTTP/CLI test owners.
PromptKit owns safe structured diagnostics for resource capture and template
compilation; ckprompt owns native presentation. At the selected versions,
capture failures preserve causes but lack the supported structured diagnostic
handoff needed for that improvement. An upstream-ready consumer feature request
and explicit adoption deferral are therefore the local outcome. A later
supported release can enable adoption for both application and native PromptKit
commands. This dependency does not delay other local remediation.
- Consolidate the shared-capacity scenario at actual server composition.
Configure capacity one with no queue, hold the first provider call, and
verify rejection of a second request without a second provider dispatch.
Release the first request and check completion. The test must exercise the
server's engine lifetime rather than inject the lifetime it intends to prove.
- Register cancellation, release, and worker joining before launching work;
bound the second request and retain one owner of channel closure. Test bounds
are cleanup mechanisms, not production deadlines. Remove the lower-level
duplicate only after equivalent protection exists; retain distinct privacy
and retry checks.
- Cover a resolved configuration that fails engine construction on a missing
message file or malformed template. Assert the typed cause, nonzero outcome,
and absence of a listen attempt. Do not require new diagnostic wording or
move message capture into configuration inspection.
- Give removed-flag tests otherwise-valid invocations. Distinguish rejection
of the removed flag using native typed evidence where available or a minimal
flag-specific fragment. Keep hard-cutover protection.
- Replace exact noncontractual HTTP error sentences with status/code/precedence,
usable nonempty-message, and private-cause exclusion assertions. Retain exact
wording only where expressly contractual.
Generic capture explanations remain until upstream support is available. The
application does not parse formatted errors, print arbitrary causes, import
upstream internals, or build a framework-error interpreter. Configuration
inspection retains its existing lifecycle without capturing message resources.
**Completion evidence:** tests protect server-owned shared admission and startup
ordering, fail for the intended invalid flag, and tolerate harmless error
rewording. Concurrency-test failure paths release and join their owned work.
## Deferred Work And Operating Limits
## Stage 3: Consolidate HTTP Terminal Reporting
The following remain conditional future work in [future.md](future.md), not
delivery commitments:
Move [internal/report](../../internal/report/report.go) and its focused tests
into dedicated files in `internal/adapter/http`. Make implementation names
private where practical, update handler/DTO references, and remove the obsolete
package. Package reduction is a consequence; the purpose is to place HTTP-only
functionality behind the maintenance-mode adapter boundary.
- Additional body-read, idle, and response-delivery deadlines.
- Aggregate input/memory controls.
- Standalone HTTP handler decomposition.
- Optional model-mapping simplification if it is not useful alongside the fixes.
- Public upstream artifact-reader reuse that preserves access policy and byte
enforcement during acquisition, independently of the local reader correction.
Carry the accounting-test correction with the move: use distinct cached-token
and cache-write-token values and meaningful known/complete combinations. Assert
the required JSON member names and values instead of only counting members.
Existing request, per-file, response, and backend controls remain; they do not
establish an aggregate-memory budget or whole-HTTP-request lifetime guarantee.
The operation budget and shutdown contract remain unchanged. No gateway
requirement or broader supported exposure is introduced. Additional controls
can be reconsidered when actual workloads or operating needs justify them.
Report relocation is accepted local work, not a deferral.
Preserve existing wire shapes, opt-in and absence semantics, success/error
attachment, terminal-only observation, detached snapshots, unknown/incomplete
counts, request isolation, and response-limit handling. Retain representative
real-engine observation coverage. This work does not add accounting fields,
change CLI reports, or create a shared reporting framework.
## Scope Coverage
**Completion evidence:** existing HTTP report behavior and strengthened projection
tests pass from the new location; production imports no longer reference the
removed package. Update the component inventory and adapter documentation with
the move. This stage is required, not deferred HTTP work.
Numbers refer to the [audit catalog](audit/catalog.md).
## Stage 4: Improve Startup Diagnostics And CLI Maintenance
| Catalog entries | Target disposition |
| --- | --- |
| 1–3, 9 | Correct acquisition, precision, and file identity; independently verify hashes. |
| 4, 7, 11–13 | Strengthen server/test lifetime, startup boundaries, flag rejection, and error assertions. |
| 10, 16 | Consolidate HTTP reports and strengthen accounting protection. |
| 8 | Improve listener explanations; retain an explicit upstream capture-diagnostic dependency. |
| 15 | Simplify genuinely shared CLI diagnostic adaptation where useful. |
| 5, 6 | Document existing limits and defer additional controls. |
| 14 | Defer standalone restructuring; allow a small adjacent extraction when useful. |
| 17 | Allow the nil-aware converter simplification alongside mapping fixes; otherwise defer. |
In [server.go](../../internal/adapter/cli/server.go), add a deliberate native
CommandKit explanation identifying the selected listen address and a useful
failure category from typed error information where available. Preserve the
cause and existing status. Cover representative operator-correctable failures
without making the entire error sentence contractual.
## Documentation End State
Consolidate the genuinely shared run/serve ConfigKit evidence selection and
adaptation into a small private CLI helper where useful. Preserve successful
result versus wrapped load-error evidence selection, distinct headings and
explanations, bootstrap reporting, and timeout/configuration precedence.
Flatten nested failure selection when clearer. Retain short duplication if
sharing would require extra options or abstractions. Native inspection already
owns its presentation and must not receive duplicate application diagnostics.
Canonical current-state documentation reflects delivered input behavior,
report ownership, diagnostic handling, trusted-network maintenance scope, and
existing limit boundaries. It preserves upstream ownership and does not imply
stronger cancellation, filesystem, shutdown, or resource guarantees.
Handle PromptKit capture diagnostics as a separate workstream:
1. Verify the selected public PromptKit and ckprompt APIs against missing-file
and malformed-template cases. Determine whether they supply safe structured
resource identity/configuration location and a useful explanation.
2. Where supported, use the native integration for application and native
PromptKit commands. Preserve typed causes, statuses, and capture lifecycle.
3. If support is missing, prepare an upstream feature request covering both
diagnostic evidence and native presentation, and record the dependency and
deferred adoption explicitly. Do not invent an API or select an unreleased
dependency in this roadmap. A later supported release can enable adoption.
Do not parse formatted errors, print arbitrary causes, import upstream internals,
or construct an application-owned framework-error interpreter. These capture
errors are not repaired merely by sharing the ConfigKit diagnostic helper.
**Completion evidence:** local listener explanations and existing diagnostic
precedence/privacy tests pass. The capture workstream has either verified native
delivery with representative coverage or a concrete upstream request and tracked
deferral. In the latter case, report capture presentation as deferred, not fixed.
That dependency does not block stages 1–3 or local listener improvements.
## Stage 5: Align Documentation And Preserve Deferred Work
Update canonical documents with delivered behavior rather than duplicating their
contracts here:
- [Operations](../operations.md) and, where applicable, the
[architecture policy](../policy/architecture.md): make the selected trusted-host,
trusted-network maintenance scope clear. Do not imply that a gateway makes
broader exposure supported by this remediation or require one for current use.
- [HTTP API](../api.md) and [source internals](../internal/sources.md): describe
corrected input behavior and regular-file acquisition without stronger
cancellation or filesystem guarantees.
- [Component overview](../internal/overview.md) and
[adapter internals](../internal/adapters.md): reflect report ownership and
delivered diagnostic handling. Preserve upstream ownership and CLI reporting.
- Operations: briefly clarify that existing transport deadlines and per-file,
request, response, and backend controls are not aggregate-memory or
whole-HTTP-request lifetime guarantees. Retain the operation-budget and
shutdown contracts. No new resource controls are part of this work.
Maintain the already-started **Deferred HTTP Adapter Work** entry in
[future.md](future.md). It must retain every HTTP deferral from this review:
additional body-read/idle/response-delivery deadlines; aggregate input/memory
controls; standalone handler decomposition; and optional model-mapping cleanup
if left unchanged. Revisit controls only when workloads or operating needs
justify them; no benchmark project or memory-control feature request is required.
Keep possible public upstream artifact-reader reuse there as separate follow-up.
Investigate whether it can remove ordinary reading/metadata duplication while
preserving access policy and byte enforcement during acquisition. Neither this
investigation nor an upstream release delays the local reader correction.
Report-package relocation must not appear as deferred. Preserve other existing
future directions, including broader HTTP review and additional accounting.
**Completion evidence:** current documentation matches the implemented scope;
every deferred HTTP item has a durable disposition in future.md. Record any
pending framework-diagnostic dependency separately so it is not mistaken for
HTTP-only work or an implemented fix.
## Validation And Completion
Follow the [development baseline](../development.md#baseline-validation) and
[testing policy](../policy/testing.md) for implementation changes: ordinary and
race-enabled tests, vet, build, formatting, whitespace, and affected documentation
and example checks. Use real internal collaborators and controlled local providers;
the default suite remains offline and independent of live credentials.
Focused tests should extend or replace the existing behavior owners. Preserve
meaningful protection before removing duplicate scenarios. Do not add coverage
quotas, exhaustive upstream matrices, mandatory mutation-testing infrastructure,
or new release gates. The audit's experiments guide regression selection; they
do not require a new ongoing test platform.
Track each stage's actual completion and any upstream-dependent deferral. Local
remediation is complete when stages 1–5 have their stated evidence, including
documentation and future-work tracking. Do not mark upstream capture presentation
delivered if only its feature request is complete.
All seven scope decisions are settled. Remaining API investigation and conditional
deferral follow the accepted ownership decision; they do not reopen application
policy. No additional significant open decision is identified at this baseline.
`future.md` describes potential future work only. Pending framework-diagnostic
adoption is recorded separately from HTTP-only deferrals and is not represented
as an implemented fix. All seven audit scope decisions are settled; no
significant product decision remains open.

View File

@@ -0,0 +1,363 @@
# Audit Remediation Implementation Plan
Prepared 2026-11-25 for a Luna coding agent.
Baseline: `e67633b9f48b42c5b0d14782c6e8e1d4c78fcdd5`.
Status: all stages not started.
## Scope And Execution
Implement the accepted [remediation target](audit-remediation.md), using the
[audit catalog](audit/catalog.md) for evidence and the accepted
[discussion](audit/discussion.md) for decision rationale. Catalog numbers below
identify findings, not additional requirements. All 17 entries have a selected
disposition; optional cleanups and deferred controls are not mandatory features.
Follow stages in order. Each stage is sized as a focused Luna assignment in one
end-to-end sprint. Intermediate stages need not compile or leave a coherent
repository; validation listed for a stage describes the evidence required by
sprint completion, not an additional per-stage green-build gate. Run focused
checks when feasible and the complete baseline once the sprint is integrated.
Record actual stage completion and any pending upstream dependency here.
Follow the repository's existing local commit policy; do not push by default.
Start with [development](../development.md) and the applicable policies:
[agents](../policy/agents.md), [architecture](../policy/architecture.md),
[testing](../policy/testing.md), and [documentation](../policy/documentation.md).
Use the canonical [HTTP](../api.md), [CLI](../cli.md),
[operations](../operations.md), [adapter](../internal/adapters.md), and
[source](../internal/sources.md) documents for existing contracts.
Keep selected dependencies unchanged: PromptKit v0.25.0, ConfigKit v1.4.0,
CommandKit v0.8.0, ckconfig v0.11.0, ckprompt v0.12.0, and ReleaseKit v0.10.0.
No library implementation, application configuration migration, new public
command, or new HTTP feature is selected. Preserve the single resolved ConfigKit
handoff, upstream execution/admission, and native CLI inspection/reporting.
## Stage 1: Preserve HTTP Provider Numbers
**Finding:** 2; optional adjacent cleanup from 17.
**Files:** `internal/adapter/http/handler.go` and `handler_test.go`.
1. Call `UseNumber` on the existing JSON decoder before decoding the request.
Keep `DisallowUnknownFields`, trailing-token rejection, request-size handling,
and typed numeric fields unchanged. Pass resulting `json.Number` values
directly through existing `ExtraParams` plumbing; PromptKit supports them.
2. Replace the concrete-float64 assertion in
`TestHandlerModelOverrideAcceptsJSONCompatibleExtraParams` with JSON-value
behavior checks. Consolidate its shape coverage into a real-engine test
rather than maintaining redundant scenarios when the stronger test covers it.
3. Exercise HTTP handler → real PromptKit engine → loopback provider with a
valid prompt/profile and `9007199254740993` at top level and in a nested
object/array. Include representative string, boolean, null, and array/object
values. Decode observed provider bytes with `UseNumber` or `RawMessage` and
compare with independent expected values, never float64-rounded expectations.
Assert successful execution and unchanged provider values. Numeric spelling
is not a new general-purpose serialization guarantee.
4. The nearby redundant `req.Model != nil` guard may be removed by calling
`executionTargetOverrideFromModelOverrideDTO(req.Model)` directly. Preserve
omission/null versus explicit-empty objects and explicit numeric zeros.
This optional simplification requires no new abstraction or standalone work.
**Evidence:** the new provider-boundary case fails without `UseNumber` and passes
with it; strict JSON, reserved parameters, typed timeout/retry validation, and
model-presence tests retain their behavior. No precision-conversion layer is added.
## Stage 2: Preserve File Identity And Independently Check Hashes
**Findings:** 3 and 9.
**Files:** `internal/adapter/http/artifact_reader.go` and
`artifact_reader_test.go`.
1. In `resolveLexicalPath`, clean the supplied URI without trimming whitespace.
Retain existing absolute/relative resolution, lexical containment, and
empty-URI behavior. Leave configured artifact-root normalization unchanged.
2. Extend the contained-file test with whitespace-padded and unpadded filenames
containing different fixed contents. Verify the requested bytes, name, URI,
size, and hash identify the intended file. Cover meaningful leading/trailing
whitespace with platform-appropriate fixtures, not a new filename grammar.
3. Replace expected hashes computed using production `artifactHash` with
independently known SHA-256 digests for at least two fixed contents. Keep
ordinary body/metadata and containment assertions. This checks the reader's
existing metadata, not a new global hash-uniqueness or upstream hash contract.
**Evidence:** file-identity cases fail with URI trimming, and fixed independent
expectations detect a constant-hash implementation. Existing containment,
absolute-path, inline, symlink, and byte-limit scenarios remain protected.
## Stage 3: Make Restricted Acquisition Cooperatively Cancellable
**Finding:** 1, including its regression protection.
**Files:** the HTTP artifact reader/tests; a Linux-specific FIFO test file if
needed, and focused handler integration coverage.
1. Thread `context.Context` from `Read` through `readFileArtifact` and
`readArtifactFile`. Check it before filesystem acquisition, between reads,
after reads, and before returning a successful artifact.
2. Use `os.Stat` before opening and reject non-regular targets. Use `Stat` on
the opened file and reject a non-regular opened target as well. `os.Stat`
follows symlinks, preserving existing symlink behavior. Treat unsupported
file kinds as ordinary artifact-read errors through the existing HTTP
`400 artifact_read_failed` mapping; no new public status/code is needed.
3. Retain `os.Open` with deferred close, opened-file size checks, MIME fallback,
metadata, and hashing. Retain during-read byte enforcement: zero remains
unlimited, positive limits read at most limit-plus-one for oversize detection,
and `math.MaxInt64` must not overflow. Do not replace enforcement with a
post-read-only size check.
4. Use a small private context-aware `io.Reader` wrapper around the file,
retaining `io.LimitReader` and `io.ReadAll`. Check context before and after
the wrapped read and explicitly before artifact success, including the EOF
path. Wrap read errors with `%w` so context and filesystem identities survive.
Keep this local; no generic acquisition framework or background-read worker.
5. Test post-start cancellation deterministically using a controlled reader
that cancels during a read, including data returned together with EOF. Test
the same wrapper/read path production uses, not a parallel test algorithm.
A small private body-reading helper is sufficient if needed to combine the
wrapper, limit, and final cancellation check for these tests.
6. Cover non-regular rejection with a portable directory case and a
platform-appropriate FIFO case. On Linux use a `_linux_test.go` file and
`syscall.Mkfifo`. Bound the test and arrange cleanup to release a FIFO-open
regression before joining workers; cancellation alone cannot unblock the
old implementation. If the worker remains pending, a bounded nonblocking
writer-open retry (`O_WRONLY|O_NONBLOCK`) can meet the waiting reader; close
that writer to supply EOF before joining. Do not leave a diagnostic
goroutine pending on failure.
7. Retain a representative real-engine HTTP cancellation path with the
restricted reader injected. A test reader decorator can cancel the request
as acquisition starts and then delegate to the actual restricted reader.
Verify context identity survives PromptKit wrapping, the HTTP cancellation
classification is retained, and no provider dispatch occurs. The controlled
reader test separately proves cancellation during reading.
**Evidence:** pre-cancel and post-start/EOF cancellation return no successful
artifact; FIFO/directory input is rejected without waiting for content; size
limits and typed mappings still work. These are cooperative checks, not a
promise to interrupt synchronous calls immediately or defend against concurrent
privileged filesystem replacement. Do not add symlink resolution, streaming
support, copied upstream implementation, or abandoned-read goroutines.
## Stage 4: Protect Shared Admission At Real Server Composition
**Findings:** 4 and 7.
**Files:** `internal/adapter/cli/lifecycle_test.go` and existing HTTP capacity
tests/helpers in `internal/adapter/http/handler_test.go`.
1. Reuse the real `serveWithListener` harness and native configuration loading.
Configure a loopback provider backend with concurrency limit one, queue
capacity zero, and no additional transient retries. Do not inject an engine
whose lifetime the test itself has selected.
2. Start the server and first HTTP run. Wait for an explicit provider-entry
signal and hold that call. While it is held, send a bounded second request;
require `503 capacity_exceeded`, no `Retry-After`, no backend/cause disclosure,
and no second provider dispatch. Track dispatches without blocking an
accidentally admitted second provider call forever.
3. Release the first call and require its successful completion. Cancel the
server invocation and join server/client/provider work. Register cleanup
before launching workers: request/server cancellation, idempotent single-owner
release, response-body closing, and bounded joins. Avoid reading buffers
while their owners may still write. Synchronize with channels rather than
sleep-based admission assumptions.
4. Once the stronger scenario preserves its meaningful assertions, remove
`TestHandlerSharesBackendCapacityAcrossConcurrentRequests` and helpers used
only by that scenario. Keep distinct deadline/capacity-wait and retry-slot
scenarios and independent error/privacy protection.
**Evidence:** the real server rejects the second call before dispatch under the
held first call, and owned workers are released on assertion-failure paths.
A per-request-engine construction would violate this test. No production engine
lifetime change is required; the current server already shares one engine.
## Stage 5: Correct Startup, Removed-Flag, And Error Test Blind Spots
**Findings:** 11–13.
**Files:** `internal/adapter/cli/lifecycle_test.go`, `app_test.go`, and HTTP
error/timeout/report tests in `handler_test.go`.
1. Add server startup coverage for a successfully resolved configuration with
either a missing message `content_file` or malformed template. Use native
loading and actual engine construction. Assert `ErrInvalidConfig`, the
underlying filesystem identity where applicable, status 1, empty stdout,
and no listen attempt through the existing listener seam. Do not fabricate
a ConfigKit `LoadError` or move capture into configuration validation.
2. Correct `TestRemovedSourceAndSchemaFlagsAreRejected`: give `run` its required
prompt operand and every base invocation a valid controlled configuration
and otherwise-valid arguments. Check Usage/status 2 plus the rejected flag
name in supported structured evidence or a minimal diagnostic fragment.
Keep all existing command/removed-flag rows; do not pin complete sentences.
3. Review assertions affected by generic HTTP model-generation/error prose,
including `TestHandlerPublicErrorMapping`, timeout cases, and report-bearing
failures. Assert HTTP status, machine code, precedence, a usable nonempty
message, and private-cause exclusion. Preserve intentionally contractual
distinctions without requiring exact noncontractual sentences. Do not weaken
privacy checks merely to make a rewording pass.
**Evidence:** engine construction fails before listening, flag tests fail for
the removed flag rather than a missing operand, and harmless generation-error
rewording does not break unrelated cases. Typed/status/privacy behavior remains
protected. The numeric assertion correction is already owned by stage 1.
## Stage 6: Move HTTP Report Implementation Into Its Adapter
**Findings:** 10 and 16.
**Files:** `internal/report/report.go`, `report_test.go`, HTTP `handler.go` and
`dto.go`; destination `internal/adapter/http/execution_report.go` and
`execution_report_test.go`.
1. Move the collector/projection and focused tests into the HTTP adapter,
retaining the native terminal observer. Use private names such as
`executionReport`, `executionUsage`, `executionTokenCount`,
`executionCollector`, and `newExecutionCollector`. Qualify short projection
helpers if needed to avoid package-name collisions. Preserve exported JSON
fields/tags required for encoding.
2. Update handler/DTO type references and all imports, then remove the obsolete
`internal/report` package. Keep CLI delivery on native `RunResult` reporting;
do not create a replacement shared report package.
3. Strengthen the moved `TestCollectorProjectsOnlyTerminalAggregates` fixture
with distinct nonzero cached-token and cache-write-token values and meaningful
known/complete combinations. Assert each of the five required usage fields'
`value`, `known`, and `complete` members and values, not just object length.
Retain known-zero, unknown, and incomplete-total cases.
4. Preserve terminal-only observation, detached snapshots, absent-event behavior,
unknown outcome/failure mapping, identifiers, zero/omission semantics, request
isolation, success/error attachment, and encoded response-size behavior.
Move the representative real-engine observation test rather than replacing
it with only hand-built events. Do not expose reasoning/cost/cache-ratio
fields; those remain future work.
**Evidence:** report tests and HTTP integration tests pass from the new owner,
swapped cache fields are detectable, and production imports no longer reference
`internal/report`. Existing wire behavior is unchanged.
## Stage 7: Improve Listener Explanations And Simplify CLI Diagnostics
**Findings:** the local portion of 8, and 15.
**Files:** `internal/adapter/cli/server.go`, `native_run.go`, `outcomes.go`, and
focused lifecycle/diagnostic tests.
1. Enrich listener-failure native explanations with the selected address and a
deliberately selected category. Use `errors.As` for `*net.AddrError` or
`*net.DNSError`, and `errors.Is` for ordinary address-in-use/permission errors
where applicable. Fall back to a generic listener-setup category for other
errors. Do not render arbitrary error strings. Retain `WithCause(err)`,
status 1, no stdout, and native presentation, including quiet-mode failures.
2. Extend actual invalid-address coverage and use the existing listener seam
for deterministic typed bind failures. Assert the selected address, a minimal
useful category, retained cause identity, and status, not whole sentences.
3. Extract the duplicated run/serve evidence selection/adaptation into a small
private application-configuration diagnostic helper. Select sources/records
from the result when present, replacing them with a wrapped nonnil ConfigKit
`LoadError`'s evidence when applicable; adapt using the existing application
heading and queue native diagnostics. Return the explanation for each caller.
Keep framework-specific headings/appended details distinct; share further
only if it stays simpler than the short duplication.
4. Flatten `requestFailure` into an ordered switch with configuration
classification after operation-timeout/canceled/deadline cases and before
remaining framework cases. Preserve every current status, cause, detail,
and message selection. Keep a single local CLI classifier, not a universal
CLI/HTTP abstraction. Native config inspection must not receive duplicate
diagnostics, and bootstrap reporting remains on its current path.
**Evidence:** listener failures expose useful selected context while retaining
their causes/statuses; existing bootstrap, load-error, precedence, presentation
failure, and provider-privacy tests remain effective. This helper refactor does
not fix PromptKit capture diagnostics.
## Stage 8: Prepare The Upstream Capture-Diagnostic Request
**Finding:** the upstream-dependent portion of 8.
**Deliverable:** `docs/roadmap/capture-diagnostics.md`, an upstream-ready consumer
request and pending-adoption record, not a library implementation.
The planning review checked the selected public APIs and the audit's native
failure evidence. PromptKit v0.25.0 preserves constructor causes but does not
provide a structured capture-diagnostic value. ckprompt v0.12.0 adapts ConfigKit
`LoadError` evidence, not these ordinary capture errors. Config validation can
succeed before engine capture fails. Select the already-approved request and
deferral path; do not leave Luna to design a local workaround or choose an upgrade.
1. Describe Scriptorium's missing-file and malformed-template operator failures
and the need for resource identity/configuration location, failure category,
and a useful safely displayable explanation through a supported public API.
Preserve typed causes and classification, with native ckprompt presentation
benefiting alongside application `run` and `serve`.
2. Supply minimal synthetic reproductions using existing fixtures, including
application commands and native `promptkit list prompts`. Record observed
status and cause identities. Explain why ordinary config inspection is not
the capture lifecycle and why raw causes cannot be indiscriminately shown.
Reuse stage 5 evidence where applicable; no paid provider is required.
3. Request public diagnostic evidence from PromptKit and native presentation
through ckprompt from the consumer perspective. Do not prescribe upstream
internals, invent an API, or copy implementations. Keep the document local
for upstream submission; no sibling repository change, submission, or push
is needed to complete this sprint.
4. Mark adoption pending a supported released API and presentation integration.
Preserve the current generic capture explanations, statuses, and causes.
Record this stage as request prepared/adoption deferred, never diagnostics
implemented. Keep this cross-CLI dependency separate from HTTP-only deferrals.
**Evidence:** a concrete request identifies both upstream responsibilities,
reproductions, desired consumer behavior, and the release dependency. The
unsupported presentation improvement does not block other local completion.
## Stage 9: Align Canonical Documentation And Validate The Sprint
**Findings:** 5, 6, 14, and 17 dispositions, plus documentation for delivered work.
1. Update [operations](../operations.md) with trusted-host/trusted-network HTTP
maintenance scope. Replace wording implying a gateway makes broader exposure
supported by this work; impose no gateway requirement for current use.
Reflect that scope briefly in the [architecture policy](../policy/architecture.md)
and align [API service guidance](../api.md#service-and-route).
2. In operations, distinguish the existing header timeout and engine operation
budget from body-read/idle/response-delivery deadlines. Explain briefly that
request, per-file, response, and backend limits are not an aggregate-memory
budget. Retain existing shutdown, timeout, cancellation, and capacity behavior;
no new timeout setting, admission layer, memory cap, benchmark project, or
mandatory authenticated gateway is part of remediation.
3. Update the HTTP API's application-specific input guidance for lossless provider
numbers, significant pathname whitespace, and regular-file input rejection.
Update [source internals](../internal/sources.md) for cooperative acquisition,
lexical/byte limits, and unchanged symlink behavior. Link upstream for native
features instead of reproducing library documentation. Do not promise immediate
interruption of filesystem calls or a whole-request deadline.
4. Update [component inventory](../internal/overview.md) and
[adapter internals](../internal/adapters.md) for HTTP-local reporting and
delivered listener/diagnostic handling. Remove obsolete package references
from current-state docs. Keep audit evidence and accepted decision history
intact; historical references are not stale implementation documentation.
5. Preserve all conditional HTTP deferrals under **Deferred HTTP Adapter Work**
in [future.md](future.md): additional transport deadlines, aggregate input/
memory controls, standalone handler decomposition, and upstream artifact-reader
reuse that retains access policy and acquisition-time limits. Keep optional
model-mapping cleanup only if it remains undone; keep other existing future
directions. Report relocation is delivered work, not future work. Keep
`future.md` future-only, and track pending capture-diagnostic adoption in
`capture-diagnostics.md` rather than folding it into the HTTP entry.
6. Format changed Go files and run the existing development baseline:
```bash
go test ./...
go test -race ./...
go vet ./...
go build ./cmd/scriptorium
git diff --check
```
Check affected links/examples and any changed documented commands. Do not
commit the local build artifact. No new release gate or coverage quota is
introduced. The suite stays offline with controlled local providers.
7. Record stage results here, including optional cleanup dispositions and the
upstream request/adoption distinction. Review the full diff for unintended
dependency, configuration, public-interface, or guarantee changes. Follow
local staging/commit policy and report checks, commits, and remaining deferrals.
**Completion:** all local fixes/refactors and their regression evidence are
delivered, canonical documentation matches them, every catalog entry has its
accepted disposition, and only the explicitly deferred upstream/HTTP work
remains pending. Preparing the upstream request completes its local workstream,
not delivery of upstream capture presentation.
## Open Questions
None requiring a user decision. The accepted scope and pinned-API review select
the upstream request/deferred-adoption outcome for capture diagnostics; a later
released capability can be evaluated separately.