From 56479dff0c438d0e77f1653a46454d5004800076 Mon Sep 17 00:00:00 2001 From: Juan Barbat Date: Thu, 12 Nov 2026 17:50:04 -0300 Subject: [PATCH] fix(installcoord): name drifted guidance assets with content drift first Refs #384 --- internal/installcoord/actor_guidance.go | 186 ++++++++++++++++++- internal/installcoord/actor_guidance_test.go | 180 ++++++++++++++++++ 2 files changed, 356 insertions(+), 10 deletions(-) diff --git a/internal/installcoord/actor_guidance.go b/internal/installcoord/actor_guidance.go index 1feb1c1..d69fba3 100644 --- a/internal/installcoord/actor_guidance.go +++ b/internal/installcoord/actor_guidance.go @@ -2,16 +2,96 @@ package installcoord import ( "errors" + "io/fs" "github.com/refactor-ia/cortex/internal/installobserve" + "github.com/refactor-ia/cortex/internal/installplan" + "github.com/refactor-ia/cortex/internal/ownership" "github.com/refactor-ia/cortex/internal/runtimematrix" ) +// ActorGuidanceRefusalStage names the preflight gate that refused an +// actor-guidance update, so a caller can report which asset failed verification +// instead of a bare reason token (issue #373). The stage is evidence only: it +// grants no write, removal, or admission authority. +type ActorGuidanceRefusalStage uint8 + +const ( + // ActorGuidanceRefusedEvidence means the captured evidence itself did not + // verify: it was invalid, stale, unadopted, or tampered with. + ActorGuidanceRefusedEvidence ActorGuidanceRefusalStage = iota + 1 + // ActorGuidanceRefusedConflict means classified artifact decisions + // conflicted with the candidate. + ActorGuidanceRefusedConflict + // ActorGuidanceRefusedShadow means the bounded shadow scan was not clean. + ActorGuidanceRefusedShadow +) + +// ActorGuidanceRefusalCause names why one captured asset no longer matches the +// installation the update would refresh. +type ActorGuidanceRefusalCause uint8 + +const ( + // ActorGuidanceContentDrift means the captured bytes are not the content + // this installation owns: they differ from the recorded digest, or the + // captured asset carries no recorded ownership at all. + ActorGuidanceContentDrift ActorGuidanceRefusalCause = iota + 1 + // ActorGuidanceModeDrift means the captured file mode differs from the + // canonical mode the asset is installed with. + ActorGuidanceModeDrift +) + +// ActorGuidanceRefusalAsset names one captured asset whose identity no longer +// matches, with its runtime-relative path, so a refusal can name the file and +// the drift instead of only the reason token. Cause is the single reason the +// asset refused verification; ModeDrift records the additional, independent +// fact that its file mode also diverged, so a conflict never silently drops the +// mode evidence the capture already carries. +type ActorGuidanceRefusalAsset struct { + LogicalID string + RelativePath string + Cause ActorGuidanceRefusalCause + ModeDrift bool + ObservedMode fs.FileMode + CanonicalMode fs.FileMode +} + +// ActorGuidanceRefusal is detached point-in-time evidence for one refused +// actor-guidance preflight: the refusing stage plus the assets and bounded +// shadow conflicts captured up to that point. It never becomes planning, apply, +// or deletion authority, and it is computed only after the refusal is decided, +// so it can neither admit nor reject on its own. +type ActorGuidanceRefusal struct { + stage ActorGuidanceRefusalStage + assets []ActorGuidanceRefusalAsset + shadows []installobserve.ShadowConflict +} + +// Valid reports whether this record describes an actual refusal. The zero value +// describes a preflight that was not refused. +func (refusal ActorGuidanceRefusal) Valid() bool { return refusal.stage != 0 } + +// Stage returns the preflight gate that refused. +func (refusal ActorGuidanceRefusal) Stage() ActorGuidanceRefusalStage { return refusal.stage } + +// Assets returns the detached captured assets that no longer match, in +// canonical slot order. +func (refusal ActorGuidanceRefusal) Assets() []ActorGuidanceRefusalAsset { + return append([]ActorGuidanceRefusalAsset{}, refusal.assets...) +} + +// Shadows returns the detached bounded role/location shadow conflicts that +// refused the update. +func (refusal ActorGuidanceRefusal) Shadows() []installobserve.ShadowConflict { + return append([]installobserve.ShadowConflict{}, refusal.shadows...) +} + // ActorGuidanceReport retains point-in-time planning evidence, never write or // deletion authority. Composed restart recovery remains unsupported. type ActorGuidanceReport struct { - report Report - proof installobserve.ActorGuidanceClassification + report Report + proof installobserve.ActorGuidanceClassification + refusal ActorGuidanceRefusal } func (report ActorGuidanceReport) Report() Report { return report.report } @@ -19,32 +99,38 @@ func (report ActorGuidanceReport) Proof() installobserve.ActorGuidanceClassifica return report.proof } +// Refusal returns the detached refusal evidence. A refused preflight keeps its +// report and proof unusable; only the diagnostic record is populated. +func (report ActorGuidanceReport) Refusal() ActorGuidanceRefusal { return report.refusal } + // PreflightActorGuidance plans one explicit local Pi update from a canonical v2 // Unit. Legacy guidance adoption is opt-in; it is not an ownership bypass. // Actions come only from ClassifyActorGuidance, with the same local runtime // policy as PreflightLocalUpdate. Shadow or skill conflicts return no usable -// report/proof. No target writes occur; later apply must freshly revalidate the -// canonical unit, exact composed candidate/proof, and cwd. This is not durable -// recovery evidence, admission, or public mutation routing. +// report/proof but do return the stage and the captured assets that refused, so +// callers can name the conflicting files. No target writes occur; later apply +// must freshly revalidate the canonical unit, exact composed candidate/proof, +// and cwd. This is not durable recovery evidence, admission, or public mutation +// routing. func PreflightActorGuidance(observations []runtimematrix.Observation, unit Unit, adoptLegacy bool, cwd string) (ActorGuidanceReport, error) { if unit.Plan.RuntimeID() != runtimematrix.RuntimePi || unit.Plan.InstalledState().SchemaVersion() != 2 || !validUnit(unit) { - return ActorGuidanceReport{}, ErrInvalid + return refusedActorGuidance(ActorGuidanceRefusedEvidence, recordedDriftAssets(unit), ErrInvalid) } matrix, err := runtimematrix.DecideLocalUpdate(observations, unit.Plan.RuntimeID()) if err != nil || !matrix.HasCompatible { - return ActorGuidanceReport{}, ErrInvalid + return refusedActorGuidance(ActorGuidanceRefusedEvidence, recordedDriftAssets(unit), ErrInvalid) } proof, err := installobserve.ClassifyActorGuidance(unit.Plan, unit.Observation, adoptLegacy) if err != nil { - return ActorGuidanceReport{}, errors.Join(ErrInvalid, err) + return refusedActorGuidance(ActorGuidanceRefusedEvidence, recordedDriftAssets(unit), errors.Join(ErrInvalid, err)) } classified := proof.Result() if !classifiedReady(classified) { - return ActorGuidanceReport{}, ErrInvalid + return refusedActorGuidance(ActorGuidanceRefusedConflict, conflictAssets(unit.Plan, classified), ErrInvalid) } shadows, err := installobserve.ObserveActorGuidanceShadows(unit.Plan, unit.Observation, proof, cwd) if err != nil || !shadows.Clean() { - return ActorGuidanceReport{}, errors.Join(ErrInvalid, err) + return ActorGuidanceReport{refusal: ActorGuidanceRefusal{stage: ActorGuidanceRefusedShadow, shadows: shadows.Conflicts()}}, errors.Join(ErrInvalid, err) } statuses := make([]Status, 0, len(matrix.Decisions)) for _, decision := range matrix.Decisions { @@ -57,3 +143,83 @@ func PreflightActorGuidance(observations []runtimematrix.Observation, unit Unit, } return ActorGuidanceReport{report: Report{statuses: statuses, ready: classifiedReady(classified)}, proof: proof}, nil } + +// refusedActorGuidance returns a refused report with its diagnostic record and +// the refusal error, so usable report/proof evidence stays empty by contract. +func refusedActorGuidance(stage ActorGuidanceRefusalStage, assets []ActorGuidanceRefusalAsset, err error) (ActorGuidanceReport, error) { + return ActorGuidanceReport{refusal: ActorGuidanceRefusal{stage: stage, assets: assets}}, err +} + +// conflictAssets names the classified artifact decisions that conflicted with +// the candidate, so a conflict refusal reports exactly what refused instead of +// every unrelated drift the same installation carries. +func conflictAssets(plan installplan.Plan, classified installobserve.Result) []ActorGuidanceRefusalAsset { + relative := make(map[string]string, len(plan.Files())) + canonical := make(map[string]fs.FileMode, len(plan.Files())) + for _, file := range plan.Files() { + relative[file.LogicalID()] = file.RelativePath() + canonical[file.LogicalID()] = file.DesiredMode().Perm() + } + assets := make([]ActorGuidanceRefusalAsset, 0, len(classified.ArtifactDecisions())) + for _, decision := range classified.ArtifactDecisions() { + if decision.Action != ownership.Conflict { + continue + } + assets = append(assets, ActorGuidanceRefusalAsset{ + LogicalID: decision.LogicalID, + RelativePath: relative[decision.LogicalID], + Cause: ActorGuidanceContentDrift, + ModeDrift: decision.ModeDrift, + ObservedMode: decision.ObservedMode.Perm(), + CanonicalMode: canonical[decision.LogicalID], + }) + } + return assets +} + +// recordedDriftAssets names each captured asset whose identity no longer +// matches the recorded installation. It is used when classification itself +// refused, so it reads captured evidence only, never the filesystem, and it +// distinguishes only the two causes spec S2 requires: mode drift from the +// canonical mode, and content drift from the recorded digest. An asset the +// recorded ledger does not own has no digest to compare, so it is reported as +// content drift instead of being dropped; without any recorded ledger nothing +// can be verified as owned, so every present candidate asset is reported. +func recordedDriftAssets(unit Unit) []ActorGuidanceRefusalAsset { + desired := make(map[string]installplan.File, len(unit.Plan.Files())) + for _, file := range unit.Plan.Files() { + desired[file.LogicalID()] = file + } + var recorded map[string]string + if prior := unit.Observation.PriorState(); prior != nil { + recorded = make(map[string]string, len(prior.Manifest.Artifacts())) + for _, artifact := range prior.Manifest.Artifacts() { + recorded[artifact.LogicalID()] = artifact.SHA256() + } + } + assets := make([]ActorGuidanceRefusalAsset, 0, len(desired)) + for _, slot := range unit.Observation.Slots() { + file, wanted := desired[slot.LogicalID] + if !wanted || !slot.Present { + continue + } + captured, found := unit.Observation.Exact(slot.LogicalID) + if !found { + continue + } + observedMode, canonicalMode := captured.Mode().Perm(), file.DesiredMode().Perm() + asset := ActorGuidanceRefusalAsset{LogicalID: slot.LogicalID, RelativePath: file.RelativePath(), ModeDrift: observedMode != canonicalMode, ObservedMode: observedMode, CanonicalMode: canonicalMode} + // Content drift takes precedence, as in classifiedConflictAssets: mode + // drift stays the independent flag, and is the cause only alone. + switch ownerHash, owned := recorded[slot.LogicalID]; { + case !owned || ownerHash != slot.SHA256: + asset.Cause = ActorGuidanceContentDrift + case asset.ModeDrift: + asset.Cause = ActorGuidanceModeDrift + default: + continue + } + assets = append(assets, asset) + } + return assets +} diff --git a/internal/installcoord/actor_guidance_test.go b/internal/installcoord/actor_guidance_test.go index 0d6f929..0139d70 100644 --- a/internal/installcoord/actor_guidance_test.go +++ b/internal/installcoord/actor_guidance_test.go @@ -189,6 +189,186 @@ func TestPreflightActorGuidance(t *testing.T) { } } +// TestPreflightActorGuidanceRefusalNamesCause pins the refusal evidence a caller +// needs to name which asset failed verification and why (issue #373, S2): the +// refusing gate, the captured drift of each mismatched asset, and the bounded +// role/location shadow conflicts. It grants no authority: the report stays +// unusable and the target is never touched. +func TestPreflightActorGuidanceRefusalNamesCause(t *testing.T) { + actorFile := func(t *testing.T, canonical installplan.Plan, logicalID string) installplan.File { + t.Helper() + for _, file := range canonical.Files() { + if file.LogicalID() == logicalID { + return file + } + } + t.Fatalf("fixture has no %s asset", logicalID) + return installplan.File{} + } + for _, tc := range []struct { + name string + stage installcoord.ActorGuidanceRefusalStage + changed bool + adopt bool + prepare func(t *testing.T, canonical installplan.Plan, cwd string) + want []string + wantMode bool + wantDriftMode bool + }{ + { + // The fixture appends external guidance to every actor while the + // recorded state stays canonical: without adoption those six actor + // files are exactly what failed verification. + name: "unadopted external guidance names every drifted actor", + stage: installcoord.ActorGuidanceRefusedEvidence, + want: []string{"actors/adversarial-tester", "actors/evidence-auditor", "actors/exploratory-tester", "actors/requirements-analyst", "actors/test-designer", "actors/test-runner"}, + }, + { + name: "skill content drift names only the conflicting skill", + stage: installcoord.ActorGuidanceRefusedConflict, + adopt: true, + prepare: func(t *testing.T, canonical installplan.Plan, cwd string) { + must(t, os.WriteFile(canonical.Files()[0].AbsolutePath(), []byte("user skill drift"), 0o600)) + }, + want: []string{"skills/adversarial-tester"}, + }, + { + name: "actor mode drift names the observed and canonical mode", + stage: installcoord.ActorGuidanceRefusedEvidence, + changed: true, + prepare: func(t *testing.T, canonical installplan.Plan, cwd string) { + must(t, os.Chmod(actorFile(t, canonical, "actors/adversarial-tester").AbsolutePath(), 0o640)) + }, + want: []string{"actors/adversarial-tester"}, + wantMode: true, + // A mode-only refusal reports mode drift as its cause and as the + // captured fact. + wantDriftMode: true, + }, + { + // An evidence-stage asset that drifted in content and in mode + // reports content drift as its cause and keeps the mode facts as + // the independent flag (issue #384). + name: "actor content and mode drift reports content drift with its mode", + stage: installcoord.ActorGuidanceRefusedEvidence, + changed: true, + prepare: func(t *testing.T, canonical installplan.Plan, cwd string) { + path := actorFile(t, canonical, "actors/adversarial-tester").AbsolutePath() + must(t, os.WriteFile(path, append(value(os.ReadFile(path)), []byte("drift")...), 0o640)) + must(t, os.Chmod(path, 0o640)) + }, + want: []string{"actors/adversarial-tester"}, + wantDriftMode: true, + }, + { + // A conflicting asset can also carry mode drift. The conflict stays + // the cause, and the mode facts are reported with it instead of + // being dropped (issue #373, S2). + name: "skill content drift also reports its mode drift", + stage: installcoord.ActorGuidanceRefusedConflict, + adopt: true, + prepare: func(t *testing.T, canonical installplan.Plan, cwd string) { + must(t, os.WriteFile(canonical.Files()[0].AbsolutePath(), []byte("user skill drift"), 0o640)) + must(t, os.Chmod(canonical.Files()[0].AbsolutePath(), 0o640)) + }, + want: []string{"skills/adversarial-tester"}, + wantDriftMode: true, + }, + { + name: "shadowed role is a shadow refusal", + stage: installcoord.ActorGuidanceRefusedShadow, + adopt: true, + prepare: func(t *testing.T, canonical installplan.Plan, cwd string) { + write(t, cwd, ".pi/subagents/alias.md", "---\nname: cortex-test-designer\n---\n") + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + canonical, cwd := coordGuidanceFixture(t, tc.changed), coordPhysicalDir(t) + wanted := make(map[string]string, len(canonical.Files())) + for _, file := range canonical.Files() { + wanted[file.LogicalID()] = file.RelativePath() + } + if tc.prepare != nil { + tc.prepare(t, canonical, cwd) + } + unit := installcoord.Unit{Plan: canonical, Observation: value(installobserve.Observe(canonical, installobserve.DefaultOptions()))} + before := coordTree(t, canonical.RootPath()) + got, err := installcoord.PreflightActorGuidance(actorAwareObservations(), unit, tc.adopt, cwd) + refusal := got.Refusal() + if err == nil || !refusal.Valid() || refusal.Stage() != tc.stage { + t.Fatalf("refusal = (err %v, stage %d), want stage %d", err, refusal.Stage(), tc.stage) + } + if got.Report().Ready() || len(got.Report().Statuses()) != 0 { + t.Fatal("refusal retained usable statuses") + } + var named []string + for _, asset := range refusal.Assets() { + if wanted[asset.LogicalID] != asset.RelativePath || asset.RelativePath == "" || filepath.IsAbs(asset.RelativePath) { + t.Fatalf("refusal asset = %#v, want its runtime-relative path", asset) + } + wantCause := installcoord.ActorGuidanceContentDrift + if tc.wantMode { + wantCause = installcoord.ActorGuidanceModeDrift + if asset.ObservedMode != 0o640 || asset.CanonicalMode != installplan.CanonicalFileMode { + t.Fatalf("mode drift asset = %#v, want observed 0640 canonical 0600", asset) + } + } + if asset.Cause != wantCause { + t.Fatalf("refusal asset = %#v, want cause %d", asset, wantCause) + } + if asset.ModeDrift != tc.wantDriftMode { + t.Fatalf("refusal asset = %#v, want ModeDrift %t", asset, tc.wantDriftMode) + } + if asset.ModeDrift && (asset.ObservedMode != 0o640 || asset.CanonicalMode != installplan.CanonicalFileMode) { + t.Fatalf("mode drift asset = %#v, want observed 0640 canonical 0600", asset) + } + named = append(named, asset.LogicalID) + } + if !reflect.DeepEqual(named, tc.want) { + t.Fatalf("refusal named %v, want %v", named, tc.want) + } + if tc.stage == installcoord.ActorGuidanceRefusedShadow { + conflicts := refusal.Shadows() + if len(conflicts) != 1 || conflicts[0].RoleID() != "test-designer" || conflicts[0].Location() != installobserve.ShadowLocationProjectSubagents { + t.Fatalf("shadow refusal = %#v, want the shadowed test-designer role", conflicts) + } + } else if len(refusal.Shadows()) != 0 { + t.Fatalf("verification refusal = %#v, want no shadow conflicts", refusal.Shadows()) + } + if !reflect.DeepEqual(before, coordTree(t, canonical.RootPath())) { + t.Fatal("refusal changed target") + } + }) + } +} + +// TestPreflightActorGuidanceRefusalIsDetachedAndValidOnlyWhenRefused pins the +// zero value contract: a successful preflight carries no refusal record, and a +// returned record cannot be mutated back into the report. +func TestPreflightActorGuidanceRefusalIsDetachedAndValidOnlyWhenRefused(t *testing.T) { + canonical, cwd := coordGuidanceFixture(t, false), coordPhysicalDir(t) + unit := installcoord.Unit{Plan: canonical, Observation: value(installobserve.Observe(canonical, installobserve.DefaultOptions()))} + ready, err := installcoord.PreflightActorGuidance(actorAwareObservations(), unit, true, cwd) + if err != nil || ready.Refusal().Valid() || len(ready.Refusal().Assets()) != 0 { + t.Fatalf("ready preflight = (err %v, refusal %#v)", err, ready.Refusal()) + } + must(t, os.WriteFile(canonical.Files()[0].AbsolutePath(), []byte("user skill drift"), 0o600)) + unit = installcoord.Unit{Plan: canonical, Observation: value(installobserve.Observe(canonical, installobserve.DefaultOptions()))} + refused, err := installcoord.PreflightActorGuidance(actorAwareObservations(), unit, true, cwd) + if err == nil { + t.Fatal("drifted guidance was accepted") + } + assets := refused.Refusal().Assets() + if len(assets) == 0 { + t.Fatal("conflict refusal lost its captured evidence") + } + assets[0].LogicalID = "tampered" + if refused.Refusal().Assets()[0].LogicalID == "tampered" { + t.Fatal("Refusal() exposed mutable state") + } +} + func TestPreflightActorGuidanceRefuses(t *testing.T) { for _, name := range []string{"default adoption refusal", "zero unit", "zero observation", "wrong root", "wrong runtime", "missing runtime", "denied runtime", "composed unit", "skill drift", "shadow", "unsafe cwd", "symlink cwd", "unsafe root", "actor mode", "v3 tamper", "stale actor", "zero runtimes"} { t.Run(name, func(t *testing.T) {