Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions docs/operating.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<relative path,...>` 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
Expand Down Expand Up @@ -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=<relative path,...>` naming the drifted prior-owned assets. Report the diagnostic notes to the user instead of forcing it.

## Never do this

Expand Down
85 changes: 83 additions & 2 deletions internal/cli/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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=<logical ID> path=<runtime-relative>`
// 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"
}
}
170 changes: 170 additions & 0 deletions internal/cli/update_guidance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading
Loading