From 2b2a89e4b821b344ba6dafa2d624b26e92bf8a65 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 12:04:31 -0500 Subject: [PATCH 1/6] =?UTF-8?q?=F0=9F=90=9B=20fix(contribute):=20pre-accep?= =?UTF-8?q?t=20Claude's=20bypass=20consent,=20never=20Enter=20on=20"No,=20?= =?UTF-8?q?exit",=20and=20say=20plainly=20when=20the=20queue=20is=20empty?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #19049 Signed-off-by: Andy Anderson --- bin/contributor-agent.sh | 55 +++- bin/contributor-agent.test.sh | 55 ++++ bin/contributor-relay.js | 299 +++++++++++++++++- bin/contributor-relay.test.js | 163 ++++++++++ bin/lib/pane-classifier.js | 41 +++ ...fixed-19049-relay-claude-bypass-consent.md | 1 + src/docs/contributor-relay.md | 8 +- 7 files changed, 610 insertions(+), 12 deletions(-) create mode 100644 changelog.d/fixed-19049-relay-claude-bypass-consent.md diff --git a/bin/contributor-agent.sh b/bin/contributor-agent.sh index 117cd44c90..1633457a5c 100755 --- a/bin/contributor-agent.sh +++ b/bin/contributor-agent.sh @@ -858,6 +858,41 @@ with open(p, 'w') as f: json.dump(d, f, indent=2) SEEDEOF chmod 600 "${HOME}/.claude.json" 2>/dev/null || true + + # Pre-accept Claude Code's "Bypass Permissions mode" consent (#19049). The + # dialog's default selection is "No, exit", so a bare Enter from any dismissal + # loop makes claude exit to the shell. The documented switch is the user-scope + # setting skipDangerousModePermissionPrompt in ${HOME}/.claude/settings.json + # (https://code.claude.com/docs/en/permission-modes). It is written only when + # this launch already runs claude in bypass mode (the container's own + # --dangerously-skip-permissions --permission-mode bypassPermissions): it + # answers the prompt for a posture the relay already asked for and grants + # nothing new. The file is merged, never replaced, so the contributor's own + # staged keys (proxy env, model, permissions) survive; an unreadable file is + # left untouched rather than overwritten. + if [[ "${SEED_CLAUDE_BYPASS_CONSENT:-}" == "1" ]]; then + python3 - <<'SETTINGSEOF' 2>/dev/null || true +import json, os +d = os.path.join(os.path.expanduser('~'), '.claude') +p = os.path.join(d, 'settings.json') +settings = {} +if os.path.exists(p): + try: + with open(p) as f: + settings = json.load(f) + except Exception: + raise SystemExit(0) + if not isinstance(settings, dict): + raise SystemExit(0) +settings['skipDangerousModePermissionPrompt'] = True +os.makedirs(d, exist_ok=True) +tmp = p + '.tmp' +with open(tmp, 'w') as f: + json.dump(settings, f, indent=2) +os.chmod(tmp, 0o600) +os.replace(tmp, p) +SETTINGSEOF + fi } if [[ "${HIVE_CONTRIBUTOR_AGENT_TEST_SEED_CLAUDE_CONFIG:-}" == "1" ]]; then @@ -1197,6 +1232,10 @@ fi # CLI. See seed_claude_config above for why OAuth/subscription claude needs # this just as much as the API-key paths do. if [[ "$AGENT_BACKEND" == "litellm" || "$AGENT_BACKEND" == "claude" ]]; then + # Pre-accept the bypass consent only when this launch really is bypass mode. + case "$PERM_FLAG" in + *bypassPermissions*|*--dangerously-skip-permissions*) export SEED_CLAUDE_BYPASS_CONSENT=1 ;; + esac seed_claude_config fi @@ -1219,7 +1258,21 @@ if [[ "$CONTRIBUTOR_MODE" == "interactive" ]]; then for _attempt in $(seq 1 $AUTO_DISMISS_ATTEMPTS); do sleep "$AUTO_DISMISS_INTERVAL" PANE=$(tmux capture-pane -t "$TMUX_SESSION" -p -S -10 2>/dev/null || true) - if echo "$PANE" | grep -q "trust this folder\|trust the files\|Confirm folder trust\|Enter to confirm"; then + if echo "$PANE" | grep -q "Bypass Permissions mode" && echo "$PANE" | grep -q "No, exit" && echo "$PANE" | grep -q "Yes, I accept"; then + # Claude Code's bypass consent (#19049). It ALSO prints "Enter to + # confirm", and its default selection is "No, exit": the generic + # branch below would send a bare Enter and make claude exit. Move to + # "Yes, I accept" first and press Enter only once the pane shows the + # cursor there. The settings seed normally keeps this from appearing. + if ! echo "$PANE" | grep -Eq "^[[:space:]]*(❯|>|›)[[:space:]]*([0-9]+\.[[:space:]]*)?Yes, I accept"; then + tmux send-keys -t "$TMUX_SESSION" Down 2>/dev/null || true + sleep 1 + PANE=$(tmux capture-pane -t "$TMUX_SESSION" -p -S -10 2>/dev/null || true) + fi + if echo "$PANE" | grep -Eq "^[[:space:]]*(❯|>|›)[[:space:]]*([0-9]+\.[[:space:]]*)?Yes, I accept"; then + tmux send-keys -t "$TMUX_SESSION" Enter 2>/dev/null || true + fi + elif echo "$PANE" | grep -q "trust this folder\|trust the files\|Confirm folder trust\|Enter to confirm"; then tmux send-keys -t "$TMUX_SESSION" Enter 2>/dev/null || true elif echo "$PANE" | grep -q "Do you trust the contents of this directory"; then # Codex's own directory-trust prompt: a numbered menu ("1. Yes, diff --git a/bin/contributor-agent.test.sh b/bin/contributor-agent.test.sh index a52b78d5ed..6126026806 100755 --- a/bin/contributor-agent.test.sh +++ b/bin/contributor-agent.test.sh @@ -1398,6 +1398,61 @@ if [[ "$(seed_key hasCompletedOnboarding)" != "True" ]]; then exit 1 fi +# 4b. hivecommons/hive#19049: Claude Code's "Bypass Permissions mode" consent +# (default selection "No, exit") is pre-accepted through the documented +# user-scope setting skipDangerousModePermissionPrompt in +# ~/.claude/settings.json, but ONLY when this launch really runs claude in +# bypass mode, and merged into the contributor's own staged settings. +agent_src_for_consent="$(dirname "$0")/contributor-agent.sh" +settings_file="${seed_home}/.claude/settings.json" +settings_key() { + python3 -c "import json,sys; print(json.load(open(sys.argv[1])).get(sys.argv[2]))" "$settings_file" "$1" 2>/dev/null +} +rm -rf "${seed_home}/.claude" "${seed_home}/.claude.json" +run_seed claude >/dev/null 2>&1 || true +if [[ -e "$settings_file" ]]; then + echo "#19049: settings.json must not be written when the launch is not bypass mode" >&2 + exit 1 +fi +mkdir -p "${seed_home}/.claude" +printf '%s' '{"model":"claude-opus-4","env":{"HTTPS_PROXY":"http://p.invalid:3128"},"permissions":{"deny":["Bash(sudo:*)"]}}' >"$settings_file" +run_seed claude SEED_CLAUDE_BYPASS_CONSENT=1 >/dev/null 2>&1 || true +if [[ "$(settings_key skipDangerousModePermissionPrompt)" != "True" ]]; then + echo "#19049: skipDangerousModePermissionPrompt must be seeded in ~/.claude/settings.json; got:" >&2 + cat "$settings_file" >&2 + exit 1 +fi +if [[ "$(settings_key model)" != "claude-opus-4" ]] || ! grep -q "HTTPS_PROXY" "$settings_file" || ! grep -q 'Bash(sudo:\*)' "$settings_file"; then + echo "#19049: the seed must MERGE into the contributor's staged settings.json, not replace it; got:" >&2 + cat "$settings_file" >&2 + exit 1 +fi +if [[ "$(settings_key defaultMode)" != "None" ]] || grep -q "bypassPermissions" "$settings_file"; then + echo "#19049: the seed must not widen permissions (no defaultMode / bypassPermissions key)" >&2 + cat "$settings_file" >&2 + exit 1 +fi +# An unreadable settings.json is left alone rather than overwritten. +printf '%s' '{not json' >"$settings_file" +run_seed claude SEED_CLAUDE_BYPASS_CONSENT=1 >/dev/null 2>&1 || true +if [[ "$(cat "$settings_file")" != '{not json' ]]; then + echo "#19049: an unparsable settings.json must be left untouched" >&2 + exit 1 +fi +# The main launch path derives the flag from PERM_FLAG, and the startup dismiss +# loop answers the dialog before its generic "Enter to confirm" branch. +if ! grep -qF 'export SEED_CLAUDE_BYPASS_CONSENT=1' "$agent_src_for_consent" || ! grep -qF '*bypassPermissions*|*--dangerously-skip-permissions*)' "$agent_src_for_consent"; then + echo "#19049: SEED_CLAUDE_BYPASS_CONSENT must be exported only for a bypass-mode PERM_FLAG" >&2 + exit 1 +fi +consent_line="$(grep -n 'grep -q "Bypass Permissions mode"' "$agent_src_for_consent" | cut -d: -f1 | head -1)" +generic_line="$(grep -n 'grep -q "trust this folder' "$agent_src_for_consent" | cut -d: -f1 | head -1)" +if [[ -z "$consent_line" || -z "$generic_line" || "$consent_line" -ge "$generic_line" ]]; then + echo "#19049: the Bypass Permissions branch must come BEFORE the generic Enter-to-confirm branch (consent=${consent_line:-none} generic=${generic_line:-none})" >&2 + exit 1 +fi +rm -rf "${seed_home}/.claude" + # 5. hivecommons/hive#7866: the interactive tmux pane must advertise true colour. # The test hook exits before the tmux session is created, so pin the contract # at the source: COLORTERM is exported (operator value honoured) before diff --git a/bin/contributor-relay.js b/bin/contributor-relay.js index 4894e13484..40b77eddc0 100755 --- a/bin/contributor-relay.js +++ b/bin/contributor-relay.js @@ -66,6 +66,7 @@ const { BLOCKED_REASON_MENU, BLOCKED_REASON_HUMAN_REQUIRED, blockingPromptKey: classifyBlockingPromptKey, + claudeBypassConsent, classifyReadiness, recentPaneLines, classifyBlockedOnHumanReason, @@ -530,6 +531,134 @@ const NETWORK_ERROR_RETRY_DELAY_MS = 5000; // kubestellar/hive#2436), wait before re-asking so we neither hang forever // (the old silent-nil behaviour) nor busy-loop the hub. const TASK_UNAVAILABLE_RETRY_MS = 30000; +// ── What the relay says when the hive has no work for it (hivecommons/hive#19049) ── +// +// The wire reason no_matching_work covers BOTH an empty queue and a queue whose +// every item was dropped by a filter the hive does not name on the wire +// (cooldown, disabled or denied repository, an open or recently merged PR +// already claiming it, own work); the hive logs which filter dropped each issue +// on its own side. Capability, repository-scope, tier (level) and rate (quota) +// refusals do have their own reasons, so those are named. A raw reason code +// every 30s read as a fault to contributors new to ClankeR, so the relay says +// the state once, in a sentence naming the hive, repeats only a short line at a +// slow cadence, announces when work appears, and checks less often while the +// answer stays the same. +const NO_MATCHING_WORK_REASON = 'no_matching_work'; +const NO_WORK_BACKOFF_MAX_MS = 5 * 60 * 1000; +const NO_WORK_BACKOFF_FACTOR = 2; +const NO_WORK_STILL_LOG_INTERVAL_MS = 10 * 60 * 1000; +const MS_PER_SECOND = 1000; +const SECONDS_PER_MINUTE = 60; +// queue_state values written to the relay status file and the tmux status line. +const QUEUE_STATE_EMPTY = 'queue-empty'; +const QUEUE_STATE_FILTERED = 'filtered'; +const QUEUE_STATE_WORKING = 'working'; +const QUEUE_STATE_WAITING_ON_CLI = 'waiting-on-cli'; + +// reason -> the filter it names and the sentence tail. `filter` is null for the +// empty-queue answer. +const NO_WORK_REASONS = { + [NO_MATCHING_WORK_REASON]: { filter: null }, + capability_mismatch: { filter: 'capability', why: 'but none of it fits what this relay declares it can do' }, + no_selected_work: { filter: 'repo', why: 'but none of it is in the repositories you selected' }, + tier_disabled: { filter: 'level', why: 'but your contributor level is switched off on this hive' }, + hourly_limit: { filter: 'quota', why: 'but you have reached this hive\'s hourly task limit for your level' }, + daily_limit: { filter: 'quota', why: 'but you have reached this hive\'s daily task limit for your level' }, + concurrency_limit: { filter: 'quota', why: 'but you are already at this hive\'s concurrent task limit for your level' }, +}; + +// noWorkRetryDelayMs: 30s, 60s, 120s, 240s, then 300s while the answer stays +// the same. With several hives the poll rotates on each answer, so the caller +// keeps the base delay to not slow the others down. +function noWorkRetryDelayMs(streak) { + return Math.min(NO_WORK_BACKOFF_MAX_MS, TASK_UNAVAILABLE_RETRY_MS * Math.pow(NO_WORK_BACKOFF_FACTOR, Math.max(0, streak - 1))); +} + +function formatRetryInterval(ms) { + const seconds = Math.round(ms / MS_PER_SECOND); + if (seconds < SECONDS_PER_MINUTE) return `${seconds} seconds`; + const minutes = Math.round(seconds / SECONDS_PER_MINUTE); + return minutes === 1 ? '1 minute' : `${minutes} minutes`; +} + +// hiveDisplayName is the public host of the hive the relay is connected to. +function hiveDisplayName(hub) { + try { return new URL(hub.sourceURL || hub.url).host || 'this hive'; } catch (_) { return 'this hive'; } +} + +// describeNoWork returns the state and the sentence for a no-work reason, or +// null when the reason is not one this table knows (the caller then prints the +// raw reason as before). `first` selects the full sentence over the short +// "still" line. +function describeNoWork(reason, target, delayMs, first) { + const entry = NO_WORK_REASONS[reason]; + if (!entry) return null; + const every = formatRetryInterval(delayMs); + if (!entry.filter) { + return { + state: QUEUE_STATE_EMPTY, + line: first + ? `The queue for ${target} is empty. There is nothing for you to work on right now. Your ClankeR relay stays connected and checks again on its own, every ${formatRetryInterval(TASK_UNAVAILABLE_RETRY_MS)} at first, then every ${formatRetryInterval(NO_WORK_BACKOFF_MAX_MS)}; work arrives when the owner queues issues for contributors. ` + + 'Issues that are queued but already claimed by an open or recently merged PR, or cooling down after an attempt, are not offered either; the hive does not say which applies.' + : `The queue for ${target} is still empty; checking again in ${every}.`, + }; + } + return { + state: `${QUEUE_STATE_FILTERED}:${entry.filter}`, + line: first + ? `Work is queued on ${target}, ${entry.why} (filter: ${entry.filter}). Your ClankeR relay stays connected and checks again every ${every}.` + : `Still nothing open to you on ${target} (filter: ${entry.filter}); checking again in ${every}.`, + }; +} + +// noWorkLogLine decides what to print for this answer, keeping per-hive state: +// the full sentence on a state change, a short line at a slow cadence after. +// Returns { state, line } where line is null when this answer should be quiet. +function noWorkLogLine(hub, reason, delayMs, now = Date.now()) { + const target = hiveDisplayName(hub); + const probe = describeNoWork(reason, target, delayMs, true); + if (!probe) return null; + const changed = hub.noWorkState !== probe.state; + if (changed) { + hub.noWorkState = probe.state; + hub.noWorkLoggedAt = now; + return probe; + } + if (now - (hub.noWorkLoggedAt || 0) >= NO_WORK_STILL_LOG_INTERVAL_MS) { + hub.noWorkLoggedAt = now; + return describeNoWork(reason, target, delayMs, false); + } + return { state: probe.state, line: null }; +} + +// The queue state shown on the status file and the tmux status line. +let lastQueueState = null; + +function relayQueueState() { + if (currentTask) return QUEUE_STATE_WORKING; + if (CONTRIBUTOR_MODE !== MODE_HEADLESS && !cliReady) return QUEUE_STATE_WAITING_ON_CLI; + return lastQueueState; +} + +const QUEUE_STATE_STATUS_LINE = { + [QUEUE_STATE_EMPTY]: 'ClankeR: queue empty, checking again soon', + [QUEUE_STATE_WORKING]: 'ClankeR: working', + [QUEUE_STATE_WAITING_ON_CLI]: 'ClankeR: waiting on the CLI', +}; + +function setQueueState(state) { + if (lastQueueState === state) return; + lastQueueState = state; + writeRelayStatus(); + if (CONTRIBUTOR_MODE === MODE_HEADLESS) return; + // Best effort: what someone sees the moment they attach to the pane. + const text = state && state.startsWith(QUEUE_STATE_FILTERED) + ? `ClankeR: work queued, filtered for you (${state.split(':')[1]})` + : (QUEUE_STATE_STATUS_LINE[state] || 'ClankeR: connected'); + try { + execSync(`tmux set-option -t ${TMUX_SESSION} status-right ${shellQuote(text)}`, { timeout: TMUX_COMMAND_TIMEOUT_MS, stdio: 'ignore' }); + } catch (_) {} +} // ── Contributor quota guard (hivecommons/hive#6833) ──────────────────────── // @@ -990,9 +1119,8 @@ function warnQuotaGuardUnprovisionedOnce() { 'see src/docs/contributor-relay.md. Work may consume paid credits.'); return; } - console.warn(`Contributor quota guard is ${QUOTA_GUARD_MODE} but no reading source is configured ` + - '(HIVE_CONTRIBUTOR_QUOTA_READING_FILE / HIVE_CONTRIBUTOR_QUOTA_READING_JSON are unset), ' + - 'so it cannot see quota and is not guarding anything this session.'); + console.warn('Contributor quota guard: no usage reading source is set, so quota is not being checked and tasks are not held back. ' + + 'You can ignore this. To turn the guard on, set HIVE_CONTRIBUTOR_QUOTA_READING_FILE or HIVE_CONTRIBUTOR_QUOTA_READING_JSON (see src/docs/contributor-relay.md).'); } let warnedQuotaGuardAwaitingPublisher = false; @@ -1760,6 +1888,11 @@ function relayReadiness(hub) { return 'connected'; } +// A short operator-facing reason the CLI is not ready, or null. Surfaced on the +// relay status file (cli_reason) and appended to the "CLI is not ready yet" log +// lines so a contributor never sees the bare, reasonless wait. +let cliNotReadyReason = null; + function writeRelayStatus() { let temporary; try { @@ -1795,6 +1928,8 @@ function writeRelayStatus() { started_at: currentTaskStartedAt || now, draining, } : null, idle_reason: relayIdleReason(), + cli_reason: cliNotReadyReason, + queue_state: relayQueueState(), }; fs.mkdirSync(path.dirname(RELAY_STATUS_FILE), { recursive: true, mode: 0o700 }); temporary = `${RELAY_STATUS_FILE}.${process.pid}.${randomUUID()}.tmp`; @@ -2356,7 +2491,7 @@ function requestWork(hub, trigger, expectedConnectGeneration = null) { return hub.readyOutstanding; } -function scheduleReadyRetry(hub, trigger) { +function scheduleReadyRetry(hub, trigger, delayMs = TASK_UNAVAILABLE_RETRY_MS) { if (!hub) return; invalidateReadyRetry(hub, `superseded by ${trigger}`); const retryGeneration = hub.readyRetryGeneration; @@ -2379,7 +2514,7 @@ function scheduleReadyRetry(hub, trigger) { if (hubs.length > 1 && hub === hubs[activeHubIndex]) chooseHubForNextTask('unavailable'); const next = hubs[activeHubIndex]; requestWork(next, `${trigger}_retry`, next ? next.connectGeneration : null); - }, TASK_UNAVAILABLE_RETRY_MS); + }, delayMs); } function sendTo(hub, msg) { @@ -2694,7 +2829,7 @@ function maybeAskActiveHubForWork() { if (CONTRIBUTOR_MODE === MODE_HEADLESS || cliReady) { requestWork(hub, 'active_hub_switch'); } else { - console.log('Active hive switched, but CLI is not ready yet — withholding ready until the CLI reaches its prompt'); + console.log(`Active hive switched, but CLI is not ready yet — withholding ready until the CLI reaches its prompt${cliNotReadySuffix()}`); } } @@ -4937,6 +5072,98 @@ function typeLaunchCommand() { return launchCmd; } +// ── Claude Code's Bypass Permissions consent (hivecommons/hive#19049) ────── +// +// The contributor container launches claude with --dangerously-skip-permissions +// / --permission-mode bypassPermissions, so a first start with no +// skipDangerousModePermissionPrompt in the user settings draws a consent +// dialog whose DEFAULT selection is "No, exit". contributor-agent.sh seeds the +// setting so it normally never appears; this is the fallback for when it does. +// +// Down and Enter are separate tmux sends with a pause between them: Claude's +// TUI redraws the selection between keystrokes, and Enter arriving in the same +// burst as Down can land before the cursor has moved. Enter is only sent once +// the pane confirms the cursor is on "Yes, I accept"; a selection that did not +// move is left alone for the next poll, because Enter on "No, exit" is exactly +// the bug (Claude exits to the shell). +const CLAUDE_CONSENT_KEY_DELAY_MS = 800; +// How many times the relay relaunches claude after it exited at the consent +// prompt before it stops and leaves the reason on the status for the operator. +const CLAUDE_CONSENT_EXIT_RELAUNCH_MAX = 3; +const CLAUDE_EXITED_AT_PERMISSIONS_REASON = 'Claude exited at the permissions prompt'; +let claudeConsentShellReadings = 0; +let claudeConsentGaveUp = false; +let claudeConsentRelaunches = 0; +function cliNotReadySuffix() { + return cliNotReadyReason ? ` [${cliNotReadyReason}]` : ''; +} + +function setCLINotReadyReason(reason) { + if (cliNotReadyReason === reason) return; + cliNotReadyReason = reason; + writeRelayStatus(); +} + +// answerClaudeBypassConsent answers the consent dialog if it is on screen. +// Returns true when the dialog was present (whatever came of the answer), so +// the caller skips the rest of this poll. +function answerClaudeBypassConsent() { + if (BACKEND !== 'claude') return false; + // A shell pane can still show the dialog's last frame above the prompt; + // keys sent to the shell would recall and run history. + if (paneIsRunningShell()) return false; + const consent = claudeBypassConsent(capturePaneText()); + if (!consent.present) return false; + try { + if (!consent.acceptSelected) { + console.log('Claude is asking to confirm Bypass Permissions mode ("No, exit" is the default); selecting "Yes, I accept"...'); + execSync(`tmux send-keys -t ${TMUX_SESSION} Down`, { timeout: TMUX_COMMAND_TIMEOUT_MS }); + sleepMs(CLAUDE_CONSENT_KEY_DELAY_MS); + if (!claudeBypassConsent(capturePaneText()).acceptSelected) { + console.log('The selection did not move to "Yes, I accept"; not pressing Enter (it would exit Claude). Retrying on the next poll.'); + return true; + } + } + execSync(`tmux send-keys -t ${TMUX_SESSION} Enter`, { timeout: TMUX_COMMAND_TIMEOUT_MS }); + } catch (_) {} + return true; +} + +// handleClaudeExitedAtConsent notices that claude answered the consent dialog +// and then left the pane (declined, or crashed), and relaunches it a bounded +// number of times. Returns 'relaunched', 'gave-up', or null when it does not +// apply. Typing the launch line directly (not relaunchCLI) mirrors the +// #7863 recreate path: this runs inside the readiness wait that is armed. +function handleClaudeExitedAtConsent() { + if (BACKEND !== 'claude' || claudeConsentGaveUp) return null; + // The pane is a shell that still shows the dialog's last frame: claude left + // at the prompt. It does not matter whether this poll ever saw the dialog + // live (the container's own startup loop may have answered it first). + const atConsentFrame = paneIsRunningShell() && claudeBypassConsent(capturePaneText()).present; + claudeConsentShellReadings = atConsentFrame ? claudeConsentShellReadings + 1 : 0; + if (claudeConsentShellReadings < CLI_GONE_CONFIRMATIONS) return null; + claudeConsentShellReadings = 0; + if (claudeConsentRelaunches >= CLAUDE_CONSENT_EXIT_RELAUNCH_MAX) { + setCLINotReadyReason(`${CLAUDE_EXITED_AT_PERMISSIONS_REASON}; gave up after ${CLAUDE_CONSENT_EXIT_RELAUNCH_MAX} relaunches. Attach and accept the prompt, or add "skipDangerousModePermissionPrompt": true to ~/.claude/settings.json`); + console.error(`${CLAUDE_EXITED_AT_PERMISSIONS_REASON} ${CLAUDE_CONSENT_EXIT_RELAUNCH_MAX + 1} times; not relaunching again.${cliNotReadySuffix()}`); + claudeConsentGaveUp = true; + return 'gave-up'; + } + claudeConsentRelaunches++; + setCLINotReadyReason(`${CLAUDE_EXITED_AT_PERMISSIONS_REASON}; relaunching (${claudeConsentRelaunches}/${CLAUDE_CONSENT_EXIT_RELAUNCH_MAX})`); + console.error(`${CLAUDE_EXITED_AT_PERMISSIONS_REASON}; relaunching (${claudeConsentRelaunches}/${CLAUDE_CONSENT_EXIT_RELAUNCH_MAX}).`); + try { + // Wipe the dialog's last frame first, so the fresh claude's pane is not + // mistaken for the dialog still being on screen. + execSync(`tmux send-keys -t ${TMUX_SESSION} C-l`, { timeout: TMUX_COMMAND_TIMEOUT_MS }); + execSync(`tmux clear-history -t ${TMUX_SESSION}`, { timeout: TMUX_COMMAND_TIMEOUT_MS }); + typeLaunchCommand(); + } catch (e) { + console.error(`Could not relaunch claude: ${e && e.message ? e.message : e}`); + } + return 'relaunched'; +} + function waitForCLI() { let loginMessageShown = false; let needsLoginTicks = 0; @@ -4966,8 +5193,25 @@ function waitForCLI() { setTimeout(check, CLI_READY_POLL_MS); return; } + if (answerClaudeBypassConsent()) { + needsLoginTicks = 0; + setTimeout(check, CLI_READY_POLL_MS); + return; + } + const consentExit = handleClaudeExitedAtConsent(); + if (consentExit === 'relaunched') { + setTimeout(check, CLI_READY_POLL_MS); + return; + } + if (consentExit === 'gave-up') { + reject(new Error(cliNotReadyReason)); + return; + } const state = getCLIState(); if (state === 'ready') { + claudeConsentRelaunches = 0; + claudeConsentGaveUp = false; + setCLINotReadyReason(null); if (loginMessageShown) { console.log('CLI authentication prompt cleared; continuing.'); } @@ -9052,9 +9296,9 @@ function handleMessage(data, hub) { } else if (CONTRIBUTOR_MODE === MODE_HEADLESS || cliReady) { requestWork(hub, 'auth_ok'); } else if (cliReadyFailed) { - console.log('Authenticated, but CLI readiness previously failed — withholding ready until the CLI recovers'); + console.log(`Authenticated, but CLI readiness previously failed — withholding ready until the CLI recovers${cliNotReadySuffix()}`); } else { - console.log('Authenticated, but CLI is not ready yet — withholding ready until the CLI reaches its prompt'); + console.log(`Authenticated, but CLI is not ready yet — withholding ready until the CLI reaches its prompt${cliNotReadySuffix()}`); } } if (!currentTask && !hubHasSelectedWork(hub)) maybeAskActiveHubForWork(); @@ -9106,6 +9350,13 @@ function handleMessage(data, hub) { break; case 'task_assign': + hub.noWorkStreak = 0; + hub.noWorkReason = null; + if (hub.noWorkState) { + console.log(`Work available on ${hiveDisplayName(hub)}, claiming ${msg.repo || 'a task'}${msg.number ? `#${msg.number}` : ''}.`); + } + hub.noWorkState = null; + setQueueState(null); // #7732: an assignment answers the `ready` it was sent for, whatever // this relay does with it below. hub.readyOutstanding = false; @@ -9398,6 +9649,26 @@ function handleMessage(data, hub) { // which could just mean network lag), so rotating on it — rather than // on a guessed timeout — means we never sit idle on a hub with no work // while a different configured hub has some. + { + const sameAnswer = hub.noWorkReason === msg.reason; + hub.noWorkStreak = sameAnswer ? (hub.noWorkStreak || 0) + 1 : 1; + hub.noWorkReason = msg.reason; + const backoff = msg.reason === NO_MATCHING_WORK_REASON && hubs.length === 1; + const delayMs = backoff ? noWorkRetryDelayMs(hub.noWorkStreak) : TASK_UNAVAILABLE_RETRY_MS; + const said = noWorkLogLine(hub, msg.reason, delayMs); + if (said) { + if (said.line) { + console.log(said.line); + if (msg.message) console.log(sanitizeHubText(msg.message)); + } + setQueueState(said.state); + scheduleReadyRetry(hub, 'task_unavailable', delayMs); + break; + } + } + hub.noWorkStreak = 0; + hub.noWorkReason = null; + hub.noWorkState = null; console.log(`No task assigned on ${hub.url} — reason: ${sanitizeHubText(msg.reason) || 'unspecified'}; retrying in ${TASK_UNAVAILABLE_RETRY_MS / 1000}s`); // #14002: some refusals carry a plain-language explanation (for example // app_not_installed names the org and the install link the operator must @@ -9679,6 +9950,18 @@ if (process.env.HIVE_RELAY_TEST_MODE === '1') { paneTail, paneLooksBlockedOnHuman, blockingPromptKey, + claudeBypassConsent, + answerClaudeBypassConsent, + handleClaudeExitedAtConsent, + getCLINotReadyReason: () => cliNotReadyReason, + noWorkRetryDelayMs, + describeNoWork, + noWorkLogLine, + relayQueueState, + formatRetryInterval, + NO_WORK_STILL_LOG_INTERVAL_MS, + resetClaudeConsentState: () => { claudeConsentGaveUp = false; claudeConsentShellReadings = 0; claudeConsentRelaunches = 0; cliNotReadyReason = null; }, + CLAUDE_CONSENT_EXIT_RELAUNCH_MAX, PANE_STATE_WORKING, PANE_STATE_BLOCKED_ON_HUMAN, PANE_STATE_IDLE_COMPLETE, diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index 83fb722672..7e991d743b 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -15922,3 +15922,166 @@ test('tls-mismatch: an ordinary error still reconnects with backoff — only the teardown(relay); } }); + +// --------------------------------------------------------------------------- +// hivecommons/hive#19049 — Claude Code's Bypass Permissions consent, and what +// the relay says when the hive has no work. +// --------------------------------------------------------------------------- + +// The real dialog, as `tmux capture-pane -p` renders it. The default selection +// is "No, exit". +const CLAUDE_CONSENT_PANE_NO_SELECTED = `WARNING: Claude Code running in Bypass Permissions mode + +In Bypass Permissions mode, Claude Code will not ask for your approval before running potentially dangerous commands. + + ❯ 1. No, exit + 2. Yes, I accept + +Enter to confirm · Esc to exit +`; +const CLAUDE_CONSENT_PANE_YES_SELECTED = CLAUDE_CONSENT_PANE_NO_SELECTED + .replace('❯ 1. No, exit', ' 1. No, exit').replace(' 2. Yes, I accept', '❯ 2. Yes, I accept'); + +test('#19049 claudeBypassConsent reads the real dialog text (table)', () => { + const cases = [ + { name: 'default selection is No, exit', pane: CLAUDE_CONSENT_PANE_NO_SELECTED, present: true, acceptSelected: false }, + { name: 'cursor already on Yes, I accept', pane: CLAUDE_CONSENT_PANE_YES_SELECTED, present: true, acceptSelected: true }, + { name: 'a shell prompt', pane: 'dev@host:~$ \n', present: false, acceptSelected: false }, + { name: 'a transcript quoting only the title', pane: 'we discussed Bypass Permissions mode earlier\n> \n', present: false, acceptSelected: false }, + { name: 'the footer of a healthy session', pane: ' ⏵⏵ bypass permissions on (shift+tab to cycle)\n', present: false, acceptSelected: false }, + ]; + for (const c of cases) { + const got = paneClassifier.claudeBypassConsent(c.pane); + assert.strictEqual(got.present, c.present, c.name); + assert.strictEqual(got.acceptSelected, c.acceptSelected, c.name); + } +}); + +test('#19049 the consent dialog classifies as onboarding for claude only, and never answers with a bare Enter', () => { + assert.strictEqual(paneClassifier.classifyReadiness(CLAUDE_CONSENT_PANE_NO_SELECTED, 'claude'), 'onboarding'); + assert.strictEqual(paneClassifier.blockingPromptKey(CLAUDE_CONSENT_PANE_NO_SELECTED, 'claude'), 'Down', + 'with "No, exit" selected the key must move off it, not press Enter'); + assert.strictEqual(paneClassifier.blockingPromptKey(CLAUDE_CONSENT_PANE_YES_SELECTED, 'claude'), null, + 'with "Yes, I accept" selected a bare Enter is the right answer'); + assert.strictEqual(paneClassifier.blockingPromptKey(CLAUDE_CONSENT_PANE_NO_SELECTED, 'copilot'), null); +}); + +function sendsAfter(relay, before) { + return relay.__tmuxSends().slice(before).map(c => c.replace(/^.*send-keys -t \S+ /, '')); +} + +test('#19049 answerClaudeBypassConsent never presses Enter while "No, exit" is still selected', () => { + // The pane never reflects the Down (a TUI that ignored it): Enter would exit Claude. + const relay = loadRelay({ backend: 'claude', procAlive: true, paneText: CLAUDE_CONSENT_PANE_NO_SELECTED }); + const log = console.log; console.log = () => {}; + try { + const before = relay.__tmuxSends().length; + assert.strictEqual(relay.answerClaudeBypassConsent(), true); + const sent = sendsAfter(relay, before); + assert.ok(sent.some(c => /^Down$/.test(c)), `Down was not sent: ${JSON.stringify(sent)}`); + assert.ok(!sent.some(c => /^Enter$/.test(c)), `Enter sent while "No, exit" selected: ${JSON.stringify(sent)}`); + } finally { console.log = log; teardown(relay); } +}); + +test('#19049 answerClaudeBypassConsent presses Enter once the pane shows Yes selected', () => { + let captures = 0; + const relay = loadRelay({ backend: 'claude', procAlive: true, + // 1st capture (consent present, No selected) -> Down -> 2nd capture shows Yes selected. + paneText: () => (captures++ === 0 ? CLAUDE_CONSENT_PANE_NO_SELECTED : CLAUDE_CONSENT_PANE_YES_SELECTED) }); + const log = console.log; console.log = () => {}; + try { + const before = relay.__tmuxSends().length; + assert.strictEqual(relay.answerClaudeBypassConsent(), true); + const sent = sendsAfter(relay, before); + const down = sent.findIndex(c => /^Down$/.test(c)); + const enter = sent.findIndex(c => /^Enter$/.test(c)); + assert.ok(down >= 0 && enter > down, `want Down then Enter, got ${JSON.stringify(sent)}`); + } finally { console.log = log; teardown(relay); } +}); + +test('#19049 a pane that is a shell showing the dialog frame gets no keys', () => { + const relay = loadRelay({ backend: 'claude', procAlive: false, paneText: CLAUDE_CONSENT_PANE_NO_SELECTED }); + try { + const before = relay.__tmuxSends().length; + assert.strictEqual(relay.answerClaudeBypassConsent(), false); + assert.deepStrictEqual(sendsAfter(relay, before), []); + } finally { teardown(relay); } +}); + +test('#19049 claude exited at the consent prompt: bounded relaunch, then a visible reason', () => { + const relay = loadRelay({ backend: 'claude', procAlive: false, paneText: CLAUDE_CONSENT_PANE_NO_SELECTED }); + const log = console.log; const error = console.error; console.log = () => {}; console.error = () => {}; + try { + relay.resetClaudeConsentState(); + const max = relay.CLAUDE_CONSENT_EXIT_RELAUNCH_MAX; + // Two shell readings are needed before the CLI is declared gone. + assert.strictEqual(relay.handleClaudeExitedAtConsent(), null); + for (let i = 1; i <= max; i++) { + assert.strictEqual(relay.handleClaudeExitedAtConsent(), 'relaunched', `relaunch ${i}`); + assert.match(relay.getCLINotReadyReason(), /Claude exited at the permissions prompt; relaunching/); + assert.strictEqual(relay.handleClaudeExitedAtConsent(), null); + } + assert.strictEqual(relay.handleClaudeExitedAtConsent(), 'gave-up'); + assert.match(relay.getCLINotReadyReason(), /Claude exited at the permissions prompt; gave up after \d+ relaunches/); + assert.match(relay.getCLINotReadyReason(), /skipDangerousModePermissionPrompt/); + // Once given up it stays quiet instead of looping. + assert.strictEqual(relay.handleClaudeExitedAtConsent(), null); + assert.strictEqual(relay.handleClaudeExitedAtConsent(), null); + const status = JSON.parse(fs.readFileSync(relay.RELAY_STATUS_FILE, 'utf8')); + assert.match(status.cli_reason, /Claude exited at the permissions prompt/); + assert.strictEqual(status.queue_state, 'waiting-on-cli'); + } finally { console.log = log; console.error = error; teardown(relay); } +}); + +test('#19049 no-work wording selection (table)', () => { + const relay = loadRelay({ backend: 'claude' }); + try { + const target = 'bluefin.example.org'; + const cases = [ + { reason: 'no_matching_work', first: true, state: 'queue-empty', + has: [/The queue for bluefin\.example\.org is empty\./, /nothing for you to work on right now/, /ClankeR relay/, /30 seconds at first, then every 5 minutes/, /owner queues issues for contributors/], not: [/no_matching_work/] }, + { reason: 'no_matching_work', first: false, state: 'queue-empty', + has: [/still empty; checking again in 5 minutes/], not: [/no_matching_work/] }, + { reason: 'capability_mismatch', first: true, state: 'filtered:capability', has: [/Work is queued on bluefin\.example\.org/, /\(filter: capability\)/], not: [/is empty/] }, + { reason: 'no_selected_work', first: true, state: 'filtered:repo', has: [/\(filter: repo\)/], not: [/is empty/] }, + { reason: 'tier_disabled', first: true, state: 'filtered:level', has: [/\(filter: level\)/], not: [/is empty/] }, + { reason: 'daily_limit', first: true, state: 'filtered:quota', has: [/daily task limit/, /\(filter: quota\)/], not: [/is empty/] }, + ]; + for (const c of cases) { + const got = relay.describeNoWork(c.reason, target, 300000, c.first); + assert.strictEqual(got.state, c.state, `${c.reason} state`); + for (const re of c.has) assert.match(got.line, re, `${c.reason}/${c.first}`); + for (const re of c.not) assert.doesNotMatch(got.line, re, `${c.reason}/${c.first}`); + } + assert.strictEqual(relay.describeNoWork('something_new', target, 30000, true), null, + 'an unknown reason keeps the raw-reason line'); + assert.deepStrictEqual([1, 2, 3, 4, 5, 9].map(relay.noWorkRetryDelayMs), [30000, 60000, 120000, 240000, 300000, 300000]); + } finally { teardown(relay); } +}); + +test('#19049 no-work is said once on a state change, then slowly; work arriving is announced', () => { + const relay = loadRelay({ backend: 'claude', procAlive: true }); + const lines = []; const log = console.log; console.log = (...a) => lines.push(a.join(' ')); + const origSetTimeout = global.setTimeout; global.setTimeout = () => 0; + try { + relay.setCliReady(true); + const hub = relay.getHubs()[0]; + const empty = () => relay.handleMessage(JSON.stringify({ type: 'task_unavailable', reason: 'no_matching_work' }), hub); + empty(); + assert.strictEqual(lines.filter(l => /is empty\./.test(l)).length, 1); + lines.length = 0; + empty(); empty(); empty(); + assert.deepStrictEqual(lines.filter(l => /queue for/.test(l)), [], 'repeats inside the slow window are quiet'); + assert.strictEqual(JSON.parse(fs.readFileSync(relay.RELAY_STATUS_FILE, 'utf8')).queue_state, 'queue-empty'); + // After the slow interval a short "still empty" line is allowed. + const later = Date.now() + relay.NO_WORK_STILL_LOG_INTERVAL_MS + 1; + assert.match(relay.noWorkLogLine(hub, 'no_matching_work', 300000, later).line, /still empty/); + // A different answer is a state change and says so in full. + relay.handleMessage(JSON.stringify({ type: 'task_unavailable', reason: 'capability_mismatch' }), hub); + assert.ok(lines.some(l => /\(filter: capability\)/.test(l))); + lines.length = 0; + relay.handleMessage(JSON.stringify({ type: 'task_assign', task_id: 't1', task_gen: 1, kind: 'issue', repo: 'foo/bar', number: 7, title: 'x' }), hub); + assert.ok(lines.some(l => /Work available on .*claiming foo\/bar#7/.test(l)), lines.join('\n')); + assert.notStrictEqual(relay.relayQueueState(), 'queue-empty', 'work arriving clears the empty state'); + } finally { global.setTimeout = origSetTimeout; console.log = log; teardown(relay); } +}); diff --git a/bin/lib/pane-classifier.js b/bin/lib/pane-classifier.js index b39c27356a..0b691d1f72 100644 --- a/bin/lib/pane-classifier.js +++ b/bin/lib/pane-classifier.js @@ -262,6 +262,36 @@ function paneQuotaExhaustion(text) { return null; } +// Claude Code's "Bypass Permissions mode" consent dialog, shown once per user +// config when a session starts in bypassPermissions mode and +// skipDangerousModePermissionPrompt is not set in the user settings: +// +// WARNING: Claude Code running in Bypass Permissions mode +// ... +// ❯ 1. No, exit +// 2. Yes, I accept +// Enter to confirm · Esc to exit +// +// The DEFAULT selection is "No, exit", so a bare Enter (what the generic +// "Enter to confirm" handling sends) declines and Claude exits to the shell. +// Accepting takes Down, then Enter. All three strings are required so a +// transcript that merely quotes one of them cannot match. +const CLAUDE_BYPASS_CONSENT_TAIL_LINES = 25; +const CLAUDE_BYPASS_CONSENT_TITLE_RE = /Bypass Permissions mode/; +const CLAUDE_BYPASS_CONSENT_ACCEPT_RE = /Yes, I accept/; +const CLAUDE_BYPASS_CONSENT_DECLINE_RE = /No, exit/; +const CLAUDE_BYPASS_CONSENT_ACCEPT_SELECTED_RE = /^\s*[❯>›]\s*(?:\d+\.\s*)?Yes, I accept/m; + +// claudeBypassConsent reports whether the consent dialog is on screen and +// whether its selection cursor is already on "Yes, I accept". +function claudeBypassConsent(text) { + const recent = paneTail(text, CLAUDE_BYPASS_CONSENT_TAIL_LINES); + const present = CLAUDE_BYPASS_CONSENT_TITLE_RE.test(recent) && + CLAUDE_BYPASS_CONSENT_ACCEPT_RE.test(recent) && + CLAUDE_BYPASS_CONSENT_DECLINE_RE.test(recent); + return { present, acceptSelected: present && CLAUDE_BYPASS_CONSENT_ACCEPT_SELECTED_RE.test(recent) }; +} + function blockingPromptKey(text, backend) { // codex: "Do you trust the contents of this directory?" → 1. Yes, continue if (/Do you trust the contents of this directory/.test(text)) return '1'; @@ -272,6 +302,15 @@ function blockingPromptKey(text, backend) { // persists, so this prompt stops coming back on every restart the way a // plain "Skip" would. if (/Update available/.test(text) && /Skip until next version/.test(text)) return '3'; + // claude: the Bypass Permissions consent. Never a bare Enter (the default + // selection is "No, exit"): move to "Yes, I accept" first. The caller must + // send the keys one at a time and confirm the selection moved (see + // answerClaudeBypassConsent in bin/contributor-relay.js); when the cursor is + // already on "Yes, I accept" a bare Enter is correct and null is returned. + if (backend === 'claude') { + const consent = claudeBypassConsent(text); + if (consent.present) return consent.acceptSelected ? null : 'Down'; + } const recent = paneTail(text, 15); // agy: "Terms of Service & Data Use" ends on a [Previous] [Done] button row // with focus on the CHECKBOX above it, where Enter toggles consent instead of @@ -318,6 +357,7 @@ function classifyReadiness(text, backend) { // flow that nothing in a container can finish. A human has to attach. if (/Select login method/.test(text)) return 'needs-login'; if (/Choose the text style|trust this folder/.test(text)) return 'onboarding'; + if (claudeBypassConsent(text).present) return 'onboarding'; // The first alternation below is startup-only: a welcome banner, the // account line printed just after login, the first-run tip. That made // claude readiness a one-shot property of the SPLASH SCREEN — and @@ -1109,6 +1149,7 @@ module.exports = { BLOCKED_REASON_MENU, BLOCKED_REASON_HUMAN_REQUIRED, blockingPromptKey, + claudeBypassConsent, classifyReadiness, recentPaneLines, classifyBlockedOnHumanReason, diff --git a/changelog.d/fixed-19049-relay-claude-bypass-consent.md b/changelog.d/fixed-19049-relay-claude-bypass-consent.md new file mode 100644 index 0000000000..0615ae89a9 --- /dev/null +++ b/changelog.d/fixed-19049-relay-claude-bypass-consent.md @@ -0,0 +1 @@ +- `just contribute-hive claude` no longer stalls at Claude Code's "Bypass Permissions mode" consent, and the relay now says plainly when the hive has no work for it. The contributor container seeded `~/.claude.json` but never the `skipDangerousModePermissionPrompt` user setting, and its startup auto-dismiss pressed a bare Enter on any screen that says "Enter to confirm", which on this dialog (default selection "No, exit") makes Claude exit to the shell, leaving the relay at "CLI is not ready yet" forever. The entrypoint now merges `skipDangerousModePermissionPrompt: true` into the staged `~/.claude/settings.json` (only for a bypass-mode launch, other keys kept), the dismiss loop and the relay select "Yes, I accept" with Down, a pause and a cursor check before Enter and never press Enter on "No, exit", and a Claude that exits at that prompt is relaunched up to three times with `Claude exited at the permissions prompt` in the log and as `cli_reason` in the relay status. Separately, an empty hive queue is reported as one sentence naming the hive instead of a raw `no_matching_work` line every 30s, with a slower retry (30s up to 5 minutes), a `Work available ... claiming` line when work appears, filters that the hive does name (capability, repo, level, quota) worded as such, a `queue_state` field on the relay status, and a one-line quota-guard notice that says it can be ignored ([#19049](https://github.com/hivecommons/hive/issues/19049)). diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index e821480cf9..d62df1cf11 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -187,7 +187,7 @@ With an explicitly configured shared pool, `just contribute-quota status` inspec ## What happens on a task 1. A successful connection logs `Connected to …`, followed by `Authenticated with … as … (tier: …)`. Authentication is not yet a task assignment. -2. The hive assigns an issue that fits your trust tier and its filters. If it says `No task assigned … reason: no_matching_work`, the relay is connected and waiting; it retries. Other reasons may require the hive operator, not another registration. +2. The hive assigns an issue that fits your trust tier and its filters. When there is nothing for you, the relay prints one plain sentence instead of a raw reason code, for example `The queue for is empty. There is nothing for you to work on right now.` This is normal, not a fault: the relay stays connected and work arrives when the hive owner queues issues for contributors. It says so once, repeats only a short `still empty` line every ten minutes, backs off from checking every 30 seconds to every 5 minutes while the queue stays empty (with more than one hive the 30 second poll rotation is kept), and prints `Work available on , claiming #` when work appears. The hive's `no_matching_work` reason covers both an empty queue and a queue whose every issue was dropped by a filter the hive does not name on the wire (cooldown, a disabled or denied repository, an open or recently merged PR already claiming the issue, your own work). Refusals that do name their filter are worded differently: `capability_mismatch` (`filter: capability`), `no_selected_work` (`filter: repo`), `tier_disabled` (`filter: level`) and `hourly_limit` / `daily_limit` / `concurrency_limit` (`filter: quota`). The state is also written to the relay status file as `queue_state` (`queue-empty`, `filtered:`, `working`, `waiting-on-cli`) and shown in the tmux status line when you attach. Other reasons may require the hive operator, not another registration. 3. The relay prepares the checkout, injects a short-lived GitHub token, and drives your coding CLI. In interactive mode, use the **attach command printed by your launch** to watch the tmux session. Container mode prints the Docker/Podman form; native mode prints `tmux attach`. Headless backends have no interactive pane. 4. Progress is reported every 2 minutes; completion/PR metadata is reported when the CLI finishes. Check the linked PR and its checks, not just a local “success” line. PRs retain the task's base branch, required hold gates, and DCO sign-off (`git commit -s`). 5. To stop your foreground relay, press **Ctrl-C** in the terminal running it; detaching from tmux is not stopping the relay. The relay cleans up its connection. If work is in flight, it is not thereby completed: inspect the PR/worktree and the hive's recorded task state before deleting local work or starting another relay. @@ -389,7 +389,9 @@ at all. It copies only `${HOME}/.claude/.credentials.json` and history, paste cache, per-project memory and your private `CLAUDE.md` — never leaves the host, because the agent in that container runs third-party repositories' test suites for real -([#7836](https://github.com/hivecommons/hive/issues/7836)). The recipe prints a +([#7836](https://github.com/hivecommons/hive/issues/7836)). + +**Claude's Bypass Permissions consent ([#19049](https://github.com/hivecommons/hive/issues/19049)).** The container launches `claude` with `--dangerously-skip-permissions --permission-mode bypassPermissions`, inside the sandboxed container only. Claude Code asks you to confirm that mode once per user config, and the dialog's default selection is `No, exit`, so a bare Enter makes Claude exit to the shell. Claude Code's documented switch for this is the user-scope setting `skipDangerousModePermissionPrompt` in `~/.claude/settings.json` ([permission modes](https://code.claude.com/docs/en/permission-modes)). The container entrypoint now merges `"skipDangerousModePermissionPrompt": true` into the staged `settings.json` (your other keys are kept; an unparsable file is left alone) and only when the launch is already in bypass mode, so it answers a prompt for a posture the relay already requested and grants nothing new. Your host `~/.claude/settings.json` is never modified: only the per-run staged copy is. If the dialog still appears, the relay selects `Yes, I accept` (Down, a short pause, a check that the cursor moved, then Enter) and never presses Enter while `No, exit` is selected. If Claude exits to the shell at that prompt, the relay relaunches it up to three times and reports `Claude exited at the permissions prompt` in its log and as `cli_reason` in the relay status instead of waiting silently. Workaround on an older relay: add `"skipDangerousModePermissionPrompt": true` to `~/.claude/settings.json` on the host before `just contribute-hive claude` (it is staged into the container), or run `claude --dangerously-skip-permissions` once on the host and accept the dialog. The recipe prints a `Staged:` line naming exactly what it copied. Important environment variables: @@ -777,7 +779,7 @@ The active profile is written first in each list, which is the hub the relay sol The relay writes three non-secret control files beside the profiles: `contributor-relay.pid`, so `hivectl hives use` can signal the native process or recorded docker/podman container; `hubs-seen.json`, so `hivectl hives list` can show when each hub last authenticated or heartbeated successfully without probing every hub; and `relay-status.json`, an owner-only (`0600`) atomic snapshot of adopted scope, subscription readiness, and current work. `HIVE_RELAY_STATUS_FILE` overrides its path. -The status file's `pid`, `started_at`, and per-start `session` match the PID record. `adopted_scope_version` and `adopted_at` change only after the relay successfully reads `contributor.env` on reload. Each `subscriptions` entry identifies its Hive by canonical HTTP origin and records `readiness` (`connected`, `scope-pending`, `scope-unsupported`, `quota-held`, `disabled`, or `discovery-unavailable`), `acknowledged_scope_version`, and `observed_at`. `current_task` has the Hive, canonical repository, issue and task identifiers, start time, and a `draining` flag when its target leaves the adopted scope; the existing lease can finish, but that target receives no new lease. `idle_reason` distinguishes an all-disabled set from a set with no selected repositories. +The status file's `pid`, `started_at`, and per-start `session` match the PID record. `adopted_scope_version` and `adopted_at` change only after the relay successfully reads `contributor.env` on reload. Each `subscriptions` entry identifies its Hive by canonical HTTP origin and records `readiness` (`connected`, `scope-pending`, `scope-unsupported`, `quota-held`, `disabled`, or `discovery-unavailable`), `acknowledged_scope_version`, and `observed_at`. `current_task` has the Hive, canonical repository, issue and task identifiers, start time, and a `draining` flag when its target leaves the adopted scope; the existing lease can finish, but that target receives no new lease. `idle_reason` distinguishes an all-disabled set from a set with no selected repositories. `cli_reason` is a short string while the CLI is not ready for a known cause (for example `Claude exited at the permissions prompt; relaunching (1/3)`) and `null` otherwise, and `queue_state` is the contributor-facing queue state described under *What happens on a task*; both are additive and consumers that do not know them ignore them. `hivectl` treats a missing, malformed, dead-process, or mismatched-session status as unknown. A saved generation remains pending until its subscription acknowledges at least that version. The snapshot contains no prompt, task payload, token, credential, or log text. From 2f228a4928661b12a88ad5a05fcf24f6cf0a2a00 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 12:10:11 -0500 Subject: [PATCH 2/6] =?UTF-8?q?=F0=9F=90=9B=20fix(contribute):=20reset=20p?= =?UTF-8?q?ane=20capture=20counter=20in=20consent=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #19049 Signed-off-by: Andy Anderson --- bin/contributor-relay.test.js | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index 7e991d743b..a49e811a28 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -15990,6 +15990,7 @@ test('#19049 answerClaudeBypassConsent presses Enter once the pane shows Yes sel paneText: () => (captures++ === 0 ? CLAUDE_CONSENT_PANE_NO_SELECTED : CLAUDE_CONSENT_PANE_YES_SELECTED) }); const log = console.log; console.log = () => {}; try { + captures = 0; // the relay's own startup poll already consumed captures const before = relay.__tmuxSends().length; assert.strictEqual(relay.answerClaudeBypassConsent(), true); const sent = sendsAfter(relay, before); From 0777761f3534db60b52cb37e8295d27b6323ad75 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 12:22:27 -0500 Subject: [PATCH 3/6] =?UTF-8?q?=F0=9F=90=9B=20fix(contribute):=20multi-hiv?= =?UTF-8?q?e=20aware=20empty-queue=20messaging,=20retry=20bookkeeping=20be?= =?UTF-8?q?hind=20HIVE=5FRELAY=5FDEBUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #19049 Signed-off-by: Andy Anderson --- bin/contributor-relay.js | 114 ++++++++++++++---- bin/contributor-relay.test.js | 65 ++++++++++ ...fixed-19049-relay-claude-bypass-consent.md | 2 +- src/docs/contributor-relay.md | 2 +- 4 files changed, 159 insertions(+), 24 deletions(-) diff --git a/bin/contributor-relay.js b/bin/contributor-relay.js index 40b77eddc0..f216232597 100755 --- a/bin/contributor-relay.js +++ b/bin/contributor-relay.js @@ -581,9 +581,21 @@ function formatRetryInterval(ms) { return minutes === 1 ? '1 minute' : `${minutes} minutes`; } -// hiveDisplayName is the public host of the hive the relay is connected to. -function hiveDisplayName(hub) { - try { return new URL(hub.sourceURL || hub.url).host || 'this hive'; } catch (_) { return 'this hive'; } +// hiveShortName is the short, public name of a hive for contributor-facing +// lines: the first label of its hostname, minus the hosted- prefix and the +// 4-character instance suffix a hosted hive carries +// (hosted--ab12.example.org becomes ). Anything else keeps its +// full host, so a self-hosted hive is still recognisable. +const HOSTED_HIVE_PREFIX_RE = /^hosted-/; +const HOSTED_HIVE_SUFFIX_RE = /-[a-z0-9]{4}$/; +function hiveShortName(hub) { + let host = ''; + try { host = new URL(hub.sourceURL || hub.url).host; } catch (_) { return 'this hive'; } + if (!host) return 'this hive'; + const label = host.split('.')[0]; + if (!HOSTED_HIVE_PREFIX_RE.test(label)) return host; + const short = label.replace(HOSTED_HIVE_PREFIX_RE, '').replace(HOSTED_HIVE_SUFFIX_RE, ''); + return short || host; } // describeNoWork returns the state and the sentence for a no-work reason, or @@ -615,7 +627,7 @@ function describeNoWork(reason, target, delayMs, first) { // the full sentence on a state change, a short line at a slow cadence after. // Returns { state, line } where line is null when this answer should be quiet. function noWorkLogLine(hub, reason, delayMs, now = Date.now()) { - const target = hiveDisplayName(hub); + const target = hiveShortName(hub); const probe = describeNoWork(reason, target, delayMs, true); if (!probe) return null; const changed = hub.noWorkState !== probe.state; @@ -640,26 +652,67 @@ function relayQueueState() { return lastQueueState; } -const QUEUE_STATE_STATUS_LINE = { - [QUEUE_STATE_EMPTY]: 'ClankeR: queue empty, checking again soon', - [QUEUE_STATE_WORKING]: 'ClankeR: working', - [QUEUE_STATE_WAITING_ON_CLI]: 'ClankeR: waiting on the CLI', -}; +// hubQueueState is one hive's own state: working (this hive leased the current +// task), the state its last no-work answer left, or null when it has not said. +function hubQueueState(hub) { + if (currentTask && currentTask._hub === hub) return QUEUE_STATE_WORKING; + return hub.noWorkState || null; +} -function setQueueState(state) { - if (lastQueueState === state) return; - lastQueueState = state; - writeRelayStatus(); +// queueRowLabel is the compact word for one hive in the status row. +function queueRowLabel(hub) { + const state = hubQueueState(hub); + if (state === QUEUE_STATE_WORKING) { + return currentTask && Number.isSafeInteger(currentTask.number) ? `working #${currentTask.number}` : 'working'; + } + if (state === QUEUE_STATE_EMPTY) return 'empty'; + if (state && state.startsWith(QUEUE_STATE_FILTERED)) return `filtered (${state.split(':')[1]})`; + return 'asking'; +} + +// queueStatusRow is one compact row, one entry per hive, for the tmux status +// line: "kubestellar-hive: empty | projectbluefin: working #123". +function queueStatusRow() { + if (CONTRIBUTOR_MODE !== MODE_HEADLESS && !cliReady) return 'ClankeR: waiting on the CLI'; + const active = hubs.filter(hub => !hub.disabled); + if (active.length === 0) return 'ClankeR: no hives enabled'; + return active.map(hub => `${hiveShortName(hub)}: ${queueRowLabel(hub)}`).join(' | '); +} + +let lastQueueStatusRow = null; + +// publishQueueRow puts the row on the tmux status line when it changed. Best +// effort: it is what someone sees the moment they attach to the pane. Called +// from writeRelayStatus, which already runs on every task and queue transition. +function publishQueueRow() { if (CONTRIBUTOR_MODE === MODE_HEADLESS) return; - // Best effort: what someone sees the moment they attach to the pane. - const text = state && state.startsWith(QUEUE_STATE_FILTERED) - ? `ClankeR: work queued, filtered for you (${state.split(':')[1]})` - : (QUEUE_STATE_STATUS_LINE[state] || 'ClankeR: connected'); + const row = queueStatusRow(); + if (row === lastQueueStatusRow) return; + lastQueueStatusRow = row; try { - execSync(`tmux set-option -t ${TMUX_SESSION} status-right ${shellQuote(text)}`, { timeout: TMUX_COMMAND_TIMEOUT_MS, stdio: 'ignore' }); + execSync(`tmux set-option -t ${TMUX_SESSION} status-right-length 200`, { timeout: TMUX_COMMAND_TIMEOUT_MS, stdio: 'ignore' }); + execSync(`tmux set-option -t ${TMUX_SESSION} status-right ${shellQuote(row)}`, { timeout: TMUX_COMMAND_TIMEOUT_MS, stdio: 'ignore' }); } catch (_) {} } +function setQueueState(state) { + lastQueueState = state; + writeRelayStatus(); +} + +// allQueuesEmptySummary is the one line for "every enabled hive said empty". +// It is announced once per such episode, and only with more than one hive (a +// single hive already got its own sentence). +let allEmptyAnnounced = false; +function maybeAnnounceAllEmpty() { + const active = hubs.filter(hub => !hub.disabled); + const allEmpty = active.length > 1 && active.every(hub => hub.noWorkState === QUEUE_STATE_EMPTY); + if (!allEmpty) { allEmptyAnnounced = false; return; } + if (allEmptyAnnounced) return; + allEmptyAnnounced = true; + console.log(`All ${active.length} queues are empty, nothing to do right now.`); +} + // ── Contributor quota guard (hivecommons/hive#6833) ──────────────────────── // // This is the local, pre-acceptance safety guard for subscription headroom. It @@ -1918,6 +1971,7 @@ function writeRelayStatus() { hive: canonicalHiveID(hub.sourceURL), readiness, acknowledged_scope_version: hub.scopeAckVersion, observed_at: hub.statusObservedAt, + queue_state: hubQueueState(hub), }; }), current_task: currentTask && !currentTask.synthetic ? { @@ -1939,6 +1993,7 @@ function writeRelayStatus() { if (temporary) { try { fs.unlinkSync(temporary); } catch (_) {} } console.error(`WARNING: could not write relay status file ${RELAY_STATUS_FILE}: ${e.message}`); } + publishQueueRow(); } let progressInterval = null; @@ -2439,12 +2494,20 @@ function clampFrame(msg, maxFrameBytes) { } +// Internal ready/retry bookkeeping is noise to a contributor (one relay can hold +// several hive connections, and each prints this per retry). It is kept behind +// HIVE_RELAY_DEBUG=1 for whoever is debugging the relay itself. +const RELAY_DEBUG = process.env.HIVE_RELAY_DEBUG === '1'; +function debugLog(message) { + if (RELAY_DEBUG) console.log(message); +} + function readyConnLabel(hub) { return hub ? (hub.connectionId || hub.connectGeneration || 0) : 0; } function logSkippedWorkRequest(hub, trigger, reason) { - console.debug(`Skipping work request (trigger=${trigger}, conn=${readyConnLabel(hub)}) — ${reason}`); + debugLog(`Skipping work request (trigger=${trigger}, conn=${readyConnLabel(hub)}) — ${reason}`); } function invalidateReadyRetry(hub, reason) { @@ -2454,7 +2517,7 @@ function invalidateReadyRetry(hub, reason) { hub.readyRetryTimer = null; } hub.readyRetryGeneration++; - if (reason) console.debug(`Cancelled ready retry for ${hub.url} (${reason}, conn=${readyConnLabel(hub)})`); + if (reason) debugLog(`Cancelled ready retry for ${hub.url} (${reason}, conn=${readyConnLabel(hub)})`); } function invalidateAllReadyRetries(reason) { @@ -2486,7 +2549,9 @@ function requestWork(hub, trigger, expectedConnectGeneration = null) { } invalidateReadyRetry(hub, `superseded by ${trigger}`); const request = ++hub.readyRequestSeq; - console.log(`Requesting work (trigger=${trigger}, conn=${conn}, request=${request})`); + // A retry is the same question asked again; only the first ask per trigger is + // worth a line, and it names the hive so several connections can be told apart. + (/_retry$/.test(trigger) ? debugLog : console.log)(`Requesting work from ${hiveShortName(hub)} (trigger=${trigger}, conn=${conn}, request=${request})`); sendTo(hub, { type: 'ready', seq: nextSeq() }); return hub.readyOutstanding; } @@ -9353,9 +9418,10 @@ function handleMessage(data, hub) { hub.noWorkStreak = 0; hub.noWorkReason = null; if (hub.noWorkState) { - console.log(`Work available on ${hiveDisplayName(hub)}, claiming ${msg.repo || 'a task'}${msg.number ? `#${msg.number}` : ''}.`); + console.log(`Work available on ${hiveShortName(hub)}, claiming ${msg.repo || 'a task'}${msg.number ? `#${msg.number}` : ''}.`); } hub.noWorkState = null; + allEmptyAnnounced = false; setQueueState(null); // #7732: an assignment answers the `ready` it was sent for, whatever // this relay does with it below. @@ -9662,6 +9728,7 @@ function handleMessage(data, hub) { if (msg.message) console.log(sanitizeHubText(msg.message)); } setQueueState(said.state); + maybeAnnounceAllEmpty(); scheduleReadyRetry(hub, 'task_unavailable', delayMs); break; } @@ -9956,6 +10023,9 @@ if (process.env.HIVE_RELAY_TEST_MODE === '1') { getCLINotReadyReason: () => cliNotReadyReason, noWorkRetryDelayMs, describeNoWork, + hiveShortName, + queueStatusRow, + maybeAnnounceAllEmpty, noWorkLogLine, relayQueueState, formatRetryInterval, diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index a49e811a28..ed57e3b6b8 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -16086,3 +16086,68 @@ test('#19049 no-work is said once on a state change, then slowly; work arriving assert.notStrictEqual(relay.relayQueueState(), 'queue-empty', 'work arriving clears the empty state'); } finally { global.setTimeout = origSetTimeout; console.log = log; teardown(relay); } }); + +// One relay, several hives: every line names its hive, the status row has one +// entry per hive, and "everything is empty" is said once. +const MULTI_HIVE_ENV = { + HIVE_HUB: 'wss://hosted-alpha-hive-ab12.hive.example.org/api/contribute/ws,wss://hosted-beta-console-cd34.hive.example.org/api/contribute/ws,wss://hosted-gamma-knuckle-ef56.hive.example.org/api/contribute/ws', + HIVE_REGISTRATION_TOKEN: 'tok-a,tok-b,tok-c', +}; + +test('#19049 hiveShortName derives a short public name from the hostname (table)', () => { + const relay = loadRelay({ backend: 'claude' }); + try { + const cases = [ + ['wss://hosted-alpha-hive-ab12.hive.example.org/api/contribute/ws', 'alpha-hive'], + ['wss://hosted-gamma-knuckle-ef56.hive.example.org/api/contribute/ws', 'gamma-knuckle'], + ['wss://hive.example.org/api/contribute/ws', 'hive.example.org'], + ['wss://hosted-x.hive.example.org/api/contribute/ws', 'hosted-x.hive.example.org'], + ['not a url', 'this hive'], + ]; + for (const [url, want] of cases) assert.strictEqual(relay.hiveShortName({ sourceURL: url }), want, url); + } finally { teardown(relay); } +}); + +test('#19049 multi-hive: one status row, per-hive states, one all-empty summary', () => { + const relay = loadRelay({ backend: 'claude', procAlive: true, env: MULTI_HIVE_ENV }); + const lines = []; const log = console.log; console.log = (...a) => lines.push(a.join(' ')); + try { + relay.setCliReady(true); + const hubs = relay.getHubs(); + assert.strictEqual(hubs.length, 3); + // Each hive gets its own full sentence, naming itself, exactly once. + for (const hub of hubs) { + const said = relay.noWorkLogLine(hub, 'no_matching_work', 30000); + assert.match(said.line, new RegExp(`The queue for ${relay.hiveShortName(hub)} is empty\\.`)); + assert.ok(!/ab12|cd34|ef56/.test(said.line), 'the instance suffix is not part of the short name'); + assert.strictEqual(relay.noWorkLogLine(hub, 'no_matching_work', 30000).line, null, 'a repeat is quiet'); + } + assert.strictEqual(relay.queueStatusRow(), 'alpha-hive: empty | beta-console: empty | gamma-knuckle: empty'); + relay.maybeAnnounceAllEmpty(); + relay.maybeAnnounceAllEmpty(); + assert.deepStrictEqual(lines.filter(l => /^All \d+ queues are empty/.test(l)), ['All 3 queues are empty, nothing to do right now.']); + // One hive filtered, one empty, one not heard from: the row says each. + hubs[1].noWorkState = 'filtered:capability'; + hubs[2].noWorkState = null; + assert.strictEqual(relay.queueStatusRow(), 'alpha-hive: empty | beta-console: filtered (capability) | gamma-knuckle: asking'); + lines.length = 0; + relay.maybeAnnounceAllEmpty(); + assert.deepStrictEqual(lines, [], 'no summary unless every queue is empty'); + const status = () => JSON.parse(fs.readFileSync(relay.RELAY_STATUS_FILE, 'utf8')); + relay.writeRelayStatus(); + assert.deepStrictEqual(status().subscriptions.map(x => x.queue_state), ['queue-empty', 'filtered:capability', null]); + } finally { console.log = log; teardown(relay); } +}); + +test('#19049 retry bookkeeping is silent by default and visible with HIVE_RELAY_DEBUG', () => { + const relay = loadRelay({ backend: 'claude', procAlive: true, env: MULTI_HIVE_ENV }); + const lines = []; const log = console.log; const dbg = console.debug; + console.log = (...a) => lines.push(a.join(' ')); console.debug = (...a) => lines.push(a.join(' ')); + const origSetTimeout = global.setTimeout; global.setTimeout = () => 0; + try { + const hubs = relay.getHubs(); + relay.scheduleReadyRetry(hubs[0], 'task_unavailable'); + relay.scheduleReadyRetry(hubs[0], 'task_unavailable_retry'); + assert.deepStrictEqual(lines.filter(l => /Cancelled ready retry|Skipping work request/.test(l)), []); + } finally { global.setTimeout = origSetTimeout; console.log = log; console.debug = dbg; teardown(relay); } +}); diff --git a/changelog.d/fixed-19049-relay-claude-bypass-consent.md b/changelog.d/fixed-19049-relay-claude-bypass-consent.md index 0615ae89a9..77f100378c 100644 --- a/changelog.d/fixed-19049-relay-claude-bypass-consent.md +++ b/changelog.d/fixed-19049-relay-claude-bypass-consent.md @@ -1 +1 @@ -- `just contribute-hive claude` no longer stalls at Claude Code's "Bypass Permissions mode" consent, and the relay now says plainly when the hive has no work for it. The contributor container seeded `~/.claude.json` but never the `skipDangerousModePermissionPrompt` user setting, and its startup auto-dismiss pressed a bare Enter on any screen that says "Enter to confirm", which on this dialog (default selection "No, exit") makes Claude exit to the shell, leaving the relay at "CLI is not ready yet" forever. The entrypoint now merges `skipDangerousModePermissionPrompt: true` into the staged `~/.claude/settings.json` (only for a bypass-mode launch, other keys kept), the dismiss loop and the relay select "Yes, I accept" with Down, a pause and a cursor check before Enter and never press Enter on "No, exit", and a Claude that exits at that prompt is relaunched up to three times with `Claude exited at the permissions prompt` in the log and as `cli_reason` in the relay status. Separately, an empty hive queue is reported as one sentence naming the hive instead of a raw `no_matching_work` line every 30s, with a slower retry (30s up to 5 minutes), a `Work available ... claiming` line when work appears, filters that the hive does name (capability, repo, level, quota) worded as such, a `queue_state` field on the relay status, and a one-line quota-guard notice that says it can be ignored ([#19049](https://github.com/hivecommons/hive/issues/19049)). +- `just contribute-hive claude` no longer stalls at Claude Code's "Bypass Permissions mode" consent, and the relay now says plainly when the hive has no work for it. The contributor container seeded `~/.claude.json` but never the `skipDangerousModePermissionPrompt` user setting, and its startup auto-dismiss pressed a bare Enter on any screen that says "Enter to confirm", which on this dialog (default selection "No, exit") makes Claude exit to the shell, leaving the relay at "CLI is not ready yet" forever. The entrypoint now merges `skipDangerousModePermissionPrompt: true` into the staged `~/.claude/settings.json` (only for a bypass-mode launch, other keys kept), the dismiss loop and the relay select "Yes, I accept" with Down, a pause and a cursor check before Enter and never press Enter on "No, exit", and a Claude that exits at that prompt is relaunched up to three times with `Claude exited at the permissions prompt` in the log and as `cli_reason` in the relay status. Separately, an empty hive queue is reported as one sentence naming the hive instead of a raw `no_matching_work` line every 30s, with a slower retry (30s up to 5 minutes), a `Work available ... claiming` line when work appears, filters that the hive does name (capability, repo, level, quota) worded as such, a `queue_state` field on the relay status (and per hive), one compact status row and one "all queues are empty" line when a relay holds several hives, internal retry bookkeeping lines moved behind `HIVE_RELAY_DEBUG=1`, and a one-line quota-guard notice that says it can be ignored ([#19049](https://github.com/hivecommons/hive/issues/19049)). diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index d62df1cf11..7f5e6f37e6 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -187,7 +187,7 @@ With an explicitly configured shared pool, `just contribute-quota status` inspec ## What happens on a task 1. A successful connection logs `Connected to …`, followed by `Authenticated with … as … (tier: …)`. Authentication is not yet a task assignment. -2. The hive assigns an issue that fits your trust tier and its filters. When there is nothing for you, the relay prints one plain sentence instead of a raw reason code, for example `The queue for is empty. There is nothing for you to work on right now.` This is normal, not a fault: the relay stays connected and work arrives when the hive owner queues issues for contributors. It says so once, repeats only a short `still empty` line every ten minutes, backs off from checking every 30 seconds to every 5 minutes while the queue stays empty (with more than one hive the 30 second poll rotation is kept), and prints `Work available on , claiming #` when work appears. The hive's `no_matching_work` reason covers both an empty queue and a queue whose every issue was dropped by a filter the hive does not name on the wire (cooldown, a disabled or denied repository, an open or recently merged PR already claiming the issue, your own work). Refusals that do name their filter are worded differently: `capability_mismatch` (`filter: capability`), `no_selected_work` (`filter: repo`), `tier_disabled` (`filter: level`) and `hourly_limit` / `daily_limit` / `concurrency_limit` (`filter: quota`). The state is also written to the relay status file as `queue_state` (`queue-empty`, `filtered:`, `working`, `waiting-on-cli`) and shown in the tmux status line when you attach. Other reasons may require the hive operator, not another registration. +2. The hive assigns an issue that fits your trust tier and its filters. When there is nothing for you, the relay prints one plain sentence instead of a raw reason code, for example `The queue for is empty. There is nothing for you to work on right now.` This is normal, not a fault: the relay stays connected and work arrives when the hive owner queues issues for contributors. It says so once, repeats only a short `still empty` line every ten minutes, backs off from checking every 30 seconds to every 5 minutes while the queue stays empty (with more than one hive the 30 second poll rotation is kept), and prints `Work available on , claiming #` when work appears. The hive's `no_matching_work` reason covers both an empty queue and a queue whose every issue was dropped by a filter the hive does not name on the wire (cooldown, a disabled or denied repository, an open or recently merged PR already claiming the issue, your own work). Refusals that do name their filter are worded differently: `capability_mismatch` (`filter: capability`), `no_selected_work` (`filter: repo`), `tier_disabled` (`filter: level`) and `hourly_limit` / `daily_limit` / `concurrency_limit` (`filter: quota`). With several hives on one relay every line names its hive by a short public name (`hosted--ab12.` shows as ``), the sentence is printed once per hive on a state change, and when every enabled hive is empty one line says `All 3 queues are empty, nothing to do right now.` The state is also written to the relay status file as `queue_state` (`queue-empty`, `filtered:`, `working`, `waiting-on-cli`), per hive as `queue_state` on each `subscriptions` entry, and shown when you attach as one compact tmux status row, for example `alpha: empty | beta: empty | gamma: working #123`. The per-retry `Requesting work ...` and `Cancelled ready retry ...` bookkeeping lines are internal and only printed with `HIVE_RELAY_DEBUG=1`. Other reasons may require the hive operator, not another registration. 3. The relay prepares the checkout, injects a short-lived GitHub token, and drives your coding CLI. In interactive mode, use the **attach command printed by your launch** to watch the tmux session. Container mode prints the Docker/Podman form; native mode prints `tmux attach`. Headless backends have no interactive pane. 4. Progress is reported every 2 minutes; completion/PR metadata is reported when the CLI finishes. Check the linked PR and its checks, not just a local “success” line. PRs retain the task's base branch, required hold gates, and DCO sign-off (`git commit -s`). 5. To stop your foreground relay, press **Ctrl-C** in the terminal running it; detaching from tmux is not stopping the relay. The relay cleans up its connection. If work is in flight, it is not thereby completed: inspect the PR/worktree and the hive's recorded task state before deleting local work or starting another relay. From 8d3da746d82d4d145d9364c912fb454a094a3510 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 12:30:23 -0500 Subject: [PATCH 4/6] =?UTF-8?q?=F0=9F=90=9B=20fix(contribute):=20no=5Fmatc?= =?UTF-8?q?hing=5Fwork=20never=20claims=20an=20empty=20queue;=20use=20the?= =?UTF-8?q?=20hive's=20actionable=5Fitems=20count?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #19049 Signed-off-by: Andy Anderson --- bin/contributor-relay.js | 97 ++++++++++++++++--- bin/contributor-relay.test.js | 76 +++++++++++---- ...fixed-19049-relay-claude-bypass-consent.md | 2 +- src/docs/contributor-relay.md | 2 +- 4 files changed, 143 insertions(+), 34 deletions(-) diff --git a/bin/contributor-relay.js b/bin/contributor-relay.js index f216232597..c9d8d73ca7 100755 --- a/bin/contributor-relay.js +++ b/bin/contributor-relay.js @@ -544,6 +544,7 @@ const TASK_UNAVAILABLE_RETRY_MS = 30000; // slow cadence, announces when work appears, and checks less often while the // answer stays the same. const NO_MATCHING_WORK_REASON = 'no_matching_work'; +const QUEUE_EMPTY_REASON = 'queue_empty'; const NO_WORK_BACKOFF_MAX_MS = 5 * 60 * 1000; const NO_WORK_BACKOFF_FACTOR = 2; const NO_WORK_STILL_LOG_INTERVAL_MS = 10 * 60 * 1000; @@ -551,6 +552,7 @@ const MS_PER_SECOND = 1000; const SECONDS_PER_MINUTE = 60; // queue_state values written to the relay status file and the tmux status line. const QUEUE_STATE_EMPTY = 'queue-empty'; +const QUEUE_STATE_NO_MATCH = 'no-match'; const QUEUE_STATE_FILTERED = 'filtered'; const QUEUE_STATE_WORKING = 'working'; const QUEUE_STATE_WAITING_ON_CLI = 'waiting-on-cli'; @@ -558,7 +560,12 @@ const QUEUE_STATE_WAITING_ON_CLI = 'waiting-on-cli'; // reason -> the filter it names and the sentence tail. `filter` is null for the // empty-queue answer. const NO_WORK_REASONS = { - [NO_MATCHING_WORK_REASON]: { filter: null }, + // no_matching_work is NOT "the queue is empty": the hive sends it both for an + // empty queue and for a queue whose every item was dropped for this contributor + // (#19052 asks the server to tell them apart). Only an explicit queue_empty + // may say the queue is empty. + [NO_MATCHING_WORK_REASON]: { filter: null, noMatch: true }, + [QUEUE_EMPTY_REASON]: { filter: null }, capability_mismatch: { filter: 'capability', why: 'but none of it fits what this relay declares it can do' }, no_selected_work: { filter: 'repo', why: 'but none of it is in the repositories you selected' }, tier_disabled: { filter: 'level', why: 'but your contributor level is switched off on this hive' }, @@ -606,23 +613,65 @@ function describeNoWork(reason, target, delayMs, first) { const entry = NO_WORK_REASONS[reason]; if (!entry) return null; const every = formatRetryInterval(delayMs); + if (entry.noMatch) { + return { + state: QUEUE_STATE_NO_MATCH, + line: first + ? `No work was assigned to you on ${target} right now. The hive may have nothing queued, or nothing that matches your setup (CLI, trust tier, repo, quota). Your ClankeR relay stays connected and checks again in ${every}.` + : `Still no work assigned to you on ${target}; checking again in ${every}.`, + }; + } if (!entry.filter) { return { state: QUEUE_STATE_EMPTY, line: first - ? `The queue for ${target} is empty. There is nothing for you to work on right now. Your ClankeR relay stays connected and checks again on its own, every ${formatRetryInterval(TASK_UNAVAILABLE_RETRY_MS)} at first, then every ${formatRetryInterval(NO_WORK_BACKOFF_MAX_MS)}; work arrives when the owner queues issues for contributors. ` + - 'Issues that are queued but already claimed by an open or recently merged PR, or cooling down after an attempt, are not offered either; the hive does not say which applies.' + ? `The queue for ${target} is empty. There is nothing for you to work on right now. Your ClankeR relay stays connected and checks again in ${every}; work arrives when the owner queues issues for contributors.` : `The queue for ${target} is still empty; checking again in ${every}.`, }; } return { state: `${QUEUE_STATE_FILTERED}:${entry.filter}`, line: first - ? `Work is queued on ${target}, ${entry.why} (filter: ${entry.filter}). Your ClankeR relay stays connected and checks again every ${every}.` + ? `Work is queued on ${target}, ${entry.why} (filter: ${entry.filter}). Your ClankeR relay stays connected and checks again in ${every}.` : `Still nothing open to you on ${target} (filter: ${entry.filter}); checking again in ${every}.`, }; } +// The hive publishes how much work it holds on GET /api/contribute/status +// (actionable_items, the offerable total). With that count the relay can say +// what no_matching_work cannot: whether anything was queued at all. Counts older +// than this are not trusted. +const HUB_COUNTS_MAX_AGE_MS = 10 * 60 * 1000; + +function hubActionableItems(hub, now = Date.now()) { + if (!hub || !Number.isFinite(hub.lastActionableItems)) return null; + if (!hub.lastStatusAt || now - hub.lastStatusAt > HUB_COUNTS_MAX_AGE_MS) return null; + return hub.lastActionableItems; +} + +// describeHubCounts is the follow-up line once the count is known, or null when +// it is not (or the hive has not answered no-match, where it adds nothing). +function describeHubCounts(hub, now = Date.now()) { + if (hub.noWorkState !== QUEUE_STATE_NO_MATCH) return null; + const items = hubActionableItems(hub, now); + if (items === null) return null; + const target = hiveShortName(hub); + if (items === 0) return `${target} reports 0 actionable items, so nothing is queued there right now.`; + return `${target} has ${items} actionable item${items === 1 ? '' : 's'}, but none was assigned to you: they may be claimed by a PR, cooling down, or not match your CLI, trust tier, repo or quota. If this lasts, ask the hive owner.`; +} + +// announceHubCounts prints the count line once per no-match episode, when the +// status fetch lands. +function announceHubCounts(hub) { + const line = describeHubCounts(hub); + if (line && !hub.noWorkCountsSaid) { + hub.noWorkCountsSaid = true; + console.log(line); + } + writeRelayStatus(); + maybeAnnounceAllEmpty(); +} + // noWorkLogLine decides what to print for this answer, keeping per-hive state: // the full sentence on a state change, a short line at a slow cadence after. // Returns { state, line } where line is null when this answer should be quiet. @@ -634,6 +683,8 @@ function noWorkLogLine(hub, reason, delayMs, now = Date.now()) { if (changed) { hub.noWorkState = probe.state; hub.noWorkLoggedAt = now; + hub.noWorkCountsSaid = false; + if (probe.state === QUEUE_STATE_NO_MATCH) refreshHubStatus(hub, { force: true, onDone: announceHubCounts }); return probe; } if (now - (hub.noWorkLoggedAt || 0) >= NO_WORK_STILL_LOG_INTERVAL_MS) { @@ -659,13 +710,18 @@ function hubQueueState(hub) { return hub.noWorkState || null; } +function hubReportsZeroItems(hub) { + return hub.noWorkState === QUEUE_STATE_NO_MATCH && hubActionableItems(hub) === 0; +} + // queueRowLabel is the compact word for one hive in the status row. function queueRowLabel(hub) { const state = hubQueueState(hub); if (state === QUEUE_STATE_WORKING) { return currentTask && Number.isSafeInteger(currentTask.number) ? `working #${currentTask.number}` : 'working'; } - if (state === QUEUE_STATE_EMPTY) return 'empty'; + if (state === QUEUE_STATE_EMPTY || hubReportsZeroItems(hub)) return 'empty'; + if (state === QUEUE_STATE_NO_MATCH) return 'idle: no match'; if (state && state.startsWith(QUEUE_STATE_FILTERED)) return `filtered (${state.split(':')[1]})`; return 'asking'; } @@ -703,14 +759,19 @@ function setQueueState(state) { // allQueuesEmptySummary is the one line for "every enabled hive said empty". // It is announced once per such episode, and only with more than one hive (a // single hive already got its own sentence). -let allEmptyAnnounced = false; +let allEmptyAnnounced = null; function maybeAnnounceAllEmpty() { const active = hubs.filter(hub => !hub.disabled); - const allEmpty = active.length > 1 && active.every(hub => hub.noWorkState === QUEUE_STATE_EMPTY); - if (!allEmpty) { allEmptyAnnounced = false; return; } - if (allEmptyAnnounced) return; - allEmptyAnnounced = true; - console.log(`All ${active.length} queues are empty, nothing to do right now.`); + if (active.length < 2) { allEmptyAnnounced = null; return; } + const empty = hub => hub.noWorkState === QUEUE_STATE_EMPTY || hubReportsZeroItems(hub); + const idle = hub => empty(hub) || hub.noWorkState === QUEUE_STATE_NO_MATCH; + let summary = null; + if (active.every(empty)) summary = `All ${active.length} queues are empty, nothing to do right now.`; + else if (active.every(idle)) summary = `No work was assigned to you on any of the ${active.length} hives right now; checking again soon.`; + if (!summary) { allEmptyAnnounced = null; return; } + if (allEmptyAnnounced === summary) return; + allEmptyAnnounced = summary; + console.log(summary); } // ── Contributor quota guard (hivecommons/hive#6833) ──────────────────────── @@ -1972,6 +2033,7 @@ function writeRelayStatus() { acknowledged_scope_version: hub.scopeAckVersion, observed_at: hub.statusObservedAt, queue_state: hubQueueState(hub), + actionable_items: hubActionableItems(hub), }; }), current_task: currentTask && !currentTask.synthetic ? { @@ -2784,8 +2846,11 @@ function contributeStatusURL(hub) { } } -function refreshHubStatus(hub) { - if (!hub || commonsStrategy !== COMMONS_STRATEGY_NEEDIEST) return; +function refreshHubStatus(hub, opts = {}) { + if (!hub) return; + if (!opts.force && commonsStrategy !== COMMONS_STRATEGY_NEEDIEST) return; + // Tests must never open a socket. + if (process.env.HIVE_RELAY_TEST_MODE === '1') return; const url = contributeStatusURL(hub); if (!url) return; const client = url.protocol === 'http:' ? http : https; @@ -2809,6 +2874,7 @@ function refreshHubStatus(hub) { hub.lastStatusAt = Date.now(); } } catch (_) {} + if (opts.onDone) opts.onDone(hub); }); }); req.on('timeout', () => req.destroy()); @@ -9421,7 +9487,8 @@ function handleMessage(data, hub) { console.log(`Work available on ${hiveShortName(hub)}, claiming ${msg.repo || 'a task'}${msg.number ? `#${msg.number}` : ''}.`); } hub.noWorkState = null; - allEmptyAnnounced = false; + allEmptyAnnounced = null; + hub.noWorkCountsSaid = false; setQueueState(null); // #7732: an assignment answers the `ready` it was sent for, whatever // this relay does with it below. @@ -10026,6 +10093,8 @@ if (process.env.HIVE_RELAY_TEST_MODE === '1') { hiveShortName, queueStatusRow, maybeAnnounceAllEmpty, + describeHubCounts, + announceHubCounts, noWorkLogLine, relayQueueState, formatRetryInterval, diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index ed57e3b6b8..1aec14c2bd 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -16037,13 +16037,20 @@ test('#19049 claude exited at the consent prompt: bounded relaunch, then a visib test('#19049 no-work wording selection (table)', () => { const relay = loadRelay({ backend: 'claude' }); try { - const target = 'bluefin.example.org'; + const target = 'bluefin-knuckle'; const cases = [ - { reason: 'no_matching_work', first: true, state: 'queue-empty', - has: [/The queue for bluefin\.example\.org is empty\./, /nothing for you to work on right now/, /ClankeR relay/, /30 seconds at first, then every 5 minutes/, /owner queues issues for contributors/], not: [/no_matching_work/] }, - { reason: 'no_matching_work', first: false, state: 'queue-empty', - has: [/still empty; checking again in 5 minutes/], not: [/no_matching_work/] }, - { reason: 'capability_mismatch', first: true, state: 'filtered:capability', has: [/Work is queued on bluefin\.example\.org/, /\(filter: capability\)/], not: [/is empty/] }, + // no_matching_work must NEVER claim the queue is empty: the hive sends it + // for an empty queue and for work that was filtered out for this contributor. + { reason: 'no_matching_work', first: true, state: 'no-match', + has: [/No work was assigned to you on bluefin-knuckle right now\./, /may have nothing queued, or nothing that matches your setup \(CLI, trust tier, repo, quota\)/, /ClankeR relay/, /checking again in 5 minutes|checks again in 5 minutes/], + not: [/is empty/, /nothing for you to work on/, /no_matching_work/] }, + { reason: 'no_matching_work', first: false, state: 'no-match', + has: [/Still no work assigned to you on bluefin-knuckle; checking again in 5 minutes/], not: [/is empty/, /no_matching_work/] }, + // Only an explicit queue_empty says the queue is empty. + { reason: 'queue_empty', first: true, state: 'queue-empty', + has: [/The queue for bluefin-knuckle is empty\./, /nothing for you to work on right now/, /owner queues issues for contributors/], not: [/queue_empty/] }, + { reason: 'queue_empty', first: false, state: 'queue-empty', has: [/still empty; checking again in 5 minutes/], not: [] }, + { reason: 'capability_mismatch', first: true, state: 'filtered:capability', has: [/Work is queued on bluefin-knuckle/, /\(filter: capability\)/], not: [/is empty/] }, { reason: 'no_selected_work', first: true, state: 'filtered:repo', has: [/\(filter: repo\)/], not: [/is empty/] }, { reason: 'tier_disabled', first: true, state: 'filtered:level', has: [/\(filter: level\)/], not: [/is empty/] }, { reason: 'daily_limit', first: true, state: 'filtered:quota', has: [/daily task limit/, /\(filter: quota\)/], not: [/is empty/] }, @@ -16060,6 +16067,23 @@ test('#19049 no-work wording selection (table)', () => { } finally { teardown(relay); } }); +test('#19049 hive counts decide what the relay can say about a no-match (table)', () => { + const relay = loadRelay({ backend: 'claude' }); + try { + const now = Date.now(); + const mk = (items, ageMs, state = 'no-match') => ({ sourceURL: 'wss://hosted-alpha-hive-ab12.hive.example.org/api/contribute/ws', + noWorkState: state, lastActionableItems: items, lastStatusAt: items === undefined ? 0 : now - ageMs }); + const six = relay.describeHubCounts(mk(6, 1000)); + assert.match(six, /alpha-hive has 6 actionable items, but none was assigned to you/); + assert.doesNotMatch(six, /empty/); + assert.match(relay.describeHubCounts(mk(1, 1000)), /has 1 actionable item, but/); + assert.match(relay.describeHubCounts(mk(0, 1000)), /alpha-hive reports 0 actionable items, so nothing is queued there right now\./); + assert.strictEqual(relay.describeHubCounts(mk(undefined, 0)), null, 'unknown counts say nothing'); + assert.strictEqual(relay.describeHubCounts(mk(6, 11 * 60 * 1000)), null, 'stale counts say nothing'); + assert.strictEqual(relay.describeHubCounts(mk(6, 1000, 'queue-empty')), null, 'only a no-match needs the count'); + } finally { teardown(relay); } +}); + test('#19049 no-work is said once on a state change, then slowly; work arriving is announced', () => { const relay = loadRelay({ backend: 'claude', procAlive: true }); const lines = []; const log = console.log; console.log = (...a) => lines.push(a.join(' ')); @@ -16069,14 +16093,15 @@ test('#19049 no-work is said once on a state change, then slowly; work arriving const hub = relay.getHubs()[0]; const empty = () => relay.handleMessage(JSON.stringify({ type: 'task_unavailable', reason: 'no_matching_work' }), hub); empty(); - assert.strictEqual(lines.filter(l => /is empty\./.test(l)).length, 1); + assert.strictEqual(lines.filter(l => /No work was assigned to you on .* right now\./.test(l)).length, 1); + assert.strictEqual(lines.filter(l => /is empty/.test(l)).length, 0, 'no_matching_work never claims an empty queue'); lines.length = 0; empty(); empty(); empty(); - assert.deepStrictEqual(lines.filter(l => /queue for/.test(l)), [], 'repeats inside the slow window are quiet'); - assert.strictEqual(JSON.parse(fs.readFileSync(relay.RELAY_STATUS_FILE, 'utf8')).queue_state, 'queue-empty'); + assert.deepStrictEqual(lines.filter(l => /No work was assigned|Still no work/.test(l)), [], 'repeats inside the slow window are quiet'); + assert.strictEqual(JSON.parse(fs.readFileSync(relay.RELAY_STATUS_FILE, 'utf8')).queue_state, 'no-match'); // After the slow interval a short "still empty" line is allowed. const later = Date.now() + relay.NO_WORK_STILL_LOG_INTERVAL_MS + 1; - assert.match(relay.noWorkLogLine(hub, 'no_matching_work', 300000, later).line, /still empty/); + assert.match(relay.noWorkLogLine(hub, 'no_matching_work', 300000, later).line, /Still no work assigned to you/); // A different answer is a state change and says so in full. relay.handleMessage(JSON.stringify({ type: 'task_unavailable', reason: 'capability_mismatch' }), hub); assert.ok(lines.some(l => /\(filter: capability\)/.test(l))); @@ -16108,34 +16133,49 @@ test('#19049 hiveShortName derives a short public name from the hostname (table) } finally { teardown(relay); } }); -test('#19049 multi-hive: one status row, per-hive states, one all-empty summary', () => { +test('#19049 multi-hive: one status row, per-hive states, summaries only when they are true', () => { const relay = loadRelay({ backend: 'claude', procAlive: true, env: MULTI_HIVE_ENV }); const lines = []; const log = console.log; console.log = (...a) => lines.push(a.join(' ')); try { relay.setCliReady(true); const hubs = relay.getHubs(); assert.strictEqual(hubs.length, 3); - // Each hive gets its own full sentence, naming itself, exactly once. + // no_matching_work: each hive gets its own sentence, naming itself, once, and + // none of them claims an empty queue. for (const hub of hubs) { const said = relay.noWorkLogLine(hub, 'no_matching_work', 30000); - assert.match(said.line, new RegExp(`The queue for ${relay.hiveShortName(hub)} is empty\\.`)); + assert.match(said.line, new RegExp(`No work was assigned to you on ${relay.hiveShortName(hub)} right now\\.`)); assert.ok(!/ab12|cd34|ef56/.test(said.line), 'the instance suffix is not part of the short name'); assert.strictEqual(relay.noWorkLogLine(hub, 'no_matching_work', 30000).line, null, 'a repeat is quiet'); } - assert.strictEqual(relay.queueStatusRow(), 'alpha-hive: empty | beta-console: empty | gamma-knuckle: empty'); + assert.strictEqual(relay.queueStatusRow(), 'alpha-hive: idle: no match | beta-console: idle: no match | gamma-knuckle: idle: no match'); + relay.maybeAnnounceAllEmpty(); relay.maybeAnnounceAllEmpty(); + assert.deepStrictEqual(lines.filter(l => /^No work was assigned to you on any of/.test(l)), + ['No work was assigned to you on any of the 3 hives right now; checking again soon.']); + assert.deepStrictEqual(lines.filter(l => /queues are empty/.test(l)), [], 'no-match is not "empty"'); + // The hive's own counts: alpha holds 6 actionable items, beta holds 0. + const now = Date.now(); + Object.assign(hubs[0], { lastActionableItems: 6, lastStatusAt: now }); + Object.assign(hubs[1], { lastActionableItems: 0, lastStatusAt: now }); + assert.strictEqual(relay.queueStatusRow(), 'alpha-hive: idle: no match | beta-console: empty | gamma-knuckle: idle: no match'); + // Every hive reporting zero items (or an explicit queue_empty) makes the summary true. + Object.assign(hubs[0], { lastActionableItems: 0, lastStatusAt: now }); + hubs[2].noWorkState = 'queue-empty'; + lines.length = 0; relay.maybeAnnounceAllEmpty(); - assert.deepStrictEqual(lines.filter(l => /^All \d+ queues are empty/.test(l)), ['All 3 queues are empty, nothing to do right now.']); - // One hive filtered, one empty, one not heard from: the row says each. + assert.deepStrictEqual(lines, ['All 3 queues are empty, nothing to do right now.']); + // One hive filtered, one not heard from: no summary, and the row says each. hubs[1].noWorkState = 'filtered:capability'; hubs[2].noWorkState = null; assert.strictEqual(relay.queueStatusRow(), 'alpha-hive: empty | beta-console: filtered (capability) | gamma-knuckle: asking'); lines.length = 0; relay.maybeAnnounceAllEmpty(); - assert.deepStrictEqual(lines, [], 'no summary unless every queue is empty'); + assert.deepStrictEqual(lines, []); const status = () => JSON.parse(fs.readFileSync(relay.RELAY_STATUS_FILE, 'utf8')); relay.writeRelayStatus(); - assert.deepStrictEqual(status().subscriptions.map(x => x.queue_state), ['queue-empty', 'filtered:capability', null]); + assert.deepStrictEqual(status().subscriptions.map(x => x.queue_state), ['no-match', 'filtered:capability', null]); + assert.deepStrictEqual(status().subscriptions.map(x => x.actionable_items), [0, 0, null]); } finally { console.log = log; teardown(relay); } }); diff --git a/changelog.d/fixed-19049-relay-claude-bypass-consent.md b/changelog.d/fixed-19049-relay-claude-bypass-consent.md index 77f100378c..6ebecffbaa 100644 --- a/changelog.d/fixed-19049-relay-claude-bypass-consent.md +++ b/changelog.d/fixed-19049-relay-claude-bypass-consent.md @@ -1 +1 @@ -- `just contribute-hive claude` no longer stalls at Claude Code's "Bypass Permissions mode" consent, and the relay now says plainly when the hive has no work for it. The contributor container seeded `~/.claude.json` but never the `skipDangerousModePermissionPrompt` user setting, and its startup auto-dismiss pressed a bare Enter on any screen that says "Enter to confirm", which on this dialog (default selection "No, exit") makes Claude exit to the shell, leaving the relay at "CLI is not ready yet" forever. The entrypoint now merges `skipDangerousModePermissionPrompt: true` into the staged `~/.claude/settings.json` (only for a bypass-mode launch, other keys kept), the dismiss loop and the relay select "Yes, I accept" with Down, a pause and a cursor check before Enter and never press Enter on "No, exit", and a Claude that exits at that prompt is relaunched up to three times with `Claude exited at the permissions prompt` in the log and as `cli_reason` in the relay status. Separately, an empty hive queue is reported as one sentence naming the hive instead of a raw `no_matching_work` line every 30s, with a slower retry (30s up to 5 minutes), a `Work available ... claiming` line when work appears, filters that the hive does name (capability, repo, level, quota) worded as such, a `queue_state` field on the relay status (and per hive), one compact status row and one "all queues are empty" line when a relay holds several hives, internal retry bookkeeping lines moved behind `HIVE_RELAY_DEBUG=1`, and a one-line quota-guard notice that says it can be ignored ([#19049](https://github.com/hivecommons/hive/issues/19049)). +- `just contribute-hive claude` no longer stalls at Claude Code's "Bypass Permissions mode" consent, and the relay now says plainly when the hive has no work for it. The contributor container seeded `~/.claude.json` but never the `skipDangerousModePermissionPrompt` user setting, and its startup auto-dismiss pressed a bare Enter on any screen that says "Enter to confirm", which on this dialog (default selection "No, exit") makes Claude exit to the shell, leaving the relay at "CLI is not ready yet" forever. The entrypoint now merges `skipDangerousModePermissionPrompt: true` into the staged `~/.claude/settings.json` (only for a bypass-mode launch, other keys kept), the dismiss loop and the relay select "Yes, I accept" with Down, a pause and a cursor check before Enter and never press Enter on "No, exit", and a Claude that exits at that prompt is relaunched up to three times with `Claude exited at the permissions prompt` in the log and as `cli_reason` in the relay status. Separately, a hive answering `no_matching_work` (which it sends both for an empty queue and for work filtered out for you) is now reported as one plain sentence naming the hive, `No work was assigned to you on right now. The hive may have nothing queued, or nothing that matches your setup`, followed once by the hive's own `actionable_items` count, instead of a raw reason line every 30s; the "queue is empty" wording is reserved for an explicit `queue_empty` from the hive. Retries back off from 30s to 5 minutes, `Work available ... claiming` prints when work appears, filters the hive does name (capability, repo, level, quota) are worded as such, the relay status gains `queue_state` (and per hive with `actionable_items`), a relay holding several hives gets one compact status row and one summary line, internal retry bookkeeping lines move behind `HIVE_RELAY_DEBUG=1`, and the quota-guard notice is one line that says it can be ignored ([#19049](https://github.com/hivecommons/hive/issues/19049)). diff --git a/src/docs/contributor-relay.md b/src/docs/contributor-relay.md index 7f5e6f37e6..90452dd637 100644 --- a/src/docs/contributor-relay.md +++ b/src/docs/contributor-relay.md @@ -187,7 +187,7 @@ With an explicitly configured shared pool, `just contribute-quota status` inspec ## What happens on a task 1. A successful connection logs `Connected to …`, followed by `Authenticated with … as … (tier: …)`. Authentication is not yet a task assignment. -2. The hive assigns an issue that fits your trust tier and its filters. When there is nothing for you, the relay prints one plain sentence instead of a raw reason code, for example `The queue for is empty. There is nothing for you to work on right now.` This is normal, not a fault: the relay stays connected and work arrives when the hive owner queues issues for contributors. It says so once, repeats only a short `still empty` line every ten minutes, backs off from checking every 30 seconds to every 5 minutes while the queue stays empty (with more than one hive the 30 second poll rotation is kept), and prints `Work available on , claiming #` when work appears. The hive's `no_matching_work` reason covers both an empty queue and a queue whose every issue was dropped by a filter the hive does not name on the wire (cooldown, a disabled or denied repository, an open or recently merged PR already claiming the issue, your own work). Refusals that do name their filter are worded differently: `capability_mismatch` (`filter: capability`), `no_selected_work` (`filter: repo`), `tier_disabled` (`filter: level`) and `hourly_limit` / `daily_limit` / `concurrency_limit` (`filter: quota`). With several hives on one relay every line names its hive by a short public name (`hosted--ab12.` shows as ``), the sentence is printed once per hive on a state change, and when every enabled hive is empty one line says `All 3 queues are empty, nothing to do right now.` The state is also written to the relay status file as `queue_state` (`queue-empty`, `filtered:`, `working`, `waiting-on-cli`), per hive as `queue_state` on each `subscriptions` entry, and shown when you attach as one compact tmux status row, for example `alpha: empty | beta: empty | gamma: working #123`. The per-retry `Requesting work ...` and `Cancelled ready retry ...` bookkeeping lines are internal and only printed with `HIVE_RELAY_DEBUG=1`. Other reasons may require the hive operator, not another registration. +2. The hive assigns an issue that fits your trust tier and its filters. When it assigns you nothing, the relay prints one plain sentence instead of a raw reason code. The hive's `no_matching_work` reason covers both an empty queue and a queue whose every issue was dropped for you by a filter the hive does not name on the wire (cooldown, a disabled or denied repository, an open or recently merged PR already claiming the issue, your own work, your CLI, trust tier or quota), so the relay never claims the queue is empty from it. It says `No work was assigned to you on right now. The hive may have nothing queued, or nothing that matches your setup (CLI, trust tier, repo, quota).`, then asks the hive's public `/api/contribute/status` for `actionable_items` and follows up once with either ` has N actionable items, but none was assigned to you` or ` reports 0 actionable items, so nothing is queued there right now`. `The queue for is empty` is printed only when the hive explicitly answers `queue_empty` ([#19052](https://github.com/hivecommons/hive/issues/19052) asks the server to send it). The relay stays connected, says each state once, repeats only a short `Still no work assigned` line every ten minutes, backs off from checking every 30 seconds to every 5 minutes while the answer stays the same (with more than one hive the 30 second poll rotation is kept), and prints `Work available on , claiming #` when work appears. Refusals that do name their filter are worded differently: `capability_mismatch` (`filter: capability`), `no_selected_work` (`filter: repo`), `tier_disabled` (`filter: level`) and `hourly_limit` / `daily_limit` / `concurrency_limit` (`filter: quota`). With several hives on one relay every line names its hive by a short public name (`hosted--ab12.` shows as ``), and when every enabled hive is idle one line says so (`All 3 queues are empty, nothing to do right now.` only when each is confirmed empty, otherwise `No work was assigned to you on any of the 3 hives right now`). The state is also written to the relay status file as `queue_state` (`no-match`, `queue-empty`, `filtered:`, `working`, `waiting-on-cli`), per hive as `queue_state` and `actionable_items` on each `subscriptions` entry, and shown when you attach as one compact tmux status row, for example `alpha: idle: no match | beta: empty | gamma: working #123`. The per-retry `Requesting work ...` and `Cancelled ready retry ...` bookkeeping lines are internal and only printed with `HIVE_RELAY_DEBUG=1`. Other reasons may require the hive operator, not another registration. 3. The relay prepares the checkout, injects a short-lived GitHub token, and drives your coding CLI. In interactive mode, use the **attach command printed by your launch** to watch the tmux session. Container mode prints the Docker/Podman form; native mode prints `tmux attach`. Headless backends have no interactive pane. 4. Progress is reported every 2 minutes; completion/PR metadata is reported when the CLI finishes. Check the linked PR and its checks, not just a local “success” line. PRs retain the task's base branch, required hold gates, and DCO sign-off (`git commit -s`). 5. To stop your foreground relay, press **Ctrl-C** in the terminal running it; detaching from tmux is not stopping the relay. The relay cleans up its connection. If work is in flight, it is not thereby completed: inspect the PR/worktree and the hive's recorded task state before deleting local work or starting another relay. From dadef203ae66370e173762296e390416833102f7 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 12:40:25 -0500 Subject: [PATCH 5/6] =?UTF-8?q?=F0=9F=90=9B=20fix(contribute):=20correct?= =?UTF-8?q?=20short-name=20test=20expectation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #19049 Signed-off-by: Andy Anderson --- bin/contributor-relay.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index 1aec14c2bd..02f32a3fef 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -16126,7 +16126,7 @@ test('#19049 hiveShortName derives a short public name from the hostname (table) ['wss://hosted-alpha-hive-ab12.hive.example.org/api/contribute/ws', 'alpha-hive'], ['wss://hosted-gamma-knuckle-ef56.hive.example.org/api/contribute/ws', 'gamma-knuckle'], ['wss://hive.example.org/api/contribute/ws', 'hive.example.org'], - ['wss://hosted-x.hive.example.org/api/contribute/ws', 'hosted-x.hive.example.org'], + ['wss://hosted-x.hive.example.org/api/contribute/ws', 'x'], ['not a url', 'this hive'], ]; for (const [url, want] of cases) assert.strictEqual(relay.hiveShortName({ sourceURL: url }), want, url); From f99c570c246a515c4bd59534e046600f6ec01219 Mon Sep 17 00:00:00 2001 From: Andy Anderson Date: Wed, 18 Nov 2026 12:56:18 -0500 Subject: [PATCH 6/6] =?UTF-8?q?=F0=9F=90=9B=20fix(contribute):=20cover=20t?= =?UTF-8?q?he=20hive-stated=20name=20in=20hiveShortName?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #19049 Signed-off-by: Andy Anderson --- bin/contributor-relay.test.js | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/contributor-relay.test.js b/bin/contributor-relay.test.js index 81efd50339..5d8310dc16 100644 --- a/bin/contributor-relay.test.js +++ b/bin/contributor-relay.test.js @@ -16172,6 +16172,7 @@ test('#19049 hiveShortName derives a short public name from the hostname (table) ['not a url', 'this hive'], ]; for (const [url, want] of cases) assert.strictEqual(relay.hiveShortName({ sourceURL: url }), want, url); + assert.strictEqual(relay.hiveShortName({ hiveName: 'stated-name', sourceURL: cases[0][0] }), 'stated-name', 'the name the hive states on auth_ok wins'); } finally { teardown(relay); } });