341 lines
13 KiB
Go
341 lines
13 KiB
Go
package stage
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
|
)
|
|
|
|
const (
|
|
extractSkipReason = "notarius_disabled"
|
|
extractLaneOutputKind = "notarius_lane"
|
|
)
|
|
|
|
type extractStage struct{}
|
|
|
|
func (extractStage) Name() string { return "extract" }
|
|
|
|
func (extractStage) NeedsAttemptViews(env *Env) bool {
|
|
return env == nil || env.Config == nil || env.Config.Pipeline == nil || env.Config.Pipeline.Notarius != nil && env.Config.Pipeline.Notarius.Enabled
|
|
}
|
|
|
|
func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (result *StageResult, resultErr error) {
|
|
if env == nil || env.Config == nil || env.Config.Pipeline == nil || env.Config.Session == nil {
|
|
return nil, fmt.Errorf("extract: resolved stage environment config is required")
|
|
}
|
|
notariusConfig := env.Config.Pipeline.Notarius
|
|
if notariusConfig == nil || !notariusConfig.Enabled {
|
|
return &StageResult{
|
|
Disposition: StageDispositionSkipped,
|
|
SkipReason: extractSkipReason,
|
|
Metadata: map[string]any{
|
|
"stage": "extract",
|
|
"notarius_enabled": false,
|
|
"reason": extractSkipReason,
|
|
},
|
|
}, nil
|
|
}
|
|
if env.ArtifactStore == nil {
|
|
return nil, fmt.Errorf("extract: artifact store is required")
|
|
}
|
|
if env.Notarius == nil {
|
|
return nil, fmt.Errorf("extract: notarius adapter is required")
|
|
}
|
|
if m == nil {
|
|
return nil, fmt.Errorf("extract: session manifest is required")
|
|
}
|
|
|
|
sessionID := strings.TrimSpace(m.SessionID)
|
|
if sessionID == "" {
|
|
sessionID = strings.TrimSpace(env.Config.Session.SessionID)
|
|
}
|
|
campaign := strings.TrimSpace(m.Campaign)
|
|
if campaign == "" {
|
|
campaign = strings.TrimSpace(env.Config.Session.Campaign)
|
|
}
|
|
runID := strings.TrimSpace(m.RunID)
|
|
if sessionID == "" || campaign == "" || runID == "" {
|
|
return nil, fmt.Errorf("extract: session id, campaign, and run id are required")
|
|
}
|
|
if !safePathSegment(runID) {
|
|
return nil, fmt.Errorf("extract: run id %q is not a safe path segment", runID)
|
|
}
|
|
|
|
paths := sessionPathsForEnv(env, sessionID)
|
|
input, err := artifacts.ResolveExtractionInputIdentity(paths, m)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve final-trimmed transcript identity: %w", err)
|
|
}
|
|
references, err := resolveExtractReferences(paths, m, notariusConfig, sessionID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve Notarius references: %w", err)
|
|
}
|
|
|
|
timeout, err := time.ParseDuration(strings.TrimSpace(notariusConfig.Timeout))
|
|
if err != nil || timeout <= 0 {
|
|
return nil, fmt.Errorf("extract: invalid notarius timeout %q", notariusConfig.Timeout)
|
|
}
|
|
resolvedBinary, err := resolveExecutable(notariusConfig.Binary)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve notarius binary: %w", err)
|
|
}
|
|
configPath, err := absolutePath(notariusConfig.ConfigPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve notarius config path: %w", err)
|
|
}
|
|
inputPath := input.Path
|
|
workingDirectory, err := absolutePath(notariusConfig.WorkingDirectory)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve notarius working directory: %w", err)
|
|
}
|
|
|
|
workspaceRoot := strings.TrimSpace(paths.WorkspaceRoot)
|
|
if workspaceRoot == "" {
|
|
workspaceRoot = env.Config.Pipeline.Workspace.Root
|
|
}
|
|
reportPath, err := absolutePath(artifacts.SessionRunNotariusReportPathForCampaign(workspaceRoot, campaign, sessionID, runID))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve completion report path: %w", err)
|
|
}
|
|
logPath, err := absolutePath(artifacts.SessionRunNotariusLogPathForCampaign(workspaceRoot, campaign, sessionID, runID))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve stderr path: %w", err)
|
|
}
|
|
outputRoot, err := absolutePath(artifacts.SessionRunNotariusOutputRootForCampaign(workspaceRoot, campaign, sessionID, runID))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve output root: %w", err)
|
|
}
|
|
directories := []string{filepath.Dir(reportPath), outputRoot}
|
|
for _, directory := range directories {
|
|
if err := fileops.EnsureWorkspaceDirectory(directory); err != nil {
|
|
return nil, fmt.Errorf("extract: create directory %q: %w", directory, err)
|
|
}
|
|
}
|
|
referenceBindings, err := materializeExtractReferenceSnapshots(paths, references)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: materialize Notarius reference snapshots: %w", err)
|
|
}
|
|
fingerprint, err := extractionFingerprint(notariusConfig, input, references.Identities)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: build configuration fingerprint: %w", err)
|
|
}
|
|
cache := notariusConfig.Cache
|
|
if env.Force {
|
|
refresh := "refresh"
|
|
cache = &refresh
|
|
}
|
|
debugDirectory, err := absolutePath(artifacts.SessionRunDebugDir(paths, runID, "extract"))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve debug directory: %w", err)
|
|
}
|
|
request := notarius.RunRequest{
|
|
Binary: resolvedBinary, Credentials: notariusConfig.Credentials, ConfigOverlay: notariusConfig.ConfigOverlay,
|
|
ConfigPath: configPath, PipelineID: notariusConfig.PipelineID,
|
|
InputPath: inputPath, OutputRoot: outputRoot, WorkingDirectory: workingDirectory,
|
|
ReportPath: reportPath, LogPath: logPath, Timeout: timeout, Cache: cache,
|
|
Debug: notariusConfig.Debug, DebugDirectory: debugDirectory, References: referenceBindings,
|
|
}
|
|
// Producer files remain inspectable even when completion delivery fails.
|
|
// Only Narratio's temporary promotion copies are cleaned below.
|
|
adapterResult, err := env.Notarius.Run(ctx, request)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: run notarius: %w", err)
|
|
}
|
|
report := adapterResult.Report
|
|
bundle := filepath.Clean(adapterResult.BundleRoot)
|
|
if report.Pipeline != notariusConfig.PipelineID || report.ArtifactCount < 0 || report.FallbackCount < 0 ||
|
|
!filepath.IsAbs(bundle) || filepath.Clean(report.OutputDirectory) != bundle {
|
|
return nil, fmt.Errorf("extract: notarius completion report is missing or incompatible")
|
|
}
|
|
if err := validateExtractBundleRoot(outputRoot, bundle); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := normalizeNotariusBundle(bundle); err != nil {
|
|
return nil, fmt.Errorf("extract: validate Notarius bundle: %w", err)
|
|
}
|
|
if err := verifyExtractReferenceSnapshots(paths, references); err != nil {
|
|
return nil, fmt.Errorf("extract: verify Notarius reference snapshots: %w", err)
|
|
}
|
|
staging, err := os.MkdirTemp(filepath.Dir(outputRoot), ".products-")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: create product staging directory: %w", err)
|
|
}
|
|
defer func() {
|
|
if cleanupErr := fileops.RemoveAllUnderRoot(filepath.Dir(staging), staging); cleanupErr != nil {
|
|
resultErr = errors.Join(resultErr, fmt.Errorf("extract: remove staged products: %w", cleanupErr))
|
|
}
|
|
}()
|
|
selected, err := stageRequiredNotariusLanes(bundle, staging, notariusConfig.Outputs)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
root, err := absolutePath(paths.Root)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: resolve session root: %w", err)
|
|
}
|
|
artifactDir := filepath.Join(root, "artifacts")
|
|
if err := checkExtractSnapshotDirectory(root, artifactDir, true); err != nil {
|
|
return nil, fmt.Errorf("extract: validate artifact directory: %w", err)
|
|
}
|
|
outputs := make([]artifacts.Ref, 0, len(selected))
|
|
for _, lane := range selected {
|
|
destination := filepath.Join(artifactDir, lane.Filename)
|
|
if info, statErr := os.Lstat(destination); statErr == nil {
|
|
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
|
|
return nil, fmt.Errorf("extract: output %q is not a regular file", destination)
|
|
}
|
|
} else if !os.IsNotExist(statErr) {
|
|
return nil, fmt.Errorf("extract: inspect output: %w", statErr)
|
|
}
|
|
checksum, err := fileops.CopyFileAtomicWithChecksum(lane.StagedPath, destination, fileops.WorkspaceFileMode)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("extract: promote lane %q: %w", lane.LaneID, err)
|
|
}
|
|
if checksum != lane.Checksum {
|
|
return nil, fmt.Errorf("extract: promoted lane %q checksum differs from staged bytes", lane.LaneID)
|
|
}
|
|
outputs = append(outputs, artifacts.Ref{
|
|
Kind: extractLaneOutputKind, SourceID: artifacts.ExtractionArtifactSourceID(lane.Key),
|
|
Category: "artifacts", SessionID: sessionID, RelativePath: filepath.ToSlash(filepath.Join("artifacts", lane.Filename)),
|
|
AbsolutePath: destination, Checksum: checksum, Size: lane.Size,
|
|
ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: report.Pipeline, ArtifactID: lane.LaneID},
|
|
})
|
|
}
|
|
completion := map[string]any{"pipeline": report.Pipeline, "artifact_count": report.ArtifactCount, "output_directory": bundle}
|
|
if report.DebugDirectory != "" {
|
|
completion["debug_directory"] = report.DebugDirectory
|
|
}
|
|
if report.FallbackCount > 0 {
|
|
completion["fallback_count"] = report.FallbackCount
|
|
env.Warn(fmt.Sprintf("Notarius completed with %d fallback operations", report.FallbackCount))
|
|
}
|
|
metadata := map[string]any{
|
|
"stage": "extract", "notarius_enabled": true, "bundle_root": bundle,
|
|
"diagnostic_path": logPath, "narratio_run_id": runID,
|
|
"configuration_fingerprint": fingerprint, "direct_input": input.Metadata(),
|
|
"reference_count": len(references.Identities), "references": extractReferenceMetadata(references.Identities),
|
|
"completion": completion,
|
|
}
|
|
result = &StageResult{Outputs: outputs, Logs: []string{reportPath, logPath}, Metadata: metadata}
|
|
return result, nil
|
|
}
|
|
|
|
func normalizeNotariusBundle(root string) error {
|
|
return filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
info, err := entry.Info()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if info.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("bundle path %q is a symlink", path)
|
|
}
|
|
if info.IsDir() {
|
|
return os.Chmod(path, fileops.WorkspaceDirectoryMode)
|
|
}
|
|
if !info.Mode().IsRegular() {
|
|
return fmt.Errorf("bundle path %q is not regular", path)
|
|
}
|
|
return os.Chmod(path, fileops.WorkspaceFileMode)
|
|
})
|
|
}
|
|
|
|
type fingerprintOutput struct {
|
|
Key string `json:"key"`
|
|
LaneID string `json:"lane_id"`
|
|
Filename string `json:"filename"`
|
|
MediaType string `json:"-"`
|
|
SchemaID string `json:"-"`
|
|
SchemaVersion string `json:"-"`
|
|
ModuleKey string `json:"-"`
|
|
}
|
|
|
|
type fingerprintDocument struct {
|
|
PipelineID string `json:"pipeline_id"`
|
|
ConfigOverlay string `json:"config_overlay,omitempty"`
|
|
Input artifacts.ExtractionInputIdentity `json:"input"`
|
|
References []extractReferenceIdentity `json:"references"`
|
|
Outputs []fingerprintOutput `json:"outputs"`
|
|
}
|
|
|
|
func extractionFingerprint(
|
|
cfg *config.NotariusConfig,
|
|
input artifacts.ExtractionInputIdentity,
|
|
references []extractReferenceIdentity,
|
|
) (string, error) {
|
|
keys := make([]string, 0, len(cfg.Outputs))
|
|
for key := range cfg.Outputs {
|
|
keys = append(keys, key)
|
|
}
|
|
sort.Strings(keys)
|
|
outputs := make([]fingerprintOutput, 0, len(keys))
|
|
for _, key := range keys {
|
|
output := cfg.Outputs[key]
|
|
outputs = append(outputs, fingerprintOutput{
|
|
Key: key, LaneID: output.LaneID, Filename: config.ExtractionFilename(key, output),
|
|
})
|
|
}
|
|
sortedReferences := append([]extractReferenceIdentity(nil), references...)
|
|
sort.Slice(sortedReferences, func(i, j int) bool {
|
|
if sortedReferences[i].Selector != sortedReferences[j].Selector {
|
|
return sortedReferences[i].Selector < sortedReferences[j].Selector
|
|
}
|
|
if sortedReferences[i].SourceID != sortedReferences[j].SourceID {
|
|
return sortedReferences[i].SourceID < sortedReferences[j].SourceID
|
|
}
|
|
return sortedReferences[i].Path < sortedReferences[j].Path
|
|
})
|
|
payload, err := json.Marshal(fingerprintDocument{
|
|
PipelineID: cfg.PipelineID, ConfigOverlay: notariusConfigOverlayReuseIdentity(cfg.ConfigOverlay),
|
|
Input: input, References: sortedReferences, Outputs: outputs,
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
digest := sha256.Sum256(payload)
|
|
return hex.EncodeToString(digest[:]), nil
|
|
}
|
|
|
|
func resolveExecutable(value string) (string, error) {
|
|
resolved, err := exec.LookPath(strings.TrimSpace(value))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return absolutePath(resolved)
|
|
}
|
|
|
|
func absolutePath(value string) (string, error) {
|
|
trimmed := strings.TrimSpace(value)
|
|
if trimmed == "" {
|
|
return "", fmt.Errorf("path is required")
|
|
}
|
|
resolved, err := filepath.Abs(trimmed)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return filepath.Clean(resolved), nil
|
|
}
|
|
|
|
func safePathSegment(value string) bool {
|
|
return value != "" && value != "." && value != ".." && filepath.Base(value) == value &&
|
|
!strings.ContainsAny(value, `/\\`)
|
|
}
|