Capture diagnostic identities and rehearsal records

This commit is contained in:
2026-12-05 22:45:28 +00:00
parent 6f01e9ef0a
commit 181e5a030c
19 changed files with 1284 additions and 60 deletions

View File

@@ -0,0 +1,27 @@
package main
import (
"context"
"fmt"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
// verifyDiagnosticTag binds dispatch to the tag's captured profile and source.
func verifyDiagnosticTag(ctx context.Context, repository, tag, commit, selector, profilePath string) (rehearsal.VerifiedTag, cli.Settings, error) {
var settings cli.Settings
verified, err := rehearsal.VerifyTag(ctx, repository, tag, commit, selector, profilePath, func(ctx context.Context, capturedCommit string, profile []byte) (releaseidentity.ResolvedSource, error) {
var err error
settings, err = cli.DecodeSettings(profile, profilePath)
if err != nil {
return releaseidentity.ResolvedSource{}, err
}
if settings.Rehearsal == nil || settings.Rehearsal.RehearsalSelector() != selector {
return releaseidentity.ResolvedSource{}, fmt.Errorf("captured profile does not select diagnostic selector %q", selector)
}
return releaseidentity.LoadCommittedSource(ctx, repository, settings.ModuleDir, capturedCommit, settings.SourceSpec())
})
return verified, settings, err
}

View File

@@ -0,0 +1,43 @@
package main
import (
"testing"
"go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli"
"go.maximumdirect.net/releasekit/internal/rehearsal"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func TestVerifyDiagnosticTagUsesCapturedProfileAndSelector(t *testing.T) {
repo := newCLIRepository(t)
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Captured","source":{},"rehearsal":{"selector":"root"}}`)
cliGitRun(t, repo, "add", "releasekit.json")
cliGitRun(t, repo, "commit", "-m", "capture diagnostic profile")
captured, err := cli.CaptureCommittedProfile(t.Context(), repo, "HEAD", "releasekit.json")
if err != nil {
t.Fatal(err)
}
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, captured.Settings.ModuleDir, captured.Commit, captured.Settings.SourceSpec())
if err != nil {
t.Fatal(err)
}
identity, attempt, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", captured.Commit)
if err != nil {
t.Fatal(err)
}
manifest := rehearsal.NewManifest(identity, attempt, "root", captured.Path, captured.Bytes)
if _, err := rehearsal.CreateDiagnosticTag(t.Context(), repo, manifest); err != nil {
t.Fatal(err)
}
writeRepositoryFile(t, repo, "releasekit.json", `{"product":"Working tree"}`)
verified, settings, err := verifyDiagnosticTag(t.Context(), repo, identity.Tag, captured.Commit, "root", captured.Path)
if err != nil || settings.Product != "Captured" || verified.Manifest.AttemptID != attempt {
t.Fatalf("verified=%+v settings=%+v error=%v", verified, settings, err)
}
if _, _, err := verifyDiagnosticTag(t.Context(), repo, identity.Tag, captured.Commit, "other", captured.Path); err == nil {
t.Fatal("accepted wrong selector")
}
if _, _, err := verifyDiagnosticTag(t.Context(), repo, identity.Tag, "0000000000000000000000000000000000000000", "root", captured.Path); err == nil {
t.Fatal("accepted wrong event commit")
}
}

View File

@@ -0,0 +1,62 @@
package cli
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"path/filepath"
"strings"
"go.maximumdirect.net/releasekit/internal/git"
)
// CommittedProfile captures the exact profile used by a rehearsal.
type CommittedProfile struct {
RepositoryDir string
Commit string
Path string
SHA256 string
Settings Settings
Bytes []byte
}
// CaptureCommittedProfile reads the chosen profile from a resolved commit,
// independent of the working checkout and index.
func CaptureCommittedProfile(ctx context.Context, repositoryDir, revision, configPath string) (CommittedProfile, error) {
var result CommittedProfile
root, err := git.RepositoryRoot(ctx, repositoryDir)
if err != nil {
return result, err
}
result.RepositoryDir = root
result.Commit, err = git.ResolveCommit(ctx, root, revision)
if err != nil {
return result, err
}
if configPath == "" {
configPath = "releasekit.json"
}
if filepath.IsAbs(configPath) {
configPath, err = filepath.Rel(root, filepath.Clean(configPath))
if err != nil {
return result, fmt.Errorf("relate profile to checkout: %w", err)
}
}
configPath = filepath.Clean(configPath)
if configPath == "." || configPath == ".." || strings.HasPrefix(configPath, ".."+string(filepath.Separator)) || filepath.IsAbs(configPath) {
return result, fmt.Errorf("rehearsal profile must be committed within the checkout")
}
result.Path = filepath.ToSlash(configPath)
result.Bytes, err = git.ReadCommitFile(ctx, root, result.Commit, result.Path)
if err != nil {
return result, fmt.Errorf("rehearsal profile %q must exist in the selected commit: %w", result.Path, err)
}
result.Settings, err = DecodeSettings(result.Bytes, result.Path)
if err != nil {
return result, err
}
digest := sha256.Sum256(result.Bytes)
result.SHA256 = hex.EncodeToString(digest[:])
return result, nil
}

View File

@@ -0,0 +1,84 @@
package cli
import (
"crypto/sha256"
"encoding/hex"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestCaptureCommittedProfileIgnoresWorkingChanges(t *testing.T) {
repo := t.TempDir()
run := func(args ...string) string {
t.Helper()
command := exec.Command("git", args...)
command.Dir = repo
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v: %s", args, err, output)
}
return strings.TrimSpace(string(output))
}
run("init", "--initial-branch=main")
run("config", "user.name", "ReleaseKit Test")
run("config", "user.email", "releasekit@example.test")
run("config", "commit.gpgsign", "false")
name := filepath.Join(repo, "releasekit.json")
first := []byte(`{"product":"Original","source":{},"rehearsal":{"woodpecker":{"base_url":"https://ci.example","repository_id":42,"workflow":"delivery","step":"publish","token_file":".releasekit/ci-token"}}}`)
if err := os.WriteFile(name, first, 0600); err != nil {
t.Fatal(err)
}
run("add", "releasekit.json")
run("commit", "-m", "first profile")
firstCommit := run("rev-parse", "HEAD")
if err := os.WriteFile(name, []byte(`{"product":"Second"}`), 0600); err != nil {
t.Fatal(err)
}
run("add", "releasekit.json")
run("commit", "-m", "second profile")
if err := os.WriteFile(name, []byte(`{"product":"Dirty"}`), 0600); err != nil {
t.Fatal(err)
}
before := run("status", "--porcelain")
captured, err := CaptureCommittedProfile(t.Context(), repo, firstCommit, name)
digest := sha256.Sum256(first)
if err != nil || captured.Commit != firstCommit || captured.Path != "releasekit.json" || captured.Settings.Product != "Original" || captured.Settings.Rehearsal == nil || captured.Settings.Rehearsal.RehearsalSelector() != "root" || captured.Settings.Rehearsal.Woodpecker.RepositoryID != 42 || captured.SHA256 != hex.EncodeToString(digest[:]) || string(captured.Bytes) != string(first) {
t.Fatalf("captured=%+v error=%v", captured, err)
}
latest, err := CaptureCommittedProfile(t.Context(), repo, "", "")
if err != nil || latest.Settings.Product != "Second" {
t.Fatalf("HEAD profile=%+v error=%v", latest, err)
}
if _, err := CaptureCommittedProfile(t.Context(), repo, "HEAD", filepath.Join(t.TempDir(), "outside.json")); err == nil || !strings.Contains(err.Error(), "within the checkout") {
t.Fatalf("external profile error=%v", err)
}
if _, err := CaptureCommittedProfile(t.Context(), repo, "HEAD", "missing.json"); err == nil || !strings.Contains(err.Error(), "selected commit") {
t.Fatalf("missing profile error=%v", err)
}
if after := run("status", "--porcelain"); after != before {
t.Fatalf("capture changed checkout: %q != %q", after, before)
}
}
func TestResolveWoodpeckerCredentialUsesSelectedFile(t *testing.T) {
repo := t.TempDir()
if err := os.WriteFile(filepath.Join(repo, "token"), []byte(" ci-secret \n"), 0600); err != nil {
t.Fatal(err)
}
token, source, err := ResolveWoodpeckerCredential(repo, &WoodpeckerSettings{TokenFile: "token"})
if err != nil || token != "ci-secret" || source.Context != LocalCredentials || source.Source != filepath.Join(repo, "token") {
t.Fatalf("token matches=%t source=%+v error=%v", token == "ci-secret", source, err)
}
if _, _, err := ResolveWoodpeckerCredential(repo, &WoodpeckerSettings{}); err == nil || !strings.Contains(err.Error(), "rehearsal.woodpecker.token_file") {
t.Fatalf("missing selection error=%v", err)
}
if err := os.WriteFile(filepath.Join(repo, "token"), []byte(" \n"), 0600); err != nil {
t.Fatal(err)
}
if _, _, err := ResolveWoodpeckerCredential(repo, &WoodpeckerSettings{TokenFile: "token"}); err == nil || strings.Contains(err.Error(), "ci-secret") {
t.Fatalf("blank token error=%v", err)
}
}

View File

@@ -3,6 +3,7 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -225,6 +226,30 @@ type Settings struct {
Build *BuildSettings `json:"build,omitempty"`
Delivery *DeliverySettings `json:"delivery,omitempty"`
Readiness *ReadinessSettings `json:"readiness,omitempty"`
Rehearsal *RehearsalSettings `json:"rehearsal,omitempty"`
}
// RehearsalSettings selects a diagnostic dispatch selector and CI observer.
type RehearsalSettings struct {
Selector string `json:"selector,omitempty"`
Woodpecker *WoodpeckerSettings `json:"woodpecker,omitempty"`
}
// WoodpeckerSettings identifies the exact repository and delivery job.
type WoodpeckerSettings struct {
BaseURL string `json:"base_url"`
RepositoryID int64 `json:"repository_id"`
Workflow string `json:"workflow"`
Step string `json:"step"`
TokenFile string `json:"token_file"`
}
// RehearsalSelector returns the configured selector or the default root row.
func (s RehearsalSettings) RehearsalSelector() string {
if s.Selector == "" {
return "root"
}
return s.Selector
}
// ReadinessSettings lists files deliberately required for setup diagnostics.
@@ -361,9 +386,17 @@ func LoadSettings(repoDir, configPath string) (Settings, error) {
return Settings{}, fmt.Errorf("open profile %q: %w", configPath, err)
}
defer file.Close()
return decodeSettings(file, configPath)
}
// DecodeSettings applies the same strict profile rules to captured bytes.
func DecodeSettings(data []byte, label string) (Settings, error) {
return decodeSettings(bytes.NewReader(data), label)
}
func decodeSettings(input io.Reader, configPath string) (Settings, error) {
var settings Settings
decoder := json.NewDecoder(file)
decoder := json.NewDecoder(input)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&settings); err != nil {
return Settings{}, fmt.Errorf("decode profile %q: %w", configPath, err)

View File

@@ -31,20 +31,9 @@ func ResolveDeliveryCredential(repositoryDir string, credentials *DeliveryCreden
if credentials == nil || credentials.Local == nil || strings.TrimSpace(credentials.Local.TokenFile) == "" {
return "", source, errors.New("local delivery requires delivery.credentials.local.token_file")
}
name := credentials.Local.TokenFile
if !filepath.IsAbs(name) {
name = filepath.Join(repositoryDir, name)
}
source.Source = git.DisplayDiagnostic(name)
contents, err := os.ReadFile(name)
if err != nil {
return "", source, fmt.Errorf("read local delivery token file: %s", git.DisplayDiagnostic(err.Error()))
}
token := strings.TrimSpace(string(contents))
if token == "" {
return "", source, fmt.Errorf("local delivery token file %q is empty or blank", source.Source)
}
return token, source, nil
token, name, err := readTokenFile(repositoryDir, credentials.Local.TokenFile, "local delivery")
source.Source = name
return token, source, err
case CICredentials:
if credentials == nil || credentials.CI == nil {
return "", source, errors.New("CI delivery requires delivery.credentials.ci")
@@ -63,3 +52,30 @@ func ResolveDeliveryCredential(repositoryDir string, credentials *DeliveryCreden
return "", source, errors.New("unknown delivery credential context")
}
}
// ResolveWoodpeckerCredential reads only the explicitly selected local CI token.
func ResolveWoodpeckerCredential(repositoryDir string, settings *WoodpeckerSettings) (string, CredentialSource, error) {
source := CredentialSource{Context: LocalCredentials}
if settings == nil || strings.TrimSpace(settings.TokenFile) == "" {
return "", source, errors.New("rehearsal requires rehearsal.woodpecker.token_file")
}
token, name, err := readTokenFile(repositoryDir, settings.TokenFile, "Woodpecker")
source.Source = name
return token, source, err
}
func readTokenFile(repositoryDir, name, label string) (string, string, error) {
if !filepath.IsAbs(name) {
name = filepath.Join(repositoryDir, name)
}
safeName := git.DisplayDiagnostic(name)
contents, err := os.ReadFile(name)
if err != nil {
return "", safeName, fmt.Errorf("read %s token file: %s", label, git.DisplayDiagnostic(err.Error()))
}
token := strings.TrimSpace(string(contents))
if token == "" {
return "", safeName, fmt.Errorf("%s token file %q is empty or blank", label, safeName)
}
return token, safeName, nil
}

View File

@@ -2,7 +2,8 @@
## Status
Draft for review.
Accepted. The implementation plan adopts this lifecycle for explicitly
temporary diagnostic resources; production release immutability is unchanged.
## Date

View File

@@ -182,6 +182,15 @@ absolute files whose readability `validate` checks. These are explicit local
inputs, not inferred SSH authentication requirements; see the
[readiness guide](consumers/readiness.md).
A `rehearsal` object can select a dispatch `selector` (default `root`) and a
`woodpecker` object with `base_url`, numeric `repository_id`, exact `workflow`
and `step` names, and a local `token_file`. These settings are required only
for rehearsal operations. Relative token paths resolve from the checkout root;
the file is read separately from the forge credential and its token is never
stored in the attempt record. See the
[rehearsal record format](integrations/rehearsal-records.md) for captured
identity and recovery evidence.
The `delivery` object contains `forge`, `base_url`, `owner`, `repository`, and
context-specific `credentials`. A delivery request must set `forge` to
`"gitea"`; a missing or unsupported selection is an error for delivery. These

View File

@@ -0,0 +1,32 @@
# Rehearsal identity and records
A diagnostic annotated tag carries the exact source and profile identity for a
single rehearsal. Its message begins with `ReleaseKit rehearsal v1`, followed
by a newline and one compact JSON object. `schema_version: 1` identifies the
manifest. Its fields include the attempt ID, selector, captured commit, profile
path and SHA-256, source directory, Go capability and optional module path,
publication and version selection, diagnostic version, and full tag. A
16-byte random attempt ID is represented by 32 lowercase hexadecimal digits;
the tag and injected version include the same ID.
The manifest is verified against the actual annotated tag target, the event
commit, the selected dispatch row, the exact committed profile bytes, and the
normalized selection decoded from those bytes. The tag namespace alone is not
proof of ownership or permission to delete anything. A profile is read from the
captured commit rather than the current working tree.
Private attempt records use `format_version: 1` and retain the manifest, Git
endpoint and remote, forge and Woodpecker destinations, planned page evidence,
tag object, observed resource IDs, timestamps, and outcomes. They do not store
resolved forge or Woodpecker tokens. Endpoints and paths may themselves contain
sensitive information, so treat records as private. By default they are stored
under the Git common directory in `releasekit/rehearsals/<attempt-id>.json`.
An explicit record-directory override follows the same worktree ignore rules as
publication records. The initial record is created exclusively; updates use a
private temporary file and rename. Records remain available for explicit
recovery and operator retention.
Manifest and record strings that contain non-UTF-8 bytes are omitted in their
lossy JSON form and represented by standard base64 values in `identity_bytes`.
A recognized override supplies the exact bytes on decoding; unknown override
names are ignored. Supported versions tolerate additive unknown fields.

View File

@@ -52,6 +52,8 @@ reports these implemented packages:
| `internal/process` | Cancellable child-process execution, including owned stdin/stdout pipes for serialized exchanges, with per-command environment overlays and removals. |
| `internal/preparation` | Coordination for expected-commit tag checkout and Go module dependency preparation. |
| `internal/readiness` | Working-input inspection and read-only setup observations for explicitly selected capabilities. |
| `internal/recordstore` | Shared private-record location and worktree safety checks. |
| `internal/rehearsal` | Diagnostic tag manifests and private attempt evidence for rehearsal recovery. |
| `internal/releaseidentity` | Committed-object and working-tree module selection, declaration reading, and semantic-version-to-tag derivation. |
| `internal/validation` | Shared Go validation with optional race, full-vet, and static package-compilation target selections, formatting, workspace-file and filesystem-replacement checks, per-blob size limits, and selected Markdown destination and fragment checking; `internal/candidate` retains capture, callback sequencing, and local-state rechecks. |
| `internal/publish` | Publication guards, one validation run, annotated tag creation, push, pre-push evidence recording, saved-attempt discovery, later observation, and recovery state. |

View File

@@ -442,6 +442,14 @@ guidance, and offline coverage are complete, then continue to Stage 9.
## Stage 9: Define rehearsal identity transport and durable attempts
**Completed:** Committed profile capture, diagnostic tag manifests and
verification, separate local Woodpecker credentials, and owner-private attempt
records now preserve exact identity and recovery evidence. Temporary diagnostic
resources are adopted in ADR 0008. The coordinator and CI dispatch that consume
these foundations follow in the later stages. Targeted Git and record tests,
the rehearsal race test, the offline `go test ./...` suite, and the compiled
API/dependency check pass.
**Work:** add internal rehearsal contracts/storage and diagnostic tag support.
1. Adopt `rehearsal.selector`, default `root`, and

View File

@@ -47,6 +47,22 @@ func RepositoryRoot(ctx context.Context, directory string) (string, error) {
return normalizeRepositoryRoot(root)
}
// ResolveCommit resolves a revision to its full commit ID without changing the checkout.
func ResolveCommit(ctx context.Context, repositoryDir, revision string) (string, error) {
if revision == "" {
revision = "HEAD"
}
output, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", "--end-of-options", revision+"^{commit}")
if err != nil {
return "", fmt.Errorf("resolve selected revision: %w", err)
}
commit := strings.TrimSpace(output)
if !validObjectID(commit) {
return "", fmt.Errorf("selected revision did not resolve to a full commit ID")
}
return commit, nil
}
// CheckTaggerIdentity checks Git's native committer identity without creating a tag.
func CheckTaggerIdentity(ctx context.Context, directory string) error {
if _, err := run(ctx, directory, nil, "var", "GIT_COMMITTER_IDENT"); err != nil {

View File

@@ -9,6 +9,79 @@ import (
"strings"
)
// AnnotatedTag is the immutable tag object and its direct commit target.
type AnnotatedTag struct {
Object string
Commit string
Message []byte
}
// ReadAnnotatedTag reads an exact local tag and requires a direct commit target.
func ReadAnnotatedTag(ctx context.Context, repositoryDir, tag string) (AnnotatedTag, error) {
if err := CheckTagRef(ctx, repositoryDir, tag); err != nil {
return AnnotatedTag{}, err
}
ref := "refs/tags/" + tag
object, err := run(ctx, repositoryDir, nil, "rev-parse", "--verify", ref)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("resolve annotated tag: %w", err)
}
object = strings.TrimSpace(object)
if !validObjectID(object) {
return AnnotatedTag{}, errors.New("invalid annotated tag object")
}
tagType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", object)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("inspect annotated tag: %w", err)
}
if strings.TrimSpace(tagType) != "tag" {
return AnnotatedTag{}, errors.New("diagnostic reference is not an annotated tag")
}
contents, err := run(ctx, repositoryDir, nil, "cat-file", "tag", object)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("read annotated tag: %w", err)
}
header, message, ok := strings.Cut(contents, "\n\n")
if !ok {
return AnnotatedTag{}, errors.New("annotated tag has no message")
}
var target, targetType, tagName string
for _, line := range strings.Split(header, "\n") {
key, value, ok := strings.Cut(line, " ")
if !ok {
continue
}
switch key {
case "object":
if target != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its target")
}
target = value
case "type":
if targetType != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its type")
}
targetType = value
case "tag":
if tagName != "" {
return AnnotatedTag{}, errors.New("annotated tag repeats its name")
}
tagName = value
}
}
if !validObjectID(target) || targetType != "commit" || tagName != tag {
return AnnotatedTag{}, errors.New("annotated tag target or name does not match")
}
actualType, err := run(ctx, repositoryDir, nil, "cat-file", "-t", target)
if err != nil {
return AnnotatedTag{}, fmt.Errorf("inspect annotated tag target: %w", err)
}
if strings.TrimSpace(actualType) != "commit" {
return AnnotatedTag{}, errors.New("annotated tag target is not a commit")
}
return AnnotatedTag{Object: object, Commit: target, Message: []byte(message)}, nil
}
// CreateAnnotatedTag records the captured note as an unsigned annotated tag
// on the captured commit. Once its type and ID are established, the ID is
// returned even if a later verification fails.

View File

@@ -10,11 +10,10 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/recordstore"
)
const recordFormatVersion = 1
@@ -184,21 +183,7 @@ func saveEvidenceNamed(ctx context.Context, repositoryDir, root, override, recor
}
func resolveRecordDir(ctx context.Context, repositoryDir, override string) (string, string, error) {
root, err := git.RepositoryRoot(ctx, repositoryDir)
if err != nil {
return "", "", err
}
if override != "" {
if filepath.IsAbs(override) {
return filepath.Clean(override), root, nil
}
return filepath.Join(root, override), root, nil
}
common, err := git.CommonDirectory(ctx, repositoryDir)
if err != nil {
return "", "", err
}
return filepath.Join(common, "releasekit", "publication-attempts"), root, nil
return recordstore.ResolveDir(ctx, repositoryDir, override, "publication-attempts")
}
func proposedRecordPath(directory string) (string, error) {
@@ -210,31 +195,5 @@ func proposedRecordPath(directory string) (string, error) {
}
func rejectUnignoredWorktreePath(ctx context.Context, repositoryDir, root, proposed string) error {
parent, err := filepath.EvalSymlinks(filepath.Dir(proposed))
if err != nil {
return fmt.Errorf("resolve record directory %q: %w", filepath.Dir(proposed), err)
}
actual := filepath.Join(parent, filepath.Base(proposed))
rel, err := filepath.Rel(root, actual)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
metadata, err := git.MetadataDirectories(ctx, repositoryDir)
if err != nil {
return err
}
for _, directory := range metadata {
rel, err := filepath.Rel(directory, actual)
if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
}
ignored, err := git.IsIgnored(ctx, repositoryDir, actual)
if err != nil {
return fmt.Errorf("check Git ignore rules for record path %q: %w", actual, err)
}
if !ignored {
return fmt.Errorf("record path %q is inside the worktree and is not ignored", actual)
}
return nil
return recordstore.CheckPath(ctx, repositoryDir, root, proposed)
}

View File

@@ -0,0 +1,63 @@
// Package recordstore owns private record location and worktree checks.
package recordstore
import (
"context"
"fmt"
"path/filepath"
"strings"
"go.maximumdirect.net/releasekit/internal/git"
)
// ResolveDir resolves an override relative to the repository or a directory in
// its shared Git metadata, returning both the record directory and checkout.
func ResolveDir(ctx context.Context, repositoryDir, override, category string) (string, string, error) {
root, err := git.RepositoryRoot(ctx, repositoryDir)
if err != nil {
return "", "", err
}
if override != "" {
if filepath.IsAbs(override) {
return filepath.Clean(override), root, nil
}
return filepath.Join(root, override), root, nil
}
common, err := git.CommonDirectory(ctx, repositoryDir)
if err != nil {
return "", "", err
}
return filepath.Join(common, "releasekit", category), root, nil
}
// CheckPath requires worktree record locations to be ignored, except for Git
// metadata directories. The record directory must already exist.
func CheckPath(ctx context.Context, repositoryDir, root, proposed string) error {
parent, err := filepath.EvalSymlinks(filepath.Dir(proposed))
if err != nil {
return fmt.Errorf("resolve record directory %q: %w", filepath.Dir(proposed), err)
}
actual := filepath.Join(parent, filepath.Base(proposed))
rel, err := filepath.Rel(root, actual)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
metadata, err := git.MetadataDirectories(ctx, repositoryDir)
if err != nil {
return err
}
for _, directory := range metadata {
rel, err := filepath.Rel(directory, actual)
if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return nil
}
}
ignored, err := git.IsIgnored(ctx, repositoryDir, actual)
if err != nil {
return fmt.Errorf("check Git ignore rules for record path %q: %w", actual, err)
}
if !ignored {
return fmt.Errorf("record path %q is inside the worktree and is not ignored", actual)
}
return nil
}

View File

@@ -0,0 +1,280 @@
// Package rehearsal owns diagnostic attempt identity and durable evidence.
package rehearsal
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"path"
"strings"
"unicode/utf8"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
const manifestHeader = "ReleaseKit rehearsal v1\n"
// Manifest binds a diagnostic tag to one committed profile and source selection.
type Manifest struct {
SchemaVersion int `json:"schema_version"`
AttemptID string `json:"attempt_id,omitempty"`
Selector string `json:"selector,omitempty"`
Commit string `json:"commit,omitempty"`
ProfilePath string `json:"profile_path,omitempty"`
ProfileSHA256 string `json:"profile_sha256,omitempty"`
SourceDir string `json:"source_dir,omitempty"`
GoEnabled bool `json:"go_enabled"`
ModulePath string `json:"module_path,omitempty"`
PublicationMode string `json:"publication_mode,omitempty"`
VersionFormat string `json:"version_format,omitempty"`
VersionPrefix string `json:"version_prefix"`
DiagnosticVersion string `json:"diagnostic_version,omitempty"`
Tag string `json:"tag,omitempty"`
IdentityBytes map[string][]byte `json:"identity_bytes,omitempty"`
}
type stringField struct {
name string
value *string
}
func manifestFields(m *Manifest) []stringField {
return []stringField{{"attempt_id", &m.AttemptID}, {"selector", &m.Selector}, {"commit", &m.Commit}, {"profile_path", &m.ProfilePath}, {"profile_sha256", &m.ProfileSHA256}, {"source_dir", &m.SourceDir}, {"module_path", &m.ModulePath}, {"publication_mode", &m.PublicationMode}, {"version_format", &m.VersionFormat}, {"version_prefix", &m.VersionPrefix}, {"diagnostic_version", &m.DiagnosticVersion}, {"tag", &m.Tag}}
}
// EncodeManifest returns the exact annotated-tag message, preserving non-UTF-8
// identity bytes through base64 overrides.
func EncodeManifest(manifest Manifest) ([]byte, error) {
manifest.IdentityBytes = nil
for _, field := range manifestFields(&manifest) {
if !utf8.ValidString(*field.value) {
if manifest.IdentityBytes == nil {
manifest.IdentityBytes = make(map[string][]byte)
}
manifest.IdentityBytes[field.name] = []byte(*field.value)
*field.value = ""
}
}
raw, err := json.Marshal(manifest)
if err != nil {
return nil, err
}
if len(manifest.IdentityBytes) != 0 {
var object map[string]json.RawMessage
if err := json.Unmarshal(raw, &object); err != nil {
return nil, err
}
for name := range manifest.IdentityBytes {
delete(object, name)
}
raw, err = json.Marshal(object)
if err != nil {
return nil, err
}
}
return append(append([]byte(manifestHeader), raw...), '\n'), nil
}
// DecodeManifest reads one supported diagnostic annotation.
func DecodeManifest(message []byte) (Manifest, error) {
var manifest Manifest
if !strings.HasPrefix(string(message), manifestHeader) {
return manifest, errors.New("diagnostic annotation has an invalid marker")
}
var object map[string]json.RawMessage
if err := json.Unmarshal(message[len(manifestHeader):], &object); err != nil {
return Manifest{}, fmt.Errorf("decode diagnostic manifest: %w", err)
}
overrides := object["identity_bytes"]
delete(object, "identity_bytes")
data, err := json.Marshal(object)
if err != nil {
return Manifest{}, err
}
if err := json.Unmarshal(data, &manifest); err != nil {
return Manifest{}, fmt.Errorf("decode diagnostic manifest: %w", err)
}
if manifest.SchemaVersion != 1 {
return Manifest{}, fmt.Errorf("unsupported diagnostic manifest version %d", manifest.SchemaVersion)
}
if err := decodeStringOverrides(overrides, manifestFields(&manifest)); err != nil {
return Manifest{}, fmt.Errorf("decode diagnostic identity bytes: %w", err)
}
return manifest, nil
}
func decodeStringOverrides(raw json.RawMessage, fields []stringField) error {
if len(raw) == 0 {
return nil
}
var values map[string]json.RawMessage
if err := json.Unmarshal(raw, &values); err != nil {
return err
}
for _, field := range fields {
value, ok := values[field.name]
if !ok {
continue
}
var encoded *string
if err := json.Unmarshal(value, &encoded); err != nil {
return fmt.Errorf("%s: %w", field.name, err)
}
if encoded == nil {
return fmt.Errorf("%s must be a base64 string", field.name)
}
decoded, err := base64.StdEncoding.DecodeString(*encoded)
if err != nil {
return fmt.Errorf("%s: %w", field.name, err)
}
*field.value = string(decoded)
}
return nil
}
func validAttemptID(value string) bool {
if len(value) != 32 || strings.ToLower(value) != value {
return false
}
_, err := hex.DecodeString(value)
return err == nil
}
func validateManifestStructure(manifest Manifest) error {
if manifest.SchemaVersion != 1 || !validAttemptID(manifest.AttemptID) {
return errors.New("invalid diagnostic attempt identity")
}
if manifest.Selector == "" || strings.Contains(manifest.Selector, "/") || manifest.Tag != "releasekit-test/"+manifest.Selector+"/"+manifest.AttemptID || manifest.DiagnosticVersion != "releasekit-test-"+manifest.AttemptID {
return errors.New("diagnostic tag and identity do not match")
}
if !git.ValidObjectID(manifest.Commit) {
return errors.New("invalid diagnostic commit")
}
if manifest.ProfilePath == "" || path.IsAbs(manifest.ProfilePath) || path.Clean(manifest.ProfilePath) != manifest.ProfilePath || manifest.ProfilePath == ".." || strings.HasPrefix(manifest.ProfilePath, "../") || strings.Contains(manifest.ProfilePath, "\\") {
return errors.New("invalid diagnostic profile path")
}
if len(manifest.ProfileSHA256) != 64 || strings.ToLower(manifest.ProfileSHA256) != manifest.ProfileSHA256 {
return errors.New("invalid diagnostic profile digest")
}
if _, err := hex.DecodeString(manifest.ProfileSHA256); err != nil {
return errors.New("invalid diagnostic profile digest")
}
if manifest.SourceDir == "" || path.IsAbs(manifest.SourceDir) || path.Clean(manifest.SourceDir) != manifest.SourceDir || manifest.SourceDir == ".." || strings.HasPrefix(manifest.SourceDir, "../") {
return errors.New("invalid diagnostic source directory")
}
if manifest.GoEnabled != (manifest.ModulePath != "") {
return errors.New("diagnostic Go selection and module path do not match")
}
if manifest.PublicationMode != "source" && manifest.PublicationMode != "go-module" {
return errors.New("invalid diagnostic publication mode")
}
if manifest.VersionFormat != "semver" && manifest.VersionFormat != "date" && manifest.VersionFormat != "year-month" {
return errors.New("invalid diagnostic version format")
}
if manifest.VersionPrefix != "" && manifest.VersionPrefix != "v" {
return errors.New("invalid diagnostic version prefix")
}
if manifest.PublicationMode == "go-module" && (!manifest.GoEnabled || manifest.VersionFormat != "semver" || manifest.VersionPrefix != "v") {
return errors.New("invalid diagnostic Go module selection")
}
return nil
}
// NewManifest binds a resolved diagnostic identity to the exact profile bytes.
func NewManifest(identity releaseidentity.Identity, attempt, selector, profilePath string, profile []byte) Manifest {
digest := sha256.Sum256(profile)
return Manifest{SchemaVersion: 1, AttemptID: attempt, Selector: selector, Commit: identity.Commit, ProfilePath: profilePath, ProfileSHA256: hex.EncodeToString(digest[:]), SourceDir: identity.SourceSubdir, GoEnabled: identity.GoEnabled, ModulePath: identity.ModulePath, PublicationMode: identity.Publication, VersionFormat: identity.VersionFormat, VersionPrefix: identity.VersionPrefix, DiagnosticVersion: identity.Version, Tag: identity.Tag}
}
// CreateDiagnosticTag creates an unsigned annotated local tag without moving
// an existing reference. Remote dispatch is a separate operation.
func CreateDiagnosticTag(ctx context.Context, repository string, manifest Manifest) (string, error) {
if err := validateManifestStructure(manifest); err != nil {
return "", err
}
message, err := EncodeManifest(manifest)
if err != nil {
return "", err
}
return git.CreateAnnotatedTag(ctx, repository, manifest.Tag, manifest.Commit, message)
}
// VerifyManifest checks the exact tag, target commit, committed profile and
// normalized source selection supplied by the caller.
func VerifyManifest(ctx context.Context, repository, tag, target, expectedProfile string, profile []byte, source releaseidentity.ResolvedSource, manifest Manifest) error {
if err := validateManifestStructure(manifest); err != nil {
return err
}
if manifest.Tag != tag {
return errors.New("diagnostic tag and identity do not match")
}
if err := git.CheckTagRef(ctx, repository, tag); err != nil {
return err
}
if !git.EqualObjectID(manifest.Commit, target) {
return errors.New("diagnostic target commit does not match")
}
if manifest.ProfilePath != expectedProfile {
return errors.New("diagnostic profile path does not match")
}
digest := sha256.Sum256(profile)
if manifest.ProfileSHA256 != hex.EncodeToString(digest[:]) {
return errors.New("diagnostic profile digest does not match")
}
if manifest.SourceDir != source.ModuleSubdir || manifest.GoEnabled != source.GoEnabled || manifest.ModulePath != source.ModulePath || manifest.PublicationMode != source.Publication || manifest.VersionFormat != source.VersionFormat || manifest.VersionPrefix != source.VersionPrefix {
return errors.New("diagnostic source selection does not match")
}
return nil
}
// VerifiedTag contains the captured identity and exact committed profile.
type VerifiedTag struct {
Manifest Manifest
TagObject string
Profile []byte
Source releaseidentity.ResolvedSource
}
// VerifyTag reads the annotated tag and profile from Git, resolves the profile's
// source through the supplied decoder, and binds them to the event identity.
func VerifyTag(ctx context.Context, repository, tag, eventCommit, expectedSelector, expectedProfile string, resolve func(context.Context, string, []byte) (releaseidentity.ResolvedSource, error)) (VerifiedTag, error) {
var result VerifiedTag
tagged, err := git.ReadAnnotatedTag(ctx, repository, tag)
if err != nil {
return result, err
}
result.TagObject = tagged.Object
if !git.EqualObjectID(tagged.Commit, eventCommit) {
return result, errors.New("diagnostic tag target does not match the event commit")
}
result.Manifest, err = DecodeManifest(tagged.Message)
if err != nil {
return result, err
}
if err := validateManifestStructure(result.Manifest); err != nil {
return result, err
}
if result.Manifest.Selector != expectedSelector || result.Manifest.ProfilePath != expectedProfile {
return result, errors.New("diagnostic selector or profile does not match dispatch")
}
result.Profile, err = git.ReadCommitFile(ctx, repository, tagged.Commit, result.Manifest.ProfilePath)
if err != nil {
return result, fmt.Errorf("read captured diagnostic profile: %w", err)
}
if resolve == nil {
return result, errors.New("diagnostic source resolver is required")
}
result.Source, err = resolve(ctx, tagged.Commit, result.Profile)
if err != nil {
return result, fmt.Errorf("resolve captured diagnostic source: %w", err)
}
if err := VerifyManifest(ctx, repository, tag, tagged.Commit, expectedProfile, result.Profile, result.Source, result.Manifest); err != nil {
return result, err
}
return result, nil
}

View File

@@ -0,0 +1,144 @@
package rehearsal
import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func rehearsalFixture(t *testing.T) (string, []byte, releaseidentity.ResolvedSource, releaseidentity.Identity, string) {
t.Helper()
repo := t.TempDir()
run := func(args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v: %s", args, err, output)
}
return strings.TrimSpace(string(output))
}
run("init", "--initial-branch=main")
run("config", "user.name", "ReleaseKit Test")
run("config", "user.email", "releasekit@example.test")
run("config", "tag.gpgsign", "false")
profile := []byte("{\"product\":\"Example\",\"source\":{}}\n")
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), profile, 0600); err != nil {
t.Fatal(err)
}
run("add", "releasekit.json")
run("commit", "-m", "capture profile")
commit := run("rev-parse", "HEAD")
source, err := releaseidentity.LoadCommittedSource(t.Context(), repo, "", commit, &releaseidentity.SourceSpec{})
if err != nil {
t.Fatal(err)
}
identity, attempt, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", commit)
if err != nil {
t.Fatal(err)
}
return repo, profile, source, identity, attempt
}
func TestDiagnosticManifestBindsAnnotatedCommitAndProfile(t *testing.T) {
repo, profile, source, identity, attempt := rehearsalFixture(t)
manifest := NewManifest(identity, attempt, "root", "releasekit.json", profile)
message, err := EncodeManifest(manifest)
if err != nil {
t.Fatal(err)
}
object, err := CreateDiagnosticTag(t.Context(), repo, manifest)
if err != nil {
t.Fatal(err)
}
tag, err := git.ReadAnnotatedTag(t.Context(), repo, identity.Tag)
if err != nil {
t.Fatal(err)
}
if tag.Object != object || tag.Commit != identity.Commit || !bytes.Equal(tag.Message, message) {
t.Fatalf("tag=%+v", tag)
}
if _, err := CreateDiagnosticTag(t.Context(), repo, manifest); err == nil {
t.Fatal("moved an existing diagnostic tag")
}
unchanged, err := git.ReadAnnotatedTag(t.Context(), repo, identity.Tag)
if err != nil || unchanged.Object != object {
t.Fatalf("existing tag changed: %+v, error=%v", unchanged, err)
}
decoded, err := DecodeManifest(tag.Message)
if err != nil {
t.Fatal(err)
}
if err := VerifyManifest(t.Context(), repo, identity.Tag, tag.Commit, "releasekit.json", profile, source, decoded); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte("changed working profile"), 0600); err != nil {
t.Fatal(err)
}
resolve := func(ctx context.Context, commit string, captured []byte) (releaseidentity.ResolvedSource, error) {
if !bytes.Equal(captured, profile) {
t.Error("used working profile instead of committed bytes")
}
return releaseidentity.LoadCommittedSource(ctx, repo, "", commit, &releaseidentity.SourceSpec{})
}
verified, err := VerifyTag(t.Context(), repo, identity.Tag, tag.Commit, "root", "releasekit.json", resolve)
if err != nil || verified.TagObject != object || !bytes.Equal(verified.Profile, profile) {
t.Fatalf("verified=%+v err=%v", verified, err)
}
if _, err := VerifyTag(t.Context(), repo, identity.Tag, tag.Commit, "other", "releasekit.json", resolve); err == nil {
t.Fatal("accepted a different dispatch selector")
}
for _, changed := range []struct {
name string
tag, commit, profilePath string
profile []byte
}{
{"tag", "releasekit-test/other/" + attempt, tag.Commit, "releasekit.json", profile},
{"commit", identity.Tag, strings.Repeat("a", 40), "releasekit.json", profile},
{"profile path", identity.Tag, tag.Commit, "other.json", profile},
{"profile bytes", identity.Tag, tag.Commit, "releasekit.json", []byte("changed")},
} {
t.Run(changed.name, func(t *testing.T) {
if err := VerifyManifest(context.Background(), repo, changed.tag, changed.commit, changed.profilePath, changed.profile, source, decoded); err == nil {
t.Fatal("accepted inconsistent diagnostic evidence")
}
})
}
source.VersionFormat = "date"
if err := VerifyManifest(t.Context(), repo, identity.Tag, tag.Commit, "releasekit.json", profile, source, decoded); err == nil {
t.Fatal("accepted changed source selection")
}
}
func TestManifestPreservesExactIdentityBytesAndRejectsMalformedOverrides(t *testing.T) {
raw := string([]byte{'p', 0xff, 'q'})
original := Manifest{SchemaVersion: 1, ProfilePath: raw, VersionPrefix: raw}
data, err := EncodeManifest(original)
if err != nil {
t.Fatal(err)
}
if bytes.Contains(data, []byte("\\ufffd")) || !bytes.Contains(data, []byte("identity_bytes")) {
t.Fatalf("encoded manifest = %q", data)
}
decoded, err := DecodeManifest(data)
if err != nil || decoded.ProfilePath != raw || decoded.VersionPrefix != raw {
t.Fatalf("decoded=%+v err=%v", decoded, err)
}
for _, data := range []string{
"not a manifest", manifestHeader + `{"schema_version":2}`,
manifestHeader + `{"schema_version":1,"identity_bytes":{"profile_path":null}}`,
manifestHeader + `{"schema_version":1,"identity_bytes":{"profile_path":"%%%"}}`,
} {
if _, err := DecodeManifest([]byte(data)); err == nil {
t.Fatalf("accepted malformed manifest %q", data)
}
}
}

View File

@@ -0,0 +1,252 @@
package rehearsal
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"sync"
"time"
"unicode/utf8"
"go.maximumdirect.net/releasekit/internal/git"
"go.maximumdirect.net/releasekit/internal/recordstore"
)
// Attempt retains the immutable identity and observations needed for recovery.
// It deliberately contains no resolved forge or Woodpecker token.
type Attempt struct {
FormatVersion int `json:"format_version"`
Manifest Manifest `json:"manifest"`
RepositoryDir string `json:"repository_dir,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Remote string `json:"remote,omitempty"`
ForgeBaseURL string `json:"forge_base_url,omitempty"`
ForgeOwner string `json:"forge_owner,omitempty"`
ForgeRepository string `json:"forge_repository,omitempty"`
WoodpeckerBaseURL string `json:"woodpecker_base_url,omitempty"`
WoodpeckerRepositoryID int64 `json:"woodpecker_repository_id,omitempty"`
Workflow string `json:"workflow,omitempty"`
Step string `json:"step,omitempty"`
ExpectedPageTitle string `json:"expected_page_title,omitempty"`
ExpectedBodySHA256 string `json:"expected_body_sha256,omitempty"`
TagObject string `json:"tag_object,omitempty"`
PageID int64 `json:"page_id,omitempty"`
PipelineIDs []int64 `json:"pipeline_ids,omitempty"`
Outcomes map[string]string `json:"outcomes,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
IdentityBytes map[string][]byte `json:"identity_bytes,omitempty"`
}
func attemptFields(a *Attempt) []stringField {
return []stringField{{"repository_dir", &a.RepositoryDir}, {"endpoint", &a.Endpoint}, {"remote", &a.Remote}, {"forge_base_url", &a.ForgeBaseURL}, {"forge_owner", &a.ForgeOwner}, {"forge_repository", &a.ForgeRepository}, {"woodpecker_base_url", &a.WoodpeckerBaseURL}, {"workflow", &a.Workflow}, {"step", &a.Step}, {"expected_page_title", &a.ExpectedPageTitle}, {"expected_body_sha256", &a.ExpectedBodySHA256}, {"tag_object", &a.TagObject}, {"created_at", &a.CreatedAt}, {"updated_at", &a.UpdatedAt}}
}
func encodeAttempt(attempt Attempt) ([]byte, error) {
attempt.FormatVersion = 1
attempt.IdentityBytes = nil
for _, field := range attemptFields(&attempt) {
if !utf8.ValidString(*field.value) {
if attempt.IdentityBytes == nil {
attempt.IdentityBytes = map[string][]byte{}
}
attempt.IdentityBytes[field.name] = []byte(*field.value)
*field.value = ""
}
}
encodedManifest, err := EncodeManifest(attempt.Manifest)
if err != nil {
return nil, err
}
raw, err := json.Marshal(attempt)
if err != nil {
return nil, err
}
var object map[string]json.RawMessage
if err := json.Unmarshal(raw, &object); err != nil {
return nil, err
}
object["manifest"] = json.RawMessage(encodedManifest[len(manifestHeader) : len(encodedManifest)-1])
for name := range attempt.IdentityBytes {
delete(object, name)
}
return json.Marshal(object)
}
// LoadAttempt reads exactly one explicitly selected private record.
func LoadAttempt(path string) (Attempt, error) {
var attempt Attempt
data, err := os.ReadFile(path)
if err != nil {
return attempt, fmt.Errorf("read rehearsal record: %w", err)
}
var object map[string]json.RawMessage
if err := json.Unmarshal(data, &object); err != nil {
return attempt, fmt.Errorf("decode rehearsal record: %w", err)
}
manifestBytes, ok := object["manifest"]
if !ok {
return attempt, errors.New("rehearsal record has no manifest")
}
delete(object, "manifest")
overrides := object["identity_bytes"]
delete(object, "identity_bytes")
remainder, err := json.Marshal(object)
if err != nil {
return attempt, err
}
if err := json.Unmarshal(remainder, &attempt); err != nil {
return Attempt{}, fmt.Errorf("decode rehearsal record: %w", err)
}
if attempt.FormatVersion != 1 {
return Attempt{}, fmt.Errorf("unsupported rehearsal record version %d", attempt.FormatVersion)
}
attempt.Manifest, err = DecodeManifest(append([]byte(manifestHeader), manifestBytes...))
if err != nil {
return Attempt{}, err
}
if err := validateManifestStructure(attempt.Manifest); err != nil {
return Attempt{}, fmt.Errorf("invalid rehearsal identity: %w", err)
}
if err := decodeStringOverrides(overrides, attemptFields(&attempt)); err != nil {
return Attempt{}, fmt.Errorf("decode rehearsal identity bytes: %w", err)
}
return attempt, nil
}
// Store serializes updates made through one handle for one attempt.
type Store struct {
Path string
mu sync.Mutex
manifest Manifest
createdAt string
identity attemptIdentity
tagObject string
}
type attemptIdentity struct {
RepositoryDir, Endpoint, Remote, ForgeBaseURL, ForgeOwner, ForgeRepository string
WoodpeckerBaseURL, Workflow, Step, ExpectedPageTitle, ExpectedBodySHA256 string
WoodpeckerRepositoryID int64
}
func identityOf(attempt Attempt) attemptIdentity {
return attemptIdentity{RepositoryDir: attempt.RepositoryDir, Endpoint: attempt.Endpoint, Remote: attempt.Remote, ForgeBaseURL: attempt.ForgeBaseURL, ForgeOwner: attempt.ForgeOwner, ForgeRepository: attempt.ForgeRepository, WoodpeckerBaseURL: attempt.WoodpeckerBaseURL, WoodpeckerRepositoryID: attempt.WoodpeckerRepositoryID, Workflow: attempt.Workflow, Step: attempt.Step, ExpectedPageTitle: attempt.ExpectedPageTitle, ExpectedBodySHA256: attempt.ExpectedBodySHA256}
}
// CreateAttempt writes an exclusive initial record before any remote effect.
func CreateAttempt(ctx context.Context, repositoryDir, override string, attempt Attempt) (*Store, error) {
if err := validateManifestStructure(attempt.Manifest); err != nil {
return nil, err
}
if attempt.TagObject != "" && !git.ValidObjectID(attempt.TagObject) {
return nil, errors.New("invalid rehearsal tag object")
}
if err := git.CheckTagRef(ctx, repositoryDir, attempt.Manifest.Tag); err != nil {
return nil, err
}
dir, root, err := recordstore.ResolveDir(ctx, repositoryDir, override, "rehearsals")
if err != nil {
return nil, err
}
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, fmt.Errorf("create rehearsal record directory: %w", err)
}
filename := filepath.Join(dir, attempt.Manifest.AttemptID+".json")
if override != "" {
if err := recordstore.CheckPath(ctx, repositoryDir, root, filename); err != nil {
return nil, err
}
}
if attempt.CreatedAt == "" {
attempt.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano)
}
attempt.UpdatedAt = attempt.CreatedAt
data, err := encodeAttempt(attempt)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return nil, fmt.Errorf("create rehearsal record: %w", err)
}
if _, err = file.Write(data); err != nil {
_ = file.Close()
_ = os.Remove(filename)
return nil, fmt.Errorf("write rehearsal record: %w", err)
}
if err = file.Close(); err != nil {
_ = os.Remove(filename)
return nil, fmt.Errorf("close rehearsal record: %w", err)
}
return &Store{Path: filename, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject}, nil
}
// OpenStore selects a previously recorded attempt explicitly.
func OpenStore(path string) (*Store, Attempt, error) {
absolute, err := filepath.Abs(path)
if err != nil {
return nil, Attempt{}, err
}
attempt, err := LoadAttempt(absolute)
if err != nil {
return nil, Attempt{}, err
}
return &Store{Path: absolute, manifest: attempt.Manifest, createdAt: attempt.CreatedAt, identity: identityOf(attempt), tagObject: attempt.TagObject}, attempt, nil
}
// Save atomically replaces one attempt record after an observation or intent.
func (store *Store) Save(attempt Attempt) (resultErr error) {
store.mu.Lock()
defer store.mu.Unlock()
if !reflect.DeepEqual(attempt.Manifest, store.manifest) {
return errors.New("rehearsal record identity cannot change")
}
if identityOf(attempt) != store.identity {
return errors.New("rehearsal destinations cannot change")
}
if store.tagObject != "" && attempt.TagObject != store.tagObject {
return errors.New("rehearsal tag object cannot change")
}
if attempt.TagObject != "" && !git.ValidObjectID(attempt.TagObject) {
return errors.New("invalid rehearsal tag object")
}
if attempt.CreatedAt != "" && attempt.CreatedAt != store.createdAt {
return errors.New("rehearsal creation time cannot change")
}
attempt.CreatedAt = store.createdAt
attempt.UpdatedAt = time.Now().UTC().Format(time.RFC3339Nano)
data, err := encodeAttempt(attempt)
if err != nil {
return err
}
file, err := os.CreateTemp(filepath.Dir(store.Path), ".rehearsal-*")
if err != nil {
return fmt.Errorf("create temporary rehearsal record: %w", err)
}
temp := file.Name()
defer func() {
if err := os.Remove(temp); err != nil && !errors.Is(err, os.ErrNotExist) {
resultErr = errors.Join(resultErr, err)
}
}()
if _, err = file.Write(data); err != nil {
_ = file.Close()
return fmt.Errorf("write rehearsal record: %w", err)
}
if err = file.Close(); err != nil {
return fmt.Errorf("close rehearsal record: %w", err)
}
if err := os.Rename(temp, store.Path); err != nil {
return fmt.Errorf("replace rehearsal record: %w", err)
}
store.tagObject = attempt.TagObject
return nil
}

View File

@@ -0,0 +1,120 @@
package rehearsal
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"go.maximumdirect.net/releasekit/internal/releaseidentity"
)
func TestAttemptStoreSerializesConcurrentUpdates(t *testing.T) {
repo, profile, _, identity, attemptID := rehearsalFixture(t)
attempt := Attempt{Manifest: NewManifest(identity, attemptID, "root", "releasekit.json", profile), RepositoryDir: repo}
store, err := CreateAttempt(t.Context(), repo, "", attempt)
if err != nil {
t.Fatal(err)
}
var wait sync.WaitGroup
for _, outcome := range []string{"first", "second", "third"} {
wait.Add(1)
go func() {
defer wait.Done()
copy := attempt
copy.Outcomes = map[string]string{"observation": outcome}
if err := store.Save(copy); err != nil {
t.Errorf("save %s: %v", outcome, err)
}
}()
}
wait.Wait()
loaded, err := LoadAttempt(store.Path)
if err != nil || loaded.Outcomes["observation"] == "" {
t.Fatalf("loaded=%+v error=%v", loaded, err)
}
}
func TestIndependentAttemptsUseSeparateRecords(t *testing.T) {
repo, profile, source, identity, firstID := rehearsalFixture(t)
secondIdentity, secondID, err := releaseidentity.NewDiagnostic(t.Context(), source, "root", identity.Commit)
if err != nil {
t.Fatal(err)
}
first, err := CreateAttempt(t.Context(), repo, "", Attempt{Manifest: NewManifest(identity, firstID, "root", "releasekit.json", profile)})
if err != nil {
t.Fatal(err)
}
second, err := CreateAttempt(t.Context(), repo, "", Attempt{Manifest: NewManifest(secondIdentity, secondID, "root", "releasekit.json", profile)})
if err != nil {
t.Fatal(err)
}
if first.Path == second.Path {
t.Fatalf("attempts share record %q", first.Path)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = CreateAttempt(ctx, repo, "", Attempt{Manifest: NewManifest(identity, firstID, "root", "releasekit.json", profile)})
if !errors.Is(err, context.Canceled) {
t.Fatalf("canceled create error = %v", err)
}
}
func TestAttemptRecordPreservesIdentityAndUpdates(t *testing.T) {
repo, profile, _, identity, attemptID := rehearsalFixture(t)
raw := string([]byte{'x', 0xff, 'y'})
attempt := Attempt{Manifest: NewManifest(identity, attemptID, "root", "releasekit.json", profile), RepositoryDir: repo, Endpoint: raw, Remote: "origin", ExpectedPageTitle: "diagnostic", Outcomes: map[string]string{"tag": "planned"}}
store, err := CreateAttempt(t.Context(), repo, "", attempt)
if err != nil {
t.Fatal(err)
}
if filepath.Base(store.Path) != attemptID+".json" {
t.Fatalf("record path = %q", store.Path)
}
info, err := os.Stat(store.Path)
if err != nil || info.Mode().Perm()&0077 != 0 {
t.Fatalf("record permissions = %v, error=%v", info, err)
}
if _, err := CreateAttempt(t.Context(), repo, "", attempt); !errors.Is(err, os.ErrExist) {
t.Fatalf("collision error = %v", err)
}
attempt.Outcomes["tag"] = "created"
attempt.TagObject = strings.Repeat("a", 40)
if err := store.Save(attempt); err != nil {
t.Fatal(err)
}
_, loaded, err := OpenStore(store.Path)
if err != nil || loaded.Endpoint != raw || loaded.Outcomes["tag"] != "created" || loaded.TagObject != attempt.TagObject || loaded.CreatedAt == "" || loaded.UpdatedAt == "" {
t.Fatalf("loaded=%+v error=%v", loaded, err)
}
changed := loaded
changed.Endpoint = "other"
if err := store.Save(changed); err == nil {
t.Fatal("accepted changed destination")
}
changed = loaded
changed.Manifest.Tag = "other"
if err := store.Save(changed); err == nil {
t.Fatal("accepted changed manifest")
}
changed = loaded
changed.TagObject = strings.Repeat("b", 40)
if err := store.Save(changed); err == nil {
t.Fatal("accepted changed tag object")
}
reloaded, err := LoadAttempt(store.Path)
if err != nil || reloaded.Endpoint != raw || reloaded.TagObject != attempt.TagObject {
t.Fatalf("record changed after rejected update: %+v %v", reloaded, err)
}
}
func TestAttemptRecordRejectsUnignoredWorktreeLocation(t *testing.T) {
repo, profile, _, identity, attempt := rehearsalFixture(t)
_, err := CreateAttempt(t.Context(), repo, "records", Attempt{Manifest: NewManifest(identity, attempt, "root", "releasekit.json", profile)})
if err == nil || !strings.Contains(err.Error(), "not ignored") {
t.Fatalf("record error = %v", err)
}
}