Files
scriptorium/docs/roadmap/implementation.md

378 lines
23 KiB
Markdown
Raw Normal View History

2026-11-25 17:21:45 +00:00
# Audit Remediation Implementation Plan
Prepared 2026-11-25 for a Luna coding agent.
Baseline: `e67633b9f48b42c5b0d14782c6e8e1d4c78fcdd5`.
Status: implementation in progress.
2026-11-25 17:21:45 +00:00
## 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
**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.
2026-11-25 17:21:45 +00:00
**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
**Status: complete.** Whitespace-sensitive file identities and fixed SHA-256
expectations are covered; the identity test failed with URI trimming in place.
2026-11-25 17:21:45 +00:00
**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
**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.
2026-11-25 17:21:45 +00:00
**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
**Status: complete.** A real configured server holds one provider call while a
second receives a private capacity rejection without another dispatch.
2026-11-25 17:21:45 +00:00
**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.