feat(tasks): attribute events, changes and config to the attempt that produced them

The events table had no attempt column, so two attempts of the same task were
indistinguishable: a retried task's stage events interleaved into one timeline and
nothing could say which run produced a given result.

- events gains an `attempt` column through the existing presence-gated
  migrateTasks loop rather than a version bump, so user_version stays 3 and an
  existing archie.db is migrated in place. A legacy-database test builds the
  pre-change schema and proves both that existing rows survive unattributed
  (attempt = 0) and that a new value round-trips.
- Event.attempt = 11 and ReadTaskLogRequest.stage = 9 are field additions to
  existing messages: no new RPC, no new table, and no change to any canonical error
  message that crosses the state-store wire.
- Every task event the workflow engine emits now carries the attempt. Producers
  that have no attempt yet (task_queued, binding_dispatch_failure) stay
  unattributed rather than guessing one.
- Changed files are captured as a durable changes_captured event at commit and push
  time, reusing the existing three-dot diff primitive: paths from FilePatches(),
  counts from Stats(), base_sha recorded as the merge base actually diffed rather
  than the base tip, a 200-file cap with totals kept complete. Consumption goes
  through an unexported optional interface so workflow.Trees -- the yaegi capability
  surface for interpreted stage plugins -- is not widened. A capture is also taken
  once the pull request exists, so the capture can link it.
- The per-attempt configuration is captured as a durable config_captured event
  carrying the non-secret config.TaskConfig, instead of a new table plus two new
  state-store RPCs: events are already this system's per-attempt provenance stream,
  so a table would have given one feature two provenance mechanisms. Redaction is
  proven against canary secrets. Measured payload: 539 bytes typical, 2333 bytes at
  20 models.
- Captures carry a schema marker and are refused unless their key set matches the
  declared payload shape, so drift surfaces as "recorded but could not be read"
  rather than as a capture of zeroes.
- Three read endpoints serve the attempt rail, the changed-file captures and a raw
  debug view, mapping to UI-owned response types rather than dumping store types.
- The task-log read gains a stage filter, bound to the stage logger for that
  stage's own lines; agent and tool output records no stage.

A task-scoped grant may already insert events on its own task, so this provenance
is exactly as trustworthy as the rest of that task's event stream. That limit is
documented rather than papered over.
This commit is contained in:
sam committed 2026-09-18 18:32:59 +10:00
1 parent 14e7512d14
commit 2c09f42ff4
39 files changed
+4264 -83

No files matched your search

+121 -9
View File
@@ -36,8 +36,11 @@ import (
"github.com/go-git/go-git/v6/plumbing"
gitclient "github.com/go-git/go-git/v6/plumbing/client"
"github.com/go-git/go-git/v6/plumbing/filemode"
fdiff "github.com/go-git/go-git/v6/plumbing/format/diff"
"github.com/go-git/go-git/v6/plumbing/object"
githttp "github.com/go-git/go-git/v6/plumbing/transport/http"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// preparedSentinel marks a worktree as fully cloned, branched and
@@ -598,38 +601,49 @@ func remoteUsesHTTP(r *git.Repository) bool {
// Diffing against the remote tip instead would attribute every commit
// landed on base since the branch started to this task.
func (m *Manager) patch(ctx context.Context, dir, base string) (*object.Patch, error) {
p, _, err := m.patchFromMergeBase(ctx, dir, base)
return p, err
}
// patchFromMergeBase is patch plus the commit the diff was actually taken
// against. That commit is the merge base of base and HEAD, which is NOT base's
// tip once anyone has landed on the base branch since this branch diverged.
// A capture records it beside the file list it measured, so the two describe
// one change set: re-resolving origin/<base> on the side would name the new
// tip instead.
func (m *Manager) patchFromMergeBase(ctx context.Context, dir, base string) (*object.Patch, plumbing.Hash, error) {
r, err := git.PlainOpen(dir)
if err != nil {
return nil, fmt.Errorf("open worktree: %w", err)
return nil, plumbing.ZeroHash, fmt.Errorf("open worktree: %w", err)
}
baseHash, err := resolveBase(r, base)
if err != nil {
return nil, err
return nil, plumbing.ZeroHash, err
}
head, err := r.Head()
if err != nil {
return nil, fmt.Errorf("resolve HEAD: %w", err)
return nil, plumbing.ZeroHash, fmt.Errorf("resolve HEAD: %w", err)
}
baseCommit, err := r.CommitObject(baseHash)
if err != nil {
return nil, fmt.Errorf("load base commit: %w", err)
return nil, plumbing.ZeroHash, fmt.Errorf("load base commit: %w", err)
}
headCommit, err := r.CommitObject(head.Hash())
if err != nil {
return nil, fmt.Errorf("load head commit: %w", err)
return nil, plumbing.ZeroHash, fmt.Errorf("load head commit: %w", err)
}
bases, err := baseCommit.MergeBase(headCommit)
if err != nil {
return nil, fmt.Errorf("find merge base for %s...HEAD: %w", remoteBase(base), err)
return nil, plumbing.ZeroHash, fmt.Errorf("find merge base for %s...HEAD: %w", remoteBase(base), err)
}
if len(bases) == 0 {
return nil, fmt.Errorf("find merge base for %s...HEAD: no common ancestor", remoteBase(base))
return nil, plumbing.ZeroHash, fmt.Errorf("find merge base for %s...HEAD: no common ancestor", remoteBase(base))
}
p, err := bases[0].PatchContext(ctx, headCommit)
if err != nil {
return nil, fmt.Errorf("diff %s...HEAD: %w", remoteBase(base), err)
return nil, plumbing.ZeroHash, fmt.Errorf("diff %s...HEAD: %w", remoteBase(base), err)
}
return p, nil
return p, bases[0].Hash, nil
}
// ChangedLines reports lines added+deleted vs the base branch -- the
@@ -687,6 +701,104 @@ func (m *Manager) ChangedFiles(ctx context.Context, dir, base string) ([]string,
return files, nil
}
// fileTypeMask is the file-type subset of a tree entry's mode: the bits that
// distinguish a regular file from a symlink or a gitlink. A mode change inside
// one type (the executable bit) is a modification, exactly as git reports it;
// a change across types is a typechange.
const fileTypeMask = 0o170000
// ChangedFileStats reports what HEAD changed against base, as the per-file
// status and line counts one attempt's capture records. It reuses patch's
// three-dot semantics: diffing against the remote tip instead would attribute
// every commit landed on base since the branch started to this task.
//
// ChangedLines, Diff and ChangedFiles stay the shape stages call; this is the
// same measurement with the detail a capture needs, so there is still exactly
// one diff path -- and it reports the base that path diffed against.
func (m *Manager) ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error) {
// The diffed base is the merge base patchFromMergeBase diffed against, not
// base's tip: the recorded pair has to describe the file list beside it.
p, diffedBase, err := m.patchFromMergeBase(ctx, dir, base)
if err != nil {
return task.ChangeStats{}, err
}
r, err := git.PlainOpen(dir)
if err != nil {
return task.ChangeStats{}, fmt.Errorf("open worktree: %w", err)
}
head, err := r.Head()
if err != nil {
return task.ChangeStats{}, fmt.Errorf("resolve HEAD: %w", err)
}
patches := p.FilePatches()
// Paths come from FilePatches and counts from Stats, joined by position,
// because Stats() carries one entry per patch that produced textual chunks
// and SKIPS the rest (binary files, and any change whose content is
// identical). Reading the two lists off the same index would shift every
// later file's counts onto the wrong path as soon as one binary file is in
// the change. Totals come from Stats so they agree with ChangedLines, which
// sums the same list.
stats := p.Stats()
next := 0
files := make([]task.FileChange, 0, len(patches))
totals := task.ChangeTotals{Files: len(patches)}
for _, fp := range patches {
change := fileChange(fp)
if change.Binary || next >= len(stats) {
files = append(files, change)
continue
}
change.Additions = stats[next].Addition
change.Deletions = stats[next].Deletion
totals.Additions += stats[next].Addition
totals.Deletions += stats[next].Deletion
next++
files = append(files, change)
}
return task.ChangeStats{
BaseSHA: diffedBase.String(),
HeadSHA: head.Hash().String(),
Files: files,
Totals: totals,
}, nil
}
// fileChange classifies one file patch: whether the file was added, deleted,
// renamed, retyped or modified, and whether it produced any textual hunks.
func fileChange(fp fdiff.FilePatch) task.FileChange {
from, to := fp.Files()
change := task.FileChange{
// No textual hunks. This is what go-git can tell us, not a claim about
// the file on disk: a binary file reports it, and so does a rename whose
// content did not change.
Binary: len(fp.Chunks()) == 0,
}
// At least one side is always present: a change with both entries empty is
// rejected upstream (object.Change.Action), so there is no third state to
// report here.
switch {
case from == nil:
change.Path = to.Path()
change.Status = task.ChangeAdded
case to == nil:
change.Path = from.Path()
change.Status = task.ChangeDeleted
case from.Path() != to.Path():
change.Path = to.Path()
change.OldPath = from.Path()
change.Status = task.ChangeRenamed
case from.Mode()&fileTypeMask != to.Mode()&fileTypeMask:
change.Path = to.Path()
change.Status = task.ChangeTypeChanged
default:
change.Path = to.Path()
change.Status = task.ChangeModified
}
return change
}
// Snapshot exports HEAD's tracked files into a fresh, empty destDir with no
// .git directory: file contents only, no commit history, branch name, or
// reflog. Used to build the adversarial reviewer's isolated workspace
+332
View File
@@ -15,6 +15,7 @@ import (
"github.com/go-git/go-git/v6/plumbing/object"
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
const testBase = "main"
@@ -1127,3 +1128,334 @@ func TestTaskBriefIsNeverCommitted(t *testing.T) {
t.Errorf("brief missing after commit: %v", err)
}
}
func TestOperationsOnNonRepositoryDiffstat(t *testing.T) {
ctx := context.Background()
m := &Manager{WorkDir: t.TempDir()}
if _, err := m.ChangedFileStats(ctx, t.TempDir(), testBase); err == nil {
t.Error("ChangedFileStats() error = nil, want a failure")
}
}
// diffstatSeed is one file written into the fixture's first commit.
type diffstatSeed struct {
path string
content string
}
// newDiffstatRepo builds a repository whose only commit is reachable as both
// the branch tip and refs/remotes/origin/<base>. That remote-tracking ref is
// what resolveBase prefers, so the three-dot base is the same commit whether
// or not the fixture ever had a remote -- and a diffstat fixture needs a base
// commit that already contains the paths a change modifies, renames or
// deletes.
func newDiffstatRepo(t *testing.T, seeds []diffstatSeed) (string, *git.Repository, plumbing.Hash) {
t.Helper()
dir := t.TempDir()
r, err := git.PlainInit(dir, false, git.WithDefaultBranch(plumbing.NewBranchReferenceName(testBase)))
if err != nil {
t.Fatalf("init fixture repo: %v", err)
}
for _, seed := range seeds {
writeSeedCommit(t, r, dir, seed.path, seed.content, "seed "+seed.path)
}
head, err := r.Head()
if err != nil {
t.Fatalf("resolve fixture HEAD: %v", err)
}
if err := r.Storer.SetReference(plumbing.NewHashReference(
plumbing.NewRemoteReferenceName(git.DefaultRemoteName, testBase), head.Hash(),
)); err != nil {
t.Fatalf("set remote-tracking base ref: %v", err)
}
return dir, r, head.Hash()
}
// commitAll commits the fixture repo's working tree, failing the test on a
// commit error.
func commitAll(t *testing.T, r *git.Repository, dir, message string) {
t.Helper()
disableSigning(t, r)
wt, err := r.Worktree()
if err != nil {
t.Fatalf("worktree: %v", err)
}
if _, err := wt.Add("."); err != nil {
t.Fatalf("add all: %v", err)
}
sig := testSignature()
if _, err := wt.Commit(message, &git.CommitOptions{Author: sig, Committer: sig}); err != nil {
t.Fatalf("commit: %v", err)
}
}
// TestChangedFileStatsReportsWhatOneAttemptChanged is the producer-side half
// of the changed-file capture: status and per-file line counts are read off
// the SAME three-dot patch the diff cap reads, where the merge base is
// resolved, so a capture can never disagree with the size gate about what
// changed.
func TestChangedFileStatsReportsWhatOneAttemptChanged(t *testing.T) {
binaryContent := []byte{0x00, 0x01, 0x02, 0xff, 0xfe}
tests := []struct {
name string
seeds []diffstatSeed
mutate func(t *testing.T, dir string, r *git.Repository)
wantFiles []task.FileChange
wantTotal task.ChangeTotals
}{
{
name: "added",
seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}},
mutate: func(t *testing.T, dir string, _ *git.Repository) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("one\ntwo\n"), 0o600); err != nil {
t.Fatal(err)
}
},
wantFiles: []task.FileChange{
{Path: "new.txt", Status: task.ChangeAdded, Additions: 2},
},
wantTotal: task.ChangeTotals{Files: 1, Additions: 2},
},
{
name: "modified",
seeds: []diffstatSeed{{path: "a.txt", content: "one\n"}},
mutate: func(t *testing.T, dir string, _ *git.Repository) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("one\ntwo\n"), 0o600); err != nil {
t.Fatal(err)
}
},
wantFiles: []task.FileChange{
{Path: "a.txt", Status: task.ChangeModified, Additions: 1},
},
wantTotal: task.ChangeTotals{Files: 1, Additions: 1},
},
{
name: "deleted",
seeds: []diffstatSeed{{path: "a.txt", content: "one\ntwo\n"}},
mutate: func(t *testing.T, dir string, _ *git.Repository) {
t.Helper()
if err := os.Remove(filepath.Join(dir, "a.txt")); err != nil {
t.Fatal(err)
}
},
wantFiles: []task.FileChange{
{Path: "a.txt", Status: task.ChangeDeleted, Deletions: 2},
},
wantTotal: task.ChangeTotals{Files: 1, Deletions: 2},
},
{
name: "renamed",
seeds: []diffstatSeed{{path: "old.txt", content: "same content\n"}},
mutate: func(t *testing.T, dir string, _ *git.Repository) {
t.Helper()
if err := os.Remove(filepath.Join(dir, "old.txt")); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("same content\n"), 0o600); err != nil {
t.Fatal(err)
}
},
// go-git reports the rename with its old path preserved and no line
// changes, because the content is identical: the line counts describe
// the content diff, not the path change.
wantFiles: []task.FileChange{
{Path: "new.txt", OldPath: "old.txt", Status: task.ChangeRenamed},
},
wantTotal: task.ChangeTotals{Files: 1},
},
{
name: "binary alongside a text file keeps both paths with their own counts",
seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}},
mutate: func(t *testing.T, dir string, _ *git.Repository) {
t.Helper()
// The binary file sorts before the text file, and go-git's
// Patch.Stats skips it entirely (no textual chunks). A capture
// that read paths and counts off one shared index would hand the
// text file's counts to the binary file here.
if err := os.WriteFile(filepath.Join(dir, "aaa-image.bin"), binaryContent, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "zzz-text.txt"), []byte("one\ntwo\n"), 0o600); err != nil {
t.Fatal(err)
}
},
wantFiles: []task.FileChange{
{Path: "aaa-image.bin", Status: task.ChangeAdded, Binary: true},
{Path: "zzz-text.txt", Status: task.ChangeAdded, Additions: 2},
},
wantTotal: task.ChangeTotals{Files: 2, Additions: 2},
},
{
name: "a regular file replaced by a symlink is a typechange",
seeds: []diffstatSeed{{path: "link.txt", content: "target\n"}},
mutate: func(t *testing.T, dir string, _ *git.Repository) {
t.Helper()
if err := os.Remove(filepath.Join(dir, "link.txt")); err != nil {
t.Fatal(err)
}
if err := os.Symlink("target", filepath.Join(dir, "link.txt")); err != nil {
t.Fatal(err)
}
},
// git reports this as a typechange: the entry changed from a regular
// file to a symlink. The line counts are the content diff (a symlink's
// blob holds the target path, without the trailing newline).
wantFiles: []task.FileChange{
{Path: "link.txt", Status: task.ChangeTypeChanged, Additions: 1, Deletions: 1},
},
wantTotal: task.ChangeTotals{Files: 1, Additions: 1, Deletions: 1},
},
{
name: "a rename alongside a binary file keeps every count with its own path",
seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}, {path: "old.txt", content: "same content\n"}},
mutate: func(t *testing.T, dir string, _ *git.Repository) {
t.Helper()
if err := os.Remove(filepath.Join(dir, "old.txt")); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("same content\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "aaa-image.bin"), binaryContent, 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "zzz-text.txt"), []byte("one\ntwo\n"), 0o600); err != nil {
t.Fatal(err)
}
},
wantFiles: []task.FileChange{
{Path: "aaa-image.bin", Status: task.ChangeAdded, Binary: true},
{Path: "new.txt", OldPath: "old.txt", Status: task.ChangeRenamed},
{Path: "zzz-text.txt", Status: task.ChangeAdded, Additions: 2},
},
wantTotal: task.ChangeTotals{Files: 3, Additions: 2},
},
{
name: "nothing changed",
seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}},
mutate: func(*testing.T, string, *git.Repository) {},
// Empty, not nil: the persisted payload carries a list, and a null
// there would read as a missing measurement rather than a measured
// zero.
wantFiles: []task.FileChange{},
wantTotal: task.ChangeTotals{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dir, r, baseHash := newDiffstatRepo(t, tt.seeds)
tt.mutate(t, dir, r)
var head plumbing.Hash
if tt.name != "nothing changed" {
commitAll(t, r, dir, "change")
got, err := r.Head()
if err != nil {
t.Fatal(err)
}
head = got.Hash()
} else {
head = baseHash
}
m := &Manager{WorkDir: t.TempDir()}
stats, err := m.ChangedFileStats(t.Context(), dir, testBase)
if err != nil {
t.Fatalf("ChangedFileStats() error = %v", err)
}
if stats.BaseSHA != baseHash.String() {
t.Errorf("BaseSHA = %q, want the resolved base %q", stats.BaseSHA, baseHash)
}
if stats.HeadSHA != head.String() {
t.Errorf("HeadSHA = %q, want HEAD %q", stats.HeadSHA, head)
}
if len(stats.Files) != len(tt.wantFiles) {
t.Fatalf("Files = %+v, want %d entries %+v", stats.Files, len(tt.wantFiles), tt.wantFiles)
}
for i, want := range tt.wantFiles {
if got := stats.Files[i]; got != want {
t.Errorf("Files[%d] = %+v, want %+v", i, got, want)
}
}
if stats.Totals != tt.wantTotal {
t.Errorf("Totals = %+v, want %+v", stats.Totals, tt.wantTotal)
}
})
}
}
// TestChangedFileStatsRecordsTheDiffedBaseNotTheAdvancedTip pins the identity
// of the recorded base to the commit the file list was actually diffed against
// -- the merge base -- and not to base's tip, which moves whenever anyone
// lands on the base branch mid-run. Naming the tip would pair a file list with
// a commit it was never compared to.
func TestChangedFileStatsRecordsTheDiffedBaseNotTheAdvancedTip(t *testing.T) {
ctx := context.Background()
host := newLocalRemote(t, "acme", "todo")
m := newManager(t, host)
dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 8, "feat: mine", "", "feature")
if err != nil {
t.Fatalf("Prepare() error = %v", err)
}
r, err := git.PlainOpen(dir)
if err != nil {
t.Fatal(err)
}
diverged, err := r.ResolveRevision(plumbing.Revision(remoteBase(testBase)))
if err != nil {
t.Fatalf("resolve the base this branch diverged from: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "mine.txt"), []byte("mine\n"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := m.CommitAll(ctx, dir, "feat: mine"); err != nil {
t.Fatalf("CommitAll() error = %v", err)
}
// Another author lands on the base branch and this clone fetches it, so
// origin/<base> now names a commit this branch never contained.
seed := filepath.Join(t.TempDir(), "other")
sr, err := git.PlainClone(seed, &git.CloneOptions{URL: filepath.Join(host, "acme", "todo.git")})
if err != nil {
t.Fatalf("clone for second author: %v", err)
}
writeSeedCommit(t, sr, seed, "theirs.txt", "theirs\n", "chore: theirs")
ref := plumbing.NewBranchReferenceName(testBase)
if err := sr.Push(&git.PushOptions{
RemoteName: git.DefaultRemoteName,
RefSpecs: []gitconfig.RefSpec{gitconfig.RefSpec(ref + ":" + ref)},
}); err != nil {
t.Fatalf("second author push: %v", err)
}
if err := r.Fetch(&git.FetchOptions{RemoteName: git.DefaultRemoteName}); err != nil {
t.Fatalf("fetch: %v", err)
}
tip, err := r.ResolveRevision(plumbing.Revision(remoteBase(testBase)))
if err != nil {
t.Fatalf("resolve the advanced base tip: %v", err)
}
if tip == diverged {
t.Fatal("the base branch did not advance; this test would assert nothing")
}
stats, err := m.ChangedFileStats(ctx, dir, testBase)
if err != nil {
t.Fatalf("ChangedFileStats() error = %v", err)
}
if stats.BaseSHA != diverged.String() {
t.Errorf("BaseSHA = %q, want the diffed merge base %q (the base tip is %q)",
stats.BaseSHA, diverged, tip)
}
// The same rule from the other side: a file list measured from the merge
// base cannot name a commit that landed on the base branch afterwards.
for _, f := range stats.Files {
if f.Path == "theirs.txt" {
t.Errorf("Files = %+v, includes another author's file: the diff is not merge-base relative", stats.Files)
}
}
}