From 8b3d98d00e2879995e1817483ccb8558c78b2f80 Mon Sep 17 00:00:00 2001 From: Juan Barbat Date: Fri, 23 Oct 2026 19:50:24 -0300 Subject: [PATCH 1/3] feat(cli): name failing assets and drift cause on actor_guidance_unverified Actor guidance preflight and re-check refusals now expose detached per-asset evidence (relative path, content vs mode drift with observed and canonical modes, bounded shadow role/location) and the update writer prints one asset= line per failing asset before the unchanged status=conflict reason=actor_guidance_unverified line (issue #373, specs S2/S4/S5). --- internal/cli/update.go | 85 ++++++++- internal/cli/update_guidance_test.go | 170 +++++++++++++++++ internal/installcoord/actor_guidance.go | 184 ++++++++++++++++++- internal/installcoord/actor_guidance_test.go | 162 ++++++++++++++++ 4 files changed, 589 insertions(+), 12 deletions(-) diff --git a/internal/cli/update.go b/internal/cli/update.go index 01a9880..00e2108 100644 --- a/internal/cli/update.go +++ b/internal/cli/update.go @@ -506,8 +506,7 @@ func updateActorGuidance(stdout, stderr io.Writer, canonical installplan.Plan, o } preflight, err := installcoord.PreflightActorGuidance(observations, installcoord.Unit{Plan: canonical, Observation: observation}, adopt, cwd) if err != nil || !preflight.Report().Ready() { - _, _ = fmt.Fprintf(stdout, "%s\nstatus=conflict reason=actor_guidance_unverified\n", header) - return exitConflict + return writeActorGuidanceRefusal(stdout, header, canonical, preflight.Refusal()) } proof := preflight.Proof() // Retain the exact immutable candidate and evidence. if !apply { @@ -535,3 +534,85 @@ func updateActorGuidance(stdout, stderr io.Writer, canonical installplan.Plan, o func nextUpdateBackupName() string { return "install-" + strconv.FormatInt(time.Now().UnixNano(), 36) } + +// writeActorGuidanceRefusal reports one refused actor-guidance update. The +// stable status line, the opaque stderr contract, and exitConflict are +// unchanged; the additive asset= diagnostics name each asset that failed +// verification and why, so reason=actor_guidance_unverified is never the only +// evidence the operator gets (issue #373, spec S2/S4/S5). +func writeActorGuidanceRefusal(stdout io.Writer, header string, canonical installplan.Plan, refusal installcoord.ActorGuidanceRefusal) int { + output := strings.Builder{} + output.WriteString(header + "\n") + for _, line := range actorGuidanceRefusalAssets(canonical, refusal) { + output.WriteString(line + "\n") + } + output.WriteString("status=conflict reason=actor_guidance_unverified\n") + _, _ = io.WriteString(stdout, output.String()) + return exitConflict +} + +// actorGuidanceRefusalAssets renders one machine-readable diagnostic line per +// asset that failed verification: content drift, mode drift with both modes, or +// the bounded role/location that shadows a closed actor. A conflicting asset +// that also drifted in mode keeps its content-drift cause and still reports the +// mode facts. Paths stay runtime-relative (S5); the writer names nothing the +// preflight did not capture. +func actorGuidanceRefusalAssets(canonical installplan.Plan, refusal installcoord.ActorGuidanceRefusal) []string { + assets, shadows := refusal.Assets(), refusal.Shadows() + lines := make([]string, 0, len(assets)+len(shadows)) + for _, asset := range assets { + line := actorGuidanceAsset(asset.LogicalID, asset.RelativePath) + if asset.Cause == installcoord.ActorGuidanceModeDrift { + lines = append(lines, line+" cause=mode_drift mode_drift=true"+actorGuidanceModes(asset)) + continue + } + line += " cause=content_drift action=conflict" + if asset.ModeDrift { + line += " mode_drift=true" + actorGuidanceModes(asset) + } + lines = append(lines, line) + } + relative := make(map[string]string, len(canonical.Files())) + for _, file := range canonical.Files() { + relative[file.LogicalID()] = file.RelativePath() + } + for _, shadow := range shadows { + logicalID := "actors/" + string(shadow.RoleID()) + lines = append(lines, actorGuidanceAsset(logicalID, relative[logicalID])+" cause=shadow_role shadow_location="+actorGuidanceShadowLocation(shadow.Location())) + } + return lines +} + +// actorGuidanceModes renders the captured and canonical modes of one asset, in +// the same shape the update operation lines already use. +func actorGuidanceModes(asset installcoord.ActorGuidanceRefusalAsset) string { + return fmt.Sprintf(" observed_mode=%04o canonical_mode=%04o", asset.ObservedMode, asset.CanonicalMode) +} + +// actorGuidanceAsset renders the `asset= path=` +// prefix of one diagnostic line, omitting the path when the candidate carries no +// file for that identity instead of inventing one. +func actorGuidanceAsset(logicalID, path string) string { + if path != "" { + return fmt.Sprintf("asset=%s path=%s", logicalID, path) + } + return "asset=" + logicalID +} + +// actorGuidanceShadowLocation names the bounded root a shadow conflict was +// found in. The scan exposes no path, so the location stays a closed symbolic +// name instead of an absolute one (S5). +func actorGuidanceShadowLocation(location installobserve.ShadowLocation) string { + switch location { + case installobserve.ShadowLocationGlobalAgents: + return "global_agents" + case installobserve.ShadowLocationGlobalSubagents: + return "global_subagents" + case installobserve.ShadowLocationProjectAgents: + return "project_agents" + case installobserve.ShadowLocationProjectSubagents: + return "project_subagents" + default: + return "unknown" + } +} diff --git a/internal/cli/update_guidance_test.go b/internal/cli/update_guidance_test.go index dd5044e..c53c94c 100644 --- a/internal/cli/update_guidance_test.go +++ b/internal/cli/update_guidance_test.go @@ -132,6 +132,176 @@ func TestUpdateGuidanceLifecycle(t *testing.T) { } } +// updateRegistersGuidance seeds one Pi installation and registers pre-existing +// external guidance through the explicit adoption apply, so later runs exercise +// the registered v3 update path instead of the first-adoption path. +func updateRegistersGuidance(t *testing.T, fixture *updateFixture) (string, updateDependencies) { + t.Helper() + fixture.catalog = must(filepath.Abs(fixture.catalog)) + t.Chdir(must(filepath.EvalSymlinks(t.TempDir()))) + root, deps := updateRootPath(t, fixture, runtimematrix.RuntimePi), fixture.dependencies(runtimematrix.RuntimePi) + if code, out, err := runUpdateCommand(t, deps, "update", "--runtime", "pi", "--catalog", fixture.catalog, "--apply"); code != exitOK || err != "" { + t.Fatalf("seed apply = (%d, %q, %q)", code, out, err) + } + for _, artifact := range updateStateIdentity(t, root).Artifacts() { + if artifact.Kind() != installstate.KindPiActor { + continue + } + path := filepath.Join(root, filepath.FromSlash(artifact.RelativePath())) + mustOK(os.WriteFile(path, append(bytes.TrimRight(must(os.ReadFile(path)), "\n"), updateGuidanceSuffix...), 0o600)) + } + if code, out, err := runUpdateCommand(t, deps, "update", "--runtime", "pi", "--catalog", fixture.catalog, "--adopt-guidance", "--apply"); code != exitOK || err != "" { + t.Fatalf("adoption apply = (%d, %q, %q)", code, out, err) + } + if state := updateStateIdentity(t, root); state.SchemaVersion() != 3 { + t.Fatalf("registered guidance state = v%d, want v3", state.SchemaVersion()) + } + return root, deps +} + +// updateGuidanceDiagnostics returns the additive per-asset refusal lines keyed +// by asset, and fails when a line carries an absolute path (issue #373, S5). +func updateGuidanceDiagnostics(t *testing.T, root, out string) map[string]string { + t.Helper() + lines := map[string]string{} + for _, line := range strings.Split(out, "\n") { + if !strings.HasPrefix(line, "asset=") { + continue + } + fields := map[string]string{} + for _, field := range strings.Fields(line) { + key, asset, found := strings.Cut(field, "=") + if !found { + t.Fatalf("diagnostic %q is not machine-readable", line) + } + fields[key] = asset + } + path := fields["path"] + if path == "" || filepath.IsAbs(path) || strings.HasPrefix(path, root+"/") { + t.Fatalf("diagnostic %q does not carry a runtime-relative path", line) + } + lines[fields["asset"]] = line + } + return lines +} + +// TestUpdateGuidanceRefusalNamesDriftedContent pins spec S2 for issue #373: a +// refused guidance update names every asset whose content drifted from the +// recorded identity, keeps the stable reason token, exit code, and opaque +// stderr, and writes nothing. +func TestUpdateGuidanceRefusalNamesDriftedContent(t *testing.T) { + fixture := newUpdateFixture(t) + root, deps := updateRegistersGuidance(t, fixture) + var drifted installstate.Artifact + for _, artifact := range updateStateIdentity(t, root).Artifacts() { + if artifact.Kind() == installstate.KindPiActor { + drifted = artifact + break + } + } + path := filepath.Join(root, filepath.FromSlash(drifted.RelativePath())) + mustOK(os.WriteFile(path, append(must(os.ReadFile(path)), []byte("drift")...), 0o600)) + before := updateGuidanceTree(t, fixture.home) + for _, flags := range [][]string{nil, {"--apply"}} { + args := append([]string{"update", "--runtime", "pi", "--catalog", fixture.catalog}, flags...) + code, out, err := runUpdateCommand(t, deps, args...) + if code != exitConflict || err != "" || !strings.Contains(out, "status=conflict reason=actor_guidance_unverified") { + t.Fatalf("drift refusal %v = (%d, %q, %q)", flags, code, out, err) + } + line, found := updateGuidanceDiagnostics(t, root, out)[drifted.LogicalID()] + if !found || !strings.Contains(line, "path="+drifted.RelativePath()) || !strings.Contains(line, "cause=content_drift") || !strings.Contains(line, "action=conflict") { + t.Fatalf("refusal %q did not name the drifted asset %s as content drift: %q", out, drifted.LogicalID(), line) + } + if !reflect.DeepEqual(before, updateGuidanceTree(t, fixture.home)) { + t.Fatal("refused guidance update wrote files") + } + } +} + +// TestUpdateGuidanceRefusalNamesModeDrift pins the mode-drift half of spec S2: +// an asset whose observed mode diverged is named with both modes instead of the +// bare unverified token. +func TestUpdateGuidanceRefusalNamesModeDrift(t *testing.T) { + fixture := newUpdateFixture(t) + root, deps := updateRegistersGuidance(t, fixture) + var drifted installstate.Artifact + for _, artifact := range updateStateIdentity(t, root).Artifacts() { + if artifact.Kind() == installstate.KindPiActor { + drifted = artifact + break + } + } + mustOK(os.Chmod(filepath.Join(root, filepath.FromSlash(drifted.RelativePath())), 0o640)) + before := updateGuidanceTree(t, fixture.home) + code, out, err := runUpdateCommand(t, deps, "update", "--runtime", "pi", "--catalog", fixture.catalog) + if code != exitConflict || err != "" || !strings.Contains(out, "status=conflict reason=actor_guidance_unverified") { + t.Fatalf("mode drift refusal = (%d, %q, %q)", code, out, err) + } + line, found := updateGuidanceDiagnostics(t, root, out)[drifted.LogicalID()] + if !found || !strings.Contains(line, "path="+drifted.RelativePath()) || !strings.Contains(line, "cause=mode_drift") || !strings.Contains(line, "observed_mode=0640 canonical_mode=0600") { + t.Fatalf("refusal %q did not name the mode-drifted asset %s: %q", out, drifted.LogicalID(), line) + } + if !reflect.DeepEqual(before, updateGuidanceTree(t, fixture.home)) { + t.Fatal("refused guidance update wrote files") + } +} + +// TestUpdateGuidanceRefusalNamesContentAndModeDrift pins the combined case: when +// an asset drifted in content and in mode, the refusal names the content drift +// as the conflict and still carries the mode facts it also captured, instead of +// dropping one of the two causes (issue #373, S2). +func TestUpdateGuidanceRefusalNamesContentAndModeDrift(t *testing.T) { + fixture := newUpdateFixture(t) + root, deps := updateRegistersGuidance(t, fixture) + var drifted installstate.Artifact + for _, artifact := range updateStateIdentity(t, root).Artifacts() { + if artifact.Kind() == installstate.KindSkill { + drifted = artifact + break + } + } + path := filepath.Join(root, filepath.FromSlash(drifted.RelativePath())) + mustOK(os.WriteFile(path, append(must(os.ReadFile(path)), []byte("drift")...), 0o640)) + mustOK(os.Chmod(path, 0o640)) + before := updateGuidanceTree(t, fixture.home) + code, out, err := runUpdateCommand(t, deps, "update", "--runtime", "pi", "--catalog", fixture.catalog) + if code != exitConflict || err != "" || !strings.Contains(out, "status=conflict reason=actor_guidance_unverified") { + t.Fatalf("combined drift refusal = (%d, %q, %q)", code, out, err) + } + line, found := updateGuidanceDiagnostics(t, root, out)[drifted.LogicalID()] + for _, want := range []string{"path=" + drifted.RelativePath(), "cause=content_drift", "action=conflict", "mode_drift=true", "observed_mode=0640 canonical_mode=0600"} { + if !found || !strings.Contains(line, want) { + t.Fatalf("refusal %q did not report %q for %s: %q", out, want, drifted.LogicalID(), line) + } + } + if !reflect.DeepEqual(before, updateGuidanceTree(t, fixture.home)) { + t.Fatal("refused guidance update wrote files") + } +} + +// TestUpdateGuidanceRefusalNamesShadowedRole pins the distinguishing half of +// spec S2: a shadow refusal names the closed role and the bounded location that +// shadows it, never an absolute path. +func TestUpdateGuidanceRefusalNamesShadowedRole(t *testing.T) { + fixture := newUpdateFixture(t) + root, deps := updateRegistersGuidance(t, fixture) + cwd := must(os.Getwd()) + mustOK(os.MkdirAll(filepath.Join(cwd, ".pi", "subagents"), 0o700)) + mustOK(os.WriteFile(filepath.Join(cwd, ".pi", "subagents", "shadow.md"), []byte("---\nname: cortex-test-designer\n---\n"), 0o600)) + before := updateGuidanceTree(t, fixture.home) + code, out, err := runUpdateCommand(t, deps, "update", "--runtime", "pi", "--catalog", fixture.catalog) + if code != exitConflict || err != "" || !strings.Contains(out, "status=conflict reason=actor_guidance_unverified") { + t.Fatalf("shadow refusal = (%d, %q, %q)", code, out, err) + } + line, found := updateGuidanceDiagnostics(t, root, out)["actors/test-designer"] + if !found || !strings.Contains(line, "cause=shadow_role") || !strings.Contains(line, "shadow_location=project_subagents") { + t.Fatalf("refusal %q did not name the shadowed role: %q", out, line) + } + if !reflect.DeepEqual(before, updateGuidanceTree(t, fixture.home)) { + t.Fatal("refused guidance update wrote files") + } +} + func TestUpdateGuidanceProductionApplyRechecks(t *testing.T) { for _, scenario := range []string{"actor", "skill", "state", "shadow"} { t.Run(scenario, func(t *testing.T) { diff --git a/internal/installcoord/actor_guidance.go b/internal/installcoord/actor_guidance.go index 1feb1c1..b01c57b 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,81 @@ 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} + switch ownerHash, owned := recorded[slot.LogicalID]; { + case asset.ModeDrift: + asset.Cause = ActorGuidanceModeDrift + case !owned || ownerHash != slot.SHA256: + asset.Cause = ActorGuidanceContentDrift + 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..6057cbc 100644 --- a/internal/installcoord/actor_guidance_test.go +++ b/internal/installcoord/actor_guidance_test.go @@ -189,6 +189,168 @@ 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, + }, + { + // 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) + } + 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) { From 7567a63130400d9638d1ffc26226802938010a44 Mon Sep 17 00:00:00 2001 From: Juan Barbat Date: Fri, 23 Oct 2026 19:56:10 -0300 Subject: [PATCH 2/3] docs(operating): document conflict path diagnostics for install, uninstall, and update refusals --- docs/operating.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/operating.md b/docs/operating.md index 2b0ba42..682c5ff 100644 --- a/docs/operating.md +++ b/docs/operating.md @@ -54,7 +54,7 @@ operation=install status=completed touch=applied create=33 replace=0 remove=0 un - `status=completed touch=applied` — the transaction applied and was read back. Running install again is a no-op reported honestly as `create=0 unchanged=33`. - `status=not_applied reason=compatibility_uncertified touch=denied` — no compatible runtime was found; nothing was written. - `status=not_applied reason=projection_unrepresentable touch=denied` — a runtime exists but cannot represent a capability honestly; Cortex refused rather than approximating. Report it; do not work around it. -- `status=not_applied reason=ownership_conflict touch=denied` (exit 3) — a target file exists without verified Cortex ownership. Someone else wrote there. Stop and ask the user; never delete or rewrite foreign files to clear the path. +- `status=not_applied reason=ownership_conflict touch=denied` (exit 3) — a target file exists without verified Cortex ownership. Someone else wrote there. Stop and ask the user; never delete or rewrite foreign files to clear the path. The status line appends `conflict_paths=` naming every asset whose ownership decision conflicted, so the conflicting files are named without reading transaction internals. - `warning=uncertified_admission runtimes=N certification=not_certified` — the transaction configured N runtimes whose exact version has no verified evidence. This is disclosed non-certified admission, not a failure; the user may accept it once they know. ## Directory targets @@ -98,13 +98,22 @@ cortex update --runtime pi --catalog ./catalog --apply # the plan, applied Default mode touches nothing — run the plan first, read it, then decide. `--apply` writes only inside that runtime's Cortex-owned root. On Pi, if legacy externally-modified guidance is detected, the plan asks for explicit consent with `--adopt-guidance`: that is a one-time adoption of external bytes (they are preserved, not overwritten), not a drift override, and drift is always refused. +When a guidance preflight or apply re-check refuses, the plan prints `status=conflict reason=actor_guidance_unverified` (exit 3) followed by one `asset=` line per failing asset naming the failing file and the cause: + +``` +asset=skills/adversarial-tester path=skills/cortex-adversarial-tester/SKILL.md cause=content_drift action=conflict +asset=skills/requirements-analyst path=skills/cortex-requirements-analyst/SKILL.md cause=mode_drift observed_mode=0640 canonical_mode=0600 +``` + +`cause=content_drift` means the bytes differ from the recorded state; `cause=mode_drift` reports the observed versus canonical file mode. Shadow conflicts (externally authored files under Cortex-owned identities) report `cause=shadow_role` with the shadow location. Paths are runtime-relative. + ## Running uninstall `cortex uninstall` removes only material verified as Cortex-owned, making a backup first. Per-runtime statuses: - `uninstall=completed remove=N` — removed exactly what it owned. - `not_installed` — nothing of Cortex's there; nothing done. -- `conflict` / `blocked` — shared actor state or unverified ownership blocks removal; the whole grouped uninstall fails closed and nothing is removed. Report the diagnostic notes to the user instead of forcing it. +- `conflict` / `blocked` — shared actor state or unverified ownership blocks removal; the whole grouped uninstall fails closed and nothing is removed. The runtime line appends `conflict_paths=` naming the drifted prior-owned assets. Report the diagnostic notes to the user instead of forcing it. ## Never do this From 40a26ef83239271c85d54d91c8bf2c447afd0678 Mon Sep 17 00:00:00 2001 From: Juan Barbat Date: Fri, 23 Oct 2026 20:17:30 -0300 Subject: [PATCH 3/3] chore: trigger fresh validate run after PR body edit