Skip to content

Commit 95f1a8c

Browse files
committed
Merge remote-tracking branch 'origin/main' into pr-388
2 parents 79102df + 348966d commit 95f1a8c

12 files changed

Lines changed: 279 additions & 18 deletions

File tree

‎docs/operating.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ operation=install status=completed touch=applied create=33 replace=0 remove=0 un
5454
- `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`.
5555
- `status=not_applied reason=compatibility_uncertified touch=denied` — no compatible runtime was found; nothing was written.
5656
- `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.
57-
- `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.
57+
- `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.
5858
- `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.
5959

6060
## Directory targets
@@ -109,6 +109,8 @@ cortex update --runtime pi --catalog ./catalog --apply # the plan, applied
109109

110110
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.
111111

112+
A plan or apply that hits an asset without verified Cortex ownership reports `operation=<logical id> action=conflict` and ends with `status=conflict conflict_paths=<relative path,...>` (exit 3), naming each conflicting asset by its path under the runtime root. Nothing is written; stop and ask the user rather than removing the file.
113+
112114
## Upgrade to alpha20
113115

114116
Use the [published alpha20 archive and checksum procedure](verification.md#verify-an-archive) for the machine's platform. Keep the extracted binary, catalog and licenses together in a versioned directory. Do not replace user model routes or runtime configuration with release defaults.
@@ -143,7 +145,7 @@ Preserve command exit codes, output and the last completed transaction. A failed
143145

144146
- `uninstall=completed remove=N` — removed exactly what it owned.
145147
- `not_installed` — nothing of Cortex's there; nothing done. The grouped uninstall exits 0; `uninstall --target-dir` exits 3 because a directory target without ownership fails closed.
146-
- `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.
148+
- `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.
147149

148150
## Never do this
149151

‎internal/cli/doctor.go‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ func runQA(ctx context.Context, args []string, stdout, stderr io.Writer) int {
401401
_, _ = fmt.Fprintf(stderr, "evidence_reason=%s\n", evidenceErr.Reason)
402402
}
403403
if evidenceErr.Detail != "" {
404-
_, _ = fmt.Fprintf(stderr, "evidence_detail=%s\n", evidenceErr.Detail)
404+
_, _ = fmt.Fprintf(stderr, "evidence_detail=%s\n", escapeDiagnosticText(evidenceErr.Detail))
405405
}
406406
}
407407
if diagnostic := qaAdmissionDiagnostic(err); diagnostic != "" {
@@ -472,6 +472,13 @@ func sanitizeRouteIdentity(value string) string {
472472
if value == "" || len(value) > 128 {
473473
return "<redacted>"
474474
}
475+
return escapeDiagnosticText(value)
476+
}
477+
478+
// escapeDiagnosticText keeps printable ASCII and renders every other byte, and
479+
// the backslash itself, as \xNN, so caller-supplied text stays readable in a
480+
// terminal diagnostic without letting escape or control sequences through.
481+
func escapeDiagnosticText(value string) string {
475482
var b strings.Builder
476483
b.Grow(len(value))
477484
for index := 0; index < len(value); index++ {
@@ -889,6 +896,9 @@ func writeUninstallResult(stdout, stderr io.Writer, results []uninstallPreflight
889896
for _, result := range results {
890897
remove, absent, conflict := uninstallCounts(result.observation)
891898
_, _ = fmt.Fprintf(&output, "runtime=%s uninstall=%s remove=%d absent=%d conflict=%d", result.root.RuntimeID(), result.status, remove, absent, conflict)
899+
if paths := result.observation.ConflictPaths(); len(paths) > 0 {
900+
_, _ = fmt.Fprintf(&output, " conflict_paths=%s", strings.Join(paths, ","))
901+
}
892902
if paths := result.observation.UnsupportedActorPaths(); len(paths) > 0 {
893903
unsupported = true
894904
_, _ = fmt.Fprintf(&output, " reason=unsupported_installation state=validated_canonical_v3 recorded_actor_paths=%s", strings.Join(paths, ","))

‎internal/cli/install.go‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,11 @@ func runDirectoryInstall(stdout, stderr io.Writer, target string, deps installDe
144144
group, err := deps.applyGroup(requests, home, backupName)
145145
if err != nil {
146146
reason, code := installFailureReason(err)
147-
return writeInstallResult(stdout, stderr, "install", "status=not_applied reason="+reason+" touch=denied", "", results, false, installtxn.Counts{}, code)
147+
status := "status=not_applied reason=" + reason + " touch=denied"
148+
if paths := installConflictPaths(requests, err); paths != "" {
149+
status += " conflict_paths=" + paths
150+
}
151+
return writeInstallResult(stdout, stderr, "install", status, "", results, false, installtxn.Counts{}, code)
148152
}
149153
return writeInstallResult(stdout, stderr, "install", "status=completed touch=applied", "", results, true, group.Counts(), exitOK)
150154
}
@@ -230,11 +234,54 @@ func runInstall(ctx context.Context, stdout, stderr io.Writer, runner runtimepro
230234
group, err := deps.applyGroup(requests, home, backupName)
231235
if err != nil {
232236
reason, code := installFailureReason(err)
233-
return writeInstallResult(stdout, stderr, operation, "status=not_applied reason="+reason+" touch=denied", "", results, false, installtxn.Counts{}, code)
237+
status := "status=not_applied reason=" + reason + " touch=denied"
238+
if paths := installConflictPaths(requests, err); paths != "" {
239+
status += " conflict_paths=" + paths
240+
}
241+
return writeInstallResult(stdout, stderr, operation, status, "", results, false, installtxn.Counts{}, code)
234242
}
235243
return writeInstallResult(stdout, stderr, operation, "status=completed touch=applied", warning, results, true, group.Counts(), exitOK)
236244
}
237245

246+
// installConflictPaths renders the conflicting logical assets as runtime-relative
247+
// paths for the operator diagnostic (issue #373). Output is deduplicated and
248+
// sorted by the transaction layer.
249+
func installConflictPaths(requests []installtxn.GroupRequest, err error) string {
250+
var conflict *installtxn.ConflictError
251+
if !errors.As(err, &conflict) || len(conflict.LogicalIDs) == 0 {
252+
return ""
253+
}
254+
plans := make([]installplan.Plan, 0, len(requests))
255+
for _, request := range requests {
256+
plans = append(plans, request.Plan)
257+
}
258+
return conflictRelativePaths(plans, conflict.LogicalIDs)
259+
}
260+
261+
// conflictRelativePaths maps conflicting LogicalIDs to the runtime-relative
262+
// paths their plans compose, preserving the given order and dropping
263+
// duplicates. LogicalIDs without a file in the plans (the state artifact) are
264+
// omitted, so every caller renders the same conflict_paths representation.
265+
func conflictRelativePaths(plans []installplan.Plan, logicalIDs []string) string {
266+
relative := make(map[string]string)
267+
for _, plan := range plans {
268+
for _, file := range plan.Files() {
269+
relative[file.LogicalID()] = file.RelativePath()
270+
}
271+
}
272+
paths := make([]string, 0, len(logicalIDs))
273+
seen := make(map[string]bool, len(logicalIDs))
274+
for _, id := range logicalIDs {
275+
path, ok := relative[id]
276+
if !ok || seen[path] {
277+
continue
278+
}
279+
seen[path] = true
280+
paths = append(paths, path)
281+
}
282+
return strings.Join(paths, ",")
283+
}
284+
238285
// installFailureReason maps a grouped-transaction failure to the operator reason
239286
// and exit code. Fail-closed refusals name their cause and remedy instead of the
240287
// opaque transaction_failed (issue #281).

‎internal/cli/install_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,24 @@ func TestRunInstallUnrepresentableProjectionIsNotApplied(t *testing.T) {
211211
t.Fatalf("install = (%q, %q)", stdout.String(), stderr.String())
212212
}
213213
}
214+
func TestRunInstallConflictListsConflictingPaths(t *testing.T) {
215+
deps := compatibleInstallDependencies(t, t.TempDir())
216+
deps.applyGroup = func([]installtxn.GroupRequest, string, string) (installtxn.GroupResult, error) {
217+
return installtxn.GroupResult{}, &installtxn.ConflictError{LogicalIDs: []string{"skills/requirements-analyst"}}
218+
}
219+
var stdout, stderr bytes.Buffer
220+
if code := runWithInstallDependencies(context.Background(), []string{"install"}, &stdout, &stderr, certifiedPiOnlyRunner(), deps); code != exitConflict {
221+
t.Fatalf("install exit = %d, want %d", code, exitConflict)
222+
}
223+
if stderr.Len() != 0 {
224+
t.Fatalf("stderr = %q, want empty", stderr.String())
225+
}
226+
want := "status=not_applied reason=ownership_conflict touch=denied conflict_paths=skills/cortex-requirements-analyst/SKILL.md"
227+
if !strings.Contains(stdout.String(), want) {
228+
t.Fatalf("stdout = %q, want conflict paths %q", stdout.String(), want)
229+
}
230+
}
231+
214232
func TestRunInstallFailuresDoNotReportCompletion(t *testing.T) {
215233
for _, tc := range []struct {
216234
name string

‎internal/cli/qa_test.go‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1072,6 +1072,53 @@ func TestQARunEvidenceDiagnosticAttribution(t *testing.T) {
10721072
}
10731073
}
10741074

1075+
func TestQARunEvidenceDetailIsEscaped(t *testing.T) {
1076+
args := reportFixture(t)
1077+
for _, tc := range []struct {
1078+
name string
1079+
data string
1080+
wantDetail string
1081+
}{
1082+
{
1083+
name: "object key with terminal escape bytes",
1084+
data: "{\"\\u001b[2J\\u001b[31mowned\\u001b[0m\": 1}",
1085+
wantDetail: "evidence_detail=top-level must be a JSON array of records, not an object with keys: \\x1b[2J\\x1b[31mowned\\x1b[0m\n",
1086+
},
1087+
{
1088+
name: "unknown record field with control bytes",
1089+
data: "[{\"id\": \"x\", \"a\\u0007b\\u007fc\": 1}]",
1090+
wantDetail: "evidence_detail=record 0 contains unknown field \"a\\x5cab\\x5cx7fc\"\n",
1091+
},
1092+
{
1093+
name: "normal object key is reported unchanged",
1094+
data: `{"records": []}`,
1095+
wantDetail: "evidence_detail=top-level must be a JSON array of records, not an object with keys: records\n",
1096+
},
1097+
} {
1098+
t.Run(tc.name, func(t *testing.T) {
1099+
path := filepath.Join(t.TempDir(), "evidence.json")
1100+
mustOK(os.WriteFile(path, []byte(tc.data), 0o600))
1101+
stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
1102+
code := Run(context.Background(), append(args, "--evidence", path), stdout, stderr, nil)
1103+
if code != exitFailure {
1104+
t.Fatalf("exit code = %d, want %d", code, exitFailure)
1105+
}
1106+
if stdout.Len() != 0 {
1107+
t.Fatalf("stdout = %q, want empty", stdout.String())
1108+
}
1109+
errOut := stderr.String()
1110+
for _, c := range []byte(errOut) {
1111+
if (c < 0x20 && c != '\n') || c == 0x7f {
1112+
t.Fatalf("stderr %q contains raw control byte 0x%02x", errOut, c)
1113+
}
1114+
}
1115+
if !strings.Contains(errOut, tc.wantDetail) {
1116+
t.Fatalf("stderr %q does not contain %q", errOut, tc.wantDetail)
1117+
}
1118+
})
1119+
}
1120+
}
1121+
10751122
func TestQAHelp(t *testing.T) {
10761123
for _, tt := range []struct {
10771124
name string

‎internal/cli/uninstall_test.go‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ func TestRunUninstallRuntimeHarness(t *testing.T) {
4646
t.Fatal(err)
4747
}
4848
code, stdout, stderr := runUninstallForTest(t, roots, nil)
49-
if code != exitConflict || stderr != "" || stdout != uninstallLines("blocked", "conflict", "blocked") {
49+
if code != exitConflict || stderr != "" || stdout != uninstallLines("blocked", "conflict", "blocked", "skills/cortex-alpha/SKILL.md") {
5050
t.Fatalf("uninstall = (%d, %q, %q)", code, stdout, stderr)
5151
}
5252
for i := range roots {
@@ -216,6 +216,11 @@ func writeInstalled(t *testing.T, root skillroot.UninstallRoot, content string)
216216
}
217217

218218
func uninstallLines(statuses ...string) string {
219+
var conflictPaths string
220+
if len(statuses) > 3 {
221+
conflictPaths = statuses[3]
222+
statuses = statuses[:3]
223+
}
219224
var output strings.Builder
220225
for i, runtime := range []string{"pi", "opencode", "claude-code"} {
221226
remove, conflict := 2, 0
@@ -224,7 +229,12 @@ func uninstallLines(statuses ...string) string {
224229
} else if statuses[i] == "conflict" {
225230
remove, conflict = 1, 1
226231
}
227-
_, _ = fmt.Fprintf(&output, "runtime=%s uninstall=%s remove=%d absent=0 conflict=%d\n", runtime, statuses[i], remove, conflict)
232+
line := fmt.Sprintf("runtime=%s uninstall=%s remove=%d absent=0 conflict=%d", runtime, statuses[i], remove, conflict)
233+
if statuses[i] == "conflict" && conflictPaths != "" {
234+
line += " conflict_paths=" + conflictPaths
235+
}
236+
output.WriteString(line)
237+
output.WriteByte('\n')
228238
}
229239
return output.String()
230240
}

‎internal/cli/update.go‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"io"
88
"os"
99
"path/filepath"
10+
"sort"
1011
"strconv"
1112
"strings"
1213
"time"
@@ -130,7 +131,7 @@ func runWithUpdateDependencies(ctx context.Context, args []string, stdout, stder
130131
}
131132
if !apply {
132133
header := fmt.Sprintf("runtime=%s outcome=%s action=%s root=%s mode=plan%s", decision.ID, decision.Outcome, decision.Action, plan.RootPath(), warning)
133-
return writeUpdateOperations(stdout, header, classified, "planned")
134+
return writeUpdateOperations(stdout, header, plan, classified, "planned")
134135
}
135136
return applyUpdate(stdout, stderr, plan, observation, classified, observations, warning)
136137
}
@@ -272,7 +273,7 @@ func runDirectoryUpdate(stdout, stderr io.Writer, targetDir, catalogDir string,
272273
}
273274
header := fmt.Sprintf("runtime=%s outcome=%s action=%s root=%s mode=plan", decision.ID, decision.Outcome, decision.Action, plan.RootPath())
274275
if !apply {
275-
return writeUpdateOperations(stdout, header, classified, "planned")
276+
return writeUpdateOperations(stdout, header, plan, classified, "planned")
276277
}
277278
return applyDirectoryUpdate(stdout, stderr, plan, observation, classified, header)
278279
}
@@ -312,7 +313,7 @@ func applyDirectoryUpdate(stdout, stderr io.Writer, plan installplan.Plan, obser
312313
return exitFailure
313314
}
314315
if !report.Ready() {
315-
return writeUpdateOperations(stdout, header, classified, "conflict")
316+
return writeUpdateOperations(stdout, header, plan, classified, "conflict")
316317
}
317318
backupRoot := filepath.Join(plan.RootPath(), ".cortex")
318319
if err := os.MkdirAll(backupRoot, 0o700); err != nil {
@@ -323,7 +324,7 @@ func applyDirectoryUpdate(stdout, stderr io.Writer, plan installplan.Plan, obser
323324
result, txErr := applyCandidate(plan, observation, backupRoot, backupName)
324325
if txErr != nil {
325326
if errors.Is(txErr, installtxn.ErrConflict) {
326-
return writeUpdateOperations(stdout, header, classified, "conflict")
327+
return writeUpdateOperations(stdout, header, plan, classified, "conflict")
327328
}
328329
writeError(stderr, "update_transaction_failed")
329330
return exitTransaction
@@ -392,12 +393,16 @@ func updateRefusalReason(outcome runtimematrix.Outcome) string {
392393
}
393394

394395
// writeUpdateOperations prints one read-only operation report with its status.
395-
func writeUpdateOperations(stdout io.Writer, header string, classified installobserve.Result, status string) int {
396+
// A conflict status names the conflicting assets by runtime-relative path in
397+
// the same conflict_paths form install and uninstall use (issue #373).
398+
func writeUpdateOperations(stdout io.Writer, header string, plan installplan.Plan, classified installobserve.Result, status string) int {
396399
output := strings.Builder{}
397400
output.WriteString(header + "\n")
401+
var conflicts []string
398402
for _, item := range classified.ArtifactDecisions() {
399403
if item.Action == ownership.Conflict {
400404
status = "conflict"
405+
conflicts = append(conflicts, item.LogicalID)
401406
}
402407
if item.ModeDrift {
403408
fmt.Fprintf(&output, "operation=%s action=%s mode_drift=true observed_mode=%04o canonical_mode=0600\n", item.LogicalID, item.Action, item.ObservedMode.Perm())
@@ -408,7 +413,14 @@ func writeUpdateOperations(stdout io.Writer, header string, classified installob
408413
if classified.StateAction() == ownership.Conflict {
409414
status = "conflict"
410415
}
411-
fmt.Fprintf(&output, "operation=state/install-state action=%s\nstatus=%s\n", classified.StateAction(), status)
416+
fmt.Fprintf(&output, "operation=state/install-state action=%s\nstatus=%s", classified.StateAction(), status)
417+
if status == "conflict" {
418+
sort.Strings(conflicts)
419+
if paths := conflictRelativePaths([]installplan.Plan{plan}, conflicts); paths != "" {
420+
output.WriteString(" conflict_paths=" + paths)
421+
}
422+
}
423+
output.WriteString("\n")
412424
_, _ = io.WriteString(stdout, output.String())
413425
if status == "conflict" {
414426
return exitConflict
@@ -429,7 +441,7 @@ func applyUpdate(stdout, stderr io.Writer, plan installplan.Plan, observation in
429441
return exitFailure
430442
}
431443
if !report.Ready() {
432-
return writeUpdateOperations(stdout, header, classified, "conflict")
444+
return writeUpdateOperations(stdout, header, plan, classified, "conflict")
433445
}
434446
backupRoot := filepath.Join(plan.RootPath(), ".cortex")
435447
if err := os.MkdirAll(backupRoot, 0o700); err != nil {
@@ -440,7 +452,7 @@ func applyUpdate(stdout, stderr io.Writer, plan installplan.Plan, observation in
440452
result, txErr := applyCandidate(plan, observation, backupRoot, backupName)
441453
if txErr != nil {
442454
if errors.Is(txErr, installtxn.ErrConflict) {
443-
return writeUpdateOperations(stdout, header, classified, "conflict")
455+
return writeUpdateOperations(stdout, header, plan, classified, "conflict")
444456
}
445457
writeError(stderr, "update_transaction_failed")
446458
return exitTransaction
@@ -517,7 +529,7 @@ func updateActorGuidance(stdout, stderr io.Writer, canonical installplan.Plan, o
517529
}
518530
proof := preflight.Proof() // Retain the exact immutable candidate and evidence.
519531
if !apply {
520-
return writeUpdateOperations(stdout, header, proof.Result(), "planned")
532+
return writeUpdateOperations(stdout, header, canonical, proof.Result(), "planned")
521533
}
522534
backupName := nextUpdateBackupName()
523535
result, err := installtxn.ApplyActorGuidance(canonical, observation, proof, cwd, filepath.Join(canonical.RootPath(), ".cortex"), backupName)

0 commit comments

Comments
 (0)