23 KiB
Audit Remediation Implementation Plan
Prepared 2026-11-25 for a Luna coding agent.
Baseline: e67633b9f48b42c5b0d14782c6e8e1d4c78fcdd5.
Status: implementation in progress.
Scope And Execution
Implement the accepted remediation target, using the audit catalog for evidence and the accepted discussion 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 and the applicable policies: agents, architecture, testing, and documentation. Use the canonical HTTP, CLI, operations, adapter, and source 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
Status: complete. The provider-boundary test exposed rounding before the decoder change and passes with lossless JSON numbers. The optional model-mapping cleanup was left unchanged.
Finding: 2; optional adjacent cleanup from 17.
Files: internal/adapter/http/handler.go and handler_test.go.
- Call
UseNumberon the existing JSON decoder before decoding the request. KeepDisallowUnknownFields, trailing-token rejection, request-size handling, and typed numeric fields unchanged. Pass resultingjson.Numbervalues directly through existingExtraParamsplumbing; PromptKit supports them. - Replace the concrete-float64 assertion in
TestHandlerModelOverrideAcceptsJSONCompatibleExtraParamswith JSON-value behavior checks. Consolidate its shape coverage into a real-engine test rather than maintaining redundant scenarios when the stronger test covers it. - Exercise HTTP handler → real PromptKit engine → loopback provider with a
valid prompt/profile and
9007199254740993at top level and in a nested object/array. Include representative string, boolean, null, and array/object values. Decode observed provider bytes withUseNumberorRawMessageand 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. - The nearby redundant
req.Model != nilguard may be removed by callingexecutionTargetOverrideFromModelOverrideDTO(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
Status: complete. Whitespace-sensitive file identities and fixed SHA-256 expectations are covered; the identity test failed with URI trimming in place.
Findings: 3 and 9.
Files: internal/adapter/http/artifact_reader.go and
artifact_reader_test.go.
- 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. - 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.
- Replace expected hashes computed using production
artifactHashwith 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
Status: complete. Acquisition checks cancellation around filesystem reads, rejects non-regular files, and retains streaming size enforcement. Controlled reader, directory, Linux FIFO, and real-engine HTTP cancellation tests pass.
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.
- Thread
context.ContextfromReadthroughreadFileArtifactandreadArtifactFile. Check it before filesystem acquisition, between reads, after reads, and before returning a successful artifact. - Use
os.Statbefore opening and reject non-regular targets. UseStaton the opened file and reject a non-regular opened target as well.os.Statfollows symlinks, preserving existing symlink behavior. Treat unsupported file kinds as ordinary artifact-read errors through the existing HTTP400 artifact_read_failedmapping; no new public status/code is needed. - Retain
os.Openwith 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, andmath.MaxInt64must not overflow. Do not replace enforcement with a post-read-only size check. - Use a small private context-aware
io.Readerwrapper around the file, retainingio.LimitReaderandio.ReadAll. Check context before and after the wrapped read and explicitly before artifact success, including the EOF path. Wrap read errors with%wso context and filesystem identities survive. Keep this local; no generic acquisition framework or background-read worker. - 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.
- Cover non-regular rejection with a portable directory case and a
platform-appropriate FIFO case. On Linux use a
_linux_test.gofile andsyscall.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. - 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
Status: complete. A real configured server holds one provider call while a second receives a private capacity rejection without another dispatch.
Findings: 4 and 7.
Files: internal/adapter/cli/lifecycle_test.go and existing HTTP capacity
tests/helpers in internal/adapter/http/handler_test.go.
- Reuse the real
serveWithListenerharness 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. - 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, noRetry-After, no backend/cause disclosure, and no second provider dispatch. Track dispatches without blocking an accidentally admitted second provider call forever. - 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.
- Once the stronger scenario preserves its meaningful assertions, remove
TestHandlerSharesBackendCapacityAcrossConcurrentRequestsand 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
Status: complete. Native engine capture fails before listening with typed causes, removed flags are identified in otherwise-valid invocations, and HTTP error tests retain classification and privacy without pinning generic prose.
Findings: 11–13.
Files: internal/adapter/cli/lifecycle_test.go, app_test.go, and HTTP
error/timeout/report tests in handler_test.go.
- Add server startup coverage for a successfully resolved configuration with
either a missing message
content_fileor malformed template. Use native loading and actual engine construction. AssertErrInvalidConfig, the underlying filesystem identity where applicable, status 1, empty stdout, and no listen attempt through the existing listener seam. Do not fabricate a ConfigKitLoadErroror move capture into configuration validation. - Correct
TestRemovedSourceAndSchemaFlagsAreRejected: giverunits 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. - 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
Status: complete. HTTP owns the terminal report projection and its real-engine tests; distinct cache-token fields and their encoded presence are verified.
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.
- 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, andnewExecutionCollector. Qualify short projection helpers if needed to avoid package-name collisions. Preserve exported JSON fields/tags required for encoding. - Update handler/DTO type references and all imports, then remove the obsolete
internal/reportpackage. Keep CLI delivery on nativeRunResultreporting; do not create a replacement shared report package. - Strengthen the moved
TestCollectorProjectsOnlyTerminalAggregatesfixture 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, andcompletemembers and values, not just object length. Retain known-zero, unknown, and incomplete-total cases. - 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
Status: complete. Listener failures identify the selected address and safe error category, and run/serve share application-configuration 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.
- Enrich listener-failure native explanations with the selected address and a
deliberately selected category. Use
errors.Asfor*net.AddrErroror*net.DNSError, anderrors.Isfor 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. RetainWithCause(err), status 1, no stdout, and native presentation, including quiet-mode failures. - 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.
- 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. - Flatten
requestFailureinto 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
Status: complete locally. The consumer request is prepared and its reproductions checked. Adoption is deferred pending a supported PromptKit release and ckprompt presentation; no upstream submission or diagnostic implementation is claimed.
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.
- 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
runandserve. - 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. - 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.
- 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.
-
Update operations 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 and align API service guidance.
-
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.
-
Update the HTTP API's application-specific input guidance for lossless provider numbers, significant pathname whitespace, and regular-file input rejection. Update source internals 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.
-
Update component inventory and adapter internals 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.
-
Preserve all conditional HTTP deferrals under Deferred HTTP Adapter Work in 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.mdfuture-only, and track pending capture-diagnostic adoption incapture-diagnostics.mdrather than folding it into the HTTP entry. -
Format changed Go files and run the existing development baseline:
go test ./... go test -race ./... go vet ./... go build ./cmd/scriptorium git diff --checkCheck 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.
-
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.