Files
narratio/docs/roadmap/remediation.md

480 lines
28 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.
# Shared pipeline cutover review findings
Reviewed Narratio commit `2ec43305da6c47709909d5cee167c7be0358b311`
against all 23 stages in [implementation.md](implementation.md) and the target
in [pipeline.md](pipeline.md). The catalog migration and controlled consumer
boundaries were included. This document records required remediations and
algorithmic refactoring opportunities for consideration. It does not implement
them or change the agreed operator contract.
## 1. Preserve available producer files after failed extraction
**Priority:** P2
**Status:** Complete
Producer output is retained on failure; temporary promotion copies still clean
up. Stage regressions cover failed delivery and missing/invalid lanes, without
promoting incidental files. Verified with `go test ./internal/stage`.
**Stages:** 11–12; failure-evidence and workspace requirements in 16 and 21–23.
**Evidence:** [extract.go](../../internal/stage/extract.go),
`extractStage.Run`, lines 154–164. Its deferred cleanup removes the entire
`notarius-output` root whenever `accepted` remains false. That includes a
subprocess failure, malformed completion, required-file failure, or failed
promotion after Notarius has already written files.
The roadmap's Notarius completion section explicitly accounts for report/capture
failure after artifact publication and requires retaining available files and
diagnostics without recovering success from them. The current cleanup discards
those producer files before an operator can inspect them. Separate stdout/stderr
logs and debug captures can survive, but they do not replace the discarded lane
payloads and optional domain evidence. This is a target-state gap, not a request
to treat partial results as successful extraction.
**Reproduction:** a temporary Go-overlay test used the existing
`nativeExtractFixture`, returned an adapter error representing failed completion
delivery, and checked an existing producer lane after `extractStage.Run` failed.
The lane was gone (`no such file or directory`). The test added no repository
file and made no model call.
**Required change:** retain the producing attempt's Notarius output tree on
failure, under its existing run-local destination. Keep the failure result and
existing canonical-promotion checks. Continue removing Narratio-owned temporary
product copies where appropriate. Failed producer output remains attempt
evidence subject to the ordinary run lifecycle; it gains neither automatic
success/reuse authority nor a new permanent-retention guarantee.
**Verification:** add a durable regression at the extraction stage boundary for
producer files present when report delivery fails, and for successful subprocess
completion followed by missing/invalid required lanes. Confirm files remain
inspectable, the stage fails, and no incidental output becomes available as a
successful extraction. Preserve prior canonical files where failure occurs
before promotion, as the existing staging test already requires.
## 2. Limit cleanup's managed-view validation to the views it owns
**Priority:** P2
**Status:** Complete
Cleanup inspects only canonical stage and restore views. Unrelated files,
directories, and links remain untouched; conflicts at owned views still fail.
Verified cleanup/resume/rotation and file-operation tests with
`go test ./internal/fileops ./internal/stage`.
**Stages:** 15 and 20; requirement-strengthening review in 21–23.
**Evidence:** [attempt_views.go](../../internal/fileops/attempt_views.go),
`ManagedAttemptTargets`, especially lines 179–188;
[cleanup_retained_bundle.go](../../internal/stage/cleanup_retained_bundle.go),
lines 36–39. Cleanup enumerates every entry in the session's `logs/` and
`debug/` roots and passes each to `existingManagedView`. A regular file or
ordinary directory causes an error even when unrelated to a stage view or to
the run being cleaned.
For example, an operator's `logs/README.txt` blocks both cleanup execution and
cleanup resume checks with a managed-view conflict. Finder metadata or other
unrelated entries can have the same effect. This introduces an undocumented
requirement that those directory roots contain exclusively valid managed
symlinks. The selected contract requires protecting Narratio's latest-attempt
targets and rejecting conflicts at a view being installed; it does not require
rejecting unrelated operator content across the entire directory.
**Reproduction:** a temporary Go-overlay test created a valid extraction result
and managed attempt views, added `logs/README.txt`, and evaluated
`cleanRunWithRetainedBundle(..., false)`. It failed with
`managed logs view "README.txt" conflicts with existing content`, before any
deletion. The test changed no repository files.
**Required change:** identify and validate Narratio-managed views narrowly when
computing protected run targets. Leave unrelated entries untouched and do not
make them prerequisites for cleanup. Preserve confinement, avoid following
arbitrary links, and retain conflict rejection when an actual managed stage view
is created or replaced. Do not fix this by documenting or enforcing a new
exclusive-directory prohibition.
**Verification:** cover unrelated regular files/directories in both roots,
correct protection of valid latest links, and unchanged rejection of unsafe or
conflicting owned views. Exercise cleanup and its resume check; unrelated files
must remain untouched and eligible run cleanup must still complete.
## 3. Replace obsolete commands in runtime recovery guidance
**Priority:** P2
**Status:** Complete
Active input-recovery diagnostics now use the native `run SESSION --stage STAGE
--force` route. Corresponding missing/corrupt-input tests were updated; retired
command rejection tests remain intact. Verified stage and application tests.
**Stages:** 9, 12, 16, and the integration/documentation reconciliation in 21–23.
**Evidence:** [extract_references.go](../../internal/stage/extract_references.go),
line 278; [analyze_input_identity.go](../../internal/stage/analyze_input_identity.go),
lines 131, 137, 187, and 193; the built-in source recovery helpers in
[analyze.go](../../internal/stage/analyze.go) and
[render.go](../../internal/stage/render.go).
Missing or invalid prepared inputs, extraction outputs, and transcript inputs
still produce commands of the form `narratio run-stage prepare SESSION --force`.
The native CLI has no `run-stage` route. Running that recommended command exits
with status 2; running it without the flag confirms the unknown-command error.
The current CLI reference correctly documents `run SESSION --stage STAGE`.
This guidance predates the sprint, but remains active in the newly integrated
prepared-reference, analysis, and render workflows. Several existing tests assert
the obsolete command substring, so the green suite perpetuates the mismatch.
This is an inherited operator-recovery gap, not a regression introduced by the
Notarius protocol migration.
**Required change:** use `narratio run SESSION --stage STAGE --force` in active
recovery messages and reconcile the corresponding tests. Preserve useful source
and stage context. Historical release notes and migration tables may correctly
name retired commands and should not be rewritten. No compatibility alias is
needed.
**Verification:** exercise missing/corrupt prepared references, required analysis
inputs, and render inputs, and check that the suggested command has a supported
native route and flags. Test semantic recovery guidance rather than snapshotting
whole diagnostic strings. No generation or paid provider is needed to establish
CLI syntax compatibility.
## 4. Reconcile accepted absolute analysis destinations with artifact identity
**Priority:** P2
**Status:** Complete
Shared session-relative identity now covers fingerprints, checkpoints, catalog
evidence, publication defaults, and restore fallback mapping. Configuration
remains unchanged. Verified equivalent-path reuse, forced generation with a
dependent artifact, portable records, publication mapping, confined paths, and
committed restore with focused stage/artifact/policy/application tests.
**Stages:** 10 and 16; analysis reuse and lifecycle integration in 18–19 and 21.
**Evidence:** [product_destinations.go](../../internal/config/product_destinations.go),
`validateProductDestinations`, lines 19–35 and 63–65, accepts an absolute
destination directly under the selected session's `artifacts/` directory.
[analyze_fingerprint.go](../../internal/stage/analyze_fingerprint.go),
`normalizedAnalyzeOutputIdentity`, lines 251–260, instead passes the configured
value to a relative-only normalizer. Analysis checkpoint creation uses that same
helper. [analyze_evidence.go](../../internal/artifacts/analyze_evidence.go),
`InspectAnalyzeEvidence`, lines 77–82, independently rejects the absolute form.
An operator can therefore supply a valid flat destination, pass configuration
validation, and then fail analysis with `relative path must not be absolute`.
Selecting the equivalent absolute path for an already completed artifact also
makes it non-resumable. Catalog hydration consequently cannot advertise that
artifact as current for dependent analysis or publication. This is an existing
relative-only assumption left unreconciled with the Stage 10 decision to retain
both absolute and relative syntax for valid canonical destinations, rather than
a new regression in the fingerprint helper itself.
**Reproduction:** temporary Go-overlay tests confirmed that concrete-artifact
and product-destination validation accept an absolute canonical path. Separate
tests using `currentAnalyzeFixture` confirmed that changing only
`artifacts/session_recap.md` to its absolute equivalent makes resume return
non-resumable and makes forced analysis fail during fingerprint computation.
The probes changed no repository code and used no real subprocess or provider.
**Required change:** derive one consistent session-relative product identity
from either supported syntax using the selected session root, and use it for
analysis fingerprints, checkpoint records, and evidence/catalog resolution.
Keep the ConfigKit result unchanged and retain the existing flat-placement and
confinement rules. Reconcile publication and restore consumers of configured
output paths as necessary. Do not resolve the mismatch by imposing a new ban
on valid absolute destinations.
**Verification:** cover successful analysis and unchanged resume for equivalent
absolute/relative canonical paths, current artifact resolution and dependent
inputs, and publication/restore with that configuration. Manifest product
identities remain portable and session-relative; paths outside the permitted
product directory remain invalid under the existing placement contract.
## 5. Index committed product paths once per restore plan
**Priority:** P3
**Status:** Complete
Restore builds one source-path index and lazily constructs one fallback catalog
per plan. Duplicate evidence remains available for agreement checks; unrelated
paths are validated only when selected. Verified committed restore, fallback,
conflict, and path-agreement tests in `internal/app`.
**Stages:** 19 and 21.
In [restore_plan.go](../../internal/app/restore_plan.go),
`buildCommittedRestoreActions` calls `restoreProductRelativePath` for each
published product. Each call scans every stage output and every per-artifact
analysis record. With P published products and A manifest output records, this
mapping costs O(P × A), quadratic when P grows with A. This is new cutover code.
Missing evidence also rebuilds the configured artifact catalog on each lookup.
Build a source-ID-to-paths index once per restore plan, then resolve each selected
source from that index. Mapping becomes expected O(A + P), plus the paths
actually checked. Build the fallback catalog at most once, lazily. Retain both
aggregate and per-artifact evidence and the existing disagreement checks;
last-write-wins indexing would hide conflicts. Validate paths for the requested
sources as today, without adding rejection rules for unrelated records.
Verification should preserve nested-remote/flat-local mappings, carried locked
objects, duplicate agreeing evidence, conflicting paths, and missing-source
fallbacks. The complexity finding follows directly from the nested call/scan;
no timing or production-size assumption is required.
## 6. Index prior audio records before S3 materialization
**Priority:** P3
**Status:** Complete
Prior audio records are indexed once by cleaned destination, retaining the first
audio match. Existing identity/hash/download checks remain unchanged. Verified
S3 reuse, missing-file replacement, unrelated kinds, and duplicate-record
precedence with `go test ./internal/stage ./internal/audio`.
**Stage:** 17.
In [prepare.go](../../internal/stage/prepare.go), `materializeS3AudioInputs`
scans `m.Inputs` for every selected S3 object (lines 436–444). For F objects and
R recorded inputs, prior-record selection is O(F × R), becoming O(F²) when
the manifest contains the same F audio inputs. This loop was introduced with
the simplified single-copy materialization path. It repeatedly cleans the same
recorded paths as well.
Index audio records by cleaned destination path once, then perform expected
constant-time lookup per object: O(R + F) selection time and O(R) auxiliary
space, treating path length separately. Preserve current first-match behavior
if duplicate records are encountered, and keep all source-identity, checksum,
size, cancellation, and download verification in `MaterializeS3Audio` unchanged.
Audio-byte hashing and transfer costs remain linear in the bytes processed;
this opportunity concerns metadata lookup, not those required checks.
Verify reuse and replacement with reordered records, unrelated input kinds,
missing records, and changed remote identities. The loop structure establishes
the complexity without a benchmark.
## 7. Replace repeated roster ambiguity scans with indexed membership
**Priority:** P3
**Status:** Complete
Names, aliases, and classes use indexed Unicode simple-fold membership; sorted
character traversal and forwarded strings are unchanged. Verified existing
roster/family checks plus Unicode ambiguity across aliases, characters, and
classes with `go test ./internal/config`.
**Stage:** 4.
In [party.go](../../internal/config/party.go), `firstPartyDomainError` and
`partyNameAmbiguous` compare each character name/alias against all earlier names
and copy the accumulated list for each character (lines 150–195 and 212–218).
N distinct names/aliases require N(N−1)/2 string comparisons. Per-character
class validation likewise takes O(K²) comparisons for K classes. String lengths
multiply these comparison costs; cumulative name-list copying can also be
quadratic. This algorithm predates the migration and remains in the newly
adopted shared-roster path; it is not a new regression. Ordinary parties are
small, so practical benefit may be modest.
Retain sorted character traversal and the selected ambiguity rules, but use
one membership set for names/aliases and one per-character class set. With
appropriate fold keys, membership becomes expected linear in total name bytes,
plus the existing O(C log C) ordering of C character IDs. Preserve exactly
`strings.EqualFold` equivalence, including Unicode simple-fold classes; plain
`strings.ToLower` is not an equivalent key function. A small canonical
simple-fold key helper is one option. Preserve original forwarded strings.
Verify within/across-character ambiguity, repeated player names, duplicate
classes, and Unicode pairs such as sigma/final-sigma and ASCII K/Kelvin sign.
This changes lookup machinery, not the agreed Narratio roster requirements.
## 8. Avoid repeatedly sorting the analysis ready queue
**Priority:** P3
**Status:** Complete
Analysis fingerprint ordering uses a standard-library lexical min-heap and no
longer sorts the ready queue on insertion. Dependency validation and the
smallest-ready-key order remain intact. Verified fingerprint, planning, and
execution graph tests with `go test ./internal/stage`.
**Stages:** 16 and 21; inherited analysis scheduling used by the cutover.
In [analyze_fingerprint.go](../../internal/stage/analyze_fingerprint.go),
`orderConfiguredAnalyzeArtifacts` sorts the entire ready slice whenever a
dependent becomes ready. A root with V−1 independent dependents causes sorts
of queues of lengths 1 through V−1. Even already sorted queues require
quadratic aggregate inspection; a general upper bound is O(V² log V), apart
from edge processing and dependency normalization. The implementation predates
this sprint; character-expanded artifact families increase its input size.
The roadmap selects deterministic dependency ordering, not this queue algorithm.
Use the standard library's `container/heap` with a lexical min-heap. Each vertex
is inserted and removed once, yielding O(E + V log V) queue/edge work for E
dependency edges, plus any retained dependency-list normalization. It preserves
the same smallest-ready-key choice; a FIFO queue would change that ordering.
Keep unknown-dependency and cycle errors. Verify wide fan-out, chains, shared
prerequisites, and map-insertion independence against the same observable order.
## 9. Prevent generated audio names from colliding with original names
**Priority:** P2
**Status:** Pending
**Stage:** 17; retained local-audio acquisition behavior.
In [prepare.go](../../internal/stage/prepare.go), `localAudioDestinations`
(lines 381–401) disambiguates equal basenames independently of other basename
groups. For `/a/one.flac` and `/b/one.flac`, it generates names containing a
source-path hash. A third recording can already have exactly one of those
generated basenames. The two distinct sources then share a destination.
`materializeLocalAudioInputs` sequentially copies both to that path, so the
later recording replaces the earlier prepared copy. Original recordings remain
untouched, but prepared membership/evidence can no longer represent both.
This is an inherited correctness defect, not a newly introduced naming scheme.
A temporary offline Go-overlay test constructed the third basename from the
first source's actual digest and confirmed duplicate destinations. No hash
collision, race, real audio, or external service was required.
Resolve destination ownership across the complete selected audio set. Reserve
unmodified names and check generated candidates against a global occupied-name
set, using deterministic conflict resolution while retaining ordinary existing
names. At minimum, detect an unresolved conflict before copying either source;
do not permit silent replacement or ban ordinary duplicate-basename inputs.
The existing assignment is expected O(F) in F paths; global membership checks
can remain expected O(F), with O(F log F) if deterministic ordering is needed.
No new persistence or compatibility machinery is required.
Verify a generated-versus-original collision, ordinary duplicate basenames,
unchanged noncolliding names, and materialization of distinct bytes to distinct
destinations. Check destination uniqueness before performing file writes.
## Review coverage and verification
| Implementation stages | Inspected boundaries |
| --- | --- |
| 1–3 | Offline schema compilation/resources, new-state rejection before execution/restore, and canonical workspace paths. |
| 4–6 | Shared roster profile and forwarding, campaign/session resolution and presence semantics, native inspection, initialization and template selection. |
| 7 | Catalog source migration, local validator/CI, schema provenance, and independent validation. |
| 8–10 | Standalone inputs and autocorrection, four individual and combined envelopes, reference snapshots, output naming/collisions and native controls. |
| 11–14 | Native completion/required products, fallback/reuse evidence, Audita inputs/destinations, and shared pipeline-aware readiness. |
| 15–17 | Managed views, producer log/debug/product routing, and single-copy audio acquisition. |
| 18–20 | Publication declarations, canonical restore/previous inputs and diagnostics, role-aware cleanup/retention. |
| 21–23 | Reuse and bounded workflows, maintained examples, controlled real consumers, canonical documentation, and attribution. |
Passing checks during review used Go 1.27.4:
- Narratio: `go test ./...`, `go test -race ./...`, `go vet ./...`, and
`go build ./...`; CGO-disabled CLI cross-builds for Linux amd64/arm64 and
darwin arm64. The macOS result establishes compilation, not native execution.
- Catalog: `go test ./...` and `go run ./cmd/validate`.
- The catalog compatibility script against the pinned Audita v4.3.0 and
Notarius v0.10.0 source builds with local HTTP provider fixtures. All ten
Notarius lanes passed; initial, cached, and forced runs used 9, 0, and 9
provider calls respectively. No paid provider was used.
- All six vendored schema/semantic files matched the released schema checkout
byte for byte. Consumer binary VCS revisions matched the roadmap baselines.
The two temporary regression probes reproduced findings 1 and 2 despite the
green existing suites. Finding 3 was confirmed against the built native CLI
and its existing diagnostic assertions. These expose coverage gaps, not flaky
default tests. No further required remediation was identified in the initial
reviewed scope.
### Integration follow-up
A second review used Narratio commit
`d3d7728f1f3809d65ab8256cd6973700bca31d93` (the implementation source is unchanged
from the reviewed commit above), following the implementation stages in order.
It examined new behavior against existing consumers and lifecycle machinery:
| Stage | Integration boundary reviewed |
| --- | --- |
| 1 | Shared structural/semantic validation consumes native resolved values; schema loading stays offline. |
| 2 | The v2 marker flows through local execution, remote discovery, previous-session acquisition, and restore. |
| 3 | Canonical path changes flow into stage staging, prepared references, previous inputs, and manifest resolution. |
| 4 | Shared roster acquisition and forwarding agree with the existing players projection and character-family derivation. |
| 5 | Campaign defaults and session clearing/replacement preserve independent field and resource-origin semantics. |
| 6 | Native acquisition/inspection and session initialization retain separate configuration results and template precedence. |
| 7 | The catalog's indexed shared sources retain consumer selectors and pass its independent validation. |
| 8 | Prepared snapshots and generated autocorrection feed existing Seriatim inputs and prepare resume checks. |
| 9 | Individual/combined vocabulary, prepared-source IDs, verified references, and content-change evidence agree. |
| 10 | Flat destination validation was compared with existing analysis identity code; finding 4 records the mismatch. |
| 11 | Native completion parsing retains exit-status authority and shares runtime argument construction with readiness. |
| 12 | Canonical extraction evidence feeds catalog, analysis, and reuse independently of the retained bundle; finding 1 still applies. |
| 13 | Audita execution/readiness use the same saved inputs and preserve existing transcript/report acceptance. |
| 14 | Selected-work projection controls readiness, real/synthetic input choice, lazy adapters, and isolated probe diagnostics. |
| 15 | Attempt transitions, failed attempts, self-skips, reuse, and latest-view ownership agree with runner lifecycle. |
| 16 | Transcript/product promotion and producer diagnostic routing remain distinct; finding 4 also affects analysis execution. |
| 17 | Audio acquisition and restore retain one verified copy while per-speaker checkpoints remain manifest-backed. |
| 18 | Prepared-file enumeration, product discovery, immutable declarations, lock carry, and current-run diagnostics preserve their roles. |
| 19 | Committed product mapping, rebased session references, previous inputs, audio verification, and restore conflict/recovery paths were inspected. |
| 20 | Cleanup authorization and role-based retention preserve latest targets and durable bundles; finding 2 still applies. |
| 21 | Semantic resume, bounded selection, artifact evidence, and operator recovery were checked; findings 3–4 remain applicable. |
| 22 | Assembled campaign/consumer workflows and controlled compatibility evidence were checked against the pinned releases. |
| 23 | Canonical documents, examples, recorded verification, and scope/ownership boundaries were reconciled with the implemented interfaces. |
The follow-up reran `go test ./...`, `go vet ./...`, `go build ./...`, documentation
checks, and focused configuration, stage, application, and managed-view
regressions with Go 1.27.4. Catalog `go test ./...` and `go run ./cmd/validate`
also passed at `016473fd16b15847f3e913670c423faa7c35720b`. Existing tests passed;
the temporary absolute-path probes exposed finding 4. Findings 1–3 remain
pending. No fixes, compatibility shims, new product restrictions, or upstream
changes were made.
### Algorithmic follow-up
Reviewed commit `4ee706bfb676ba2d0cf24be7aaf8472e778a6696`, in implementation
stage order. Findings 5–8 are optimization candidates for consideration;
finding 9 is a correctness remediation. Prior findings retain their statuses.
Complexities are analytical, with ordinary expected-time Go map operations;
no measured performance improvement is claimed.
| Stage | Algorithmic review |
| --- | --- |
| 1 | Schema compilation is cached with `sync.Once`; glossary uniqueness uses per-collection sets. |
| 2 | Version checks are constant-time after manifest decoding; shared remote verification remains authoritative. |
| 3 | Canonical path construction scales with path length rather than session file count. |
| 4 | Shared validation/projection was inspected; repeated ambiguity scans are finding 7. |
| 5 | Field defaulting is bounded by the fixed interface; native ConfigKit resolution remains upstream-owned. |
| 6 | Initialization and standalone rendering scale with selected document size; independent native inspections remain intentional. |
| 7 | Catalog checking compiles its schema once and uses collection-ID sets and deterministic index traversal. |
| 8 | Input reconciliation indexes kind/destination pairs; snapshots and checksum passes scale with input bytes. |
| 9 | Four individual envelopes plus one combined projection add fixed-factor serialization/validation work selected by the plan. |
| 10 | Destination collision checks use a destination-owner map after existing deterministic ordering. |
| 11 | Completion decoding is bounded and linear in report size; command/reference construction has no all-pairs scan. |
| 12 | Required-lane mapping uses owner maps and stages one payload at a time; whole-file checks and promotion remain selected behavior. |
| 13 | Audita receives the fixed four prepared files; no new variable-size matching algorithm was introduced. |
| 14 | Required-lane/readiness matching uses sets; native provider checks and ConfigKit internals are outside this audit. |
| 15 | Latest-view operations handle two categories and validate paths; managed-target enumeration is linear in view entries. |
| 16 | Producer routing is path/byte proportional; reused analysis ordering is considered in finding 8. |
| 17 | S3 prior-record lookup is finding 6; retained local destination assignment has the correctness defect in finding 9. |
| 18 | Publication enumerates declared records and indexes source/lock/destination ownership; file verification remains byte-proportional. |
| 19 | Per-product whole-manifest scans and repeated fallback catalogs are finding 5. |
| 20 | Cleanup prefix checks scan a protection set bounded by the fixed stage inventory plus bundle markers; this is not quadratic in run file count. |
| 21 | Analysis fingerprint ordering re-sorts growing ready queues (finding 8); map-backed prepare reconciliation is already linear. |
| 22 | Workflow fixtures and controlled consumer checks protect behavior, without asserting unmeasured scalability. |
| 23 | Documentation/verification adds no runtime algorithm; the recorded opportunities preserve the selected contracts. |
Explicit planning choices were left intact: native configuration composition,
deterministic ordering, five glossary documents, whole-file content evidence,
per-file staged promotion, and the retained content/lifecycle boundaries.
Nested traversal of distinct entries/classes/lanes is not by itself quadratic;
findings identify repeated traversal of the same growing collections.
Existing tests passed for configuration, stages, application, artifacts, audio,
shared validation, glossaries, file operations, and previous inputs using Go
1.27.4; documentation checks and `git diff --check` also passed. The separate
temporary audio-name probe failed as expected, reproducing finding 9. No
implementation or upstream files were changed, and no live provider or
real-world performance measurements were used.