diff --git a/bin/contributor-relay.js b/bin/contributor-relay.js index 7ed007aaef..ef1d4641a5 100755 --- a/bin/contributor-relay.js +++ b/bin/contributor-relay.js @@ -4529,7 +4529,7 @@ function runHeadlessTask(task) { failCurrentTask(reason, { outputTail: outTail, permanent: false, - kind: BACKEND === 'pi' ? 'environment' : undefined, + kind: (BACKEND === 'pi' || CLI_USAGE_ERROR_RE.test(diagnostic || '')) ? 'environment' : undefined, }); }); return; @@ -7522,6 +7522,13 @@ function restartBackoffMs(attempt) { // Only headless callers pass it: they have no pane of their own, and any tmux // session that happens to share TMUX_SESSION's name on the host belongs to // someone else, so when it is supplied it is used instead of a pane capture. +// A CLI that rejects the flags the relay launched it with (a version older than +// the one the backend table assumes) is a client-environment failure, not a +// failure of the work: it will repeat on every task until the CLI is upgraded. +// How many trailing CLI output lines failCurrentTask prints to the local log. +const FAILURE_TAIL_LOCAL_LINES = 8; +const CLI_USAGE_ERROR_RE = /\b(unrecognized|unknown|invalid) (flag|option|argument)s?\b/i; + function failCurrentTask(reason, opts) { if (!currentTask) return; const permanent = !!(opts && opts.permanent); @@ -7539,6 +7546,10 @@ function failCurrentTask(reason, opts) { // the reality agree at the instant the hub acts on it. stopAgentForTaskExit({ skipCLI: !!(opts && opts.skipCLI) }); console.error(`Task ${taskId} failed${permanent ? ' permanently' : ''}${kind ? ` [${kind}]` : ''}: ${reason}`); + // The tail goes to the hub in task_failed below; print it here too so the + // contributor sees the CLI's own error, not only the one-line reason. + const shownTail = tmuxLines.map(l => String(l).trim()).filter(Boolean).slice(-FAILURE_TAIL_LOCAL_LINES); + if (shownTail.length > 0) console.error(` CLI output tail:\n${shownTail.map(l => ` ${l}`).join('\n')}`); send({ type: 'task_failed', seq: nextSeq(), @@ -10033,6 +10044,7 @@ if (process.env.HIVE_RELAY_TEST_MODE === '1') { // rule set and is where the interesting cases live; resolveTaskPR is the // wiring, exercised through a stubbed gh. prAttributionEvidence, + CLI_USAGE_ERROR_RE, verifyTaskPR, resolveTaskPR, PR_ATTRIBUTION_CONFIRMED, diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index a65ed6e1d5..74dfd6a200 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -15964,3 +15964,26 @@ test('tls-mismatch: an ordinary error still reconnects with backoff — only the teardown(relay); } }); + +test('headless failure: a CLI that rejects the launch flags is classed as an environment failure', () => { + const relay = loadRelay({ backend: 'opencode' }); + const re = relay.CLI_USAGE_ERROR_RE; + assert.ok(re.test('Unrecognized flag: --auto in command opencode run')); + assert.ok(re.test('error: unknown option --yolo')); + assert.ok(!re.test('TypeError: cannot read properties of undefined')); + assert.ok(!re.test('2 tests failed')); +}); + +test('failCurrentTask prints the CLI output tail to the local log, not only the reason', () => { + const relay = loadRelay({ backend: 'claude' }); + const err = console.error; const lines = []; + console.error = (...a) => { lines.push(a.join(' ')); }; + try { + relay.setCliReady(true); + assignTask(relay, 't-opencode-tail'); + relay.failCurrentTask('headless CLI exited with error: code 1', { outputTail: ['Unrecognized flag: --auto in command opencode run'], permanent: false }); + } finally { + console.error = err; + } + assert.ok(lines.some(l => l.includes('CLI output tail') && l.includes('Unrecognized flag: --auto')), lines.join('\n')); +}); diff --git a/changelog.d/fixed-19060-opencode-auto-flag-failure-reason.md b/changelog.d/fixed-19060-opencode-auto-flag-failure-reason.md new file mode 100644 index 0000000000..b23e8094fa --- /dev/null +++ b/changelog.d/fixed-19060-opencode-auto-flag-failure-reason.md @@ -0,0 +1 @@ +- The contributor relay no longer launches `opencode run` with `--auto` when the installed opencode rejects that flag, classes unrecognized-flag CLI errors as environment failures, prints the CLI output tail in its local log on task failure, and the activity feed now shows a scrubbed reason on failed runs ([#19060](https://github.com/hivecommons/hive/issues/19060)). diff --git a/config/backends.conf b/config/backends.conf index 090179bb03..f536aaa80d 100644 --- a/config/backends.conf +++ b/config/backends.conf @@ -270,6 +270,20 @@ copilot_local_perm_flag_shell() { # on-disk config file is mutated. Explicit deny wins because opencode # evaluates patterns in order with "last matching rule wins", and this key is # assembled with catch-all "allow" first, "*" host-state denials last. +# opencode_auto_flag prints --auto only when the installed opencode accepts it. +# Older opencode releases reject it ("Unrecognized flag: --auto in command +# opencode run", exit 1 within a second of pickup). Without that flag opencode +# still runs unattended: the OPENCODE_PERMISSION allow rules and its default +# allow-all posture cover the tools a task needs. When opencode is absent +# (tests, image build) or its help lists the flag, keep --auto as before. +opencode_auto_flag() { + if command -v opencode >/dev/null 2>&1 \ + && ! opencode run --help 2>&1 | grep -qe '--auto'; then + return 0 + fi + echo "--auto" +} + OPENCODE_HOST_DENY_PATTERNS='sudo *:pkexec *:doas *:su *:rpm-ostree *:bootc *:ostree *:grubby *:bootctl *:efibootmgr *' opencode_local_perm_flag_shell() { @@ -295,10 +309,13 @@ opencode_local_perm_flag_shell() { # opencode reads OPENCODE_PERMISSION as inline JSON (no config file # mutation, no risk of an agent rewriting a persisted settings file). - local -a args=(--auto) + local -a args=() + local auto_flag + auto_flag="$(opencode_auto_flag)" + [[ -n "$auto_flag" ]] && args+=("$auto_flag") local word out out="OPENCODE_PERMISSION=$(printf '%q' "$perm_json") " - for word in "${args[@]}"; do + for word in ${args[@]+"${args[@]}"}; do out+="$(printf '%q' "$word") " done printf '%s\n' "${out% }" @@ -645,7 +662,7 @@ backend_perm_flag() { # --auto is opencode's unattended auto-approve flag ("Automatically accept # all permissions", `opencode run --help`), the equivalent of agy's # --dangerously-skip-permissions. See kubestellar/hive#4970. - opencode) echo "--auto" ;; + opencode) opencode_auto_flag ;; # Kilo --auto approves prompts; it is not an OS sandbox. kilo) echo "--auto" ;; # openhands --always-approve is OpenHands' unattended auto-approve flag diff --git a/src/pkg/dashboard/contribute_landing.go b/src/pkg/dashboard/contribute_landing.go index 907c2c3338..0871b025f8 100644 --- a/src/pkg/dashboard/contribute_landing.go +++ b/src/pkg/dashboard/contribute_landing.go @@ -7070,7 +7070,7 @@ function ccNarrate(e){ case 'left': body=who+' left the hive'; break; case 'picked up': body=who+' grabbed'+pickedRef; break; case 'completed': body=who+' completed'+(e.task?' '+ccTaskRefLink(e.task):''); break; - case 'failed': body=who+' hit a snag on'+(e.task?' '+ccTaskRefLink(e.task):''); break; + case 'failed': body=who+' hit a snag on'+(e.task?' '+ccTaskRefLink(e.task):'')+(e.reason?' ('+esc(e.reason)+')':''); break; case 'promoted': body=who+' was promoted to '+esc(e.task||e.role||'contributor')+''; break; default: body=who+' '+esc(e.action)+ref; } diff --git a/src/pkg/dashboard/contribute_opencode_auto_flag_test.go b/src/pkg/dashboard/contribute_opencode_auto_flag_test.go new file mode 100644 index 0000000000..a5d9aa6dd8 --- /dev/null +++ b/src/pkg/dashboard/contribute_opencode_auto_flag_test.go @@ -0,0 +1,71 @@ +package dashboard + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// fakeOpencodeOnPath installs an `opencode` whose `run --help` prints help. +func fakeOpencodeOnPath(t *testing.T, help string) string { + t.Helper() + dir := t.TempDir() + script := "#!/bin/sh\ncat <<'EOF_HELP'\n" + help + "\nEOF_HELP\n" + if err := os.WriteFile(filepath.Join(dir, "opencode"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + return "PATH=" + dir + string(os.PathListSeparator) + os.Getenv("PATH") +} + +// An opencode that rejects --auto ("Unrecognized flag: --auto in command +// opencode run") must not be launched with it. +func TestOpencodeAutoFlagOmittedWhenUnsupported(t *testing.T) { + env := fakeOpencodeOnPath(t, "opencode run [message..]\n --model model to use") + out, code := runBackendsConfFunc(t, "backend_perm_flag", []string{"opencode"}, env) + if code != 0 || strings.Contains(out, "--auto") { + t.Fatalf("unsupported opencode got --auto: code=%d out=%q", code, out) + } + out, code = runBackendsConfFunc(t, "opencode_local_perm_flag_shell", nil, env) + if code != 0 || strings.Contains(out, "--auto") || !strings.Contains(out, "OPENCODE_PERMISSION=") { + t.Fatalf("local mode must keep the deny-list but drop --auto: code=%d out=%q", code, out) + } +} + +func TestOpencodeAutoFlagKeptWhenSupported(t *testing.T) { + env := fakeOpencodeOnPath(t, "opencode run [message..]\n --auto Automatically accept all permissions") + out, code := runBackendsConfFunc(t, "backend_perm_flag", []string{"opencode"}, env) + if code != 0 || !strings.Contains(out, "--auto") { + t.Fatalf("supported opencode lost --auto: code=%d out=%q", code, out) + } +} + +// A failed run's feed entry carries a scrubbed, bounded reason. +func TestActivityFailureReasonOnFailedEntry(t *testing.T) { + _, s := covK2Hub(t) + long := "headless CLI exited with error: code 1: Unrecognized flag: --auto " + strings.Repeat("x", 400) + s.contributeHub.addActivityWithReason(long, "alice", "failed", "", "opencode", "", "", "issue org/repo#1: t") + s.contributeHub.addActivity("alice", "picked up", "", "opencode", "", "", "issue org/repo#1: t") + got, _, _ := activityRequest(t, s, "") + var failed, picked *ActivityEntry + for i := range got { + switch got[i].Action { + case "failed": + failed = &got[i] + case "picked up": + picked = &got[i] + } + } + if failed == nil || picked == nil { + t.Fatalf("missing entries: %+v", got) + } + if !strings.Contains(failed.Reason, "Unrecognized flag: --auto") { + t.Fatalf("reason lost: %q", failed.Reason) + } + if n := len([]rune(failed.Reason)); n > 121 { + t.Fatalf("reason not bounded: %d runes", n) + } + if picked.Reason != "" { + t.Fatalf("non-failed entry carries a reason: %q", picked.Reason) + } +} diff --git a/src/pkg/dashboard/contribute_ws.go b/src/pkg/dashboard/contribute_ws.go index de6479d84b..ab61fa5863 100644 --- a/src/pkg/dashboard/contribute_ws.go +++ b/src/pkg/dashboard/contribute_ws.go @@ -878,6 +878,16 @@ type ActivityEntry struct { AdvisorModel string `json:"advisor_model,omitempty"` AdvisorEffort string `json:"advisor_effort,omitempty"` Task string `json:"task,omitempty"` + // Reason is the bounded, scrubbed failure reason carried ONLY by "failed" + // entries, so the feed says why a run failed instead of just that it did. + Reason string `json:"reason,omitempty"` +} + +// activityFailureReason scrubs (emails, links, tokens, repo refs) and bounds +// (scrubBattleLogText caps at 120 runes) a relay-reported failure reason for +// the public activity feed. +func activityFailureReason(reason string) string { + return scrubBattleLogText(reason) } // advisorInfo is the optional trailing argument to addActivity: the advisor @@ -1351,6 +1361,12 @@ func taskDescOf(task *WSTaskAssign) string { } func (h *ContributeWSHub) addActivity(username, action, role, cli, model, effort, task string, advisor ...advisorInfo) { + h.addActivityWithReason("", username, action, role, cli, model, effort, task, advisor...) +} + +// addActivityWithReason is addActivity plus the failure reason shown on a +// "failed" feed entry. +func (h *ContributeWSHub) addActivityWithReason(reason, username, action, role, cli, model, effort, task string, advisor ...advisorInfo) { adv := advisorInfo{} if len(advisor) > 0 { adv = advisor[0] @@ -1401,6 +1417,7 @@ func (h *ContributeWSHub) addActivity(username, action, role, cli, model, effort AdvisorModel: adv.Model, AdvisorEffort: adv.Effort, Task: task, + Reason: activityFailureReason(reason), } h.activity = append(h.activity, entry) if len(h.activity) > maxActivityEntries { @@ -4371,7 +4388,7 @@ func (s *wsSession) handleTaskFailed(msg WSMessage) { if s.contributor.cliBackend == "pi" { provider, _, _ = strings.Cut(s.contributor.model, "/") } - h.addActivity(s.contributor.profile.GitHubUsername, "failed", s.contributor.role, s.contributor.cliBackend, s.contributor.model, s.contributor.reasoningEffort, failedDesc, s.contributor.advisor()) + h.addActivityWithReason(msg.Reason, s.contributor.profile.GitHubUsername, "failed", s.contributor.role, s.contributor.cliBackend, s.contributor.model, s.contributor.reasoningEffort, failedDesc, s.contributor.advisor()) h.logger.Info("[contribute-ws] task failed", "username", s.contributor.profile.GitHubUsername, "task", msg.TaskID,