From 4186ff3a9a09bcc094d625960da59df3f614bfbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=ED=8F=89=EC=8B=9D?= Date: Thu, 1 Oct 2026 17:37:34 +0900 Subject: [PATCH 1/3] feat: route OpenCode permission asks to a captain decision An OpenCode 2 permission ask renders as a modal inside the worker's own TUI. The captain never sees it and firstmate has no record of it, so a worker asking for a path outside its worktree simply blocks with no visible decision anywhere. bin/fm-opencode-permission.sh bridges one real request to the captain through the existing Discord decision path and applies the keyed answer back to exactly that request. The generated OpenCode plugin only forwards permission.asked and decides nothing: a plugin that approved anything would be the invisible grant this change exists to remove. decide refuses unless the record names that exact task and request, is still pending, carries the task's current busy generation, and the server still reports it pending with the same id, session, and action. The read-check-consume sequence is one critical section and the record becomes consumed before the POST, so a replay or a concurrent second caller refuses rather than granting twice. A captured Discord reply now also enqueues its own durable wake. The stdout contract only reaches a session when the watcher ran the poll, so an operator-run or LaunchAgent-run ingress poll captured a reply whose marker then made every later watcher poll suppress it. Capture is now the wake; the stdout contract is unchanged for the watcher's own dispatch. answer-one gains an optional occurrence guard, and the reply path passes it. The decision key already carries the occurrence the captain was actually asked at, so a reply arriving after a call was answered and re-held would otherwise resolve the newer question they were never asked. Every decision answer is then confirmed to the captain, after the keyed command succeeds. An answer with no receipt is indistinguishable from a lost reply. --- .agents/skills/fmx-respond/SKILL.md | 14 +- bin/fm-captain-hold.sh | 41 +- bin/fm-discord-notify.js | 3 + bin/fm-discord-notify.sh | 6 +- bin/fm-discord-poll.sh | 45 +- bin/fm-opencode-permission.sh | 371 ++++++++++++++ bin/fm-spawn.sh | 39 ++ bin/fm-teardown.sh | 4 + docs/scripts.md | 1 + tests/fm-captain-hold-lifecycle.test.sh | 64 +++ tests/fm-discord-decision-push.test.sh | 38 ++ tests/fm-opencode-permission-plugin.test.sh | 125 +++++ tests/fm-opencode-permission.test.sh | 510 ++++++++++++++++++++ tests/fm-teardown.test.sh | 18 + 14 files changed, 1274 insertions(+), 5 deletions(-) create mode 100755 bin/fm-opencode-permission.sh create mode 100755 tests/fm-opencode-permission-plugin.test.sh create mode 100755 tests/fm-opencode-permission.test.sh diff --git a/.agents/skills/fmx-respond/SKILL.md b/.agents/skills/fmx-respond/SKILL.md index 467e61ec7fa..9752f90ced3 100644 --- a/.agents/skills/fmx-respond/SKILL.md +++ b/.agents/skills/fmx-respond/SKILL.md @@ -148,12 +148,24 @@ Images are only for actual visual artifacts - a generated illustration, a screen Before classifying an inbox item as a new mention, check whether `source` is `discord-selfhosted-decision`. Such an item is an answer to a specific pushed decision: use its `.decision` object and `.text`, and do not reply publicly or treat it as fresh work. -For `trigger=captain-hold`, call `bin/fm-captain-hold.sh answer-one "$key" "$answer" "Discord reply" --source discord-selfhosted`; it folds tabs and line breaks in the answer into spaces before keyed resolution. +For `trigger=captain-hold`, call `bin/fm-captain-hold.sh answer-one "$task_id" "$answer" "Discord reply" --source discord-selfhosted --expect-occurrence "$occurrence"`; it folds tabs and line breaks in the answer into spaces before keyed resolution. +`$task_id` is `.decision.task_id` and `$occurrence` is the trailing integer of `.decision.key`, which has the shape `captain-hold--`; both come from the decision object, and never be derived from the reply text. +`--expect-occurrence` is not optional for a Discord reply: without it a reply that arrives after the call was answered and re-held resolves the *newer* question the captain was never asked, which is a silent wrong answer rather than a visible failure. +A refusal naming the occurrence is a real outcome, not an error to retry: the captain's reply answered a question that has since moved on, so leave the inbox record in place, report the refusal in the plain outcome channel, and do not resolve anything. For `trigger=ask-user` or `trigger=pr-ready`, invoke `bin/fm-send.sh --resolve-key "$answer"` with the captured answer as one quoted argument. +For `trigger=perm-ask`, invoke `bin/fm-opencode-permission.sh decide "$task_id" "$request_id" `, where `$task_id` is `.decision.task_id` and `$request_id` is `.decision.key` with its `perm-` prefix removed. +Map the captain's words to exactly one of the three options the message offered, and pass only that word: `Approve once` becomes `once`, `Approve once and remember this` becomes `always`, and `Reject the request` becomes `reject`. +When the reply does not clearly select one of the three offered options, do not guess and do not apply anything: report the three options in the plain outcome channel and leave the request pending. +That script is the only thing that can grant, and it refuses on its own when the request expired, was already answered, or belongs to a task generation that has moved on. These are the existing keyed-answer paths; never edit status files directly. Remove the inbox record only after the matching command confirms success. On failure leave it for retry and report the exact error. +Every decision answer is applied and then confirmed, in that order. +Confirmation is what tells the captain their reply landed, and it is the only receipt they get: `bin/fm-discord-notify.sh --report ""`, using `.channel_id` from the decision object and stating plainly which decision was applied and what it enabled. +Post it after the keyed command succeeds, never before, and never instead of applying. +Without that receipt the captain answered a decision and got no evidence it was consumed, which is indistinguishable from the reply being lost. + This is a drain over the inbox, not a single reply. The watcher coalesces same-key `check:` wakes, so one `x-mention` wake can stand in for several pending mentions. Treat `state/x-inbox/` as the source of truth and process **every** file you find there, not just the `request_id` named in the wake. diff --git a/bin/fm-captain-hold.sh b/bin/fm-captain-hold.sh index 03beecad0fc..07e67c34760 100755 --- a/bin/fm-captain-hold.sh +++ b/bin/fm-captain-hold.sh @@ -23,6 +23,8 @@ # fm-captain-hold.sh hold --reason \ # [--title ] [--repo <repo>] [--origin <origin-id>] [--until YYYY-MM-DD] # fm-captain-hold.sh answer <task-id> --decision-file <path> [--release] +# fm-captain-hold.sh answer-one <task-id> <answer> <label> \ +# --source <provenance> [--expect-occurrence <n>] # fm-captain-hold.sh answers [<legacy-origin> | --any-origin] --source <provenance> (keyed answers on stdin) # fm-captain-hold.sh reconcile-requests --source-id <source-id> --source <provenance> (task ids on stdin) # fm-captain-hold.sh bind <source-id> [<legacy-origin> | --any-origin] @@ -115,6 +117,14 @@ # and pipe them here. It must never map keys to tasks, build decision records, # choose a close mode beyond what its card declared, or close anything itself. # +# `answer-one` is the single-key form of that same intake, for a channel that +# captured exactly one decision. `--expect-occurrence <n>` is its occurrence +# guard: pass the occurrence the decision was actually asked at, and a task +# that is no longer at that occurrence - already answered, or answered and +# re-held, or no longer captain-held - is refused before any resolution is +# written. Without the flag the guard does not run, so an existing caller that +# has no occurrence to assert keeps its current behavior. +# # `bind`, `unbind`, and `binding` record that a captured-answer SOURCE feeds # this intake, for any channel whose answers arrive detached from their origin # (a process-event source id, for example). The binding is a private record @@ -1933,11 +1943,12 @@ command_open() { # <task-id> [--identity] [--distinguish-absent] } command_answer_one() { - local key=${1:-} answer=${2:-} label=${3:-} source='' + local key=${1:-} answer=${2:-} label=${3:-} source='' occurrence='' [ "$#" -ge 3 ] || { usage >&2; exit 2; } shift 3 while [ "$#" -gt 0 ]; do case "$1" in + --expect-occurrence) shift; occurrence=${1:-} ;; --expect-occurrence=*) occurrence=${1#*=} ;; --source) shift; source=${1:-} ;; *) usage >&2; exit 2 ;; esac @@ -1946,12 +1957,40 @@ command_answer_one() { [ -n "$source" ] || fail "--source provenance is required so the durable decision records where the answer came from" validate_slug task-id "$key" [ "${#key}" -le 128 ] || fail "task-id must be at most 128 characters" + if [ -n "$occurrence" ]; then + require_current_occurrence "$key" "$occurrence" + fi answer=$(sanitize_field "$answer") label=$(sanitize_field "$label") printf '%s\t%s\t%s\n' "$key" "$answer" "$label" \ | command_answers --any-origin --source "$source" } +# Refuse a keyed answer that names a superseded occurrence of a still-open +# captain call. The Discord decision key carries the occurrence +# `captain-hold-<task-id>-<occurrence>` that was actually put in front of the +# captain, so a reply that arrives after the call was answered and re-held +# targets an occurrence the captain was never asked about. Resolution is +# refused rather than forwarded, so a stale reply cannot silently answer a +# newer question. A closed task, an unreadable body, or an absent task fails +# closed here exactly as it does in the resolution path itself. +require_current_occurrence() { # <task-id> <expected-occurrence> + local key=$1 expected=$2 show body hold_kind count + case "$expected" in ''|*[!0-9]*|0) fail "--expect-occurrence must be a positive integer" ;; esac + task_show "$key" || fail "no captain-held task $key in this home's configured backlog (data directory $DATA)" + show=$TASK_SHOW_OUTPUT + body=$(show_field_value "$show" body) + hold_kind=$(show_field_value "$show" hold_kind) + count=$(resolution_record_count "$body") || count='' + case "$count" in ''|*[!0-9]*) count=0 ;; esac + if [ "$hold_kind" != captain ]; then + fail "refusing the answer: $key is not currently held for the captain (hold_kind=$hold_kind), so its occurrence $((count + 1)) cannot be confirmed" + fi + if [ "$((count + 1))" != "$expected" ]; then + fail "refusing the answer: $key is at occurrence $((count + 1)), not the occurrence $expected this decision was asked at" + fi +} + case "${1:-}" in hold) shift; command_hold "$@" ;; answer) shift; command_answer "$@" ;; diff --git a/bin/fm-discord-notify.js b/bin/fm-discord-notify.js index 29b75d0579c..4a611e34f93 100755 --- a/bin/fm-discord-notify.js +++ b/bin/fm-discord-notify.js @@ -59,6 +59,9 @@ function localize(value) { "Leave it open": "열린 상태로 두기", "Continue with the request": "요청대로 계속 진행", "Leave it on hold": "보류 상태로 두기", + "Approve once": "이 1회만 허용", + "Approve once and remember this": "허용하고 이 경로를 기억", + "Reject the request": "요청 거부", })[value] || value; } diff --git a/bin/fm-discord-notify.sh b/bin/fm-discord-notify.sh index bf1089167a6..47a89a33afd 100755 --- a/bin/fm-discord-notify.sh +++ b/bin/fm-discord-notify.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # Send one firstmate-initiated decision to the configured self-hosted Discord channel. -# Usage: fm-discord-notify.sh <captain-hold|ask-user|pr-ready> <task-id> <key> <summary> <option|option...> [status-task-id] +# `perm-ask` carries a real OpenCode permission request; its key is `perm-<request-id>`. +# Usage: fm-discord-notify.sh <captain-hold|ask-user|pr-ready|perm-ask> <task-id> <key> <summary> <option|option...> [status-task-id] set -u SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -19,7 +20,7 @@ elif [ "${1:-}" = --retry-pending ]; then [ "$#" -eq 1 ] || { echo "usage: fm-discord-notify.sh --retry-pending" >&2; exit 2; } retry_pending=1 elif [ "$#" -lt 5 ] || [ "$#" -gt 6 ]; then - echo "usage: fm-discord-notify.sh <captain-hold|ask-user|pr-ready> <task-id> <key> <summary> <option|option...> [status-task-id]" >&2 + echo "usage: fm-discord-notify.sh <captain-hold|ask-user|pr-ready|perm-ask> <task-id> <key> <summary> <option|option...> [status-task-id]" >&2 exit 2 fi if [ "$retry_pending" -eq 0 ] && [ "$report_mode" -eq 0 ]; then @@ -56,6 +57,7 @@ case "$trigger:$decision_key" in captain-hold:captain-hold-*) ;; ask-user:nm-*) ;; pr-ready:pr-ready-*) ;; + perm-ask:perm-*) ;; *) echo "fm-discord-notify: trigger does not match its decision key" >&2; exit 2 ;; esac case "$summary" in *$'\n'*|*$'\r'*) echo "fm-discord-notify: summary must be one line" >&2; exit 2 ;; esac diff --git a/bin/fm-discord-poll.sh b/bin/fm-discord-poll.sh index 422cfb30b50..4ec7210fe70 100755 --- a/bin/fm-discord-poll.sh +++ b/bin/fm-discord-poll.sh @@ -7,6 +7,15 @@ # state/discord-watch.check.sh matches the expected byte-static identity shim. # # Its contract: output "x-mention <request_id>" => wake firstmate, silence => keep sleeping. +# +# A captured item is also enqueued into the durable wake queue here, so capture +# itself is the wake. The stdout contract only reaches a session when the WATCHER +# ran this script: an operator-run or LaunchAgent-run ingress poll reaches nobody +# that way, because its stdout goes to a log file while the offered marker +# written during capture then makes every later watcher poll suppress the item. +# That combination captured a captain reply and never woke anyone for it. The +# enqueue is additive, so the watcher's own validated check dispatch still sees +# and still forwards the same line. set -u @@ -30,4 +39,38 @@ export FM_DISCORD_EXCLUDES="${FM_DISCORD_EXCLUDES-}" export FM_DISCORD_ALLOW_DMS="${FM_DISCORD_DMS:-true}" export FM_DISCORD_AUTHORIZED_USER_IDS="${FM_DISCORD_AUTHORIZED_USERS:-}" -exec node "$SCRIPT_DIR/fm-discord-poll.js" +# Only a token-gated run can capture anything, so the wake library is loaded +# only here: without a token this stays a hard no-op that touches no state. +if [ ! -r "$FM_ROOT/bin/fm-wake-lib.sh" ]; then + printf 'fm-discord-poll: cannot enqueue a wake (missing %s)\n' "$FM_ROOT/bin/fm-wake-lib.sh" >&2 + exit 1 +fi +# shellcheck source=/dev/null +FM_ROOT_OVERRIDE="$FM_ROOT" FM_HOME="$FM_HOME" STATE="$STATE" . "$FM_ROOT/bin/fm-wake-lib.sh" + +OUT_FILE=$(mktemp "${TMPDIR:-/tmp}/fm-discord-poll.XXXXXX") || exit 1 +trap 'rm -f "$OUT_FILE"' EXIT +node "$SCRIPT_DIR/fm-discord-poll.js" > "$OUT_FILE" +poll_rc=$? +cat "$OUT_FILE" +while IFS= read -r line || [ -n "$line" ]; do + case "$line" in + 'x-mention '*) ;; + *) continue ;; + esac + request_id=${line#x-mention } + case "$request_id" in + ''|.*|*[!A-Za-z0-9._-]*) + printf 'fm-discord-poll: refusing to wake on an unusable request id\n' >&2 + continue + ;; + esac + # The notifier's own decision-poll shim owns the same durable key, so a + # duplicate here is absorbed by the queue's per-key dedupe instead of + # surfacing the same reply twice. A failed enqueue never loses the capture: + # the inbox record is already on disk, so report it loudly and let a later + # poll's own capture retry. + fm_wake_append check "discord-$request_id" "check: $line" \ + || printf 'fm-discord-poll: captured %s but could not enqueue its wake\n' "$request_id" >&2 +done < "$OUT_FILE" +exit "$poll_rc" diff --git a/bin/fm-opencode-permission.sh b/bin/fm-opencode-permission.sh new file mode 100755 index 00000000000..7c02805ece7 --- /dev/null +++ b/bin/fm-opencode-permission.sh @@ -0,0 +1,371 @@ +#!/usr/bin/env bash +# Bridge one real OpenCode v2 permission request to the captain's existing +# decision path, and apply the captain's answer to exactly that request. +# +# The installed OpenCode 2 server exposes the ask as a pending request record +# (`GET /api/session/<sessionID>/permission/<requestID>`) and accepts the +# answer at `POST /api/session/<sessionID>/permission/<requestID>/reply` with +# the body `{"decision":"once"|"always"|"reject"}`. The v1-era typings shipped +# in the same install document `{reply, message}` and a `/permissions/` +# plural route; both are rejected by the running server, so nothing here reads +# those typings. The three decisions below are the installed server's own enum. +# +# Two subcommands, both identity-checked and idempotent: +# +# ask <task-id> <session-id> <request-id> +# Verify the request the server currently reports, record it durably +# under state/<task-id>.opencode-permission/<request-id>.json, and push +# the captain decision through bin/fm-discord-notify.sh with the +# `perm-ask` trigger and a `perm-<request-id>` key. That key makes the +# push single-fire: the notifier derives its record path and Discord +# nonce from (trigger, task, key), so a repeated ask re-uses the same +# message instead of sending a second one. Prints the key on success. +# +# decide <task-id> <request-id> <once|always|reject> +# Apply the captain's answer. Requires, in order: the record exists and +# names this exact task; its state is `pending`; the task's current +# busy generation still equals the one captured at ask time; the live +# server still reports that request as pending with the same id and +# session. The record is then marked `consumed` BEFORE the POST, so a +# concurrent or replayed call finds a non-pending record and refuses +# without granting. A consumed record whose POST failed stays +# `consumed` with the error: the captain's answer is spent and only the +# captain can grant a fresh one. +# +# settle <task-id> <request-id> <once|always|reject> +# Record a decision the worker applied itself (or the TUI answered), so +# the audit trail closes on a server-confirmed outcome rather than +# leaving the record pending forever. Never POSTs. +# +# Everything refuses rather than guessing. A missing, unreadable, mismatched, +# already-decided, stale-generation, or no-longer-pending request yields a +# nonzero exit and no API write. Teardown removes the whole record directory +# with the task's other state; a request that is never answered simply expires +# on the server, which is fail-closed by construction. +# +# No secrets, no second notification path, and no second approval ledger: the +# durable record here is the audit trail for THIS surface only, and the +# captain decision travels the existing Discord decision path. +set -u + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" +FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" +STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" + +RECORD_DIR_NAME="opencode-permission" +RECORD_SCHEMA="fm-opencode-permission-request.v1" +TRIGGER="perm-ask" + +# shellcheck source=bin/fm-busy-lib.sh +. "$SCRIPT_DIR/fm-busy-lib.sh" +# shellcheck source=/dev/null +# The wake library is also the repo's one portable lock implementation, and +# decide needs it: the record transition from pending to consumed has to be a +# single-writer critical section, or two concurrent decides could both read +# pending and both post. Sourcing it is a no-op when it is already loaded. +if ! command -v fm_lock_acquire_wait >/dev/null 2>&1; then + . "$SCRIPT_DIR/fm-wake-lib.sh" +fi + +fail() { + printf 'fm-opencode-permission: %s\n' "$*" >&2 + exit 1 +} + +validate_slug() { # <label> <value> + case "$2" in + ''|.*|*[!A-Za-z0-9._-]*) fail "$1 must be a non-empty privacy-safe slug: $2" ;; + esac +} + +record_dir() { # <task-id> + printf '%s/%s.%s' "$STATE" "$1" "$RECORD_DIR_NAME" +} + +record_path() { # <task-id> <request-id> + printf '%s/%s.json' "$(record_dir "$1")" "$2" +} + +opencode_bin() { + local bin + bin=$(command -v opencode) || fail "opencode executable not found on PATH" + printf '%s' "$bin" +} + +# Fetch one permission request and print the response body. +# A non-2xx response is an empty result, not a crash: the request has expired +# or never existed, and the caller decides what an absent request means. +permission_get() { # <session-id> <request-id> + "$(opencode_bin)" api GET "/api/session/$1/permission/$2" 2>/dev/null || true +} + +# Read one JSON field with jq, printing nothing when absent or unparsable. +json_field() { # <json> <field> + printf '%s' "$1" | jq -r --arg f "$2" '.[$f] // empty' 2>/dev/null || true +} + +json_array() { # <json> <field> -> newline-separated + printf '%s' "$1" | jq -r --arg f "$2" '(.[$f] // [])[] | tostring' 2>/dev/null || true +} + +command_ask() { + [ "$#" -eq 3 ] || fail "usage: fm-opencode-permission.sh ask <task-id> <session-id> <request-id>" + local task_id=$1 session_id=$2 request_id=$3 body live_id live_session action resources save tmp + validate_slug task-id "$task_id" + validate_slug session-id "$session_id" + validate_slug request-id "$request_id" + command -v jq >/dev/null 2>&1 || fail "missing jq" + + # The record is written only from what the SERVER reports about this exact + # request, never from a caller's claim about it. A request the server does + # not confirm is never pushed to the captain and never becomes decidable. + body=$(permission_get "$session_id" "$request_id") + [ -n "$body" ] || fail "refusing: the server reports no permission request $request_id in session $session_id" + live_id=$(json_field "$body" id) + live_session=$(json_field "$body" sessionID) + [ "$live_id" = "$request_id" ] \ + || fail "refusing: server returned request id '$live_id' for requested id '$request_id'" + [ "$live_session" = "$session_id" ] \ + || fail "refusing: server returned session id '$live_session' for requested session '$session_id'" + action=$(json_field "$body" action) + [ -n "$action" ] || fail "refusing: request $request_id carries no action" + resources=$(json_array "$body" resources) + save=$(json_array "$body" save) + [ -n "$resources" ] || fail "refusing: request $request_id names no resource" + + local dir gen + dir=$(record_dir "$task_id") + # A record that already exists is the same request seen again. Do not + # overwrite it: the captured generation and options are the identity a + # decision is checked against, and the notifier already made the push + # single-fire for this key. + if [ -e "$(record_path "$task_id" "$request_id")" ]; then + printf 'perm-%s\n' "$request_id" + return 0 + fi + mkdir -p "$dir" || fail "cannot create $dir" + chmod 700 "$dir" || fail "cannot secure $dir" + # Fail closed when the task's generation cannot be read: a decide with no + # generation to compare against could not detect a relaunched task. + gen=$(fm_busy_current_gen "$STATE" "$task_id") \ + || fail "refusing: task $task_id has no current busy generation, so a later answer could not be proven to belong to this run" + + tmp=$(mktemp "$dir/.ask.XXXXXX") || fail "cannot stage the request record" + # The resource and save lists go in as JSON arrays built from the server's own + # fields, never re-joined and re-split on a delimiter: a path may legally + # contain a comma, and a delimiter round trip would silently alter the scope + # the captain is being shown. + if ! jq -n \ + --arg schema "$RECORD_SCHEMA" \ + --arg task "$task_id" \ + --arg session "$session_id" \ + --arg request "$request_id" \ + --arg gen "$gen" \ + --arg at "$(date +%s)" \ + --argjson body "$body" \ + '{schema:$schema, task_id:$task, session_id:$session, request_id:$request, + action:$body.action, resources:($body.resources // []), save:($body.save // []), + generation:$gen, state:"pending", asked_at:($at|tonumber)}' \ + > "$tmp" 2>/dev/null; then + rm -f "$tmp" + fail "cannot render the request record" + fi + chmod 600 "$tmp" || { rm -f "$tmp"; fail "cannot secure the staged request record"; } + mv "$tmp" "$(record_path "$task_id" "$request_id")" \ + || { rm -f "$tmp"; fail "cannot publish the request record"; } + + push_captain_decision "$task_id" "$request_id" "$action" "$resources" "$save" + printf 'perm-%s\n' "$request_id" +} + +# The captain-facing question carries what the ask is, what it touches, what +# would be remembered if the answer were `always`, and this surface's +# recommendation, so the reply is answerable from the message alone. +push_captain_decision() { # <task-id> <request-id> <action> <resources> <save> + local task_id=$1 request_id=$2 action=$3 resources=$4 save=$5 + local summary first_resource saved_note + first_resource=$(printf '%s\n' "$resources" | head -1) + if [ -n "$save" ]; then + saved_note="Choosing 'remember this' would save: $(printf '%s' "$save" | paste -sd' ' -)" + else + saved_note="Nothing would be remembered: this ask has no save pattern." + fi + summary=$(printf 'OpenCode worker needs permission: action=%s resource=%s | %s | Recommendation: approve once and keep the saved scope unchanged; approve with remember only when the same path will be needed again this run.' \ + "$action" "$first_resource" "$saved_note") + [ "${#summary}" -le 1800 ] || summary="${summary:0:1800}…" + "$SCRIPT_DIR/fm-discord-notify.sh" "$TRIGGER" "$task_id" "perm-$request_id" \ + "$summary" \ + "Approve once|Approve once and remember this|Reject the request" >/dev/null \ + || printf 'actionable: the permission request was recorded but the captain decision push failed\n' >&2 +} + +# Load the record, or fail. Sets RECORD_BODY and RECORD_PATH. +load_record() { # <task-id> <request-id> + RECORD_PATH=$(record_path "$1" "$2") + [ -f "$RECORD_PATH" ] && [ ! -L "$RECORD_PATH" ] \ + || fail "refusing: no permission request record at $RECORD_PATH" + RECORD_BODY=$(cat "$RECORD_PATH" 2>/dev/null) \ + || fail "refusing: the permission request record at $RECORD_PATH is unreadable" + [ "$(json_field "$RECORD_BODY" schema)" = "$RECORD_SCHEMA" ] \ + || fail "refusing: $RECORD_PATH is not a $RECORD_SCHEMA record" + [ "$(json_field "$RECORD_BODY" task_id)" = "$1" ] \ + || fail "refusing: $RECORD_PATH belongs to task $(json_field "$RECORD_BODY" task_id), not $1" + [ "$(json_field "$RECORD_BODY" request_id)" = "$2" ] \ + || fail "refusing: $RECORD_PATH records request $(json_field "$RECORD_BODY" request_id), not $2" +} + +# Refuse anything already decided. Runs BEFORE the live read so a replay never +# reaches the server at all. +require_pending() { # <record-body> + local state + state=$(json_field "$1" state) + case "$state" in + pending) ;; + '') fail "refusing: the permission request record has no state" ;; + *) fail "refusing: the permission request is already $state, so no second answer can apply" ;; + esac +} + +# Refuse when the task has moved on since the ask. A relaunched task is a +# different run: its generation differs, so the captain's answer to the earlier +# run's request is not an answer to anything this run can grant. +require_current_generation() { # <task-id> <record-body> + local recorded current + recorded=$(json_field "$2" generation) + [ -n "$recorded" ] || fail "refusing: the permission request record carries no task generation" + current=$(fm_busy_current_gen "$STATE" "$1") \ + || fail "refusing: task $1 has no current busy generation, so this answer cannot be proven to belong to a live run" + [ "$current" = "$recorded" ] \ + || fail "refusing: task $1 has moved to generation $current since this request was asked at $recorded" +} + +# Refuse when the server no longer reports the request pending. This is the +# check that makes an expired, already-answered, or unknown request fail +# closed instead of posting a reply to a request that is not there. +require_pending_on_server() { # <session-id> <request-id> <record-body> + local body live_id live_session + body=$(permission_get "$1" "$2") + [ -n "$body" ] \ + || fail "refusing: the server no longer reports request $2 pending; it was answered, rejected, or expired" + live_id=$(json_field "$body" id) + live_session=$(json_field "$body" sessionID) + [ "$live_id" = "$2" ] \ + || fail "refusing: the server returned request id '$live_id' where $2 was expected" + [ "$live_session" = "$1" ] \ + || fail "refusing: the server returned session id '$live_session' where $1 was expected" + local recorded_action + recorded_action=$(json_field "$3" action) + [ -z "$recorded_action" ] || [ "$(json_field "$body" action)" = "$recorded_action" ] \ + || fail "refusing: the server now reports action '$(json_field "$body" action)' for request $2, not the recorded '$recorded_action'" +} + +write_state() { # <record-body> <new-state> [decision] [error] + local body=$1 state=$2 decision=${3:-} error=${4:-} tmp + tmp=$(mktemp "$(dirname "$RECORD_PATH")/.settle.XXXXXX") || fail "cannot stage the record update" + if ! jq -n --argjson base "$body" --arg state "$state" --arg decision "$decision" \ + --arg error "$error" --arg at "$(date +%s)" \ + '$base + {state:$state, decided_at:($at|tonumber)} + + (if $decision == "" then {} else {decision:$decision} end) + + (if $error == "" then {} else {apply_error:$error} end)' > "$tmp" 2>/dev/null; then + rm -f "$tmp" + fail "cannot render the record update" + fi + chmod 600 "$tmp" || { rm -f "$tmp"; fail "cannot secure the staged record update"; } + mv "$tmp" "$RECORD_PATH" || { rm -f "$tmp"; fail "cannot publish the record update"; } +} + +# Mark the record consumed BEFORE the API write. This is the commit point: any +# second caller, in this process or another, now refuses on the state check and +# cannot grant twice even if the first POST is still in flight. +consume() { # <record-body> <decision> + local body=$1 decision=$2 tmp + tmp=$(mktemp "$(dirname "$RECORD_PATH")/.consume.XXXXXX") || fail "cannot stage the record transition" + if ! jq -n --argjson base "$body" --arg decision "$decision" --arg at "$(date +%s)" \ + '$base + {state:"consumed", decision:$decision, consumed_at:($at|tonumber)}' > "$tmp" 2>/dev/null; then + rm -f "$tmp" + fail "cannot render the consumed record" + fi + chmod 600 "$tmp" || { rm -f "$tmp"; fail "cannot secure the staged consumed record"; } + mv "$tmp" "$RECORD_PATH" || { rm -f "$tmp"; fail "cannot publish the consumed record"; } +} + +command_decide() { + [ "$#" -eq 3 ] || fail "usage: fm-opencode-permission.sh decide <task-id> <request-id> <once|always|reject>" + local task_id=$1 request_id=$2 decision=$3 session_id body response tmp lock + validate_slug task-id "$task_id" + validate_slug request-id "$request_id" + case "$decision" in + once|always|reject) ;; + *) fail "refusing: '$decision' is not one of once, always, reject; no grant was made" ;; + esac + + # Refuse an unknown request before taking any lock, so a task with no records + # at all fails fast instead of waiting on a lock. + load_record "$task_id" "$request_id" + + # The whole read-check-consume sequence is one critical section per request. + # Without it two decides arriving together both read `pending` and both post: + # the record state alone cannot prevent that, because the check and the + # transition are separate operations. The lock is what makes "applied once" + # true rather than merely intended. + # + # The lock lives directly in state/, never inside the per-task record + # directory: a lock whose parent directory does not exist yet cannot be + # created by the lock primitive, and waiting on one is an unbounded spin + # rather than a refusal. state/ is this home's own durable root, so its + # parent always exists, and both path components are validated slugs. + lock="$STATE/.opencode-permission-$task_id-$request_id.lock" + fm_lock_acquire_wait "$lock" || fail "refusing: cannot take the decision lock for $request_id" + + # Re-read under the lock: the read above was only a fast refusal, and this + # one is the authoritative state the decision is based on. + load_record "$task_id" "$request_id" + body=$RECORD_BODY + session_id=$(json_field "$body" session_id) + validate_slug session-id "$session_id" + require_pending "$body" + require_current_generation "$task_id" "$body" + require_pending_on_server "$session_id" "$request_id" "$body" + + consume "$body" "$decision" + + if ! response=$("$(opencode_bin)" api POST \ + "/api/session/$session_id/permission/$request_id/reply" \ + -d "$(jq -nc --arg decision "$decision" '{decision:$decision}')" 2>&1); then + write_state "$body" "consumed" "$decision" "$response" + fm_lock_release "$lock" + fail "the captain's answer was recorded as consumed but the server refused it; no access was granted: $response" + fi + write_state "$body" "replied" "$decision" + fm_lock_release "$lock" + printf 'applied %s to %s\n' "$decision" "$request_id" +} + +command_settle() { + [ "$#" -eq 3 ] || fail "usage: fm-opencode-permission.sh settle <task-id> <request-id> <once|always|reject>" + local task_id=$1 request_id=$2 decision=$3 body + validate_slug task-id "$task_id" + validate_slug request-id "$request_id" + case "$decision" in + once|always|reject) ;; + *) fail "refusing: '$decision' is not one of once, always, reject" ;; + esac + load_record "$task_id" "$request_id" + body=$RECORD_BODY + case "$(json_field "$body" state)" in + replied) printf 'already settled %s\n' "$request_id"; return 0 ;; + esac + write_state "$body" "replied" "$decision" + printf 'settled %s as %s\n' "$request_id" "$decision" +} + +case "${1:-}" in + ask) shift; command_ask "$@" ;; + decide) shift; command_decide "$@" ;; + settle) shift; command_settle "$@" ;; + -h|--help|"") + awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$0" + ;; + *) fail "unknown subcommand: $1" ;; +esac diff --git a/bin/fm-spawn.sh b/bin/fm-spawn.sh index 06b54d5f2e4..f4912c53b6a 100755 --- a/bin/fm-spawn.sh +++ b/bin/fm-spawn.sh @@ -4207,6 +4207,45 @@ export default { }; EOF exclude_path '.opencode/plugins/fm-busy-state.js' + # OpenCode 2 renders a permission ask as a modal inside the worker's own + # TUI, which the captain never sees and firstmate has no record of: the ask + # simply blocks the worker. This plugin is the only thing that makes a real + # ask reach the captain, so it records and delegates and decides nothing + # itself. bin/fm-opencode-permission.sh owns the ask, the durable record, + # the captain decision, and every fail-closed check. + cat >"$WT/.opencode/plugins/fm-opencode-permission.js" <<EOF +// Firstmate OpenCode permission bridge; written by fm-spawn under the contract +// owned by bin/fm-opencode-permission.sh. Records every permission.asked event +// for this task's sessions and hands it to that script, which verifies the +// request against the live server before anything is pushed to the captain. +// Deliberately no decision logic, no grant, and no second notification path: a +// plugin that approved anything here would be exactly the invisible grant this +// exists to remove. +import { execFile } from "node:child_process"; +const run = (...args) => + new Promise((resolve) => { + execFile("$FM_ROOT/bin/fm-opencode-permission.sh", args, () => resolve()); + }); +export default { + id: "fm-opencode-permission", + setup(ctx) { + const controller = new AbortController(); + void (async () => { + try { + for await (const event of ctx.event.subscribe({ signal: controller.signal })) { + if (event?.type !== "permission.asked") continue; + const data = event.data || {}; + if (!data.id || !data.sessionID) continue; + await run("ask", "$ID", data.sessionID, data.id); + } + } catch { + } + })(); + return () => controller.abort(); + }, +}; +EOF + exclude_path '.opencode/plugins/fm-opencode-permission.js' ;; pi | pi-signed) # Written OUTSIDE the worktree: pi's project-trust gate fires on any extension diff --git a/bin/fm-teardown.sh b/bin/fm-teardown.sh index 5ca0e3ce3dd..5923ab0bae8 100755 --- a/bin/fm-teardown.sh +++ b/bin/fm-teardown.sh @@ -3608,6 +3608,10 @@ rm -f "$STATE/$ID.turn-ended" "$STATE/$ID.progress" \ # retired endpoint; teardown only runs after landing is confirmed, so any # leftover unhandled steer here is moot rather than unlanded work. rm -rf "$STATE/$ID.inbox" +# OpenCode permission request records (bin/fm-opencode-permission.sh). The +# retired endpoint cannot answer them anymore, so the records go with it; a +# request that was never answered has already expired on the server. +rm -rf "$STATE/$ID.opencode-permission" # The record is gone, so the backlog must not still show this task in flight # when teardown reports success. Still under this task's meta lock, so a steer # racing the same id stays serialized exactly as it was before. A captain-held diff --git a/docs/scripts.md b/docs/scripts.md index c78501083d1..d50452a871e 100644 --- a/docs/scripts.md +++ b/docs/scripts.md @@ -156,6 +156,7 @@ The shared no-mistakes gate refusal for fleet lifecycle entrypoints is summarize | `fm-discord-notify.js` | Persist and deliver self-hosted Discord decision notifications through the REST API | | `fm-discord-poll.sh` | Invoke the bounded self-hosted Discord poll for mentions and authorized decision replies | | `fm-discord-poll.js` | Poll Discord messages, capture authorized decision replies, and emit inbox wakes | +| `fm-opencode-permission.sh` | Record a real OpenCode permission request, push it to the captain as a keyed decision, and apply the keyed answer to exactly that request | | `fm-x-reply.sh` | Post or dry-run preview a composed Relay reply or follow-up | | `fm-x-dismiss.sh` | Dismiss a skipped Relay mention at the relay without replying | | `fm-x-link.sh` | Link a spawned task to its originating Relay mention in task meta | diff --git a/tests/fm-captain-hold-lifecycle.test.sh b/tests/fm-captain-hold-lifecycle.test.sh index 55b44bbf7d1..6e896223159 100755 --- a/tests/fm-captain-hold-lifecycle.test.sh +++ b/tests/fm-captain-hold-lifecycle.test.sh @@ -2412,6 +2412,68 @@ test_answer_one_keeps_multiline_reply_in_one_field() { pass "answer-one folds embedded separators before keyed resolution" } +test_answer_one_occurrence_guard_refuses_a_superseded_question() { + local home show + home=$(make_home answer-one-occurrence) + run_captain "$home" hold sample-occurrence --title "Choose an answer" \ + --reason "first question" --repo sample >/dev/null \ + || fail "could not register the occurrence fixture" + + # The pushed decision key is captain-hold-<task-id>-<occurrence>, and a fresh + # hold starts at occurrence 1. Answer it with a release so the row stays open + # and can carry the next question, which is the shape a re-held call has. + printf 'yes, and keep the row open\n' > "$home/first.txt" + run_captain "$home" answer sample-occurrence --decision-file "$home/first.txt" --release >/dev/null \ + || fail "could not answer and release the occurrence fixture" + + # Re-held: a NEW question is now pending, at occurrence 2. A reply that + # arrives for the occurrence 1 message must not answer it. + run_captain "$home" hold sample-occurrence \ + --reason "second question" >/dev/null \ + || fail "could not re-hold the occurrence fixture" + printf 'stale reply to the first question\n' > "$home/stale.txt" + if run_captain "$home" answer-one sample-occurrence "stale reply to the first question" \ + "Discord reply" --source discord-selfhosted --expect-occurrence 1 \ + > "$home/stale.out" 2> "$home/stale.err"; then + fail "a reply to a superseded question resolved the newer occurrence" + fi + assert_contains "$(cat "$home/stale.err")" "occurrence 2" \ + "the refusal must name the current occurrence" + show=$(tasks_in "$home" show sample-occurrence --full) + assert_contains "$show" "second question" \ + "the re-held question must still be the open one" + assert_not_contains "$show" "Answer: stale reply to the first question" \ + "the stale reply was recorded as the captain's answer" + + # The occurrence the current decision was asked at still applies. + run_captain "$home" answer-one sample-occurrence "yes to the second" "Discord reply" \ + --source discord-selfhosted --expect-occurrence 2 >/dev/null \ + || fail "answer-one refused the current occurrence" + pass "answer-one refuses a reply to a superseded occurrence and applies the current one" +} + +test_answer_one_occurrence_guard_refuses_without_a_captain_hold() { + local home + home=$(make_home answer-one-occurrence-unheld) + tasks_in "$home" add sample-not-held --title "No hold" >/dev/null 2>&1 \ + || fail "could not register the unheld fixture" + if run_captain "$home" answer-one sample-not-held "yes" "Discord reply" \ + --source discord-selfhosted --expect-occurrence 1 \ + > "$home/unheld.out" 2> "$home/unheld.err"; then + fail "an occurrence guard passed on a task that is not held for the captain" + fi + assert_contains "$(cat "$home/unheld.err")" "not currently held for the captain" \ + "the refusal must name the missing captain hold" + if run_captain "$home" answer-one sample-not-held "yes" "Discord reply" \ + --source discord-selfhosted --expect-occurrence zero \ + > "$home/bad.out" 2> "$home/bad.err"; then + fail "a non-numeric occurrence was accepted" + fi + assert_contains "$(cat "$home/bad.err")" "positive integer" \ + "a non-numeric occurrence must be refused before any read" + pass "the occurrence guard refuses a task that is not captain-held, and a non-numeric occurrence" +} + test_origin_slug_validation_precedes_path_construction() { local home home=$(make_home slug-validation) @@ -4070,6 +4132,8 @@ test_legacy_identities_keep_working test_board_answer_reaches_the_keyed_answer_intake test_chat_channel_feeds_the_same_keyed_answer_intake test_answer_one_keeps_multiline_reply_in_one_field +test_answer_one_occurrence_guard_refuses_a_superseded_question +test_answer_one_occurrence_guard_refuses_without_a_captain_hold test_origin_slug_validation_precedes_path_construction test_status_resolution_over_an_open_hold_is_signalled test_legitimate_holds_produce_no_divergence_signal diff --git a/tests/fm-discord-decision-push.test.sh b/tests/fm-discord-decision-push.test.sh index fe7ccb2b06a..6cb60251df8 100644 --- a/tests/fm-discord-decision-push.test.sh +++ b/tests/fm-discord-decision-push.test.sh @@ -350,6 +350,43 @@ EOF assert_equals "1352000000000001000" "$(jq -r '.replied_to.message_id' "$record")" "notification accepts only one reply" pass "reply to a pushed decision enters x-inbox with keyed answer context" } +test_perm_ask_reply_carries_the_identity_the_applier_needs() { + local home record wake req inbox + home="$TMP_ROOT/perm-ask-reply" + mkdir -p "$home/state/x-context" "$home/state/x-inbox" + chmod 700 "$home/state" "$home/state/x-context" "$home/state/x-inbox" + make_fake_node "$home" + record="$home/state/x-context/discord-notify-test.json" + cat > "$record" <<'EOF' +{"schema":"fm-discord-decision-notification.v1","kind":"decision-notification","state":"sent","task_id":"oc-perm-task","key":"perm-per_abc123","trigger":"perm-ask","channel_id":"1000000000000000001","message_id":"1352000000000002000","summary":"OpenCode worker needs permission: action=external_directory resource=/tmp/x/*","options":["Approve once","Approve once and remember this","Reject the request"],"recorded_at":1790319000} +EOF + chmod 600 "$record" + FM_TEST_REAL_NODE=$(command -v node) \ + FM_DISCORD_FAKE_MESSAGES='[{"id":"1352000000000002001","channel_id":"1000000000000000001","guild_id":"1000000000000000000","author":{"id":"8000000000000000001","username":"captain"},"content":"Approve once","message_reference":{"message_id":"1352000000000002000","channel_id":"1000000000000000001"}}]' \ + PATH="$home/fake-bin:$BASE_PATH" FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" \ + FM_DISCORD_BOT_TOKEN=fake-token FM_DISCORD_CHANNEL_ID=1000000000000000001 \ + FM_DISCORD_AUTHORIZED_USER_IDS=8000000000000000001 \ + "$ROOT/bin/fm-discord-poll.sh" > "$home/wake.log" || fail "poll failed" + wake=$(cat "$home/wake.log") + req=discord-sh-1352000000000002001 + assert_equals "x-mention $req" "$wake" "the permission reply wakes the responder" + inbox="$home/state/x-inbox/$req.json" + assert_present "$inbox" "the permission reply is captured in the existing inbox" + assert_equals "discord-selfhosted-decision" "$(jq -r '.source' "$inbox")" "the permission reply is a decision reply, not fresh work" + # Everything the applier needs is already in the captured object: the task it + # belongs to, the request id behind the key, the exact options offered, and + # the channel a confirmation goes back to. + assert_equals "oc-perm-task" "$(jq -r '.decision.task_id' "$inbox")" "the owning task is carried" + assert_equals "perm-ask" "$(jq -r '.decision.trigger' "$inbox")" "the trigger is carried" + assert_equals "perm-per_abc123" "$(jq -r '.decision.key' "$inbox")" "the request key is carried" + assert_equals "3" "$(jq -r '.decision.options | length' "$inbox")" "all three decisions are carried" + assert_equals "1000000000000000001" "$(jq -r '.channel_id' "$inbox")" "the channel a confirmation posts to is carried" + assert_equals "Approve once" "$(jq -r '.text' "$inbox")" "the captain's own words are preserved" + # And the capture is durable even when this ingress run is not the watcher's. + assert_equals "1" "$(awk -F '\t' -v want="discord-$req" 'NF >= 5 && $3 == "check" && $4 == want { n++ } END { print n + 0 }' "$home/state/.wake-queue")" \ + "the captured permission reply enqueued its own durable wake" + pass "a permission reply reaches the inbox with the exact identity the applier needs" +} test_captured_reply_without_offer_recovers_one_wake() { local home record req inbox offered wake home="$TMP_ROOT/recover-reply-wake" @@ -505,6 +542,7 @@ test_stale_sending_notification_recovers_without_duplicate_post test_captain_hold_triggers_push test_captain_hold_truncates_long_reason_for_discord test_reply_to_notification_enters_existing_inbox +test_perm_ask_reply_carries_the_identity_the_applier_needs test_captured_reply_without_offer_recovers_one_wake test_unauthorized_decision_reply_is_ignored test_no_unrelated_reply_is_captured diff --git a/tests/fm-opencode-permission-plugin.test.sh b/tests/fm-opencode-permission-plugin.test.sh new file mode 100755 index 00000000000..3c5f8fc1e7d --- /dev/null +++ b/tests/fm-opencode-permission-plugin.test.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# Behavior test for the OpenCode permission bridge plugin that bin/fm-spawn.sh +# generates into a worker's worktree. +# +# It runs the REAL fm-spawn against a fake tmux pane and an isolated worktree, +# then loads the generated plugin in a plain Node host and feeds it a real +# permission.asked event, so the generated artifact, the real +# bin/fm-opencode-permission.sh, and the durable record are exercised together +# with no live OpenCode server and no Discord send. +set -u + +# shellcheck source=tests/fixtures.sh +. "$(dirname "${BASH_SOURCE[0]}")/fixtures.sh" + +TMP_ROOT=$(fm_test_tmproot fm-opencode-permission-plugin) + +test_plugin_records_a_permission_ask_and_grants_nothing() { + local rec id=oc-perm-plugin-1 out plugin call_log + rec=$(make_spawn_case oc-permission opencode "$id") + read_case_record "$rec" + out=$(run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$id" "$PROJ_DIR") + expect_code 0 $? "opencode spawn should succeed: $out" + plugin="$WT_DIR/.opencode/plugins/fm-opencode-permission.js" + assert_present "$plugin" "opencode spawn did not write the permission plugin" + + # The bridge calls the owning script; point that at a recorder so this test + # asserts what the plugin DELIVERED without granting or contacting anything. + call_log="$TMP_ROOT/oc-permission/calls.log" + : > "$call_log" + cat > "$TMP_ROOT/oc-permission/bridge.sh" <<SH +#!/usr/bin/env bash +set -u +printf '%s\n' "\$*" >> "$call_log" +SH + chmod +x "$TMP_ROOT/oc-permission/bridge.sh" + + # The generated plugin embeds the absolute path of the real script, so drive + # it with that script shadowed by the recorder through a path-preserving copy. + local shadow="$TMP_ROOT/oc-permission/shadow" + mkdir -p "$shadow" + sed "s|$ROOT/bin/fm-opencode-permission.sh|$TMP_ROOT/oc-permission/bridge.sh|" \ + "$plugin" > "$shadow/fm-opencode-permission.js" + + out=$(drive_oc_permission_plugin "$shadow/fm-opencode-permission.js" \ + '{"type":"permission.asked","data":{"id":"per_plugintest00001","sessionID":"ses_plugintest001","action":"external_directory","resources":["/tmp/x/*"],"save":["/tmp/x/*"]}}' \ + '{"type":"permission.asked","data":{"sessionID":"ses_plugintest001"}}' \ + '{"type":"session.idle","data":{"sessionID":"ses_plugintest001"}}') \ + || fail "driving the permission plugin failed: $out" + + # Exactly the permission.asked event with a complete identity is delivered, + # with this task's id and the event's own session and request. The event + # missing an id and the unrelated event type are both dropped. + assert_equals "ask $id ses_plugintest001 per_plugintest00001" \ + "$(cat "$call_log")" "the plugin forwards only the complete permission.asked identity" + pass "the generated plugin forwards a real permission.asked identity to the owning script and nothing else" +} + +make_spawn_case() { # <name> <harness> <id> + local name=$1 harness=$2 id=$3 case_dir home proj wt fakebin + case_dir="$TMP_ROOT/$name" + home="$case_dir/home" + proj="$case_dir/project" + wt="$case_dir/wt" + fakebin=$(make_spawn_fakebin "$case_dir/fake" pi opencode claude codex gemini) + fm_test_spawn_home "$home" "$harness" + fm_git_worktree "$proj" "$wt" "wt-$name" + fm_test_spawn_brief "$home" "$id" + printf '%s\n' "$case_dir|$home|$proj|$wt|$fakebin" +} + +run_spawn() { # <home> <wt> <fakebin> <spawn-args...> + local home=$1 wt=$2 fakebin=$3 + shift 3 + GROK_HOME="$home/grok-home" \ + fm_test_run_spawn "$home" "$wt" "$fakebin" "$@" --mode no-mistakes --yolo off +} + +read_case_record() { + # shellcheck disable=SC2034 # CASE_DIR is part of the shared record shape + IFS='|' read -r CASE_DIR HOME_DIR PROJ_DIR WT_DIR FAKEBIN_DIR <<EOF +$1 +EOF +} + +# drive_oc_permission_plugin <plugin> <event-json>...: load a generated plugin +# in a plain Node host, feed it the queued events, and wait for the stream to +# drain so an execFile the plugin awaits has actually run. The same seam +# tests/fm-busy-adapter-wiring.test.sh uses for the busy-state plugin. +drive_oc_permission_plugin() { + local plugin=$1 + shift + PLUGIN_PATH="$plugin" node --input-type=module - "$@" 2>&1 <<'EOF' +import { pathToFileURL } from "node:url"; +const mod = await import(pathToFileURL(process.env.PLUGIN_PATH).href); +if (!mod.default || typeof mod.default.setup !== "function") { + throw new Error("generated plugin is not an OpenCode 2 default export with setup()"); +} +const queued = process.argv.slice(2).map((arg) => JSON.parse(arg)); +let drained = false; +const ctx = { + event: { + subscribe({ signal } = {}) { + return (async function* () { + for (const event of queued) { + if (signal?.aborted) return; + yield event; + } + drained = true; + })(); + }, + }, +}; +const cleanup = await mod.default.setup(ctx); +const deadline = Date.now() + 5000; +while (!drained && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); +} +if (!drained) throw new Error("plugin never drained the event stream"); +await new Promise((resolve) => setTimeout(resolve, 500)); +cleanup?.(); +EOF +} + +test_plugin_records_a_permission_ask_and_grants_nothing +echo "all fm-opencode-permission-plugin tests passed" diff --git a/tests/fm-opencode-permission.test.sh b/tests/fm-opencode-permission.test.sh new file mode 100755 index 00000000000..820e78380a6 --- /dev/null +++ b/tests/fm-opencode-permission.test.sh @@ -0,0 +1,510 @@ +#!/usr/bin/env bash +# Behavior tests for the OpenCode permission decision bridge and the Discord +# capture wake. Every case drives the real scripts through their public +# interface against a fake opencode client and a fake Discord bot; nothing here +# contacts a live OpenCode server or Discord. +set -u + +# shellcheck source=tests/lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +BASE_PATH=${FM_TEST_BASE_PATH:-/usr/bin:/bin:/usr/sbin:/sbin} +JQ_DIR=$(command -v jq 2>/dev/null) && JQ_DIR=$(dirname "$JQ_DIR") || JQ_DIR= +[ -n "$JQ_DIR" ] && BASE_PATH="$JQ_DIR:$BASE_PATH" +PASTE_DIR=$(command -v paste 2>/dev/null) && PASTE_DIR=$(dirname "$PASTE_DIR") || PASTE_DIR= +[ -n "$PASTE_DIR" ] && BASE_PATH="$PASTE_DIR:$BASE_PATH" + +TMP_ROOT=$(fm_test_tmproot fm-opencode-permission-tests) + +TASK=firstmate-perm-test-20261001 +SESSION=ses_permtest0000000001 +REQUEST=per_permtest000000001 + +# A fake `opencode` whose behavior is driven by two env vars, so each test +# states the server state it needs instead of the script knowing about tests. +# FM_FAKE_PERM_STATE=pending the request is live and answerable +# FM_FAKE_PERM_STATE=gone the server no longer reports it (expired/answered) +# FM_FAKE_PERM_STATE=mismatch the server reports a different id or session +# FM_FAKE_PERM_STATE=refuse the reply POST fails +# FM_FAKE_PERM_CALLS records every invocation, so a test can prove that a +# refused decision issued no API write at all. +make_fake_opencode() { + local home=$1 + mkdir -p "$home/fake-bin" + cat > "$home/fake-bin/opencode" <<'SH' +#!/usr/bin/env bash +set -u +printf '%s\n' "$*" >> "$FM_FAKE_PERM_CALLS" +[ "${1:-}" = api ] || exit 0 +state=${FM_FAKE_PERM_STATE:-pending} +case "${2:-}" in + GET) ;; + POST) ;; + *) exit 0 ;; +esac +path=${3:-} +case "$path" in + */permission/*/reply) + [ "$state" = refuse ] && { echo '{"_tag":"InvalidRequestError","message":"refused"}' >&2; exit 1; } + [ "$state" = gone ] && { echo 'not found' >&2; exit 1; } + printf '{"data":{"id":"%s","effect":"allow"}}\n' "$FM_FAKE_PERM_REQUEST" + ;; + */permission/*) + case "$state" in + gone) echo 'not found' >&2; exit 1 ;; + mismatch) printf '{"id":"per_someoneelse","sessionID":"ses_someoneelse","action":"external_directory","resources":["/tmp/x"]}\n' ;; + *) printf '{"id":"%s","sessionID":"%s","action":"external_directory","resources":["/tmp/fake-probe/*"],"save":["/tmp/fake-probe/*"],"metadata":{}}\n' \ + "$FM_FAKE_PERM_REQUEST" "$FM_FAKE_PERM_SESSION" ;; + esac + ;; +esac +SH + chmod +x "$home/fake-bin/opencode" +} + +# A task record plus a busy generation, which is what makes a decide's +# generation check meaningful rather than vacuous. +arm_task() { # <home> + local home=$1 + mkdir -p "$home/state" + chmod 700 "$home/state" + printf 'g1.1.1\n' > "$home/state/$TASK.busy-gen" + chmod 600 "$home/state/$TASK.busy-gen" +} + +# perm_env <home> <fake-state> -> the env assignments for the script under test. +# Passed through `env` rather than exported, so the assignments are scoped to +# exactly one invocation and never reach the rest of the suite. +perm_env() { + local home=$1 state=$2 + printf '%s\n' \ + "FM_FAKE_PERM_STATE=$state" \ + "FM_FAKE_PERM_REQUEST=$REQUEST" \ + "FM_FAKE_PERM_SESSION=$SESSION" \ + "FM_FAKE_PERM_CALLS=$home/state/opencode-calls.log" \ + "PATH=$home/fake-bin:$BASE_PATH" \ + "FM_HOME=$home" \ + "FM_STATE_OVERRIDE=$home/state" +} + +# run_perm <home> <fake-state> <subcommand> [args...]: run the script under +# test against a fake opencode whose server state this test states. +run_perm() { + local home=$1 state=$2 + shift 2 + local -a assigns=() + mapfile -t assigns < <(perm_env "$home" "$state") + env "${assigns[@]}" "$ROOT/bin/fm-opencode-permission.sh" "$@" +} + +test_ask_records_only_a_server_confirmed_request() { + local home out rc record + home="$TMP_ROOT/ask-confirmed"; arm_task "$home" + make_fake_opencode "$home" + out=$(run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" 2>"$home/err"); rc=$? + expect_code 0 "$rc" "ask exit" + assert_equals "perm-$REQUEST" "$out" "ask prints the decision key" + + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_present "$record" "request record written" + assert_equals "pending" "$(jq -r '.state' "$record")" "record starts pending" + assert_equals "$SESSION" "$(jq -r '.session_id' "$record")" "record binds the session" + assert_equals "g1.1.1" "$(jq -r '.generation' "$record")" "record captures the task generation" + assert_equals "/tmp/fake-probe/*" "$(jq -r '.resources[0]' "$record")" "record captures the resource" + assert_equals "/tmp/fake-probe/*" "$(jq -r '.save[0]' "$record")" "record captures the save pattern" + pass "ask records only a request the live server confirms" +} + +test_ask_refuses_a_request_the_server_does_not_confirm() { + local home out rc record + home="$TMP_ROOT/ask-gone"; arm_task "$home" + make_fake_opencode "$home" + out=$(run_perm "$home" gone \ + ask "$TASK" "$SESSION" "$REQUEST" 2>"$home/err"); rc=$? + [ "$rc" -ne 0 ] || fail "ask must fail when the server reports no request" + assert_absent "$home/state/$TASK.opencode-permission/$REQUEST.json" "no record for an unconfirmed request" + assert_contains "$(cat "$home/err")" "refusing" "refusal names itself as a refusal" + pass "ask refuses a request the server does not report" +} + +test_ask_refuses_a_mismatched_identity() { + local home rc + home="$TMP_ROOT/ask-mismatch"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" mismatch \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "ask must fail when the server reports a different identity" + assert_absent "$home/state/$TASK.opencode-permission/$REQUEST.json" "no record for a mismatched identity" + pass "ask refuses when the server's id or session is not the requested one" +} + +test_ask_refuses_without_a_task_generation() { + local home rc + home="$TMP_ROOT/ask-nogen"; mkdir -p "$home/state"; chmod 700 "$home/state" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "ask must fail when the task has no current generation" + assert_absent "$home/state/$TASK.opencode-permission/$REQUEST.json" "no record without a generation to check later" + pass "ask refuses when the task generation is unreadable, so a later answer cannot be proven current" +} + +test_decide_applies_once_and_refuses_a_replay() { + local home first record calls + home="$TMP_ROOT/decide-once"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + first=$(run_perm "$home" pending \ + decide "$TASK" "$REQUEST" once 2>"$home/err"); rc=$? + expect_code 0 "$rc" "first decide exit" + assert_contains "$first" "applied once" "first decide reports the applied decision" + + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "replied" "$(jq -r '.state' "$record")" "record closes as replied" + assert_equals "once" "$(jq -r '.decision' "$record")" "record carries the decision as the receipt" + + # The replay runs against a server that would happily answer again, so a + # non-refusal here would be a second real grant. + run_perm "$home" pending \ + decide "$TASK" "$REQUEST" always >"$home/replay.out" 2>"$home/err2"; rc=$? + [ "$rc" -ne 0 ] || fail "a replayed decide must be refused" + assert_contains "$(cat "$home/err2")" "already" "replay refusal names the spent state" + assert_equals "once" "$(jq -r '.decision' "$record")" "a refused replay does not overwrite the applied decision" + pass "decide applies the captain's answer once and refuses the replay without granting again" +} + +test_decide_refuses_an_expired_request_without_writing() { + local home rc record calls_after + home="$TMP_ROOT/decide-expired"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + : > "$home/state/opencode-calls.log" + run_perm "$home" gone \ + decide "$TASK" "$REQUEST" always >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "decide must fail when the request is no longer pending" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "pending" "$(jq -r '.state' "$record")" "an expired request stays pending, never consumed" + calls_after=$(grep -c reply "$home/state/opencode-calls.log" 2>/dev/null || true) + assert_equals "0" "$calls_after" "no reply POST was issued for an expired request" + pass "decide refuses an expired request and issues no API write" +} + +test_decide_refuses_a_stale_task_generation() { + local home rc record + home="$TMP_ROOT/decide-stale-gen"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + # The task was relaunched: a new generation means a different run. + printf 'g2.2.2\n' > "$home/state/$TASK.busy-gen" + run_perm "$home" pending \ + decide "$TASK" "$REQUEST" once >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "decide must fail for a stale task generation" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "pending" "$(jq -r '.state' "$record")" "a stale-generation request stays pending" + assert_contains "$(cat "$home/err")" "generation" "refusal names the generation mismatch" + pass "decide refuses an answer to a task generation that has moved on" +} + +test_decide_refuses_a_foreign_task() { + local home other rc record + home="$TMP_ROOT/decide-foreign"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + other=some-other-task-20261001 + printf 'g1.1.1\n' > "$home/state/$other.busy-gen" + # Another task id addresses its own record directory, so this task's request + # is simply not there to be answered. + run_perm "$home" pending \ + decide "$other" "$REQUEST" once >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "another task must not be able to answer this request" + assert_contains "$(cat "$home/err")" "no permission request record" "the foreign task id reaches no record" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "pending" "$(jq -r '.state' "$record")" "the owning task's request stays pending" + + # And a record planted under a foreign task's directory is still refused on + # the task binding it carries, so copying a record cannot move a decision. + mkdir -p "$home/state/$other.opencode-permission" + cp "$record" "$home/state/$other.opencode-permission/$REQUEST.json" + run_perm "$home" pending \ + decide "$other" "$REQUEST" once >/dev/null 2>"$home/err2"; rc=$? + [ "$rc" -ne 0 ] || fail "a copied record must not be answerable under another task id" + assert_contains "$(cat "$home/err2")" "belongs to task" "the refusal names the task the record actually belongs to" + pass "one task's request cannot be answered by another task id, and a copied record is refused on its own binding" +} + +test_decide_refuses_an_unknown_decision() { + local home rc record + home="$TMP_ROOT/decide-bad-decision"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + run_perm "$home" pending \ + decide "$TASK" "$REQUEST" yes >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "a decision outside the server's enum must be refused" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "pending" "$(jq -r '.state' "$record")" "an unusable decision leaves the request pending" + pass "decide refuses a decision outside once/always/reject without granting" +} + +test_decide_records_a_consumed_receipt_when_the_server_refuses() { + local home rc record + home="$TMP_ROOT/decide-server-refusal"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + run_perm "$home" refuse \ + decide "$TASK" "$REQUEST" always >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "a server refusal must surface as a failure" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "consumed" "$(jq -r '.state' "$record")" "the spent answer stays consumed, not retryable" + assert_equals "always" "$(jq -r '.decision' "$record")" "the receipt records what the captain chose" + assert_contains "$(jq -r '.apply_error' "$record")" "refused" "the receipt carries the server's exact refusal" + pass "a server refusal leaves a consumed receipt naming the error, and never grants" +} + +test_settle_closes_the_record_without_an_api_write() { + local home out rc record calls + home="$TMP_ROOT/settle"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + : > "$home/state/opencode-calls.log" + out=$(run_perm "$home" pending \ + settle "$TASK" "$REQUEST" reject 2>"$home/err"); rc=$? + expect_code 0 "$rc" "settle exit" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "replied" "$(jq -r '.state' "$record")" "settle closes the record" + assert_equals "reject" "$(jq -r '.decision' "$record")" "settle records the decision" + calls=$(grep -c reply "$home/state/opencode-calls.log" 2>/dev/null || true) + assert_equals "0" "$calls" "settle issues no reply POST of its own" + # And a decided record can no longer be decided, whatever asked first. + run_perm "$home" pending \ + decide "$TASK" "$REQUEST" always >/dev/null 2>"$home/err2" \ + && fail "a settled request must not be decidable again" + pass "settle closes the audit record on an externally applied decision and posts nothing" +} + +test_ask_is_idempotent_and_keeps_the_original_record() { + local home record + home="$TMP_ROOT/ask-idempotent"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + local before after + before=$(cat "$record") + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + after=$(cat "$record") + assert_equals "$before" "$after" "a repeated ask leaves the captured identity untouched" + pass "a repeated ask for the same request does not rewrite its record" +} + +test_concurrent_decides_post_exactly_once() { + local home record posts + home="$TMP_ROOT/decide-concurrent"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + # A slow reply so both decides are inside the read-check-consume window + # together, which is the only way a record-state check alone can be raced. + cat > "$home/fake-bin/opencode" <<'SH' +#!/usr/bin/env bash +set -u +printf '%s\n' "$*" >> "$FM_FAKE_PERM_CALLS" +case "${3:-}" in + */reply) sleep 1; printf '{"data":{"id":"%s","effect":"allow"}}\n' "$FM_FAKE_PERM_REQUEST" ;; + *) printf '{"id":"%s","sessionID":"%s","action":"external_directory","resources":["/tmp/fake-probe/*"],"save":["/tmp/fake-probe/*"],"metadata":{}}\n' \ + "$FM_FAKE_PERM_REQUEST" "$FM_FAKE_PERM_SESSION" ;; +esac +SH + chmod +x "$home/fake-bin/opencode" + mapfile -t assigns < <(perm_env "$home" pending) + env "${assigns[@]}" "$ROOT/bin/fm-opencode-permission.sh" decide "$TASK" "$REQUEST" once \ + > "$home/a.out" 2>"$home/a.err" & + local a=$! + env "${assigns[@]}" "$ROOT/bin/fm-opencode-permission.sh" decide "$TASK" "$REQUEST" always \ + > "$home/b.out" 2>"$home/b.err" & + local b=$! + wait "$a"; wait "$b" + + posts=$(grep -c '/reply' "$home/state/opencode-calls.log" 2>/dev/null || true) + assert_equals "1" "$posts" "two concurrent decides issued exactly one reply POST" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "replied" "$(jq -r '.state' "$record")" "the record closed on the single applied answer" + case "$(jq -r '.decision' "$record")" in + once|always) ;; + *) fail "the record does not carry one of the two racing decisions" ;; + esac + pass "two concurrent decides apply exactly one answer, not two grants" +} + +test_the_documented_reply_derivation_reaches_the_right_request() { + local home inbox out rc record + home="$TMP_ROOT/documented-derivation"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + + # A captured decision reply, in exactly the shape bin/fm-discord-poll.js + # writes. The next block derives its arguments the way the fmx-respond skill + # documents, so this test fails if that documented derivation ever drifts + # away from what the applier actually accepts. + mkdir -p "$home/state/x-inbox" + chmod 700 "$home/state/x-inbox" + inbox="$home/state/x-inbox/discord-sh-1352000000000002001.json" + jq -n --arg task "$TASK" --arg key "perm-$REQUEST" \ + '{request_id:"discord-sh-1352000000000002001", text:"Approve once", + source:"discord-selfhosted-decision", channel_id:"1000000000000000001", + message_id:"1352000000000002001", + decision:{task_id:$task, key:$key, trigger:"perm-ask", + options:["Approve once","Approve once and remember this","Reject the request"]}}' \ + > "$inbox" + chmod 600 "$inbox" + + local decision_task decision_key request_id decision + decision_task=$(jq -r '.decision.task_id' "$inbox") + decision_key=$(jq -r '.decision.key' "$inbox") + request_id=${decision_key#perm-} + # The captain chose "Approve once", which the skill maps to `once`. + decision=once + + out=$(run_perm "$home" pending decide "$decision_task" "$request_id" "$decision" 2>"$home/err"); rc=$? + expect_code 0 "$rc" "the documented derivation reaches the right request" + assert_contains "$out" "applied once" "the derived invocation applied the captain's choice" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "replied" "$(jq -r '.state' "$record")" "the derived invocation closed the real record" + pass "the derivation the skill documents turns a captured reply into the right applied answer" +} + +test_ask_records_a_resource_containing_a_comma_verbatim() { + # A delimiter round trip between the server's list and the record would + # silently narrow or widen the scope the captain is shown and the applier + # later checks, so the list is carried as JSON. + local home record calls + home="$TMP_ROOT/ask-comma"; arm_task "$home" + make_fake_opencode "$home" + cat > "$home/fake-bin/opencode" <<'SH' +#!/usr/bin/env bash +set -u +printf '%s\n' "$*" >> "$FM_FAKE_PERM_CALLS" +printf '{"id":"%s","sessionID":"%s","action":"external_directory","resources":["/tmp/a,b/*","/tmp/plain/*"],"save":["/tmp/a,b/*"],"metadata":{}}\n' \ + "$FM_FAKE_PERM_REQUEST" "$FM_FAKE_PERM_SESSION" +SH + chmod +x "$home/fake-bin/opencode" + run_perm "$home" pending ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>"$home/err" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + assert_equals "/tmp/a,b/*" "$(jq -r '.resources[0]' "$record")" "a comma-bearing resource is stored verbatim" + assert_equals "2" "$(jq -r '.resources | length' "$record")" "the resource list keeps its own boundaries" + assert_equals "/tmp/plain/*" "$(jq -r '.resources[1]' "$record")" "the following resource is not merged into the first" + assert_equals "/tmp/a,b/*" "$(jq -r '.save[0]' "$record")" "a comma-bearing save pattern is stored verbatim" + pass "a resource or save pattern containing a comma is recorded and shown verbatim" +} + +test_discord_capture_enqueues_a_durable_wake() { + local home wake_rows + home="$TMP_ROOT/discord-wake" + mkdir -p "$home/state/x-inbox" "$home/state/x-context" + chmod 700 "$home/state" "$home/state/x-inbox" "$home/state/x-context" + mkdir -p "$home/fake-bin" + # Reuse the connector's own fetch seam: a bot mention the poll captures. + cat > "$home/fake-bin/node" <<'SH' +#!/usr/bin/env bash +set -u +exec "$FM_TEST_REAL_NODE" --input-type=module -e ' + import { pathToFileURL } from "node:url"; + const script = process.argv[1]; + const messages = JSON.parse(process.env.FM_DISCORD_FAKE_MESSAGES || "[]"); + globalThis.fetch = async (url) => { + if (url === "https://discord.com/api/v10/users/@me") return Response.json({ id: "9000000000000000001" }); + if (url.includes("/channels/")) return Response.json(messages); + return new Response("not found", { status: 404 }); + }; + await import(pathToFileURL(script).href); +' "$1" +SH + chmod +x "$home/fake-bin/node" + + # Run the poll the way an operator-run or LaunchAgent-run ingress does: its + # stdout goes to a log, so only a durable wake can reach a session. + FM_TEST_REAL_NODE=$(command -v node) \ + FM_DISCORD_FAKE_MESSAGES='[{"id":"1352000000000000199","channel_id":"1000000000000000001","guild_id":"1000000000000000000","author":{"username":"captain"},"mentions":[{"id":"9000000000000000001"}],"content":"<@9000000000000000001> yes","attachments":[]}]' \ + PATH="$home/fake-bin:$BASE_PATH" FM_HOME="$home" FM_STATE_OVERRIDE="$home/state" FM_DISCORD_BOT_TOKEN="fake-test-token" \ + FM_DISCORD_CHANNEL_ID="1000000000000000001" FM_DISCORD_EXCLUDE_CHANNELS="1551134713727426570" \ + "$ROOT/bin/fm-discord-poll.sh" > "$home/ingress.log" 2>"$home/ingress.err" + + wake_rows=$(awk -F '\t' 'NF >= 5 && $3 == "check" && $4 == "discord-discord-sh-1352000000000000199"' \ + "$home/state/.wake-queue" 2>/dev/null | wc -l | tr -d ' ') + assert_equals "1" "$wake_rows" "capture enqueued exactly one durable check wake for the captured reply" + # The stdout contract is unchanged, so the watcher's own dispatch still works. + assert_contains "$(cat "$home/ingress.log")" "x-mention discord-sh-1352000000000000199" "stdout wake line is preserved" + pass "a capture that reaches no watcher still enqueues a durable wake, and the stdout contract is unchanged" +} + +test_ask_pushes_the_captain_decision_through_the_existing_notifier() { + local home calls summary + local -a assigns + home="$TMP_ROOT/ask-pushes-decision"; arm_task "$home" + make_fake_opencode "$home" + calls="$home/state/notifier-calls.log" + # Shadow ONLY the notifier, by running the real script from a copy whose + # sibling notifier is a recorder. The script under test stays the real one. + mkdir -p "$home/shadow" + cp "$ROOT/bin/fm-opencode-permission.sh" "$home/shadow/fm-opencode-permission.sh" + cp "$ROOT/bin/fm-busy-lib.sh" "$home/shadow/fm-busy-lib.sh" + cat > "$home/shadow/fm-discord-notify.sh" <<'SH' +#!/usr/bin/env bash +set -u +printf '%s\n' "$*" >> "$FM_FAKE_NOTIFIER_CALLS" +SH + chmod +x "$home/shadow/fm-opencode-permission.sh" "$home/shadow/fm-discord-notify.sh" + + mapfile -t assigns < <(perm_env "$home" pending) + env "${assigns[@]}" "FM_FAKE_NOTIFIER_CALLS=$calls" \ + "$home/shadow/fm-opencode-permission.sh" ask "$TASK" "$SESSION" "$REQUEST" \ + > "$home/out" 2>"$home/err" + assert_equals "perm-$REQUEST" "$(cat "$home/out")" "ask reports the decision key" + assert_present "$calls" "the captain decision was pushed" + summary=$(cat "$calls") + assert_contains "$summary" "perm-ask $TASK perm-$REQUEST" "the push uses the perm-ask trigger and the perm- key" + assert_contains "$summary" "action=external_directory" "the question states the action" + assert_contains "$summary" "resource=/tmp/fake-probe/*" "the question states the resource" + assert_contains "$summary" "would save" "the question states the proposed remember scope" + assert_contains "$summary" "Recommendation:" "the question states a recommendation" + assert_contains "$summary" "Approve once|Approve once and remember this|Reject the request" \ + "the question offers exactly the three installed-API decisions" + pass "the ask reaches the existing notifier with the action, resource, save scope, and a recommendation" +} + +test_ask_refuses_an_unusable_identity() { + local home rc + home="$TMP_ROOT/ask-bad-slug"; arm_task "$home" + make_fake_opencode "$home" + run_perm "$home" pending \ + ask "$TASK" "$SESSION" "per/../../etc/passwd" >/dev/null 2>"$home/err"; rc=$? + [ "$rc" -ne 0 ] || fail "an unusable request id must be refused before any path is built" + pass "ask refuses a request id that is not a privacy-safe slug" +} + +test_ask_records_only_a_server_confirmed_request +test_ask_pushes_the_captain_decision_through_the_existing_notifier +test_ask_refuses_a_request_the_server_does_not_confirm +test_ask_refuses_a_mismatched_identity +test_ask_refuses_without_a_task_generation +test_ask_refuses_an_unusable_identity +test_ask_is_idempotent_and_keeps_the_original_record +test_ask_records_a_resource_containing_a_comma_verbatim +test_decide_applies_once_and_refuses_a_replay +test_decide_refuses_an_expired_request_without_writing +test_decide_refuses_a_stale_task_generation +test_decide_refuses_a_foreign_task +test_decide_refuses_an_unknown_decision +test_decide_records_a_consumed_receipt_when_the_server_refuses +test_settle_closes_the_record_without_an_api_write +test_concurrent_decides_post_exactly_once +test_the_documented_reply_derivation_reaches_the_right_request +test_discord_capture_enqueues_a_durable_wake diff --git a/tests/fm-teardown.test.sh b/tests/fm-teardown.test.sh index 57d72301cfa..aacddc1693d 100755 --- a/tests/fm-teardown.test.sh +++ b/tests/fm-teardown.test.sh @@ -704,6 +704,23 @@ test_local_only_fork_remote_allows() { pass "local-only worktree with HEAD on a fork remote is torn down and the home summary is refreshed" } +test_teardown_removes_opencode_permission_records() { + local case_dir out + case_dir=$(make_case opencode-permission-records) + write_meta "$case_dir" no-mistakes ship + seed_backlog_in_flight "$case_dir" + # A permission request that was never answered is still pending here, so this + # proves the retired endpoint's records go with it rather than lingering as + # records nobody can answer. + mkdir -p "$case_dir/state/task-x1.opencode-permission" + printf '{"schema":"fm-opencode-permission-request.v1","state":"pending"}\n' \ + > "$case_dir/state/task-x1.opencode-permission/per_abc123.json" + out=$(run_teardown "$case_dir") || fail "teardown failed with a permission record present" + assert_absent "$case_dir/state/task-x1.opencode-permission" \ + "teardown left a retired task's permission request records behind" + pass "teardown removes the retired task's OpenCode permission request records" +} + test_teardown_closes_the_backlog_item_itself() { local case_dir out case_dir=$(make_case tasks-axi-close) @@ -3694,6 +3711,7 @@ EOF } test_local_only_fork_remote_allows +test_teardown_removes_opencode_permission_records test_teardown_closes_the_backlog_item_itself test_teardown_accepts_an_already_archived_done_item test_teardown_manual_backend_leaves_the_backlog_to_the_operator From dd518927f05e6859d25fdfcad75253895d3a8299 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=ED=8F=89=EC=8B=9D?= <aliceriddel@gmail.com> Date: Thu, 1 Oct 2026 17:44:40 +0900 Subject: [PATCH 2/3] fix: retry a failed captain push and show every requested path Two review findings, both real. A notification that failed once was never retried. The existing-record path in ask returned before the push, so a Discord outage left the captain never asked while the worker stayed blocked. The push is idempotent per (trigger, task, key), so it now runs on that path too, and the captured record is still left untouched. The question rendered only resources[0] and flattened the save list on spaces. Approving a request grants every resource it names, so the captain could approve scope he was never shown, and a path containing a space lost its boundary. Both lists are now carried as compact JSON and rendered whole. Each is proven by a negative control: reverting the retry fails the push-count assertion, and reverting the rendering fails the full-list assertion. --- bin/fm-opencode-permission.sh | 44 +++++++++----- tests/fm-opencode-permission.test.sh | 86 +++++++++++++++++++++++++++- 2 files changed, 114 insertions(+), 16 deletions(-) diff --git a/bin/fm-opencode-permission.sh b/bin/fm-opencode-permission.sh index 7c02805ece7..f58a3ade138 100755 --- a/bin/fm-opencode-permission.sh +++ b/bin/fm-opencode-permission.sh @@ -105,8 +105,12 @@ json_field() { # <json> <field> printf '%s' "$1" | jq -r --arg f "$2" '.[$f] // empty' 2>/dev/null || true } -json_array() { # <json> <field> -> newline-separated - printf '%s' "$1" | jq -r --arg f "$2" '(.[$f] // [])[] | tostring' 2>/dev/null || true +# Compact one-line JSON for a field, so a caller can render a list with its +# element boundaries intact. A delimiter-joined or space-joined rendering cannot +# do that: a path may contain spaces, commas, or newlines, so any delimiter the +# renderer picks can appear inside a value and silently misstate the scope. +json_compact() { # <json> <field> + printf '%s' "$1" | jq -c --arg f "$2" '(.[$f] // [])' 2>/dev/null || printf '[]' } command_ask() { @@ -130,9 +134,9 @@ command_ask() { || fail "refusing: server returned session id '$live_session' for requested session '$session_id'" action=$(json_field "$body" action) [ -n "$action" ] || fail "refusing: request $request_id carries no action" - resources=$(json_array "$body" resources) - save=$(json_array "$body" save) - [ -n "$resources" ] || fail "refusing: request $request_id names no resource" + resources=$(json_compact "$body" resources) + save=$(json_compact "$body" save) + [ "$resources" != "[]" ] || fail "refusing: request $request_id names no resource" local dir gen dir=$(record_dir "$task_id") @@ -141,6 +145,14 @@ command_ask() { # decision is checked against, and the notifier already made the push # single-fire for this key. if [ -e "$(record_path "$task_id" "$request_id")" ]; then + # A push that failed once must be retried here, or the captain never sees + # the decision and the worker stays blocked. The push is idempotent per + # (trigger, task, key) - the notifier derives its record path and Discord + # nonce from those, re-sends a prior failed record, and the poll's offered + # marker refuses a duplicate reply - so re-pushing is safe. The captured + # record is left untouched: its generation and lists are the identity a + # later decision is checked against, and come from that first server read. + push_captain_decision "$task_id" "$request_id" "$action" "$resources" "$save" printf 'perm-%s\n' "$request_id" return 0 fi @@ -179,20 +191,22 @@ command_ask() { printf 'perm-%s\n' "$request_id" } -# The captain-facing question carries what the ask is, what it touches, what -# would be remembered if the answer were `always`, and this surface's -# recommendation, so the reply is answerable from the message alone. -push_captain_decision() { # <task-id> <request-id> <action> <resources> <save> +# The captain-facing question carries what the ask is, every resource it +# touches, everything an `always` answer would remember, and this surface's +# recommendation, so the reply is answerable from the message alone. Both lists +# arrive as compact JSON and are rendered whole: a request can name several +# resources, and approving it grants all of them, so showing only the first +# would have the captain approve scope he was never shown. +push_captain_decision() { # <task-id> <request-id> <action> <resources-json> <save-json> local task_id=$1 request_id=$2 action=$3 resources=$4 save=$5 - local summary first_resource saved_note - first_resource=$(printf '%s\n' "$resources" | head -1) - if [ -n "$save" ]; then - saved_note="Choosing 'remember this' would save: $(printf '%s' "$save" | paste -sd' ' -)" + local summary saved_note + if [ "$save" != "[]" ]; then + saved_note="Choosing 'remember this' would save these paths: $save" else saved_note="Nothing would be remembered: this ask has no save pattern." fi - summary=$(printf 'OpenCode worker needs permission: action=%s resource=%s | %s | Recommendation: approve once and keep the saved scope unchanged; approve with remember only when the same path will be needed again this run.' \ - "$action" "$first_resource" "$saved_note") + summary=$(printf 'OpenCode worker needs permission: action=%s resources=%s | %s | Recommendation: approve once and keep the saved scope unchanged; approve with remember only when the same path will be needed again this run.' \ + "$action" "$resources" "$saved_note") [ "${#summary}" -le 1800 ] || summary="${summary:0:1800}…" "$SCRIPT_DIR/fm-discord-notify.sh" "$TRIGGER" "$task_id" "perm-$request_id" \ "$summary" \ diff --git a/tests/fm-opencode-permission.test.sh b/tests/fm-opencode-permission.test.sh index 820e78380a6..0b42c966089 100755 --- a/tests/fm-opencode-permission.test.sh +++ b/tests/fm-opencode-permission.test.sh @@ -305,6 +305,88 @@ test_ask_is_idempotent_and_keeps_the_original_record() { pass "a repeated ask for the same request does not rewrite its record" } +test_ask_retries_a_push_that_failed_and_leaves_the_record_untouched() { + # A notification that fails once must not be lost: the second ask for the + # same request has to retry it, or the captain never sees the decision and + # the worker stays blocked. + local home record pushes before after + home="$TMP_ROOT/ask-retry-push"; arm_task "$home" + make_fake_opencode "$home" + pushes="$home/state/notifier-calls.log" + mkdir -p "$home/shadow" + cp "$ROOT/bin/fm-opencode-permission.sh" "$home/shadow/fm-opencode-permission.sh" + cp "$ROOT/bin/fm-busy-lib.sh" "$home/shadow/fm-busy-lib.sh" + cat > "$home/shadow/fm-discord-notify.sh" <<'SH' +#!/usr/bin/env bash +set -u +printf '%s\n' "$*" >> "$FM_FAKE_NOTIFIER_CALLS" +[ "${FM_FAKE_NOTIFIER_FAIL:-0}" = 1 ] && exit 1 +exit 0 +SH + chmod +x "$home/shadow/fm-opencode-permission.sh" "$home/shadow/fm-discord-notify.sh" + : > "$pushes" + record="$home/state/$TASK.opencode-permission/$REQUEST.json" + + mapfile -t assigns < <(perm_env "$home" pending) + env "${assigns[@]}" "FM_FAKE_NOTIFIER_CALLS=$pushes" FM_FAKE_NOTIFIER_FAIL=1 \ + "$home/shadow/fm-opencode-permission.sh" ask "$TASK" "$SESSION" "$REQUEST" \ + >/dev/null 2>"$home/first.err" + assert_equals "1" "$(wc -l < "$pushes" | tr -d ' ')" "the first ask attempted the push" + assert_present "$record" "the record survives a failed push, so the decision is retryable" + assert_contains "$(cat "$home/first.err")" "push failed" "a failed push is reported as actionable" + + before=$(cat "$record") + env "${assigns[@]}" "FM_FAKE_NOTIFIER_CALLS=$pushes" \ + "$home/shadow/fm-opencode-permission.sh" ask "$TASK" "$SESSION" "$REQUEST" \ + >/dev/null 2>"$home/second.err" + after=$(cat "$record") + assert_equals "2" "$(wc -l < "$pushes" | tr -d ' ')" "the repeated ask retried the captain push" + assert_equals "$before" "$after" "the retry left the captured record bytes untouched" + pass "a failed captain push is retried on the next ask without rewriting the record" +} + +test_the_question_shows_every_resource_and_remembered_path() { + # Approving a request grants every resource it names, so the question must + # show all of them. A path can contain spaces, so a space-joined rendering + # would misstate the boundary between two entries. + local home summary + home="$TMP_ROOT/ask-multiple-resources"; arm_task "$home" + make_fake_opencode "$home" + cat > "$home/fake-bin/opencode" <<'SH' +#!/usr/bin/env bash +set -u +printf '%s\n' "$*" >> "$FM_FAKE_PERM_CALLS" +printf '{"id":"%s","sessionID":"%s","action":"external_directory","resources":["/private/a","/private/b","/tmp/dir with space/x"],"save":["/private/a","/tmp/dir with space/x"],"metadata":{}}\n' \ + "$FM_FAKE_PERM_REQUEST" "$FM_FAKE_PERM_SESSION" +SH + chmod +x "$home/fake-bin/opencode" + calls="$home/state/notifier-calls.log" + mkdir -p "$home/shadow" + cp "$ROOT/bin/fm-opencode-permission.sh" "$home/shadow/fm-opencode-permission.sh" + cp "$ROOT/bin/fm-busy-lib.sh" "$home/shadow/fm-busy-lib.sh" + cat > "$home/shadow/fm-discord-notify.sh" <<'SH' +#!/usr/bin/env bash +set -u +printf '%s\n' "$*" >> "$FM_FAKE_NOTIFIER_CALLS" +SH + chmod +x "$home/shadow/fm-opencode-permission.sh" "$home/shadow/fm-discord-notify.sh" + mapfile -t assigns < <(perm_env "$home" pending) + env "${assigns[@]}" "FM_FAKE_NOTIFIER_CALLS=$calls" \ + "$home/shadow/fm-opencode-permission.sh" ask "$TASK" "$SESSION" "$REQUEST" >/dev/null 2>&1 + summary=$(cat "$calls") + assert_contains "$summary" '/private/a' "the first resource is shown" + assert_contains "$summary" '/private/b' "the last resource is shown too, not only the first" + assert_contains "$summary" '/tmp/dir with space/x' "a resource containing a space is shown whole" + assert_contains "$summary" 'resources=["/private/a","/private/b","/tmp/dir with space/x"]' \ + "the full resource list is shown with its element boundaries intact" + assert_contains "$summary" 'these paths: ["/private/a","/tmp/dir with space/x"]' \ + "the complete remember scope is shown with its boundaries intact" + case "$summary" in + *$'\n'*) fail "the pushed summary must stay one line" ;; + esac + pass "the captain is shown every resource and every remembered path, boundaries intact" +} + test_concurrent_decides_post_exactly_once() { local home record posts home="$TMP_ROOT/decide-concurrent"; arm_task "$home" @@ -472,7 +554,7 @@ SH summary=$(cat "$calls") assert_contains "$summary" "perm-ask $TASK perm-$REQUEST" "the push uses the perm-ask trigger and the perm- key" assert_contains "$summary" "action=external_directory" "the question states the action" - assert_contains "$summary" "resource=/tmp/fake-probe/*" "the question states the resource" + assert_contains "$summary" 'resources=["/tmp/fake-probe/*"]' "the question states the complete resource list" assert_contains "$summary" "would save" "the question states the proposed remember scope" assert_contains "$summary" "Recommendation:" "the question states a recommendation" assert_contains "$summary" "Approve once|Approve once and remember this|Reject the request" \ @@ -497,7 +579,9 @@ test_ask_refuses_a_mismatched_identity test_ask_refuses_without_a_task_generation test_ask_refuses_an_unusable_identity test_ask_is_idempotent_and_keeps_the_original_record +test_ask_retries_a_push_that_failed_and_leaves_the_record_untouched test_ask_records_a_resource_containing_a_comma_verbatim +test_the_question_shows_every_resource_and_remembered_path test_decide_applies_once_and_refuses_a_replay test_decide_refuses_an_expired_request_without_writing test_decide_refuses_a_stale_task_generation From 388552d5a3904d1509b1f45475d2f004e7504ed7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=ED=8F=89=EC=8B=9D?= <aliceriddel@gmail.com> Date: Thu, 1 Oct 2026 20:28:15 +0900 Subject: [PATCH 3/3] no-mistakes(document): Add missing opencode-permission state path to layout reference --- .agents/skills/firstmate-layout/SKILL.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.agents/skills/firstmate-layout/SKILL.md b/.agents/skills/firstmate-layout/SKILL.md index ab2188d808b..0a4a26a9e71 100644 --- a/.agents/skills/firstmate-layout/SKILL.md +++ b/.agents/skills/firstmate-layout/SKILL.md @@ -66,6 +66,7 @@ state/ runtime records and signals; gitignored <id>.reconcile-nudged epoch second of the last inventory-reconcile nudge sent to this secondmate; bin/fm-secondmate-reconcile.sh owns its per-home cooldown window <id>.backlog-close the exact backlog transition a teardown recorded before removing the task's record, so an interrupted cleanup can still be finished at the next session start; bin/fm-backlog-transition-lib.sh owns its format and replay, and a landed transition removes it <id>.inbox/ durable steering inbox: sequenced firstmate instruction records the worker acknowledges by moving them into its handled/ subdirectory; written by fm-send, with ordinary records re-rung and escalated by the watcher while explicit fire-and-forget records are excluded from that ladder, and removed by teardown (bin/fm-task-inbox-lib.sh) + <id>.opencode-permission/<request-id>.json durable record of one OpenCode permission request pushed to the captain as a perm-ask decision; bin/fm-opencode-permission.sh owns the schema and the ask/decide/settle lifecycle; removed by teardown <id>.meta task metadata; each producer script's header owns its exact fields and mutation contract, with docs/configuration.md routing operator-facing backend and trace-context details <id>.herdr-presentation quarantinable attempt and restart-binding journal for Herdr's optional visual projection; never task or endpoint authority; see docs/herdr-backend.md "Presentation spaces" <id>.check.sh authenticated slow poll; the watcher dispatches validated PR data and the byte-identified Relay shim through trusted repository scripts, runs registered custom checks from hash-validated private snapshots, and rejects every other state check without execution