From c46340d72f0efffd0d8b25e4174fd4252d1c8fab Mon Sep 17 00:00:00 2001 From: "Darwin D. Wu" Date: Fri, 23 Oct 2026 18:09:04 -0700 Subject: [PATCH 1/3] chore(rfd): remove in-repo RFD status checker RFDs now live in chaba-dev/rfds, which has its own checks, so the check-rfds target and its scripts have nothing left to check. --- Makefile | 5 - scripts/check-rfd-status-test.sh | 185 ----------------- scripts/check-rfd-status.sh | 344 ------------------------------- 3 files changed, 534 deletions(-) delete mode 100755 scripts/check-rfd-status-test.sh delete mode 100755 scripts/check-rfd-status.sh diff --git a/Makefile b/Makefile index 86419ed..4ac5720 100644 --- a/Makefile +++ b/Makefile @@ -24,11 +24,6 @@ rs-test: .PHONY: lint lint: ex-lint rs-lint -.PHONY: check-rfds -check-rfds: - @./scripts/check-rfd-status.sh - @./scripts/check-rfd-status-test.sh - .PHONY: ex-lint ex-lint: mix credo diff --git a/scripts/check-rfd-status-test.sh b/scripts/check-rfd-status-test.sh deleted file mode 100755 index 24a420b..0000000 --- a/scripts/check-rfd-status-test.sh +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -checker="${repo_root}/scripts/check-rfd-status.sh" -test_root="$(mktemp -d "${TMPDIR:-/tmp}/kodo-rfd-check.XXXXXX")" -rfd_root="${test_root}/rfd" -output="${test_root}/output" - -trap 'rm -rf "${test_root}"' EXIT - -reset_fixtures() { - rm -rf "${rfd_root}" - mkdir -p "${rfd_root}" - printf '# Test RFDs\n' >"${rfd_root}/README.md" -} - -run_success() { - local expected="${1:-}" - - if ! NO_COLOR=1 RFD_DIR="${rfd_root}" bash "${checker}" >"${output}" 2>&1; then - cat "${output}" >&2 - printf 'expected RFD checker to pass\n' >&2 - exit 1 - fi - - if [[ -n "${expected}" ]] && ! grep -Fq "${expected}" "${output}"; then - cat "${output}" >&2 - printf 'RFD checker output did not include: %s\n' "${expected}" >&2 - exit 1 - fi -} - -run_failure() { - local expected="$1" - - if NO_COLOR=1 RFD_DIR="${rfd_root}" bash "${checker}" >"${output}" 2>&1; then - cat "${output}" >&2 - printf 'expected RFD checker to fail with: %s\n' "${expected}" >&2 - exit 1 - fi - - if ! grep -Fq "${expected}" "${output}"; then - cat "${output}" >&2 - printf 'RFD checker failure did not include: %s\n' "${expected}" >&2 - exit 1 - fi -} - -write_valid_rfd() { - local state="$1" - local discussion="$2" - local implementation_format="${3:-org}" - local implementation_name - - case "${implementation_format}" in - org) implementation_name="IMPLEMENTATION.org" ;; - md) implementation_name="IMPLEMENTATION.md" ;; - *) - printf 'unsupported test implementation format: %s\n' "${implementation_format}" >&2 - exit 1 - ;; - esac - - mkdir -p "${rfd_root}/0001" - cat >"${rfd_root}/0001/README.adoc" < -:state: ${state} -:discussion: ${discussion} -:labels: software, process - -= RFD 1 Valid RFD - -== Implementation - -See link:${implementation_name}[implementation checklist]. -EOF - - case "${implementation_format}" in - org) - cat >"${rfd_root}/0001/${implementation_name}" <<'EOF' -#+TITLE: RFD 0001 implementation checklist - -Implements [[file:README.adoc][RFD 1: Valid RFD]]. - -- [ ] Complete the work. -EOF - ;; - md) - cat >"${rfd_root}/0001/${implementation_name}" <<'EOF' -# RFD 0001 implementation checklist - -Implements [RFD 1: Valid RFD](README.adoc). - -- [ ] Complete the work. -EOF - ;; - esac -} - -reset_fixtures -write_valid_rfd discussion https://example.com/pull/1 -cat >>"${rfd_root}/0001/IMPLEMENTATION.org" <<'EOF' -- [X] Finished task. - - [x] Finished nested task. -EOF -sed -i.bak 's/Valid RFD/A title that is deliberately longer than thirty-five characters/' "${rfd_root}/0001/README.adoc" -rm "${rfd_root}/0001/README.adoc.bak" -run_success "0001 discussion 2/3 A title that is deliberately longer than thirty-five characters software, process" - -reset_fixtures -write_valid_rfd discussion https://example.com:8443/pull/1 -run_success - -reset_fixtures -write_valid_rfd prediscussion "" md -cat >>"${rfd_root}/0001/IMPLEMENTATION.md" <<'EOF' -- [x] Finished task. -+ [X] Another finished task. -EOF -run_success "0001 prediscussion 2/3" - -reset_fixtures -write_valid_rfd prediscussion "" -rm "${rfd_root}/0001/IMPLEMENTATION.org" -run_failure "missing implementation checklist" - -reset_fixtures -write_valid_rfd prediscussion "" -printf '\n* [ ] This belongs in the implementation document.\n' >>"${rfd_root}/0001/README.adoc" -run_failure "implementation checkboxes belong in a separate implementation document" - -reset_fixtures -write_valid_rfd prediscussion "" -printf '\n** [ ] Nested implementation work also belongs elsewhere.\n' >>"${rfd_root}/0001/README.adoc" -run_failure "implementation checkboxes belong in a separate implementation document" - -reset_fixtures -write_valid_rfd prediscussion "" -printf '# RFD 0001 implementation checklist\n\nImplements [RFD 1](README.adoc).\n' >"${rfd_root}/0001/IMPLEMENTATION.md" -run_failure "multiple implementation checklist formats" - -reset_fixtures -write_valid_rfd draft "" -run_failure "invalid state: draft" - -reset_fixtures -write_valid_rfd discussion "" -run_failure "state discussion requires a discussion URL" - -reset_fixtures -write_valid_rfd prediscussion "" -sed -i.bak '1a\ -:authors: Another Author -' "${rfd_root}/0001/README.adoc" -rm "${rfd_root}/0001/README.adoc.bak" -run_failure "exactly one non-empty authors attribute" - -reset_fixtures -write_valid_rfd prediscussion "" -sed -i.bak 's/Example Author //' "${rfd_root}/0001/README.adoc" -rm "${rfd_root}/0001/README.adoc.bak" -run_failure "authors must include a name and address in angle brackets" - -reset_fixtures -write_valid_rfd discussion https:// -run_failure "discussion must be empty or an HTTP(S) URL" - -reset_fixtures -write_valid_rfd discussion https://:443/path -run_failure "discussion must be empty or an HTTP(S) URL" - -reset_fixtures -write_valid_rfd prediscussion "" -sed -i.bak 's/= RFD 1 /= RFD 2 /' "${rfd_root}/0001/README.adoc" -rm "${rfd_root}/0001/README.adoc.bak" -run_failure "does not match directory number 1" - -reset_fixtures -mkdir -p "${rfd_root}/1" -printf '= RFD 1 Invalid directory\n' >"${rfd_root}/1/README.adoc" -run_failure "invalid RFD entry" - -printf 'RFD checker tests passed.\n' diff --git a/scripts/check-rfd-status.sh b/scripts/check-rfd-status.sh deleted file mode 100755 index 3b2b5c8..0000000 --- a/scripts/check-rfd-status.sh +++ /dev/null @@ -1,344 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -rfd_root="${RFD_DIR:-${repo_root}/rfd}" - -if [[ -z "${NO_COLOR:-}" && (-t 1 || -n "${FORCE_COLOR:-}") ]]; then - color_reset=$'\033[0m' - color_bold=$'\033[1m' - color_red=$'\033[31m' - color_green=$'\033[32m' - color_yellow=$'\033[33m' - color_blue=$'\033[34m' - color_dim=$'\033[2m' -else - color_reset="" - color_bold="" - color_red="" - color_green="" - color_yellow="" - color_blue="" - color_dim="" -fi - -if [[ ! -d "${rfd_root}" ]]; then - printf "%sRFD directory not found:%s %s\n" "${color_red}" "${color_reset}" "${rfd_root}" >&2 - exit 1 -fi - -colorize_state() { - local state="$1" - local padded="$2" - - case "${state}" in - prediscussion | ideation) printf "%s%s%s" "${color_blue}" "${padded}" "${color_reset}" ;; - discussion) printf "%s%s%s" "${color_yellow}" "${padded}" "${color_reset}" ;; - published | committed) printf "%s%s%s" "${color_green}" "${padded}" "${color_reset}" ;; - abandoned) printf "%s%s%s" "${color_dim}" "${padded}" "${color_reset}" ;; - *) printf "%s%s%s" "${color_red}" "${padded}" "${color_reset}" ;; - esac -} - -read_rfd() { - local source="$1" - local source_name="$2" - local expected_number="$3" - - awk -v source_name="${source_name}" -v expected_number="${expected_number}" ' - function problem(message) { - printf " %s: %s\n", source_name, message > "/dev/stderr" - errors++ - } - - function clean(value) { - sub(/^:[^:]+:[[:space:]]*/, "", value) - if (index(value, "\t") > 0) { - problem("attribute values must not contain tabs") - gsub(/\t/, " ", value) - } - return value - } - - function valid_authors(value, owners, count, i) { - count = split(value, owners, /;[[:space:]]*/) - for (i = 1; i <= count; i++) { - if (owners[i] !~ /^[^<[:space:]][^<]*[[:space:]]+<[^<>[:space:]]+>$/) { - return 0 - } - } - return count > 0 - } - - function valid_discussion_url(value, rest, authority, host, labels, count, i) { - if (value !~ /^https?:\/\// || value ~ /[[:space:]]/) return 0 - - rest = value - sub(/^https?:\/\//, "", rest) - authority = rest - sub(/[\/?#].*$/, "", authority) - - if (substr(authority, 1, 1) == "[") { - return authority ~ /^\[[0-9A-Fa-f:.]+\](:[0-9]+)?$/ - } - - host = authority - if (host ~ /:/) { - if (host !~ /:[0-9]+$/) return 0 - sub(/:[0-9]+$/, "", host) - } - count = split(host, labels, /\./) - for (i = 1; i <= count; i++) { - if (labels[i] !~ /^([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])$/) { - return 0 - } - } - return count > 0 - } - - BEGIN { - authors = "" - state = "" - discussion = "" - labels = "" - title = "" - title_number = "" - title_seen = 0 - errors = 0 - } - - !title_seen && $0 ~ /^:authors:[[:space:]]*/ { - authors_count++ - if (authors_count == 1) authors = clean($0) - next - } - - !title_seen && $0 ~ /^:state:[[:space:]]*/ { - state_count++ - if (state_count == 1) state = clean($0) - next - } - - !title_seen && $0 ~ /^:discussion:[[:space:]]*/ { - discussion_count++ - if (discussion_count == 1) discussion = clean($0) - next - } - - !title_seen && $0 ~ /^:labels:[[:space:]]*/ { - labels_count++ - if (labels_count == 1) labels = clean($0) - next - } - - $0 ~ /^= RFD [0-9]+ .+/ { - title_count++ - if (title_count == 1) { - value = $0 - sub(/^= RFD /, "", value) - title_number = value - sub(/ .*/, "", title_number) - title = value - sub(/^[0-9]+ /, "", title) - } - title_seen = 1 - } - - END { - if (authors_count != 1 || authors == "") { - problem("document must contain exactly one non-empty authors attribute") - } else if (!valid_authors(authors)) { - problem("authors must include a name and address in angle brackets") - } - - if (state_count != 1 || state == "") { - problem("document must contain exactly one non-empty state attribute") - } else if (state !~ /^(prediscussion|ideation|discussion|published|committed|abandoned)$/) { - problem("invalid state: " state) - } - - if (discussion_count != 1) { - problem("document must contain exactly one discussion attribute") - } else if (discussion != "" && !valid_discussion_url(discussion)) { - problem("discussion must be empty or an HTTP(S) URL") - } else if (state ~ /^(discussion|published|committed)$/ && discussion == "") { - problem("state " state " requires a discussion URL") - } - - if (labels_count != 1 || labels == "") { - problem("document must contain exactly one non-empty labels attribute") - } - - if (title_count != 1 || title == "") { - problem("document must contain exactly one RFD title") - } else if (title_number != expected_number) { - problem("title number " title_number " does not match directory number " expected_number) - } - - printf "%s\t%s\t%s\t%s\t%s\t%d\n", state, title, authors, labels, discussion, errors - } - ' "${source}" -} - -failures=0 -found=0 -rfd_width=4 -state_width=13 -tasks_width=5 -title_width=35 -row_rfds=() -row_states=() -row_tasks=() -row_titles=() -row_labels=() - -shopt -s nullglob -entries=("${rfd_root}"/*) -shopt -u nullglob - -for entry in "${entries[@]}"; do - entry_name="$(basename "${entry}")" - - if [[ "${entry_name}" == "README.md" ]]; then - continue - fi - - if [[ ! -d "${entry}" || ! "${entry_name}" =~ ^[0-9]{4}$ ]]; then - printf "%sinvalid RFD entry%s: %s\n" "${color_red}" "${color_reset}" "${entry_name}" >&2 - failures=$((failures + 1)) - continue - fi - - found=1 - source="${entry}/README.adoc" - - if [[ ! -f "${source}" ]]; then - printf "%smissing canonical RFD source%s: %s/README.adoc\n" "${color_red}" "${color_reset}" "${entry_name}" >&2 - failures=$((failures + 1)) - continue - fi - - number="$(printf '%s\n' "${entry_name}" | sed 's/^0*//')" - if [[ -z "${number}" ]]; then - number="0" - fi - - implementations=() - [[ -f "${entry}/IMPLEMENTATION.org" ]] && implementations+=("${entry}/IMPLEMENTATION.org") - [[ -f "${entry}/IMPLEMENTATION.md" ]] && implementations+=("${entry}/IMPLEMENTATION.md") - task_summary="-" - - if [[ "${#implementations[@]}" -eq 0 ]]; then - printf "%smissing implementation checklist%s: %s/IMPLEMENTATION.org or IMPLEMENTATION.md\n" "${color_red}" "${color_reset}" "${entry_name}" >&2 - failures=$((failures + 1)) - elif [[ "${#implementations[@]}" -gt 1 ]]; then - printf "%smultiple implementation checklist formats%s: %s\n" "${color_red}" "${color_reset}" "${entry_name}" >&2 - failures=$((failures + 1)) - else - implementation="${implementations[0]}" - implementation_name="$(basename "${implementation}")" - read -r implementation_total implementation_completed < <( - awk ' - /^[[:space:]]*[-+*][[:space:]]+\[[ xX]\][[:space:]]/ { - total++ - if ($0 ~ /^[[:space:]]*[-+*][[:space:]]+\[[xX]\][[:space:]]/) completed++ - } - END { printf "%d %d\n", total, completed } - ' "${implementation}" - ) - task_summary="${implementation_completed}/${implementation_total}" - - case "${implementation_name}" in - IMPLEMENTATION.org) - expected_heading="#+TITLE: RFD ${entry_name} implementation checklist" - backlink="[[file:README.adoc][" - ;; - IMPLEMENTATION.md) - expected_heading="# RFD ${entry_name} implementation checklist" - backlink="](README.adoc)" - ;; - esac - - if [[ "$(head -n 1 "${implementation}")" != "${expected_heading}" ]]; then - printf "%sinvalid implementation checklist heading%s: %s/%s\n" "${color_red}" "${color_reset}" "${entry_name}" "${implementation_name}" >&2 - failures=$((failures + 1)) - fi - - if ! grep -Fq "${backlink}" "${implementation}"; then - printf "%simplementation checklist must link to its RFD%s: %s/%s\n" "${color_red}" "${color_reset}" "${entry_name}" "${implementation_name}" >&2 - failures=$((failures + 1)) - fi - - if ! grep -Fq "link:${implementation_name}[" "${source}"; then - printf "%sRFD must link to its implementation checklist%s: %s/README.adoc\n" "${color_red}" "${color_reset}" "${entry_name}" >&2 - failures=$((failures + 1)) - fi - fi - - if grep -Eq '^\*+[[:space:]]+\[[ xX]\]' "${source}"; then - printf "%simplementation checkboxes belong in a separate implementation document%s: %s/README.adoc\n" "${color_red}" "${color_reset}" "${entry_name}" >&2 - failures=$((failures + 1)) - fi - - parsed="$(read_rfd "${source}" "${entry_name}/README.adoc" "${number}")" - state="${parsed%%$'\t'*}" - remainder="${parsed#*$'\t'}" - title="${remainder%%$'\t'*}" - remainder="${remainder#*$'\t'}" - remainder="${remainder#*$'\t'}" - labels="${remainder%%$'\t'*}" - remainder="${remainder#*$'\t'}" - parser_errors="${remainder##*$'\t'}" - failures=$((failures + parser_errors)) - - display_state="${state:-\(missing\)}" - display_title="${title:-\(missing title\)}" - display_labels="${labels:-\(missing labels\)}" - row_rfds+=("${entry_name}") - row_states+=("${display_state}") - row_tasks+=("${task_summary}") - row_titles+=("${display_title}") - row_labels+=("${display_labels}") - (( ${#entry_name} > rfd_width )) && rfd_width=${#entry_name} - (( ${#display_state} > state_width )) && state_width=${#display_state} - (( ${#task_summary} > tasks_width )) && tasks_width=${#task_summary} - (( ${#display_title} > title_width )) && title_width=${#display_title} -done - -printf -v rfd_rule '%*s' "${rfd_width}" '' -printf -v state_rule '%*s' "${state_width}" '' -printf -v tasks_rule '%*s' "${tasks_width}" '' -printf -v title_rule '%*s' "${title_width}" '' -rfd_rule="${rfd_rule// /-}" -state_rule="${state_rule// /-}" -tasks_rule="${tasks_rule// /-}" -title_rule="${title_rule// /-}" - -printf "%s%-*s %-*s %*s %-*s %s%s\n" "${color_bold}" \ - "${rfd_width}" "RFD" "${state_width}" "State" "${tasks_width}" "Tasks" \ - "${title_width}" "Title" "Labels" "${color_reset}" -printf "%s%s %s %s %s %s%s\n" "${color_dim}" "${rfd_rule}" \ - "${state_rule}" "${tasks_rule}" "${title_rule}" "--------------------" "${color_reset}" - -for index in "${!row_rfds[@]}"; do - state_field="$(printf '%-*s' "${state_width}" "${row_states[index]}")" - state_text="$(colorize_state "${row_states[index]}" "${state_field}")" - printf "%-*s %s %*s %-*s %s\n" "${rfd_width}" "${row_rfds[index]}" \ - "${state_text}" "${tasks_width}" "${row_tasks[index]}" \ - "${title_width}" "${row_titles[index]}" "${row_labels[index]}" -done - -if [[ "${found}" -eq 0 ]]; then - printf "%sno RFDs found%s in %s\n" "${color_red}" "${color_reset}" "${rfd_root}" >&2 - exit 1 -fi - -if [[ "${failures}" -gt 0 ]]; then - echo - printf "%sRFD status check failed%s with %s issue(s).\n" "${color_red}" "${color_reset}" "${failures}" >&2 - exit 1 -fi - -echo -printf "%sRFD status check passed.%s\n" "${color_green}" "${color_reset}" From 6af7d9f38acd36135e448224e710f3eb852dc1e5 Mon Sep 17 00:00:00 2001 From: "Darwin D. Wu" Date: Fri, 23 Oct 2026 18:09:18 -0700 Subject: [PATCH 2/3] docs(rfd): move RFDs to chaba-dev/rfds The RFDs in rfd/ moved to the shared chaba-dev/rfds repository (https://github.com/chaba-dev/rfds), published at https://chaba-rfds.pages.dev. They were renumbered on the way: - RFD 1 -> RFD 7 - RFD 2 -> RFD 8 - RFD 3 -> RFD 14 - RFD 4 -> RFD 15 - RFD 5 -> RFD 17 Delete the local copies and point the remaining references in docs/mvp.org at the new numbers on the published site. --- docs/mvp.org | 4 +- rfd/0001/IMPLEMENTATION.org | 25 - rfd/0001/README.adoc | 118 -- rfd/0002/IMPLEMENTATION.org | 37 - rfd/0002/README.adoc | 221 ---- rfd/0003/IMPLEMENTATION.org | 34 - rfd/0003/README.adoc | 153 --- rfd/0004/IMPLEMENTATION.org | 53 - rfd/0004/README.adoc | 238 ---- rfd/0005/CODEX_CONTRACT.adoc | 404 ------- rfd/0005/COMPATIBILITY-gpt-5.4-alpha-v1.adoc | 131 --- rfd/0005/IMPLEMENTATION.org | 486 -------- rfd/0005/README.adoc | 1056 ------------------ rfd/README.md | 84 -- 14 files changed, 2 insertions(+), 3042 deletions(-) delete mode 100644 rfd/0001/IMPLEMENTATION.org delete mode 100644 rfd/0001/README.adoc delete mode 100644 rfd/0002/IMPLEMENTATION.org delete mode 100644 rfd/0002/README.adoc delete mode 100644 rfd/0003/IMPLEMENTATION.org delete mode 100644 rfd/0003/README.adoc delete mode 100644 rfd/0004/IMPLEMENTATION.org delete mode 100644 rfd/0004/README.adoc delete mode 100644 rfd/0005/CODEX_CONTRACT.adoc delete mode 100644 rfd/0005/COMPATIBILITY-gpt-5.4-alpha-v1.adoc delete mode 100644 rfd/0005/IMPLEMENTATION.org delete mode 100644 rfd/0005/README.adoc delete mode 100644 rfd/README.md diff --git a/docs/mvp.org b/docs/mvp.org index 0371f96..636a95e 100644 --- a/docs/mvp.org +++ b/docs/mvp.org @@ -122,7 +122,7 @@ replicated Phoenix deployment is supported. Kodo ships as one binary. The current transitional interface uses ~kodo start~ and ~kodo resume~ to host the workspace runner and interact with a session. Running ~kodo --headless~ hosts the runner without an interactive client and -reports which sessions send it work. RFD 4 proposes making the full-screen TUI +reports which sessions send it work. [[https://chaba-rfds.pages.dev/rfd/0015/][RFD 15]] proposes making the full-screen TUI the default ~kodo~ behavior once it reaches parity with the transitional commands. There is no separate daemon or standard-input tool protocol. @@ -760,7 +760,7 @@ Pareto tradeoff rather than simply selecting the highest raw quality score. ** DONE Milestone 6: Bound control-plane database load The design boundary and acceptance measurements are tracked in -[[file:../rfd/0001/README.adoc][RFD 1: Bound control-plane database load]]. This milestone remains the MVP +[[https://chaba-rfds.pages.dev/rfd/0007/][RFD 7: Bound control-plane database load]]. This milestone remains the MVP delivery checklist. - [X] Stop terminal session coordinators after finalization and lazily restart diff --git a/rfd/0001/IMPLEMENTATION.org b/rfd/0001/IMPLEMENTATION.org deleted file mode 100644 index 02d6aef..0000000 --- a/rfd/0001/IMPLEMENTATION.org +++ /dev/null @@ -1,25 +0,0 @@ -#+TITLE: RFD 0001 implementation checklist - -Implements [[file:README.adoc][RFD 1: Bound control-plane database load]]. - -- [X] Instrument bounded-cardinality query counts and durations for instance - heartbeats, recovery discovery, ownership fencing, and session-index refreshes. -- [X] Add a partial index covering sessions in ~running~ or - ~awaiting_approval~ state and verify the recovery query plan does not scan - terminal history. -- [X] Stop terminal session coordinators after finalization and restart them - lazily for follow-up turns without losing durable sequence reconciliation. -- [X] Replace fixed per-replica recovery scans with configurable, - cluster-coordinated work that preserves the documented failure-detection - bound and ownership epoch fencing. -- [X] Scope session-index notifications by user, fetch only the affected scoped - row, and coalesce event bursts that do not require repeated index updates. -- [X] Add stable keyset pagination and an ordering-compatible user-session index - so navigation does not load unbounded session and runner history. -- [X] Regression tests prove unrelated users perform no list query when another - user's session emits events and one turn does not trigger a full refresh per - durable event. -- [X] Load tests vary completed history, active sessions, replicas, connected - users, and events per turn while asserting the scaling boundaries in the RFD. -- [X] Operational documentation defines expected steady-state query rates, - recovery timing, metrics, and safe tuning ranges. diff --git a/rfd/0001/README.adoc b/rfd/0001/README.adoc deleted file mode 100644 index 2389bc6..0000000 --- a/rfd/0001/README.adoc +++ /dev/null @@ -1,118 +0,0 @@ -:authors: Darwin D Wu -:state: discussion -:discussion: https://github.com/chaba-dev/kodo/pull/13 -:labels: software, performance, database, operations - -= RFD 1 Bound control-plane database load - -== Goal - -Keep Kodo's control-plane database work bounded by live replicas and active -sessions while preserving durable execution, ownership fencing, and timely -recovery after a control-plane failure. - -The current MVP correctly favors durable coordination, but its periodic and -event-driven queries will become disproportionately expensive as completed -sessions, connected clients, and control-plane replicas increase. This RFD -defines the scaling boundary before those costs become part of the operational -contract. - -== Current pressure - -One control-plane replica periodically heartbeats its instance record and scans -all sessions in `running` or `awaiting_approval` state for recovery. Active -session coordinators also perform ownership-fencing checks. Terminal -coordinators currently remain alive, so coordinator count can grow with session -history rather than current work. - -The browser session index adds another multiplier. Durable session events are -broadcast on a global topic, and every connected session index or detail view -responds by querying and preloading its complete user session list. A turn that -emits many events therefore causes repeated full-list queries for users whose -session index did not change, including unrelated users. - -The heartbeat itself is expected and remains necessary. The problem is the -combined query amplification: work scales with replicas, retained coordinators, -event count, connected clients, and unbounded session history rather than with -the small set of live instances and active sessions that require coordination. - -== Required scaling boundary - -Kodo must satisfy these properties: - -* Heartbeat work is constant per live control-plane replica and does not depend - on session count. -* Recovery discovery reads only active recovery candidates through an - appropriate partial index and does not scan historical terminal sessions. -* Recovery polling is configurable and coordinated across the cluster so every - replica does not perform the same unbounded scan, while a failed owner is - still detected within the documented availability bound. -* Terminal session coordinators stop after finalization and restart lazily when - a follow-up turn requires one. -* Session-index notifications are scoped to the owning user and identify the - affected session. A connected client updates that row instead of reloading - the complete list for every durable event. -* Bursts of events that do not change index-visible state do not produce one - index query per event. -* Session navigation is bounded and uses stable pagination supported by an - index matching its user scope and ordering. -* Ownership optimization never weakens epoch fencing or permits two - coordinators to mutate one session concurrently. - -== Recovery and ownership - -Recovery candidates remain sessions whose durable status can require a live -coordinator. PostgreSQL provides the authoritative state; in-memory cluster -membership may reduce redundant work but must not become the sole source of -truth. - -Only one cluster participant needs to perform a recovery sweep for a given -interval or partition of candidates. Coordination may use a database lease, -advisory lock, deterministic partitioning, or an equivalent mechanism, provided -loss of the elected participant cannot suppress recovery beyond the configured -bound. - -Claims continue to increment and verify the durable ownership epoch. Heartbeat -freshness and ownership assertions remain database-time based so clock skew -between nodes cannot create authority. - -== Session-index updates - -Session index broadcasts use a user-scoped topic and carry the affected session -identifier. Consumers fetch that session through the authenticated scope and -use a targeted stream insertion or deletion. The event payload itself does not -grant access and must never substitute for the scoped query. - -Index-visible changes may be emitted only when fields shown or ordered in the -index change, or coalesced over a short bounded interval. Session detail events -continue to use the session-specific durable sequence stream and are not routed -through the index refresh path. - -Historical navigation uses keyset pagination with a stable tie-breaker. The -supporting index begins with `user_id` and matches the selected ordering. The UI -must not preload runners or sessions outside the visible page. - -== Measurement and rollout - -Telemetry distinguishes heartbeat, recovery discovery, ownership fencing, and -session-index refresh queries. Metrics use bounded-cardinality labels; session, -user, and instance identifiers belong in logs or traces rather than metric -labels. - -Load tests cover increasing completed-session history, active sessions, -replicas, connected users, and events per turn. They record query counts and -database time, not only end-to-end latency. The acceptance threshold is a -constant upper bound per heartbeat and index-visible update, plus work linear in -the active recovery candidates assigned to a replica. Completed history and -events that do not alter index-visible state must not increase steady-state -query rates. - -The changes may roll out independently: indexes first, then coordinator -lifecycle, scoped index updates, and coordinated recovery. Each step retains a -fallback that preserves correctness even if it temporarily performs redundant -work. - -== Implementation - -Progress against this proposal is tracked in the -link:IMPLEMENTATION.org[RFD 1 implementation checklist]. diff --git a/rfd/0002/IMPLEMENTATION.org b/rfd/0002/IMPLEMENTATION.org deleted file mode 100644 index ae8d3a7..0000000 --- a/rfd/0002/IMPLEMENTATION.org +++ /dev/null @@ -1,37 +0,0 @@ -#+TITLE: RFD 0002 implementation checklist - -Implements [[file:README.adoc][RFD 2: Extend Kodo to mobile and tablet clients]]. - -- [ ] Define and test responsive phone and tablet layouts for the session list, - session detail, timeline, approvals, composer, runner state, and diff viewer. -- [ ] Expose connection state in the interface, preserve the last rendered - content, and clearly identify stale disconnected state. -- [ ] Disable server mutations while disconnected and keep approval and - cancellation controls disabled until fresh state is loaded after reconnect. -- [ ] Persist message drafts by account and session with bounded retention, - user-controlled clearing, and purge on logout or account transition; require - explicit submission after reconnection rather than silently queueing them. -- [ ] Generate and persist a client request identifier before message - submission, reuse it through explicit retries until authoritative - confirmation, and replace it only for a genuinely new or edited message. -- [ ] Verify reconnect reloads the authoritative projection, catches up durable - events, and does not create duplicate turns when a response is lost. -- [ ] Add a web app manifest, installable icons, safe-area support, and the - static-asset caching needed for a generic offline fallback without caching - authenticated HTML or API responses. -- [ ] Bind each Web Push service-worker subscription to at most one user through - authenticated, CSRF-protected requests; replace refreshed endpoints and - unbind on logout, account transition, account deletion, or global session - invalidation. -- [ ] Deliver selected durable session events with event-appropriate - time-to-live values and let users revoke individual browser installations. -- [ ] Keep push payloads private, deep-link through normal authentication, - discard invalid subscriptions, and reconcile authoritative session state when - a client reconnects even if push delivery failed or expired. -- [ ] Exercise representative phones and tablets for touch targets, - accessibility, software-keyboard behavior, long timelines, and wide diffs. -- [ ] Measure PWA limitations and user demand before selecting a native wrapper, - cross-platform client, or separate platform-native applications. -- [ ] If a native client is approved, define and test the versioned user API, - device-session lifecycle, realtime recovery, push registration, idempotency, - and compatibility contract described by the RFD. diff --git a/rfd/0002/README.adoc b/rfd/0002/README.adoc deleted file mode 100644 index 50d550f..0000000 --- a/rfd/0002/README.adoc +++ /dev/null @@ -1,221 +0,0 @@ -:authors: Darwin D Wu -:state: prediscussion -:discussion: -:labels: software, mobile, pwa, user-interface - -= RFD 2 Extend Kodo to mobile and tablet clients - -== Goal - -Allow phones and tablets to monitor and control Kodo sessions without moving -repository access or command execution onto those devices. The first client -should be a responsive Progressive Web App built on the existing Phoenix -LiveView interface, while the control-plane boundary must leave room for native -clients if product needs later justify a separate application. - -Mobile and tablet devices are control surfaces. They display session history, -agent output, tool activity, runner status, and diffs; send follow-up messages; -and resolve approval requests. Existing desktop or hosted runners continue to -own workspaces and execute tools. - -== Options considered - -=== Responsive LiveView PWA - -A responsive PWA reuses the existing browser authentication, LiveView session -pages, server-side rendering, and realtime updates. It provides one client -implementation across desktop browsers, phones, and tablets and is the fastest -way to validate the mobile information architecture. - -The PWA may be installed to a device home screen and can later add Web Push for -completed turns, failures, and approval requests. Its principal limitation is -that LiveView navigation and interaction require a connection to the control -plane. - -=== Native wrapper - -A Capacitor or small platform WebView wrapper could distribute the responsive -application through app stores and incrementally add deep links, secure -credential integration, and native notifications. This remains an option after -the PWA is usable, but it should not drive the initial architecture. A wrapper -introduces cookie, navigation, file-handling, and app-review concerns without -removing the server connectivity requirement. - -=== Cross-platform native client - -A React Native, Expo, Flutter, or equivalent client could provide stronger -platform integration, background behavior, secure storage, and adaptive tablet -navigation. It would also create a second UI implementation and require a -stable, versioned client API with device authentication and realtime event -delivery. - -=== Platform-native clients - -Separate SwiftUI and Android clients offer the greatest platform-specific -polish and the highest implementation and maintenance cost. They are not -justified for the first mobile release. LiveView Native may be evaluated as a -prototype, but ecosystem maturity, library availability, debugging, and -staffing must be assessed before relying on it for primary clients. - -== Decision - -Kodo will begin with a responsive LiveView PWA. It will be a connected -application with graceful disconnection, not an offline-first application. -Native clients may follow if notifications, background operation, platform -integration, app-store expectations, or measured product usage justify the -additional codebase. - -This decision does not require replacing LiveView with Svelte, React, or -another client-side UI framework. LiveView remains the primary UI and owns -server-rendered state, authenticated navigation, and connected interactions. A -web app manifest, service worker, responsive styles, connection-state handling, -and small client hooks add PWA capabilities around that interface. Rewriting -the UI would introduce a second state-management and API layer without making -server and runner operations available offline. - -Phone layouts use navigation between the session list and session detail. -Tablet layouts use the available width for a persistent session sidebar and a -detail pane. Both layouts prioritize the timeline, pending approvals, runner -state, a message composer, and readable diffs. Touch targets, safe areas, -keyboard behavior, horizontal diff navigation, and accessibility are part of -the supported interface rather than later polish. - -== Connectivity and offline boundary - -LiveView initially renders HTML on the server and then maintains the page over -a WebSocket. When connectivity is lost, the already rendered page can remain -visible, but server-driven updates, navigation, and controls cannot complete. -LiveView reconnects automatically; after reconnection Kodo reloads -authoritative session state and resumes durable event delivery. - -This limitation matches Kodo's execution boundary. Sending a prompt, resolving -an approval, cancelling work, receiving new output, and operating a remote -runner all require the control plane. A native client could cache more data but -could not perform those operations while the backend is unavailable. - -The PWA must therefore provide these disconnected behaviors: - -* Keep the last rendered session visible and clearly label it stale. -* Disable send, approve, deny, cancel, and other server mutations while - disconnected. -* Preserve unsent message drafts locally and let the user explicitly submit - them after reconnection. -* Reconnect and refresh authoritative session, approval, runner, and timeline - state automatically. -* Cache the application manifest and static assets needed to show a generic - offline fallback after an offline reload or cold launch. - -Kodo must not automatically queue approvals, denials, or cancellation. Those -commands can become invalid or unsafe while the device is disconnected and -must be confirmed against fresh state. The initial PWA preserves message drafts -but does not silently queue their submission. - -The initial offline guarantee applies to a page whose rendered document remains -open. Reloading that page, launching the PWA while offline, or returning after -the browser evicts it shows only the generic fallback. The service worker must -not cache authenticated HTML or API responses. Persisted session snapshots -would require a separate design for freshness, storage protection, retention, -account transitions, and shared-device disclosure. - -Locally stored drafts may contain repository content or secrets. They are -namespaced by account and session, have a bounded retention period, can be -cleared by the user, and are purged on logout or account transition before a -different account can use the installation. - -== Reconnection and consistency - -PostgreSQL events and session projections remain authoritative. The client -must never infer that a control action succeeded merely because it was tapped. -After reconnecting, it refreshes the current projection and replays events after -its last durable sequence or accepts an equivalent full LiveView remount. - -Approval and cancellation controls remain unavailable until fresh state is -known. Before submitting a message, the client generates and persists a stable -client request identifier with the draft. It reuses that identifier for every -explicit retry until authoritative session state confirms the turn. Editing the -message into a genuinely new submission creates a new identifier. The server -must not generate a replacement identifier for a retried client submission; -otherwise a response lost after commit can produce a duplicate turn. - -== Future native-client boundary - -The initial PWA does not require a new mobile API. If a native client is -approved, Kodo should expose a versioned, user-facing API rather than treating -the existing agent token and CLI-oriented endpoints as the permanent mobile -contract. That boundary should include: - -* Separately revocable device sessions, secure credential storage, and token - rotation appropriate for untrusted mobile devices. -* Paginated session, timeline, and runner queries scoped to the authenticated - user. -* Realtime session events through an authenticated user WebSocket channel or - server-sent events, with cursor-based recovery after disconnection. -* Stable schemas, machine-readable errors, idempotent retryable mutations, and - compatibility rules across client and server releases. -* Device registration, push notification preferences, and deep links to the - affected session or pending approval. - -The runner WebSocket remains private to runners and is not reused as a user -client protocol. - -== Security and notifications - -Notification bodies should disclose no repository content, command text, diff, -or model output on a locked device by default. A notification identifies the -event category and opens the authenticated session, where current authorization -and session ownership are checked again. Approval actions should not execute -directly from a notification until the product defines an authenticated, -fresh-state confirmation flow. - -Each installed PWA may have a separate Web Push subscription owned by its -browser service-worker registration. A subscription represents a browser -installation, not a reliably identifiable physical device, and has at most one -active user binding. Creating, replacing, or deleting that binding requires an -authenticated, CSRF-protected request. Kodo unbinds it on logout, account -transition, account deletion, and global session invalidation before it can be -associated with another user. - -When a durable session event becomes notification-worthy, Kodo sends a push to -each enabled subscription bound to that user. The browser may wake the service -worker and display an operating-system notification even when the PWA and its -LiveView connection are closed. Subscription refresh replaces the prior -endpoint atomically, and permanent push-service rejection invalidates the -stored binding. - -A powered-off or disconnected device cannot display the notification -immediately. The push service may retain it until the device reconnects, -subject to the event's time-to-live, but delivery is best effort. Completion -notifications may use a longer time-to-live than approval requests, whose -meaning can become stale quickly. Users can disable or revoke individual -browser installations. - -Push delivery is not a record of whether a user has seen an event. Kodo -reconciles the authoritative session projection and durable event history when -a client reconnects, so a dropped or expired push cannot hide a completed task -or pending approval. The initial rollout does not infer read state from push -delivery and does not add notification badges or a separate unread model. If a -later product requirement adds them, it must define acknowledgement scope, -deduplication, retention, and behavior across installations. When a session is -already visible in a connected client, Kodo may suppress a duplicate -operating-system notification for that browser installation. - -Browser sessions continue to use the existing authenticated LiveView router -scope. Any future native API passes the authenticated user scope into context -operations and enforces ownership in database queries. - -== Rollout and acceptance - -The responsive interface and disconnected state ship before installability or -push notifications. Representative phone and tablet viewport tests cover the -session list, active timeline, long diff, pending approval, software keyboard, -disconnection, and reconnection. Reconnection tests verify that controls remain -disabled until fresh state arrives and that missed events and changed approval -state are rendered without duplicate turns. - -Native-client work requires a separate decision based on observed PWA limits -and must not delay a usable mobile web experience. - -== Implementation - -Progress against this proposal is tracked in the -link:IMPLEMENTATION.org[RFD 2 implementation checklist]. diff --git a/rfd/0003/IMPLEMENTATION.org b/rfd/0003/IMPLEMENTATION.org deleted file mode 100644 index 1040164..0000000 --- a/rfd/0003/IMPLEMENTATION.org +++ /dev/null @@ -1,34 +0,0 @@ -#+TITLE: RFD 0003 implementation checklist - -Implements [[file:README.adoc][RFD 3: Define behavioral evaluation and release benchmarking]]. - -- [ ] Define the fingerprinted ~behavior-alpha-v1~ suite schema for setup state, - event-triggered turns, allowed actions, prohibited outcomes, expected - evidence, and applicable rubric dimensions. -- [ ] Author five to eight pilot episodes spanning every critical rubric - dimension and representative non-critical dimensions. -- [ ] Implement deterministic assertions for changed paths, command and check - execution, external actions, required ordering, and preservation of unrelated - state. -- [ ] Implement structured rubric judgment with dimension-level evidence - citations and no dependency on hidden reasoning or implementation-specific - instructions. -- [ ] Build and manually label a calibration set containing full successes, - partial recovery, critical failures, and fluent claims contradicted by final - state. -- [ ] Measure judge agreement by dimension, review disagreements, and document - the calibration level required before scores become regression gates. -- [ ] Run the pilot at least three times for the balanced, Terra-oriented, and - Sol-primary/Terra-search-review candidate mappings; record quality, variance, - latency, token usage, cost, and harness failures. -- [ ] Expand the calibrated suite to 20 to 30 episodes with each rubric - dimension exercised at least three times. -- [ ] Add behavioral result validation and accepted-baseline checks to the - generic benchmark tests without changing the historical ~mvp-v1~ contract. -- [ ] Adopt fingerprint-bound regression thresholds only after repeated runs - establish a stable accepted baseline. -- [ ] Define and execute the release-candidate benchmark checklist for ~0.1.0~, - including complete role-quality and behavioral runs against the frozen code - and model-role mapping. -- [ ] Record release benchmark provenance on a revision reachable from the - release while reserving Git tags exclusively for product releases. diff --git a/rfd/0003/README.adoc b/rfd/0003/README.adoc deleted file mode 100644 index da36360..0000000 --- a/rfd/0003/README.adoc +++ /dev/null @@ -1,153 +0,0 @@ -:authors: Darwin D Wu -:state: prediscussion -:discussion: -:labels: evaluation, benchmarks, agents, quality, releases -:toc: - -= RFD 3 Define behavioral evaluation and release benchmarking - -== Goal - -Evaluate whether Kodo completes coding tasks correctly and whether it makes -sound decisions across realistic multi-turn interactions. The benchmark system -must distinguish model capability, agent behavior, evaluator reliability, and -operational tradeoffs without depending on hidden model reasoning or -implementation-specific instructions. - -This RFD defines the stable suite boundaries, scoring evidence, calibration, -threshold lifecycle, and release procedure. Machine-readable criteria, task -fixtures, and recorded results remain outside the RFD so they can evolve under -their own versioned contracts. - -== Decision - -Kodo will maintain separate but complementary benchmark suites: - -* Role-quality suites evaluate bounded search, review, and implementation - outcomes against purpose-built fixtures. The existing `mvp-v1` suite remains - frozen as historical evidence for this boundary. -* Behavioral suites evaluate observable decisions and final state over - multi-turn episodes. The first suite will be named `behavior-alpha-v1` and - will use the `agent-behavior-v1` rubric in - link:../../test/evals/criteria.json[`test/evals/criteria.json`]. - -Results from one suite cannot compensate for failure in the other. Strong code -generation does not excuse an unauthorized external action, and safe -interaction does not excuse an incorrect implementation. - -== Behavioral episode design - -Behavioral episodes are synthetic, reproducible interactions derived from -general task patterns rather than private conversations or account history. -They must not contain personal names, service identifiers, repository secrets, -or provider-specific agent instructions. - -The initial suite should contain 20 to 30 episodes and exercise every rubric -dimension at least three times. One episode may cover several dimensions when -their interaction is the behavior under test. Scenarios should include paired -forms where practical: - -* a direct, self-contained instruction and a multi-turn equivalent with a late - correction; -* a uniquely resolved contextual reference and one with multiple consequential - interpretations; -* permission to implement and a distinct request or refusal to publish; -* a reported diagnosis supported by current evidence and one contradicted by - the source of truth; -* an idempotent local failure and a non-idempotent external action whose outcome - is uncertain; and -* a requested change with explicit scope and a tempting unrelated cleanup. - -Episodes define setup state, allowed actions, prohibited outcomes, injected -turns, expected evidence, and applicable rubric dimensions. Injected turns are -triggered by observable events rather than timing assumptions so runs remain -repeatable across models with different latency. - -== Evidence and scoring - -Scoring uses observable events and resulting state. Deterministic assertions -own facts that the harness can establish directly, including changed paths, -commands executed, checks completed, external actions attempted, ordering of -required steps, and preservation of unrelated state. - -A structured model judge may score judgment that cannot be reduced to state -assertions, such as whether clarification was proportionate or a completion -claim was calibrated to its evidence. Every judged score must identify the -applicable dimension and cite the turns or actions that support it. The judge -must not infer hidden reasoning or reward recital of the rubric. - -Each applicable dimension receives `0`, `0.5`, or `1` according to the named -rubric. Reports include every dimension, deterministic assertion outcomes, the -weighted mean, critical failures, harness failures, latency, token usage, and -estimated cost. Aggregate scores never hide dimension-level results. - -== Judge calibration - -Automated behavioral scores are not regression or release gates until the -judge is calibrated against a manually labeled reference set. Calibration must -include clear successes, clear failures, partially recovered behavior, and -adversarial cases where fluent explanations conflict with the observed state. - -The evaluation report records agreement by dimension and preserves judge -disagreements for review. Recurring disagreements are resolved by clarifying -scenario evidence or rubric semantics, not by changing expected labels to favor -a preferred model. A model under evaluation should not be its sole judge. - -Before a full suite run, a pilot of five to eight representative episodes runs -each candidate configuration at least three times. The pilot validates harness -behavior, judge stability, scenario discrimination, and expected cost before -additional provider usage is authorized. - -== Targets and regression thresholds - -The desirable behavioral target is a weighted episode score of at least `0.9`. -A zero on any critical dimension fails the episode regardless of its aggregate. -Dimension-specific targets remain defined by the versioned rubric. - -Targets guide improvement but are not automatically release gates. A suite may -adopt regression thresholds only after calibration and repeated runs establish -a stable accepted baseline. Thresholds are anchored to one suite fingerprint -and may be raised when stronger evidence is accepted. They are not lowered -merely to admit a regressing candidate. - -Changes to metric meaning, scoring semantics, or critical-failure policy create -a new named rubric or standard. Adding scenarios creates a new suite fingerprint -or suite generation rather than silently rewriting historical results. - -== Release-candidate procedure - -Benchmark runs used for a release occur after the release-candidate code and -model-role mapping are frozen. The release report includes: - -* the complete role-quality suite; -* the calibrated behavioral suite; -* repeated runs needed to characterize stochastic variance; -* correctness, behavior, harness reliability, latency, token usage, and cost; - and -* the rationale for the selected model-role mapping and any accepted exceptions. - -The pre-MVP benchmark artifacts are development evidence and need not retain -permanent Git reachability. Before release `0.1.0`, Kodo will run a fresh -benchmark round against the frozen release candidate and record its reachable -revision. Git tags are reserved for product releases; benchmark provenance must -not create non-release tags. - -== Artifact ownership - -The benchmark sources have distinct responsibilities: - -* link:../../test/evals/criteria.json[`test/evals/criteria.json`] owns versioned - standards, rubrics, targets, and the suite catalog. -* `test/evals//` owns fingerprinted tasks, suite thresholds, accepted - baselines, and candidate results. -* link:../../test/evals/README.adoc[`test/evals/README.adoc`] owns the benchmark - data model, lifecycle, governance, and reference-generation contract. -* link:../../docs/evaluations.md[`docs/evaluations.md`] owns run analysis and - comparisons. -* This RFD owns the durable separation of suites, evidence boundary, - calibration requirement, and release procedure. - -== Implementation - -Progress against this proposal is tracked in the -link:IMPLEMENTATION.org[RFD 3 implementation checklist]. diff --git a/rfd/0004/IMPLEMENTATION.org b/rfd/0004/IMPLEMENTATION.org deleted file mode 100644 index 82d163b..0000000 --- a/rfd/0004/IMPLEMENTATION.org +++ /dev/null @@ -1,53 +0,0 @@ -#+TITLE: RFD 0004 implementation checklist - -Implements [[file:README.adoc][RFD 4: Introduce a full-screen terminal interface]]. - -* Phase 0: Simplify the runner contract - -- [X] Remove the public ~daemon~ command and stdin tool protocol, rename the - internal connected dispatcher, and expose runner-only operation as - ~kodo --headless~ with connection and first-seen session status. - -* Phase 1: Establish the reusable application core - -- [ ] Resolve the remaining interaction, diff-view, minimum-size, model - boundary, and transport questions through RFD discussion. -- [ ] Extract an application core that owns authenticated actions, durable - replay, projection, retries, request identifiers, and runner lifetime. -- [ ] Define a deterministic Elm-style model/message/update/effect loop with - I/O performed by a dispatcher and results returned as typed messages. -- [ ] Keep Kodo domain messages and effects independent of Ratatui and Crossterm - so an Iced frontend can reuse behavior without sharing widget abstractions. -- [ ] Prove existing start, resume, approval, cancellation, reconnect, and - output behavior is preserved while transitional commands still exist. - -* Phase 2: Prove the terminal foundation - -- [ ] Prototype terminal initialization, alternate-screen restoration, - resize, suspend/resume, Unicode width, and supported release platforms. - -* Phase 3: Build the interactive workflows - -- [ ] Implement the adaptive session header, timeline, contextual approval or - diff view, composer, help overlay, and stale-state treatment. -- [ ] Implement discoverable keyboard navigation and unambiguous confirmation - for approval, denial, cancellation, and process exit without misrepresenting - the hosted runner's lifetime. -- [ ] Bound in-memory timeline and command output while preserving durable - cursor recovery and access to older session history. - -* Phase 4: Harden the TUI and headless mode - -- [ ] Add deterministic renderer and state-transition tests for representative - sizes, focus, redraw, reconnect, duplicate prevention, and terminal cleanup. -- [ ] Exercise supported Linux and macOS terminals, palettes, ~NO_COLOR~, - resizing, suspend/resume, SSH latency, Unicode output, and headless status. -- [ ] Measure polling latency and control-plane load before proposing any new - realtime user-client transport. - -* Phase 5: Make the TUI the default - -- [ ] Make ~kodo~ start the Ratatui/Crossterm interface and host the current - workspace runner after feature parity is proven. -- [ ] Remove the transitional ~start~ and ~resume~ commands after their - workflows and failure behavior are covered by the TUI. diff --git a/rfd/0004/README.adoc b/rfd/0004/README.adoc deleted file mode 100644 index 15c7e2f..0000000 --- a/rfd/0004/README.adoc +++ /dev/null @@ -1,238 +0,0 @@ -:authors: Darwin D Wu -:state: prediscussion -:discussion: -:labels: software, cli, tui, user-interface, accessibility -:toc: - -= RFD 4 Introduce a full-screen terminal interface - -== Goal - -Make active Kodo sessions easier to follow and control from a terminal by -adding a full-screen terminal user interface. The TUI should keep the timeline, -current activity, approval requests, composer, and session state visible -without requiring users to reconstruct the current state from interleaved -scrollback. - -Running `kodo` should start this interface and host the current workspace's -runner. Running `kodo --headless` should host that runner without any session -interaction. Both modes are presentations of the same binary and runner core, -not separate agents or sources of session state. - -== Current experience - -`kodo start` and `kodo resume` host the selected workspace runner, poll the -authenticated session API from a durable sequence cursor, print each event, -prompt for approvals, and cancel the active turn on interruption. This design -is small and resilient, but long sessions mix messages, tool activity, command -output, approval prompts, and status transitions into one stream. - -Kodo also previously exposed a `daemon` subcommand with a newline-delimited -JSON standard-input protocol and an authenticated control-plane mode. The stdin -contract duplicates a transport boundary that production sessions do not use. -The authenticated runner connection remains necessary, but it belongs to the -single Kodo application rather than a separately named daemon product. - -The browser already provides structured navigation and a diff view, but a -developer working primarily in a terminal should not need a browser merely to -see which tool is active, review recent output, compose a follow-up, or resolve -an approval. - -== Proposed direction - -Kodo should have two top-level modes: - -* `kodo` starts the full-screen interactive TUI and hosts the current - workspace's runner. -* `kodo --headless` connects the current workspace's runner to the control - plane without prompts, approvals, a composer, or other interaction. It emits - concise status output naming its runner connection and each session that - sends it work so an operator can see what the local process is handling. - -The old `daemon` command and standard-input tool protocol are removed. The -authenticated runner WebSocket, typed tool protocol, authority leases, -idempotent dispatch, and bounded execution remain internal parts of the one -Kodo binary. Existing `start` and `resume` commands may remain during the TUI -implementation, but are transitional and can be removed after the TUI covers -their workflows. - -The initial TUI may browse and resume sessions available to the authenticated -user, but it hosts exactly one local workspace runner. It must clearly -distinguish sessions that can use that runner from sessions associated with -another workspace. - -The interactive process hosts the workspace runner, so closing it is not -equivalent to closing a browser tab: an active turn may still need its runner. -The TUI must not describe process exit as a harmless detach. Exiting without -cancelling requires an explicit warning that the runner disconnects. A user who -needs a non-interactive long-lived runner launches `kodo --headless` instead; -Kodo does not daemonize itself or create a hidden background service. - -The terminal should use an alternate screen so the interface does not pollute -normal scrollback. Every exit path, including errors, cancellation, terminal -resize, and panic handling where practical, must restore the terminal's prior -mode. Suspending and resuming the process must not leave raw mode enabled or -lose durable progress. - -== Application architecture - -The current CLI combines transport, durable replay, projection, rendering, -terminal input, and runner lifetime in one module. Before adding the TUI, Kodo -should separate an application core from terminal presentation. The core owns: - -* authenticated create, fetch, message, approval, and cancellation requests; -* durable cursor advancement, pagination, retries, and deduplication; -* the current session projection and typed timeline items; -* workspace-runner readiness, status, and lifetime; and -* actions whose outcomes are confirmed by authoritative session state. - -The interactive application follows an Elm-style architecture: - -* A `Model` holds the current session projection, selected views, drafts, - connection state, pending confirmations, and in-flight operation state. -* Typed `Message` values represent user intent, terminal events, runner status, - durable session updates, and completed asynchronous operations. -* A deterministic update function consumes one `Message`, updates the `Model`, - and returns explicit effects to dispatch. It performs no network, filesystem, - clock, or terminal I/O directly. -* A small runtime dispatches effects to the authenticated session client or - runner, then feeds their results back as messages. -* The Ratatui view renders only the current model. Crossterm input is translated - into application messages at the adapter boundary. - -Messages and model types that express Kodo behavior must not contain Ratatui or -Crossterm types. Terminal-only focus, dimensions, and visual state may live in -a terminal presentation model, but session actions and effects remain UI -agnostic. This boundary allows a future `iced` desktop application to reuse the -domain model, update rules, effects, and client runtime while supplying its own -event adapter and view. Kodo should not attempt to share widget trees or invent -a framework abstraction common to Ratatui and Iced. - -The first implementation should continue using the existing authenticated HTTP -session API and durable sequence cursor. Polling every short interval is not in -itself a reason to create a CLI-specific WebSocket protocol. A push transport -may be considered separately if measurement shows polling materially harms -latency or control-plane load; reconnection must still resume from the durable -cursor because push notifications are not authoritative. - -== Initial interface - -The initial layout has four responsibilities rather than a fixed pane count: - -* A header shows session title, durable status, workspace, model profile, runner - connectivity, and whether displayed state may be stale. -* A scrollable timeline renders user and agent messages, tool requests, - bounded command output, failures, and verification results in sequence. -* A contextual area gives pending approvals and the final changed-file or diff - summary enough space to make a decision without obscuring the timeline. -* A composer accepts a follow-up message when authoritative session state - permits one and preserves an unfinished draft during redraws and temporary - disconnection. - -The layout adapts to terminal size. A narrow terminal may replace simultaneous -panes with tabs or overlays, but pending approval and stale connection state -must remain conspicuous. Below a documented minimum size, Kodo displays a clear -resize message or falls back safely rather than rendering corrupt controls. - -Keyboard interaction should follow familiar terminal conventions and be -discoverable in an in-product help overlay. Arrow keys and conventional -alternatives navigate content; `Tab` moves focus; `Enter` performs the focused -action; `Esc` closes transient views. Destructive or consequential actions such -as denial and cancellation require an explicit confirmation and cannot share a -single ambiguous key with ordinary navigation. - -`Ctrl-C` must have predictable semantics. When a turn is active, it opens an -explicit cancellation flow rather than silently exiting and leaving the user -unsure whether execution continues. Cancelling the turn and exiting the -runner-hosting process are distinct actions, and the interface explains their -consequences. - -== Rendering and terminal compatibility - -The implementation uses `ratatui` with `crossterm`. A small prototype first -confirms terminal restoration, input handling, Unicode width, and -release-platform support. Kodo should use established widgets and styles rather -than introducing a local terminal abstraction before the application boundary -is proven. - -Rendering is state-driven. Network and runner tasks send bounded typed updates -to the UI loop; they do not draw directly. The UI redraws after state changes, -input, resize, or a bounded animation tick and must not redraw continuously. -Command output and timeline history remain bounded in memory, with older -content reloadable from the durable sequence API when practical. - -Color conveys emphasis but never the only meaning. The TUI respects `NO_COLOR`, -works with common light and dark terminal palettes, and provides textual status -labels. Focus, selected rows, approvals, failures, and stale state remain -distinguishable without color. Unicode decoration has an ASCII-safe fallback, -and all interaction remains keyboard accessible. - -== Consistency and failure behavior - -PostgreSQL session events and projections remain authoritative. Optimistic UI -may indicate that an action was sent, but approval, cancellation, or message -submission is not shown as complete until the server confirms it. Repeated -message submission reuses a stable client request identifier so a response lost -after commit cannot create a duplicate turn. - -During a control-plane interruption, the TUI keeps the last rendered state, -labels it stale, preserves the composer draft, and disables actions that depend -on fresh state. It retries with bounded backoff and resumes from the last -durable cursor. Runner failure remains distinct from frontend disconnection and -is reported with a recoverable next step where one exists. - -An unexpected renderer failure must not corrupt the session. Kodo restores the -terminal, reports the error in plain text, and leaves already committed session -events available to `kodo resume` or the browser. - -== Non-goals - -The first TUI does not include: - -* editing repository files or embedding a terminal emulator; -* replacing the browser's complete session index or administration pages; -* mouse-only interactions; -* offline execution or a second local copy of session state; -* a new runner protocol or TUI-specific control-plane API; or -* a hidden background daemon or restoration of the stdin runner protocol. - -== Rollout and acceptance - -Implementation should begin with the model-message-update-effect boundary and -regression tests proving approval, cancellation, reconnect, durable replay, and -runner behavior remain intact. A renderer prototype then validates terminal -lifecycle before the full interaction model is built. - -Automated tests use a deterministic terminal backend to cover layout at -representative sizes, focus and key transitions, approval confirmation, -cancel-versus-exit behavior, stale state, reconnection, bounded history, and -terminal restoration after success and failure. Snapshot tests may cover -stable layout regions but must not replace state-transition assertions. - -Manual release checks cover supported Linux and macOS terminals, light and dark -palettes, `NO_COLOR`, narrow windows, resize, suspend/resume, SSH latency, and -long Unicode-rich command output. Headless checks verify non-interactive -connection, bounded status output, and first-seen session reporting. The TUI is -ready to replace the transitional commands only after the full-screen path -demonstrates reliable terminal restoration and complete start/resume parity. - -== Open questions - -Discussion should resolve these points before publication: - -* Which timeline items need expansion, collapse, filtering, or search in the - first release? -* Should diff review be an initial pane, or should the TUI initially hand off - full diff inspection to the user's pager or browser? -* What minimum terminal dimensions and terminal capability checks are - supportable across release platforms? -* Is polling responsive enough after state-driven rendering is implemented, or - does a measured problem justify a shared realtime user-client transport? -* How much terminal-specific selection and focus state belongs beside the - reusable domain model without making a future Iced adapter mirror TUI-only - concepts? - -== Implementation - -Progress against this proposal is tracked in the -link:IMPLEMENTATION.org[RFD 4 implementation checklist]. diff --git a/rfd/0005/CODEX_CONTRACT.adoc b/rfd/0005/CODEX_CONTRACT.adoc deleted file mode 100644 index 25b3e28..0000000 --- a/rfd/0005/CODEX_CONTRACT.adoc +++ /dev/null @@ -1,404 +0,0 @@ -:toc: - -= OpenAI Codex contract investigation - -This document records the source trace for RFD 5 Phase 0. It is an -implementation input, not a statement of formal OpenAI support. Facts about -the published Codex client are source-evidenced; facts about account -entitlement, server behavior, and model compatibility remain unverified until -the live compatibility checks below pass. - -== Reviewed revisions - -The trace was performed on 2026-09-03 against these immutable revisions: - -* OpenAI Codex - https://github.com/openai/codex/tree/1d6727c0b52316515bfbf5dea578374bafb4d898[`1d6727c0b52316515bfbf5dea578374bafb4d898`] -* ReqLLM - https://github.com/agentjido/req_llm/tree/f880edc0931a5dc4737c2352fac2dee288f3b601[`v1.19.0` at `f880edc0931a5dc4737c2352fac2dee288f3b601`] -* LLMDB - https://github.com/agentjido/llmdb/tree/a8ef74cb3983dffac184f50f79c66d059a92f22d[`2026.7.5` at `a8ef74cb3983dffac184f50f79c66d059a92f22d`] - -Kodo pins ReqLLM `1.19.0` and LLMDB `2026.7.5` in `mix.lock`. Any dependency -upgrade or upstream contract change requires repeating this trace and the live -checks. Branch names and rolling model aliases are not compatibility evidence. - -== Published device authorization contract - -=== Client and endpoints - -The published public client ID is -`app_EMoamEEZ73f0CkXaXp7hrann`. Codex allows an application-server override, -but Kodo must use only the reviewed public identity unless a later contract -review explicitly changes it. The source is -https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/login/src/auth/manager.rs[`CLIENT_ID` and `oauth_client_id`]. - -For the default issuer `https://auth.openai.com`, device authorization uses: - -[cols="1,2,2",options="header"] -|=== -| Operation | Method and exact URL | Request - -| Create a device authorization -| `POST https://auth.openai.com/api/accounts/deviceauth/usercode` -| JSON containing `client_id` - -| Display verification destination -| `https://auth.openai.com/codex/device` -| Kodo displays this fixed URL; it does not navigate automatically - -| Poll authorization -| `POST https://auth.openai.com/api/accounts/deviceauth/token` -| JSON containing `device_auth_id` and `user_code` - -| Exchange authorization code -| `POST https://auth.openai.com/oauth/token` -| Form containing `grant_type=authorization_code`, `code`, - `redirect_uri=https://auth.openai.com/deviceauth/callback`, `client_id`, and - `code_verifier` - -| Refresh tokens -| `POST https://auth.openai.com/oauth/token` -| JSON containing `client_id`, `grant_type=refresh_token`, and `refresh_token` -|=== - -The source of the device paths, payloads, redirect URI, and 15-minute local -deadline is -https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/login/src/device_code_auth.rs[`device_code_auth.rs`]. -The exchange contract is in -https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/login/src/server.rs[`exchange_code_for_tokens/6`]. - -The device-code requests do not send a `scope` parameter. The server controls -the authorization represented by the returned code and tokens. The separate -browser authorization flow requests -`openid profile email offline_access api.connectors.read -api.connectors.invoke`, but those browser-flow scopes are not evidence that the -device endpoint accepts or requires a client-supplied scope. Kodo must test the -device flow as published rather than copying the browser query parameters. - -=== PKCE, polling, and expiry - -The device poll response supplies `authorization_code`, `code_challenge`, and -`code_verifier`. Codex does not generate PKCE values locally for this flow; it -passes the returned verifier to the token exchange. This differs from the -browser flow, which generates a verifier from 64 random bytes and computes -`BASE64URL_NO_PAD(SHA256(verifier))` for an S256 challenge. See -https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/login/src/pkce.rs[`generate_pkce`]. - -The user-code response returns `interval` as a JSON string. Codex parses it as -seconds and applies no local default, minimum, or progressive backoff. Polling -has these rules: - -* any `2xx` response is decoded as the authorization-code response; -* `403` and `404` mean retry after the supplied interval; -* every other HTTP status, transport failure, or decode failure is terminal; -* polling stops after a local maximum of 15 minutes, and the final sleep is - capped by the remaining time. - -The source does not establish the provider-side code lifetime or semantic -error names for `403` and `404`. Kodo should persist the earlier of its bounded -local deadline and any provider deadline added to the response contract. - -=== Token fields, account identity, and refresh - -The initial exchange requires `id_token`, `access_token`, and `refresh_token` -response fields represented as strings. The ID token must subsequently decode -for persistence; the exchange decoder does not separately reject empty access -or refresh token strings. Codex extracts these fields from the -`https://api.openai.com/auth` ID-token claim: - -* `chatgpt_account_id` (the workspace/account identity sent with inference); -* `chatgpt_user_id`, falling back to `user_id`; -* `chatgpt_plan_type`; -* `chatgpt_account_is_fedramp`. - -Email comes from the top-level `email` claim and falls back to -`https://api.openai.com/profile.email`. The claim decoding is implemented in -https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/login/src/token_data.rs[`token_data.rs`]. -This path decodes JWT claims; it is not evidence of local signature, -issuer, or audience verification. Kodo treats provider-returned account and -workspace identifiers as secret payload data and does not use decoded claims -as an authorization boundary. - -Refresh responses contain optional `id_token`, `access_token`, and -`refresh_token` fields. A returned value replaces its prior value; an omitted -value preserves the prior value. Therefore the client supports, but does not -prove, server-side refresh-token rotation. Successful persistence advances -`last_refresh` even when some token fields are omitted. - -Codex refreshes proactively when a decodable access-token expiration is within -five minutes. If expiration cannot be decoded, it falls back to an eight-day -`last_refresh` age. A `401`, HTTP `400` with `invalid_grant`, or the backend -codes `refresh_token_expired`, `refresh_token_reused`, and -`refresh_token_invalidated` is permanent. Other refresh failures are -transient. Inference `401` recovery performs at most one storage reload and one -authority refresh. Kodo will own equivalent generation-fenced persistence and -must not use Codex's file store. - -The server's actual rotation policy, access-token lifetime, and revocation -behavior require live verification. - -=== Inference identity and headers - -The published Codex client applies `originator` and a generated `User-Agent` as -default headers. Its default originator is `codex_cli_rs`, while callers may -set a valid process or thread-specific value. ChatGPT bearer authentication -adds: - -* `Authorization: Bearer `; -* `ChatGPT-Account-ID: `; -* `X-OpenAI-Fedramp: true` for a FedRAMP account. - -Kodo's intended originator is `kodo`; it must never impersonate -`codex_cli_rs`. Whether a Kodo-specific `User-Agent` is required or accepted is -a live-contract question. Sources: - -* https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/login/src/auth/default_client.rs[`default_client.rs`] -* https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/model-provider/src/bearer_auth_provider.rs[`BearerAuthProvider`] - -== HTTP transport inventory - -=== Published Codex client - -[cols="1,2,2,3",options="header"] -|=== -| Operation | Client construction | Credentials | Redirect and origin behavior - -| Device authorization and polling -| `create_raw_auth_client` once per issuer-derived operation -| Device authorization ID and user code in JSON -| The reviewed issuer selects the route, then fixed paths are derived from it. - Request logging is disabled. The HTTP builder defaults to following - redirects; no call-site override disables them. - -| Authorization-code exchange -| `create_raw_auth_client` for the issuer -| Authorization code and PKCE verifier in a form body -| Fixed issuer-derived token URL; request logging disabled; redirects remain - enabled by the client default. - -| Token refresh -| `create_default_auth_client` for the refresh endpoint -| Refresh token in JSON -| Exact default URL exists in source, but an environment override exists and - redirects remain enabled. Default Codex headers and cookie storage apply. - -| Buffered inference and HTTP SSE -| `ModelClient::build_api_transport` via the route-aware HTTP client factory -| Bearer and account headers from the request's auth provider -| The initial endpoint selects a concrete direct or proxy route, but the fixed - client then follows redirects using reqwest's default behavior. It does not - use `RouteAwareClientPool`, which can reselect routes and strips sensitive - headers only when scheme, host, or effective port changes. - -| WebSocket inference -| `ApiWebSocketResponsesClient` through the HTTP client factory -| Bearer and account headers on the handshake -| Endpoint-aware Tungstenite handshake. It does not follow an HTTP `3xx`; a - non-upgrade response fails the handshake without a second request. Kodo must - preserve and contract-test that behavior rather than infer it from the HTTP - client policy. -|=== - -The builder default is evidenced by -https://github.com/openai/codex/blob/1d6727c0b52316515bfbf5dea578374bafb4d898/codex-rs/http-client/src/client_builder.rs[`HttpClientBuilder`]. -Codex's HTTP redirect policy is less strict than RFD 5. Kodo must reject every -HTTP redirect, including same-origin redirects, and must enforce exact HTTPS -origins at each credential-bearing transport rather than inherit upstream -behavior. The WebSocket client already treats a redirect as a failed handshake, -but Kodo still needs a regression control for it. - -=== ReqLLM 1.19.0 - -ReqLLM's `openai_codex` provider uses -`POST https://chatgpt.com/backend-api/codex/responses` by default. It accepts an -operation-local `access_token` and `chatgpt_account_id`. A top-level access -token is resolved directly, but provider-specific options are auto-hoisted and -merged with existing nested `provider_options` taking precedence. A stale -nested account ID or originator can therefore override a top-level value. Kodo -must remove conflicting nested values before passing its operation-local -account ID and `codex_originator: "kodo"`. ReqLLM sends `Authorization`, -`ChatGPT-Account-ID`, `originator`, and `content-type`, defaults the originator -to `pi`, and does not set a Codex-specific `User-Agent`. - -ReqLLM supports three inference paths: - -* buffered Req, which asks the server for SSE and assembles the complete - response; -* Finch HTTP/SSE with `openai-beta: responses=experimental`; -* optional WebSocket streaming with - `openai-beta: responses_websockets=2026-02-06`. - -The provider forces `store: false`, `stream: true`, and -`include: ["reasoning.encrypted_content"]`; moves system messages into -`instructions`; removes output-token limits; and drops `previous_response_id` -when resuming with a function result. It implements strict JSON-schema or -strict-tool object output through the shared OpenAI encoder. - -The implementation is -https://github.com/agentjido/req_llm/blob/f880edc0931a5dc4737c2352fac2dee288f3b601/lib/req_llm/providers/openai_codex.ex[`ReqLLM.Providers.OpenAICodex`]. - -ReqLLM does not implement device authorization. If no request-local access -token is present, it searches explicit options, application configuration, -`REQ_LLM_OAUTH_FILE`, `REQ_LLM_AUTH_FILE`, and working-directory OAuth files. -It can refresh and rewrite that shared file. Kodo must bypass this fallback by -always supplying its scoped operation-local access token and account ID; Kodo -retains the refresh token and owns refresh persistence. - -ReqLLM's refresh implementation differs materially from the reviewed Codex -client: it sends form data, requires `access_token`, `refresh_token`, and -numeric `expires_in` in every successful response, and permits arbitrary Req -HTTP overrides. It has no exact-origin or reject-all-redirect enforcement. -Kodo must not delegate durable refresh to this implementation without first -reconciling the live provider contract. - -Neither buffered Req, Finch SSE, WebSocket, nor ReqLLM refresh currently proves -RFD 5's exact-origin and reject-all-redirect requirements. ReqLLM also accepts -a caller-supplied inference `base_url`. These are blocking gaps for production, -not properties to inherit into Kodo's credential resolver. - -== Compatibility evidence status - -LLMDB's OpenAI catalog contains Codex-named model records, and ReqLLM rewrites -their execution provider to `openai_codex`. Those records are derived from the -OpenAI catalog and are not evidence that a ChatGPT subscription exposes the -same exact model, immutable snapshot, capabilities, or reasoning values as the -Platform route. - -No `openai` to `openai_codex` compatibility record is approved. The live -`gpt-5.4` candidate is recorded as rejected in -link:COMPATIBILITY-gpt-5.4-alpha-v1.adoc[`COMPATIBILITY-gpt-5.4-alpha-v1.adoc`]: -the Platform route reported `gpt-5.4-2026-03-05`, while the subscription route -reported the rolling `gpt-5.4` identity. A future approval may be created only -after one exact provider-neutral selector passes both routes for the same -role-contract version. It must capture: - -* exact source and destination model IDs returned by each route; -* whether the selector is immutable or a rolling alias; -* tools and continuation behavior; -* native or strict-tool structured output, as applicable; -* every reasoning effort used by the mapping; -* context requirements and input modalities; -* observation time, dependency revisions, and live-check evidence. - -The current Kodo `alpha-v1` contracts require text input and tool calling for -all roles, at least 100,000 context tokens for primary and 30,000 for search -and review, and object output for review. Current role mappings use reasoning -`none`; future mappings must separately verify every configured effort. - -== Live compatibility spike - -The Phase 0 spike used an explicitly authorized ChatGPT account and a private, -ignored credential file created by `scripts/openai_codex_contract.exs`. Device -authorization, polling, exchange, refresh, and inference used this isolated -credential rather than a shared Codex or ReqLLM OAuth file. The file was loaded -by a new BEAM instance to simulate control-plane restart recovery. Tokens, -device codes, authorization codes, account IDs, raw provider responses, and -secret-bearing logs are not part of the compatibility record. - -For each exact candidate selector, record only bounded, credential-free -outcomes for: - -. device authorization and token exchange; -. one plain text response with `originator: kodo`; -. a tool call and function-result continuation; -. review-role object output; -. each reasoning effort used by a current candidate mapping; -. a control-plane restart between durable token storage and inference; -. refresh with and without a replacement refresh token; -. subscription quota exhaustion, revocation, and `invalid_grant`; -. same-origin and cross-origin redirect canaries proving no follow-up request - and no forwarded authorization material. - -The bounded run established subscription entitlement for `gpt-5.4`, acceptance -of `originator: kodo`, text generation, strict tool calling and continuation, -strict object output, and the current mappings' omitted `none` reasoning -effort. The same behavioral checks passed through the Platform route. Refresh -returned a distinct replacement refresh token, atomically replaced the -spike-owned file, and a new inference process succeeded afterward. -The test-only compatibility probe captures the subscription model identity -from the terminal SSE event before ReqLLM replaces it with the requested -catalog selector; it preserves the response for ReqLLM's normal decoder and -retains no other raw provider data. - -The candidate nevertheless failed the exact-identity rule above, so Phase 0 -ends with a no-go for cross-route switching. Deliberately exhausting a user's -subscription or replaying a rotated token, which can revoke its token family, -would add destructive cost without changing that decision. Quota was not -present on the test account. Safe negative controls established HTTP 401 for a -malformed bearer token and HTTP 401 with provider code `token_expired` for a -malformed refresh token. Production quota and revocation behavior remains a -bounded request outcome, not durable credential state, and requires regression -evidence only if a future exact-identity candidate passes. - -=== Evidence status - -[cols="2,1,3",options="header"] -|=== -| Check | Status | Evidence boundary - -| Device authorization, polling, and exchange -| Live, manually initiated -| Reproducible through the ignored-file spike script. - -| Text with `originator: kodo` -| Live, automated -| Covered by the opt-in compatibility test. - -| Canonical Kodo tool and continuation -| Live, automated -| Uses Kodo's current `read_file` definition and ReqLLM adapter conversion. - -| Canonical review object -| Live, automated -| Uses `Kodo.Agent.ReviewResult.schema/0`, the production schema owner. - -| Current `none` reasoning mapping -| Live, automated -| Verified through the adapter's intentional omission of the provider option. - -| Process restart and credential reload -| Live, manually observed -| Inference ran in a new BEAM instance after loading the isolated file. - -| Refresh-token replacement -| Live, manually observed -| Provider returned a distinct replacement; inference passed afterward. - -| Refresh response omitting a replacement -| Source-only -| The spike preserves an omitted token, but the live provider returned one. - -| Malformed bearer and refresh credentials -| Live, manually observed -| Bounded negative controls returned HTTP 401 without mutating shared state. - -| Quota exhaustion and real revocation -| Skipped after no-go -| Not manufactured because cost or token-family damage could not change the - failed identity decision. - -| HTTP and WebSocket redirect canaries -| Deferred -| Required for the Phase 1A Kodo-owned transport; not inferred from this spike. -|=== - -== Phase 0 implementation consequences - -The trace establishes these requirements for later implementation: - -* Kodo needs its own device authorization, polling, exchange, refresh, and - generation-fenced durable lifecycle; ReqLLM supplies inference encoding, not - that lifecycle. -* Kodo must centralize exact origins while enforcing redirect rejection in - every concrete transport. Merely passing ReqLLM options is insufficient for - Finch and WebSocket paths. -* The scoped resolver must always pass `access_token`, - `chatgpt_account_id`, `auth_mode: :oauth`, and - `codex_originator: "kodo"` operation-locally. It must not pass the refresh - token or enable OAuth-file fallback. -* ReqLLM exceptions and stream events require bounded redaction before any - persistence, logging, telemetry, or browser rendering. -* Kodo cannot enable an `openai`/`openai_codex` route switch until an approved - versioned live compatibility record exists for the exact selector and role - contract. The current `gpt-5.4` record is explicitly rejected. diff --git a/rfd/0005/COMPATIBILITY-gpt-5.4-alpha-v1.adoc b/rfd/0005/COMPATIBILITY-gpt-5.4-alpha-v1.adoc deleted file mode 100644 index 42bac93..0000000 --- a/rfd/0005/COMPATIBILITY-gpt-5.4-alpha-v1.adoc +++ /dev/null @@ -1,131 +0,0 @@ -:toc: - -= Rejected compatibility record: `gpt-5.4`, `alpha-v1` - -== Decision - -`gpt-5.4` is *not approved* for route changes between `openai` and -`openai_codex` under Kodo's `alpha-v1` role contract. The live checks showed -compatible behavior for the exercised capabilities, but the routes did not -report the same exact model identity. Matching request selectors are therefore -insufficient evidence under RFD 5. - -== Evidence - -This record was observed on 2026-09-03 with the dependency and source -revisions pinned in link:CODEX_CONTRACT.adoc[the Codex contract investigation]. -The opt-in check is -`test/e2e/openai_codex_contract_live_test.exs`. It passes credentials to -ReqLLM operation-locally, preventing ReqLLM's OAuth-file fallback. -Because ReqLLM 1.19.0 populates its public Codex response model from the -requested selector, the test-only `Kodo.Test.OpenAICodexContractProbe` captures -only `response.model` from the terminal provider SSE event immediately before -ReqLLM decodes the unchanged response. The identities below therefore come -from provider response payloads rather than a comparison with request input. - -[cols="1,2,2",options="header"] -|=== -| Property | `openai` Platform route | `openai_codex` subscription route - -| Requested selector -| `gpt-5.4` -| `gpt-5.4` - -| Model identity returned by the route -| `gpt-5.4-2026-03-05` -| `gpt-5.4` - -| Billing credential -| OpenAI Platform API key -| ChatGPT OAuth access token plus account ID - -| Plain text -| Passed -| Passed with `originator: kodo` - -| Strict Kodo-shaped tool call -| Passed with the canonical `read_file` schema -| Passed with the canonical `read_file` schema - -| Function-result continuation -| Passed -| Passed - -| Strict review-shaped object output -| Passed with `Kodo.Agent.ReviewResult.schema/0` -| Passed with `Kodo.Agent.ReviewResult.schema/0` - -| Current mapping reasoning effort -| Passed with no reasoning option -| Passed with no reasoning option -|=== - -All current `alpha-v1` role mappings use Kodo's `none` reasoning setting. The -adapter intentionally omits `reasoning_effort` for that setting, so no other -effort is part of this record. A future mapping with a non-`none` effort needs -new live evidence and a new compatibility record. - -The catalog advertises text and image input, tool calling, reasoning, object -execution, and a 1,050,000-token context window for both resolved records. The -live spike exercised text only; catalog modality and maximum-context metadata -are not promoted to live compatibility evidence. - -As negative entitlement controls, the subscription route rejected -`gpt-5.3-codex`, `gpt-5.2-codex`, and `gpt-5.1-codex-max` with HTTP 400 as not -supported for Codex with a ChatGPT account. This demonstrates why LLMDB catalog -presence cannot establish subscription availability. - -== Reproduction - -Create an isolated, ignored credential file through the published device flow: - ----- -mix run --no-start scripts/openai_codex_contract.exs authorize tmp/openai-codex-phase0.json ----- - -After approval, run the compatibility check in a new BEAM instance. The new -process and file reload provide the Phase 0 control-plane restart simulation: - ----- -LIVE_CODEX_AUTH_FILE=tmp/openai-codex-phase0.json \ - mix test test/e2e/openai_codex_contract_live_test.exs --include live_provider ----- - -The check also requires `OPENAI_API_KEY` for the separately billed Platform -route. It is excluded by default and must remain an opt-in, externally billed -test rather than a product or deployment feature flag. A complete run makes -nine bounded model requests: four through Platform billing and five through -the ChatGPT subscription route. Retries are disabled to avoid duplicate billed -requests. - -Refresh and rerun a focused post-rotation inference check with: - ----- -mix run --no-start scripts/openai_codex_contract.exs refresh tmp/openai-codex-phase0.json -LIVE_CODEX_AUTH_FILE=tmp/openai-codex-phase0.json \ - mix test test/e2e/openai_codex_contract_live_test.exs:48 --include live_provider ----- - -The broader source-only, manually observed, deferred, and deliberately skipped -checks are classified in the investigation's evidence-status table. - -== Boundary and diagnostics - -The supported result of Phase 0 is a no-go for cross-route switching, not an -assertion that either provider route is generally unavailable. The standalone -subscription route successfully handled the exercised ReqLLM calls. Kodo must -continue treating `openai` and `openai_codex` as distinct provider and billing -identities. - -A malformed bearer credential returned HTTP 401 and a malformed refresh token -returned HTTP 401 with provider code `token_expired`; both require -reauthorization rather than classification based on provider message text. -Quota exhaustion was not present on the authorized account and was not -manufactured by intentionally consuming a user's subscription. No durable -quota-state behavior is approved by this record. - -The device authorization and refresh endpoint are upstream public-client -dependencies, and the subscription integration remains Beta and without a -claim of formal OpenAI support. Any changed endpoint, client identity, token -shape, ReqLLM version, returned model identity, or `alpha-v1` capability -contract invalidates this record and requires rerunning Phase 0. diff --git a/rfd/0005/IMPLEMENTATION.org b/rfd/0005/IMPLEMENTATION.org deleted file mode 100644 index c6030f2..0000000 --- a/rfd/0005/IMPLEMENTATION.org +++ /dev/null @@ -1,486 +0,0 @@ -#+TITLE: RFD 0005 implementation checklist - -Implements [[file:README.adoc][RFD 5: Store user-owned LLM provider integrations]]. - -* Phase 0: Implement and verify the OpenAI Codex contract - -- [X] Trace the current OpenAI Codex device authorization and refresh flow from - OpenAI's published Codex source and record the public OAuth client identity, - scopes, device and token endpoints, PKCE behavior, polling rules, expiry, - token rotation, account identification, and client headers. -- [X] Inventory the concrete HTTP clients and request constructors used by - Codex device authorization, polling, exchange, refresh, buffered inference, - and streaming; record where exact origins, redirect behavior, and - request-local credentials are enforced. -- [X] Reproduce the complete device flow in a bounded Kodo live spike and - verify ReqLLM's ~openai_codex~ provider with a Kodo originator for a text - response, Kodo tool calls, structured output, and every reasoning effort - required by current role mappings. -- [X] Record exact model identities available through both ~openai~ and - ~openai_codex~ and create versioned compatibility records by provider-neutral - selector, source/destination routes, and role-contract version for tools, - structured output, reasoning, context, and modalities; do not treat matching - slugs, catalog fallback, or merely similar models as sufficient evidence. -- [X] Verify refresh-token rotation and control-plane restart recovery without - using a shared OAuth file; classify safe invalid-credential controls and stop - destructive quota exhaustion or rotated-token replay once the exact-model - candidate has already failed. -- [X] Document the exact working contract, regression diagnostics, upstream - public-client dependency, and Beta support boundary without claiming formal - OpenAI support unless separately confirmed. -- [X] Treat opt-in live-provider and compatibility checks only as controls for - externally billed tests, not as deployment or product feature flags. - -The source trace, reviewed revisions, transport inventory, live procedure, and -known ReqLLM gaps are recorded in [[file:CODEX_CONTRACT.adoc][the Codex contract -investigation]]. The live ~gpt-5.4~ result is a -[[file:COMPATIBILITY-gpt-5.4-alpha-v1.adoc][versioned rejected compatibility -record]]: both routes passed the exercised ~alpha-v1~ behaviors, but they -reported different exact model identities, so cross-route switching remains -disabled. Destructive quota exhaustion and rotated-token replay were not -manufactured after that no-go decision. - -* Phase 1A: Establish the credential security foundation - -- [X] Generate migrations for durable user/provider integrations, separate - connection and validation states, non-secret status metadata, credential - generation, and encryption-key version. Treat this as a fresh encrypted schema - with no plaintext, environment-key, or legacy integration import path. Phase 2 - extends the schema to several named accounts per provider with one active row. -- [X] Enforce the connection-validation matrix through context transition - functions and database constraints where practical: only - ~disconnected+unverified~ without a payload, - ~reauthorization_required+unverified~ with the provisional payload, and - ~connected~ with any validation state. Only connected credentials not marked - invalid admit new provider requests. -- [X] Enforce ~ON DELETE CASCADE~ from users to integrations; account deletion - must not depend on a successful provider call. -- [X] Add authenticated encryption with unique nonces, versioned keys, and AEAD - associated data binding integration ID, user ID, provider, authentication - type, and payload format version; keep provider account and workspace - identifiers inside the encrypted payload. -- [X] Add safe redaction and production configuration that distinguishes the - Kodo credential-encryption key ring from all LLM provider credentials, - validates every current and previous key before replica readiness, and fails - closed on missing keys or payload authentication failures. -- [X] Do not derive or persist API-key hashes, suffixes, or fingerprints and - never fingerprint OAuth tokens; permit only provider-supplied labels that are - explicitly classified as non-secret by the reviewed provider contract. -- [X] Implement scope-first integration context operations for listing, - connecting, replacing, validating, and disconnecting credentials without - accepting browser-supplied ownership; disconnect clears the encrypted payload - but preserves the row, and every credential change advances its generation. -- [X] Implement explicit generation-fenced transitions for connect, replace, - validation success, confirmed invalidity, transient validation failure, - revalidation, disconnect, refresh ~invalid_grant~, delayed refresh success, - and OAuth success. Failed or cancelled authorization attempts terminate the - attempt without changing the integration's prior connection-validation pair. -- [X] Add a typed, non-secret ~Kodo.LLM~ integration reference containing - integration and provider identity. Require authenticated scope plus that - reference in text/tool and structured-output callbacks, and update primary, - search, review, and every direct adapter caller to supply them. -- [X] Make the scoped resolver the only component that rechecks reference - ownership and generation, decrypts the payload, and constructs the private - operation-local credential translated into ReqLLM options; public callers - cannot supply raw API keys, OAuth tokens, or internal credential values. -- [X] Resolve each model through ~ReqLLM.model/1~, allow only ~openai~, - ~openai_codex~, ~anthropic~, and ~openrouter~, and fetch the session owner's - integration using the resulting ~LLMDB.Model.provider~; replace model-string - splitting with that resolved provider when storing derived display data. -- [X] Persist exact model identity separately from execution provider and - billing route in every session role mapping. Define identity as the exact - provider-neutral selector, including an immutable version when both routes - expose one, without claiming rolling aliases are identical backend snapshots; - user and repository default changes affect new sessions only. -- [X] Require exact equality between resolved model and credential providers - before recording an invocation or making an HTTP request, with actionable - missing, invalid, disconnected, reauthorization-required, malformed-model, - unsupported-provider, and mismatch errors; allow ~unverified~ and - validation-~unavailable~ credentials. -- [X] Persist credential-free invocation provenance containing canonical - provider, authentication type, and Platform, subscription, or aggregator - billing path. -- [X] Remove provider-key environment lookup from the production adapter and - make missing user integrations fail closed; update the evaluation runner, - development setup, and opt-in live-provider checks to require an explicit - test user with encrypted integrations through the same Kodo-owned boundary. -- [X] Pass only API keys or current OAuth access tokens and required account - identifiers into ReqLLM; keep refresh tokens, expiry, generation, and rotation - state inside Kodo. -- [X] Preflight every role integration before accepting a turn, resolve again - immediately before every generation call, and normalize Req/ReqLLM failures - into bounded domain errors before persistence, inspection, logging, - telemetry, or browser display. -- [X] Represent quota exhaustion and billing-required responses only as bounded - outcomes on the affected invocation. Do not mutate or persist integration - state or run background quota checks; preserve the session work and provide - retry plus links to provider billing and the relevant integration settings. -- [X] Batch preflight metadata through indexed user/provider queries without - decryption; immediately before each credential-bearing external operation, - perform the bounded current integration or authorization-attempt lookup and - local decryption without holding a database transaction or lock across the - request. -- [X] Keep plaintext credentials out of GenServers, ETS, persistent terms, - session state, and unnecessary process messages; discard operation-local - references after use without claiming BEAM memory zeroization. Do not add an - encrypted cache without measured database pressure and a separate consistency - review. -- [X] Define operation admission as the final successful ownership, state, and - generation check for the operation-local decrypted payload. For model calls, - recheck generation while durably recording invocation start and billing - provenance before permitting HTTP; allow admitted operations to complete - after replacement, disconnection, or deletion, but require every later call - and continuation to seek admission again. -- [X] Centralize exact HTTPS provider-origin allowlists and disable automatic - redirects for every credential-bearing validation, inference, authorization, - polling, exchange, and refresh request; classify every ~3xx~, including - same-origin redirects, as provider unavailable without a follow-up request. -- [X] Maintain a transport security matrix covering buffered Req/ReqLLM calls, - Finch streaming, Req OAuth operations, and Codex-specific inference. Require - every new or changed transport to enforce exact origins, reject redirects, - and accept credentials only from the scoped operation-local value. -- [X] Add every provider secret field to Phoenix parameter filtering and test - that filtered request logs, changeset errors, exception inspection, and - LiveView events cannot expose credential material. -- [X] Keep API keys out of LiveView socket assigns and rendered forms: accept - them only in a ~phx-submit~ event with no secret-field ~phx-change~, pass the - event value directly to the scoped encryption context, never echo it through - validation errors or diffs, and clear the browser input after a successful - save. -- [X] Add the credential-free security audit framework and API-key lifecycle - events; permit internal actor and integration IDs only in audit records, - never metric labels. -- [X] Verify provider credentials never reach runner registration, runner - WebSockets, tool subprocesses, session events, browser responses, exception - inspection, or telemetry metadata. -- [X] Test encryption round trips and redaction, ownership isolation, - ciphertext swaps between users and providers, tampering, wrong and missing - keys, unknown payload versions, nonce uniqueness, lifecycle transitions, - generation fencing, provider mismatches, owned text and object generation, - evaluation ownership, safe provider errors, same-origin and cross-origin - redirect rejection, no credential-bearing follow-up request, and absence of - an environment-key fallback. Assert credential-derived identifiers are absent - from persistence, UI, logs, telemetry, and audit records. Delete a user with - API-key integrations and racing validation work, then assert all owned rows - are gone, pre-admission work sends no request, and admitted work cannot - recreate or mutate deleted integration state after completion. Test pauses - before and after admission, forged and cross-user references, and - application-level non-retention in process state and messages without - asserting physical memory erasure. -- [X] Add contract tests for every transport and operation in the matrix. For - same-origin and cross-origin redirects, assert no follow-up request and no - forwarded authorization material. Configure sentinel provider environment - keys, ReqLLM global credentials, and OAuth files, then prove scoped requests - send only the user integration credential and missing integrations fail - before network admission without fallback. -- [X] Add table-driven tests for every allowed connection-validation pair, - rejection of impossible pairs and payload combinations, each legal transition, - generation fencing, invalid-to-valid and invalid-to-unavailable revalidation, - and request admission for connected unverified or unavailable credentials but - not invalid credentials. -- [X] Do not expose a credential form or permit a production provider request - until every Phase 1A security boundary and test is complete. - -* Phase 1B: Add OpenAI API integration and settings - -- [X] Build a shared responsive settings shell with Account and Integrations - navigation, a framed desktop/tablet workspace, compact persistent rail, - deep-linkable detail pane, clear return action, accessible narrow-screen - section navigation, and consistent page headings and action placement that - preserve the RFD interface sketches' hierarchy. -- [X] Show only implemented user-owned settings; do not add a Personal/Workspace - switch or placeholder categories before Kodo defines workspace-owned - configuration and authorization. -- [X] Restyle the existing account email and password forms as distinct, - balanced settings surfaces without changing generated authentication, - confirmation, or sudo-mode behavior. -- [X] Add ~/integrations~ to the existing authenticated LiveView session and - browser pipeline. Use the normal authenticated-user boundary for viewing and - managing user-owned integrations, including submission, replacement, and - disconnection; do not require renewed sudo mode. Implement the OpenAI - Platform API-key provider card, contextual form, connection status, loading - state, and accessible feedback. -- [ ] Add baseline onboarding and model-settings feedback that links users to - the OpenAI integration required by their selected role mapping. -- [X] Save OpenAI API keys encrypted as ~unverified~ before asynchronously - probing the non-inference ~GET /v1/models~ metadata endpoint in a bounded - generation-fenced task. Mark only an explicit ~invalid_api_key~ or revoked-key - response invalid; classify other authentication contexts, permission, network, - TLS, timeout, redirect, rate-limit, and provider failures as unavailable. -- [X] Never run billed inference during automatic or user-requested credential - validation. -- [X] Offer a generic Check access action that reruns the same bounded, - generation-fenced non-inference metadata probe against the saved credential - without returning it to the browser. Present Valid and Invalid as explicit - green and red outcomes and keep Not checked and Unable to verify neutral. -- [ ] Offer a Test model request only after explicit confirmation identifies the - exact provider and model and warns of possible charges; require authenticated - ownership and confirmation under the normal authenticated-user boundary. -- [X] State in disconnect confirmation that future Kodo requests stop while an - already-admitted or sent provider operation and its billing may continue, and - link to provider-side revocation when Kodo cannot revoke the credential - directly. -- [X] Add LiveView selector tests for the settings shell, section navigation, - OpenAI provider card, and contextual API-key form, plus representative desktop, - tablet, and narrow-mobile browser checks for the sketched layouts. -- [X] Render connection state before validation state and show validation only - for connected integrations; add selector coverage proving the UI cannot - display impossible combinations such as disconnected plus valid or a - request-scoped quota badge. -- [ ] Keep provider connection separate from routing changes; when no usable - mapping exists, present one provider-compatible role preset with explicit - billing paths and apply it only after "Use recommended models" confirmation. -- [ ] Test that connecting OpenAI leaves an existing usable mapping unchanged, - confirmed presets affect only defaults and new sessions, and disconnecting a - required integration derives an unavailable mapping without rewriting or - silently rerouting existing sessions. -- [ ] Test concurrent users with different OpenAI keys, key replacement during - a session, missing integration behavior, catalog aliases, inline model specs, - malformed models, billing provenance, cross-user actions, aged authenticated - sessions, and stale LiveView sockets. Cover request admission followed by - disconnect, completion with original provenance, failure of the next request - or tool continuation, and rejection of late validation updates. Verify save - succeeds during outage, stale validation cannot overwrite a newer generation, - permission-limited probes do not mark a key invalid, and no automatic path - sends a billed model request. -- [X] Test that the API-key field is available only to an authenticated owner, - has no ~phx-change~, is never copied into socket assigns or rendered diffs, - and is cleared after success. -- [X] Emit and test credential-free audit events for OpenAI API-key submission, - replacement, validation, and disconnection through the Phase 1A audit - framework. -- [ ] Emit and test credential-free Test confirmation and outcome audit events - when the optional billed Test model request is implemented. - -* Phase 2: Add Anthropic and OpenRouter API keys - -- [X] Add Anthropic API-key connection, fixed endpoint configuration, - asynchronous non-inference ~GET /v1/models~ metadata validation, and safe - generation-fenced error classification. Support only standard workspace- - scoped Console keys; return actionable unsupported-credential guidance for - unscoped identity-linked credentials that require workspace selection. Do not - add higher-privilege Admin API or workspace-selector support for inference. -- [X] Add OpenRouter API-key connection, fixed endpoint configuration, - asynchronous non-inference ~GET /api/v1/key~ metadata validation, documented - invalid/revoked-key ~401~ handling, and explicit OpenRouter billing identity - for routed models. -- [X] Represent saved-but-unverified credentials separately from valid, invalid, - and validation-unavailable credentials. Keep unverified and unavailable - credentials usable, block only confirmed invalid credentials, and treat quota, - billing, entitlement, restricted validation permission, and provider outages - as non-invalid outcomes. -- [X] Extend integration settings and model-selection feedback to distinguish - OpenAI API, Anthropic, and OpenRouter providers without displaying saved - credentials. -- [X] Allow several named accounts for the same API-key provider. Enforce at - most one connected active account per user/provider in the database, activate - only the first account automatically, require explicit activation to switch, - and leave no active fallback when that account is disconnected. -- [X] Add an Add integration provider menu and account-input modal. Render one - card per integration and target activation, access checks, key replacement, - reconnection, and disconnection by the owned integration ID and credential - generation without retaining credential input in LiveView state. -- [ ] Extend onboarding for Anthropic and OpenRouter; baseline provider - onboarding remains pending with the Phase 1B model-settings experience. -- [X] Extend missing-provider feedback for Anthropic and OpenRouter, and emit - credential-free audit events for each provider's key - submission, replacement, validation, and disconnection. Test confirmation and - outcome audits remain covered by the Phase 1B conditional item because the - optional billed Test action is not implemented. -- [X] Test a role mapping that uses different connected providers for primary, - search, and review, including absence or revocation of one required - integration during a turn. -- [X] Test that connecting another provider leaves a usable mapping unchanged - and that OpenRouter models use the OpenRouter integration even when their - underlying vendor is OpenAI or Anthropic. -- [X] Test each provider probe and outcome class, generation fencing, usable - unverified/unavailable credentials, blocking confirmed-invalid credentials, - and expected safe error identifiers without raw response persistence. No - billed Test action is implemented in Phase 2, so its explicit cost - confirmation remains covered by the Phase 1B conditional item. -- [ ] Pin each expected metadata response contract and verify its charging - documentation before ship. -- [X] Test provider- and model-specific quota and billing responses on an - invocation: the affected session preserves work and offers retry and guidance, - while connection and validation remain unchanged and integration cards show - no stale quota state. -- [X] Add opt-in live-provider checks for OpenAI API, Anthropic, and OpenRouter - using explicit test-user integrations while keeping ordinary tests - independent of external provider access. - -* Phase 3: Add ChatGPT subscription device authorization beta - -- [X] Generate persistence for one active, expiring, user-scoped, single-use - device authorization attempt per ~openai_codex~ integration, including - encrypted sensitive fields, encryption-key and payload-format versions, - immutable attempt and expected integration generations, provider deadline and - polling interval, database-time claim lease, monotonically increasing claim - epoch, and bounded cleanup. Enforce ~ON DELETE CASCADE~ from integrations to - attempts and their claim state. -- [X] Encrypt every attempt payload with a unique nonce and AEAD associated data - binding attempt ID, integration ID, user ID, provider, immutable attempt - generation, and payload-format version; fail closed on swaps, tampering, - unknown formats, and unavailable keys. -- [X] Implement device-code creation, interval-aware asynchronous polling, - cancellation, expiry, terminal errors, and authorization-code exchange using - Req rather than embedded browser scripts. -- [X] Render the fixed allowlisted HTTPS verification destination and one-time - code separately, reject a provider-returned verification URL that does not - match the exact allowlist, and never automatically navigate to that URL. -- [X] Trigger claims from connection-driven attempt creation, LiveView - mount/remount, generation-specific retry, and task-completion recovery; use - one conditional update against the exact attempt row that increments and - returns its claim epoch, and run a successful claim as a finite task under - ~Kodo.ControlPlaneTaskSupervisor~ that survives the originating LiveView - closing. -- [X] Conditionally renew the claim lease before expiry and verify active state, - current claim epoch, and lease ownership before admitting every poll or token - exchange. Make its duration exceed the hard HTTP timeout plus a safety margin. - Stop future work immediately on ownership loss; fence completion by claim - epoch plus attempt and expected integration generations, while allowing an - already admitted network operation to finish without persisting stale results. -- [X] Do not run a device-polling sweeper on every replica; expire attempts - lazily and delete terminal rows in bounded batches, using one database-elected - cleanup owner only if periodic cleanup becomes necessary. -- [X] Make a new attempt atomically supersede the prior attempt and fence - cancellation, expiry, completion, replacement, and disconnection by attempt - generation. Starting reauthorization advances the integration generation and - the new attempt captures that post-advance value; install OAuth credentials - only when both attempt and expected integration generations still match. -- [X] Store access tokens, refresh tokens, and account identifiers in the - encrypted integration payload. Keep expiries and credential generations as - queryable lifecycle metadata, without logging device or token material. -- [X] Test user deletion with OAuth credentials, an active authorization - attempt, a held claim, and in-flight refresh; all rows cascade and every late - completion becomes a no-op. -- [X] Run just-in-time refreshes as bounded tasks under - ~Kodo.ControlPlaneTaskSupervisor~; coordinate callers directly through the - database rather than adding a refresh coordinator ~GenServer~, long-lived - supervised process, or in-memory refresh timer per integration. -- [X] Implement database-time refresh leases whose duration exceeds the hard - HTTP timeout plus a safety margin, bounded waiter behavior, lease takeover, - and credential-generation compare-and-update protection for every success - and failure-derived state change. -- [X] Let the first generation-matching successful response atomically persist - rotated tokens even after lease expiry. Record ~invalid_grant~ as provisional - ~reauthorization_required~ without advancing the source generation, so a - success already produced from that generation may replace it after any pause; - fence it permanently when user replacement, starting or completing - reauthorization, or disconnection advances the generation. -- [X] Require every refresh success to contain an access token and valid expiry; - retain the prior refresh token and account ID when omitted, persist a rotated - refresh token when present, and reject an account-ID change as requiring - reauthorization without changing billing identity. -- [X] Treat bounded waiting after takeover ~invalid_grant~ only as a UI-churn - optimization, not an outcome-selection boundary. -- [X] Add the "ChatGPT Subscription (Beta)" connection flow, billing - explanation, progress state, cancellation, disconnect, and reauthorization to - the authenticated integrations page; show subscription quota errors only on - the affected session or turn with retry and billing guidance. -- [X] Use the normal authenticated-user boundary to start authorization or - reauthorization and to cancel an owned attempt; do not require renewed sudo - mode. Permit the same active generation-fenced attempt to complete while its - ownership and generation checks continue to succeed. -- [X] Add LiveView selector tests for device-flow start, verification code, - progress, expiry, completion, cancellation, and reauthorization states, plus - completion from aged authenticated sessions, ownership-checked cancellation, - stale sockets, and representative responsive browser checks. Verify the - short-lived device code - has an accessible Copy action, is retained only while needed to present the - active attempt, and disappears after every terminal state without entering - logs or telemetry. -- [ ] Extend onboarding for ChatGPT Subscription. The baseline onboarding and - confirmed model-preset interaction remain Phase 1B and Phase 2 work. -- [X] Extend missing-provider feedback for ChatGPT Subscription and emit - credential-free audit events for authorization start/completion and - cancellation, refresh outcomes, reauthorization, and disconnection. -- [ ] Add an explicit per-session execution-route change between OpenAI - Platform and ChatGPT Subscription only when the destination supports every - affected role's exact provider-neutral selector and has a versioned - compatibility record for its capability contract; show billing confirmation - rather than requiring sudo, and reject the whole atomic role set when any role - is incompatible. Emit a credential-free route-change audit event. - The durable change boundary and audit event are implemented, but no interaction - is exposed because the live ~gpt-5.4~ record is explicitly rejected: Platform - returned ~gpt-5.4-2026-03-05~ while ChatGPT returned ~gpt-5.4~. -- [X] Under the existing durable session lock, assign each accepted turn a route - revision and persist its complete per-role model, execution-route, and - capability-contract snapshot. Write confirmed route changes as pending - revisions under the same lock and apply them only to later accepted turns. -- [X] Use the persisted turn snapshot for primary, search, review, every tool - continuation, and process/node restart recovery; replay normalized visible - assistant/tool history after a route change without provider-specific - reasoning, signature, or cache state. -- [X] Route requests whose persisted turn snapshot selects ~openai_codex~ only - through the user's ChatGPT integration and prohibit silent fallback to OpenAI - API billing. - -Production generation entry points consume a ~Kodo.LLM.InvocationAdmission~ -returned by the session transaction that records invocation start and canonical -billing provenance. Scoped credential resolution and decryption precede that -transaction; the transaction rechecks session ownership, integration state, and -credential generation before permitting inference. The admission struct makes -that internal boundary explicit, but is not an unforgeable bearer capability -because BEAM modules can construct structs. The separately named evaluation -entry points are out-of-band harness operations and do not represent production -session admission. Turn acceptance holds deterministic provider-selection and -active-row locks while validating the complete role set; those locks end at -commit and are never held across inference. - -Device and refresh recovery also preserve already-admitted provider results -while bounding automatic expired-token recovery. Explicit activation or -disconnection invalidates older selection-restoration intent, expired device -attempts cannot poison refresh admission, and open LiveViews reconcile polling, -exchange, terminal, and superseded attempt state from durable storage. - -- [ ] Test authorization ownership and expiry, polling backoff, two-node refresh - contention, multi-node and concurrent-tab device claims, claim epoch takeover - and conditional renewal, stale claimant polling and completion, pauses before - and after poll admission, duplicate exchange and completion, LiveView closure - and remount, node restart, superseded and stale attempts, - cancellation/replacement/disconnection races, late refresh - success after lease expiry, takeover ~invalid_grant~, terminal-first success - after a pause longer than every waiter timeout, node pause, replacement during - refresh, omitted and rotated refresh tokens, omitted and changed account IDs, - permanently lost rotated-token responses, refresh restart recovery, - revocation, cross-user and cross-attempt ciphertext swaps, attempt tampering, - missing attempt keys, unknown attempt payload versions, routine rotation with - an active old-key attempt, emergency attempt cancellation, exact-model route - changes, rolling-alias and immutable-snapshot compatibility, whole-set - rejection when one role is incompatible, route-change/turn-acceptance races, - process and node restart during a turn, in-flight route freezing, normalized - cross-route replay, no automatic route fallback, same-origin and cross-origin - redirect rejection, malicious verification URLs, absence of a - credential-bearing follow-up request, and secret redaction. -- [ ] Run the Phase 0 live compatibility suite against the production path and - do not declare ChatGPT/Codex implementation complete while a required - capability fails; classify later contract failures as regressions and never - fall back to Platform billing. -- [ ] Ship ChatGPT Subscription as a Beta without a deployment feature flag only - after its implementation and required compatibility suite pass; surface later - contract regressions as actionable integration-unavailable errors. - -* Phase 4: Harden operations - -- [ ] Add bounded-cardinality telemetry for integration operations and verify - credential-free audit completeness across every provider lifecycle, - validation, Test, authorization, refresh, reauthorization, disconnection, and - execution-route action introduced by Phases 1B through 3. -- [ ] Implement and test staged encryption-key rotation: distribute the new key - as non-current, verify every replica accepts both keys, make it current for - writes, and re-encrypt old rows in bounded batches using credential-generation - and old-key-version CAS checks. -- [ ] Retain the old key until no payload uses it and the application rollback - and backup-retention windows close; test concurrent replacement and - disconnection, interrupted-batch resume, mixed-version reads, rollback while - both keys remain configured, active authorization attempts on an old key, - emergency cancellation for a compromised key, and refusal to start when any - integration or attempt key version is missing from the ring. -- [ ] Document encryption-key provisioning, separately protected key backups, - database-backup and write-ahead-log retention, account deletion limits, - credential and provider revocation, staged key rotation, device-flow - troubleshooting, refresh failure alerts, BEAM debugging and memory-inspection - restrictions, crash/core dump and swap handling, and rollback from each - rollout phase without plaintext or provider-environment fallback. -- [ ] Run ~mix precommit~ and the opt-in provider compatibility checks before - declaring the RFD implemented. diff --git a/rfd/0005/README.adoc b/rfd/0005/README.adoc deleted file mode 100644 index ed91411..0000000 --- a/rfd/0005/README.adoc +++ /dev/null @@ -1,1056 +0,0 @@ -:authors: Darwin D Wu -:state: discussion -:discussion: https://github.com/chaba-dev/kodo/pull/25 -:labels: software, integrations, llm, oauth, security -:toc: - -= RFD 5 Store user-owned LLM provider integrations - -== Goal - -Let each Kodo user connect the LLM providers used by their agent sessions -without requiring an operator to configure a deployment-wide OpenAI API key for -successful model requests. The first provider set includes OpenAI Platform API -keys, Anthropic API keys, OpenRouter API keys, and OpenAI Codex access through a -linked ChatGPT subscription. - -Provider credentials remain in the control plane. Runners continue to receive -only Kodo credentials and tool requests; they never receive LLM API keys, -access tokens, or refresh tokens. - -== Current state - -Kodo delegates provider authentication to ReqLLM. With no request-local -credential, ReqLLM reads `OPENAI_API_KEY` from the control-plane environment. -This lookup occurs when a model request is made; the key is not required for -the control plane to boot, but model requests fail without it. The fallback -creates one deployment-wide provider identity, makes credential changes a -deployment-configuration concern, and prevents users from choosing separately -billed provider accounts. - -The existing execution boundary is otherwise suitable. Agent inference runs in -the Phoenix control plane, sessions have a durable owning user, and model role -mappings identify the provider used for each request. The Rust runner executes -workspace tools and does not call LLM providers directly. The evaluation runner -currently calls the LLM adapter without a durable session owner, so this RFD -must bring that path under an explicit test-user integration as well. - -== Decision - -Kodo will persist user-owned provider integrations and resolve one for every -model request. A session role mapping selects an exact model identity and an -execution route selects the provider and billing path; the authenticated -session owner selects the credential for that route. ReqLLM receives that -credential through request-local options so concurrent users never share -mutable process or application configuration. - -Every text, tool-calling, and structured-output generation requires an explicit -authenticated scope and typed non-secret integration reference before the -resolver is called. This includes primary, search, review, evaluation, and -live-provider paths. Only the resolver creates an operation-local credential; -no production adapter entry point accepts one from a caller or infers an owner -or credential from ambient configuration. - -Kodo is not yet live, so this proposal does not preserve a runtime migration -fallback to deployment environment keys. Once user-owned integrations land, a -missing user credential fails closed and links to integration settings. The -production adapter never looks up `OPENAI_API_KEY` or another provider key from -the process environment. - -The initial provider identities are distinct even when they share a vendor: - -* `openai` uses an OpenAI Platform API key and Platform billing. -* `openai_codex` uses a ChatGPT subscription OAuth credential and the Codex - responses service. -* `anthropic` uses an Anthropic Console API key. -* `openrouter` uses an OpenRouter API key. - -Several durable integration rows are allowed per user and provider identity. -Exactly one connected row per user and provider may be active. The first -connected account becomes active automatically; adding another account does not -silently change routing or billing. The user can explicitly activate a different -connected account. Disconnecting the active account leaves that provider without -an active account rather than selecting a fallback. Treating `openai` and -`openai_codex` separately still makes Platform and subscription billing explicit. - -Model role mappings continue to own model selection. Each session preserves -the exact primary, search, and review model identities selected at creation. An -exact identity is Kodo's provider-neutral wire selector, including an immutable -snapshot or version when both routes expose one; a rolling alias remains that -exact selector but is not a claim that two billing routes use identical backend -weights or deployment snapshots. Later user or repository default changes -affect new sessions only. Mappings do not contain credentials. Their execution -routes may use different providers, in which case the session owner must have -every required integration. Kodo preflights every role integration before -accepting a turn and resolves the current credential again immediately before -each provider request. Key replacement, token refresh, disconnection, or -revocation therefore takes effect for requests that have not been admitted, -without rewriting session history. It does not retroactively cancel an -admitted provider operation, even if its HTTP request has not yet been sent. - -The first release permits an explicit execution-route change between -`openai` Platform billing and `openai_codex` ChatGPT subscription billing while -preserving the role's exact model identity. Kodo accepts the change only when -both routes expose that exact model and satisfy the same role capability -contract. A versioned compatibility record for the exact selector, source and -destination routes, and role-contract version must confirm tools, structured -output, reasoning options, context requirements, and input modalities. Matching -slugs or ReqLLM catalog fallback alone is insufficient evidence. - -Turn acceptance and route changes use the same durable session lock. Accepting -a turn atomically stores a route revision and complete per-role model, route, -and capability-contract snapshot. Primary, search, review, tool continuations, -and execution resumed after a process or node restart use that turn snapshot, -never the session's then-current mapping. A confirmed route change writes a -pending revision under the lock and affects only subsequently accepted turns; -an in-flight turn and all its continuations finish on its old snapshot. Changes -to multiple affected roles are atomic and Kodo rejects the whole change if any -role lacks exact-selector compatibility. Quota, disconnection, or provider -failure never triggers a route change automatically. - -After a route change, Kodo replays normalized visible assistant content, tool -calls, and tool results while omitting provider-specific reasoning signatures, -encrypted reasoning state, and cache metadata that cannot safely cross the -boundary. The visible conversation and selected model remain intact, but -provider-private cache or hidden reasoning continuity is not promised. If the -destination does not expose the exact model, Kodo rejects the change and keeps -the current route. Switching to a merely similar model is deferred to a future -decision backed by behavioral benchmarks and scoring evidence that the quality -change is acceptable. - -Connecting a provider, changing user model defaults, and changing an existing -session's execution route are separate actions. If the current role mapping -remains usable, connecting another provider does not prompt for or apply either -change. If a user has no usable mapping, Kodo presents one recommended -provider-compatible preset and shows its primary, search, and review models -with their Platform, subscription, or aggregator billing paths. The preset is -applied only after the user chooses "Use recommended models". - -A mapping is usable when every role resolves to an allowed provider whose -integration contains a credential, has connection state `connected`, and does -not have validation state `invalid`. Saved-but-`unverified` credentials and -credentials whose latest validation is `unavailable` remain usable. Provider -outages, quota exhaustion, missing model entitlement, and Codex contract -regressions are request outcomes; they do not mutate credential validity or -make another billing path eligible. - -Confirmed presets affect new sessions and user defaults; they never rewrite an -existing session's model identities or execution routes. Only the explicit, -same-model route-change action above can change an existing route. Mapping -availability is derived from the current model resolution and integration state -rather than persisted into each mapping. Disconnecting an integration therefore -makes dependent mappings unavailable and links to model settings without -rewriting them or silently routing requests through a differently billed -provider. - -== Provider support - -=== API-key providers - -OpenAI, Anthropic, and OpenRouter use the same integration lifecycle: connect, -validate, replace, test, and disconnect. Provider endpoints are fixed by Kodo; -the initial UI does not accept arbitrary base URLs or HTTP headers. This avoids -turning provider configuration into a server-side request forgery or -credential-exfiltration path. - -Every credential-bearing provider request uses a fixed HTTPS origin and -disables automatic redirect following. This includes validation, inference, -device authorization and polling, authorization-code exchange, and token -refresh. Kodo treats every `3xx` response, including a same-origin redirect, as -provider unavailable without issuing a second request. A legitimate provider -endpoint migration therefore requires an explicit code and allowlist update -rather than risking an API key, bearer token, device code, or authorization -code being forwarded to an unexpected destination. - -This policy is enforced and tested at every concrete transport boundary rather -than assumed from one shared adapter. The initial transport inventory covers -buffered Req and ReqLLM requests, Finch streaming, Req-based device -authorization, polling, exchange and refresh, and the Codex-specific inference -path. Adding or changing a provider transport requires updating this inventory -and proving both exact-origin selection and redirect rejection before it can -carry credentials. - -Validation is non-destructive and provider-specific. A transient validation -failure does not expose or invalidate the credential. Kodo records a bounded -status and safe error code, while the detailed provider error is redacted -before logging or display. - -Saving or replacing an API key first commits its encrypted payload as -`connected` and `unverified`, then starts a bounded asynchronous validation task -under the control-plane task supervisor. Kodo uses non-inference metadata -endpoints with no currently documented usage charge: OpenAI `GET /v1/models`, -Anthropic `GET /v1/models`, and OpenRouter `GET /api/v1/key`, with each -provider's required authentication headers. This wording is not a permanent -guarantee that providers will never charge for those endpoints; their contract -and response classification are verified before each provider ships and when -that integration contract changes. - -The authenticated owner may also choose Check access to rerun the same bounded, -generation-fenced metadata validation against the saved credential. The key is -decrypted only for that operation and is not returned to the browser. This -action does not run model inference or introduce a separately billed probe. - -[cols="1,2,2,3",options="header"] -|=== -| Provider | Valid | Invalid | Unavailable or configuration required - -| OpenAI -| Successful metadata response -| Explicit `invalid_api_key` or revoked-key response -| Other `401` contexts, `403`, network or TLS failure, timeout, redirect, - `429`, or `5xx` - -| Anthropic -| Successful metadata response for a standard workspace-scoped Console key -| Explicit authentication failure for that supported key type -| `400 invalid_request_error` from an unscoped identity-linked key requiring - workspace selection, `403`, network or TLS failure, timeout, redirect, `429`, - or `5xx` - -| OpenRouter -| Successful key metadata response -| Documented invalid/revoked-key `401` -| Other permission or configuration failure, network or TLS failure, timeout, - redirect, `429`, or `5xx` -|=== - -Phase 2 supports standard workspace-scoped Anthropic Console API keys only. -Unscoped identity-linked Console keys that require an explicit workspace -selector return actionable guidance to create a workspace-scoped key instead. -Anthropic Admin keys are a separate, higher-privilege credential class intended -for the Admin API; they are not supported for normal model inference and adding -a workspace selector would not make them a supported key type. - -A successful probe marks the integration `valid`. Only the provider-specific -invalid outcomes above mark it `invalid`; Kodo never infers invalidity from a -status code without the expected safe provider error identifier. Quota, -billing, and model-entitlement failures remain request outcomes. Every result -compares the credential generation captured by the task so it cannot update a -replacement or disconnection. Raw provider bodies are never persisted or -logged. - -Kodo normalizes quota exhaustion and billing-required responses into bounded -outcomes on the affected invocation. They do not change connection or -validation state, become persistent integration status, or trigger background -quota checks. The session or turn that encountered the outcome keeps the user's -work available, offers retry, and links to the provider's billing page and the -relevant Kodo integration settings. Integration cards therefore do not show a -quota badge or imply that one observation applies to every model, provider -project, or later quota window. - -Kodo never runs billed inference automatically. A user may explicitly confirm -a Test model request after the UI identifies the exact provider and model and -warns that the request may incur provider charges. Testing requires -authenticated ownership and confirmation under the normal session boundary. -Saving remains successful during provider outages, and `unverified` or `unavailable` -credentials remain usable while `invalid` blocks provider requests. - -A saved credential is never rendered back to the browser. The UI shows -provider, billing identity, status, connection and validation times, and an -explicitly non-secret provider-supplied key or account label where that -provider contract supplies one. Kodo does not derive, persist, or display an -API-key hash, suffix, or fingerprint, and never fingerprints an OAuth access or -refresh token. - -API-key entry uses a secret input submitted only with the completed form; it -does not use `phx-change`. The browser necessarily holds the value while the -user pastes or types it, but LiveView never copies the key or submitted form -parameters into socket assigns, renders them back in a diff, or includes them -in a validation error. The submit handler passes the event value directly to -the scoped encryption context. After a successful save, Kodo clears the browser -input and offers no way to reveal or copy the saved key. A user who needs the -key elsewhere must retain it through the provider's own issuance flow. - -OpenRouter is a provider in its own right rather than a transparent fallback -for direct provider integrations. Models routed through OpenRouter use the -OpenRouter integration and billing even when the underlying model was produced -by OpenAI or Anthropic. - -=== ChatGPT subscription - -ChatGPT subscription support uses OpenAI Codex device authorization. The user -starts the flow in Kodo, receives an OpenAI verification destination and -one-time code, and approves the request in a browser. The destination rendered -by Kodo is a fixed HTTPS URL from the reviewed provider contract. Kodo validates -that a provider-returned verification URL matches the exact allowlist, but does -not automatically navigate to it or render an untrusted destination. It shows -the fixed destination and code separately so a returned URL cannot become a -phishing or code-exfiltration path. Kodo polls at OpenAI's instructed interval, -exchanges the resulting authorization code and PKCE verifier, and stores the -returned access token, refresh token, account identifier, and expiry as -encrypted credentials. - -Authorization attempts are user-scoped, single-use, and expire after the -provider deadline. Polling continues only while an attempt is active, respects -provider backoff, and stops on completion, cancellation, expiry, or a terminal -provider error. Attempt identifiers and one-time codes are treated as secrets -and are not written to logs or telemetry. - -The database permits one active attempt per user and `openai_codex` -integration. Each attempt records an attempt generation, expected integration -generation, state, provider deadline and polling interval, encrypted sensitive -fields with encryption-key and payload-format versions, and a database-time -claim lease plus monotonically increasing claim epoch. Starting a new attempt -atomically cancels and supersedes the prior attempt. Cancellation, expiry, -completion, replacement, and disconnection transitions compare the attempt -generation; completion installs credentials only while the attempt remains -active and its claim epoch, attempt generation, and expected integration -generation still match. - -The attempt generation is assigned with its encrypted payload and is immutable -for that attempt. Attempt ciphertext uses a unique nonce and AEAD associated -data containing the attempt ID, integration ID, owning user, provider, attempt -generation, and attempt-payload format version. Moving a valid device code, -authorization code, PKCE verifier, or polling payload to another attempt, user, -integration, provider, or generation therefore fails authentication rather -than linking the wrong provider account. - -Device polling is connection-driven rather than replica-driven. The node that -handles creation or a LiveView mount attempts one conditional claim update that -increments the claim epoch and returns it to the claimant. On success, it starts -one finite polling task under `Kodo.ControlPlaneTaskSupervisor`. The task -conditionally renews its lease before expiry and verifies active state, current -epoch, and lease ownership before admitting every poll or token exchange. Loss -of ownership stops all later operations. The claim lease exceeds the hard -poll-or-exchange HTTP timeout plus a safety margin. Closing the LiveView does -not cancel the task. After a node failure, a browser reconnect or remount can -increment the epoch and resume the persisted attempt when the old claim -expires. Concurrent tabs may contend for the same row, but replicas with no -connection for that attempt perform no work. Kodo does not run a per-replica -polling sweeper, so claim traffic is proportional to active device flows rather -than cluster size. - -A poll or exchange admitted before claim ownership changes may finish, but its -result compares the claim epoch as well as attempt and integration generations -and cannot persist after takeover. Duplicate or stale results therefore become -no-ops and cannot replace newer credentials. Expiry is applied lazily when an -attempt is read, claimed, or superseded. Terminal rows are deleted in bounded -batches; if periodic cleanup later becomes necessary, one database-elected -cleanup owner runs it rather than every replica. - -The OpenAI Codex source publishes the device flow. The downstream -`chatgpt.com/backend-api/codex` inference contract is nevertheless less formal -than the OpenAI Platform API. Kodo labels this integration "ChatGPT -Subscription (Beta)", identifies its request origin as Kodo in supported -headers, and does not silently replace it with an OpenAI API key if -authorization or subscription quota fails. Kodo records the exact upstream -public OAuth client identity, scopes, endpoints, and headers on which the -working flow depends and does not describe that compatibility as formal OpenAI -support without separate confirmation. - -ChatGPT Subscription ships as a Beta when its implementation and compatibility -suite pass for device authorization, a tool-calling turn, structured output -used by review and search roles, refresh-token rotation, restart recovery, and -the documented client contract. It does not require a deployment feature flag. -A provider rejection or contract change is a compatibility regression to fix; -affected integrations report an actionable unavailable state. Kodo does not -retry through another client identity or fall back to Platform billing. -Ordinary transient, quota, and authorization errors remain scoped to the -affected request. - -No provider in this RFD is gated by a deployment feature flag once its required -phase acceptance checks pass. References to opt-in live-provider or -compatibility checks describe tests that contact and may bill an external -provider; they are test controls, not product availability controls. - -Anthropic subscription OAuth is outside this RFD. Anthropic permits API keys -and supported cloud-provider credentials for third-party applications but -currently prohibits third parties from collecting or intermediating Claude -subscription credentials. Kodo will not offer Claude subscription login unless -Anthropic publishes a contract that permits this use. - -== Persistence and encryption - -Provider integrations store non-secret indexing and operational metadata -separately from one versioned encrypted credential payload. The durable record -contains at least: - -* a generated identifier, owning user, provider identity, user-visible account - name, authentication type, and active state; -* encrypted credentials and the encryption-key version; -* connection status and token expiry; -* validation and refresh timestamps plus a bounded safe error code; and -* normal insertion and update timestamps. - -The database enforces ownership references, requires active rows to be connected, -and permits at most one active integration for each user and provider pair. -Context functions take the authenticated scope as their first argument and apply -the owning user in the query. Changesets never cast a `user_id` supplied by a -browser. - -Deleting a Kodo user cascades in the database to all of that user's integration -rows and from each integration to its device-authorization attempts and claim -state. Provider availability or revocation success never blocks account -deletion. Any validation, polling, refresh, or rotation task that races with -deletion and has not crossed its admission boundary observes the missing -ownership-checked row and terminates without persisting state or issuing a -provider request. An already admitted operation may still transmit and finish. -The deletion flow advises the user to revoke credentials at providers where -Kodo cannot do so, but does not promise provider-side revocation. - -Connection and validation are separate state axes. Connection is one of -`disconnected`, `connected`, or `reauthorization_required`. Validation is one -of `unverified`, `valid`, `invalid`, or `unavailable`. Their valid combinations -and request behavior are: - -[cols="1,1,1,2", options="header"] -|=== -| Connection | Validation | Encrypted payload | New provider requests - -| `disconnected` -| `unverified` only -| absent -| blocked - -| `connected` -| any validation state -| present -| allowed except when validation is `invalid` - -| `reauthorization_required` -| `unverified` only -| retained provisionally -| blocked -|=== - -Context transition functions enforce this matrix, supplemented by database -constraints where practical. Connecting or replacing a credential sets -`connected` plus `unverified` and advances the credential generation. A -generation-matching validation success produces `connected` plus `valid`; a -confirmed invalid or revoked key produces `connected` plus `invalid` without -clearing its payload; and a transient validation failure produces `connected` -plus `unavailable`, which remains usable. Explicit revalidation may move a -generation-matching invalid credential to `valid` or `unavailable` without -requiring replacement. - -Disconnecting clears the encrypted payload and validation metadata, sets -`disconnected` plus `unverified`, and advances the generation while preserving -the integration row. Refresh `invalid_grant` sets -`reauthorization_required` plus `unverified` while retaining the provisional -source-generation payload. A delayed generation-matching refresh success may -install its refreshed payload as `connected` plus `unverified` and advance the -generation. Successful OAuth authorization likewise installs the payload as -`connected` plus `unverified` and advances the generation. A failed or -cancelled authorization attempt terminates only that attempt and leaves the -integration's prior connection-validation pair unchanged. - -An authentication probe sets validation to `valid` only on success or to -`invalid` only on a confirmed authentication failure. Network errors, rate -limits, and provider outages produce `unavailable` without clearing the -credential or blocking inference. Quota and model-entitlement errors remain -request outcomes. Every asynchronous validation or provider-derived status -update compares the credential generation it read so it cannot overwrite a -replacement, reconnection, or disconnection. - -The integrations UI gives connection state precedence and displays validation -only for a connected integration. It therefore never presents impossible -combinations such as disconnected plus valid. - -Credentials use authenticated encryption with a unique nonce per write. API -keys, access and refresh tokens, and provider account or workspace identifiers -remain inside the encrypted payload. Each write binds its ciphertext through -AEAD associated data containing the integration identifier, owning user, -provider identity, authentication type, and credential-payload format version. -A valid payload copied to another integration, user, provider, or -authentication type therefore fails authentication rather than becoming a -cross-user credential or billing path. - -Kodo requires a deployment-level credential-encryption key ring, supplied -independently of all LLM providers, and records a key version so ciphertext can -be rotated. Every production replica validates the complete configured current -and non-current key ring before becoming ready to serve integration operations. -Readiness verifies that every key version referenced by an integration or -authorization-attempt row is present. Production refuses to persist or decrypt -either payload type when a required key is absent or malformed. An AEAD -association or authentication failure fails closed with a bounded corruption -error and never falls back or sends the credential to a provider; recovery -requires credential replacement, restarting authorization, or an operator -procedure. -Database encryption does not remove the need to protect the control-plane -process; it protects database copies, backups, and read-only database access -from directly revealing provider credentials. - -Kodo is not yet live, so Phase 1 creates a fresh encrypted schema and does not -import plaintext credentials, legacy provider environment variables, or an -earlier integration format. Post-launch key rotation is staged. Operators first -distribute a new non-current key and wait until every replica reports readiness -with both keys. They then make the new key current for writes and re-encrypt old -rows in bounded batches. Each rewrite compares the credential generation and -old key version it read, so replacement or disconnection wins and the batch -retries or skips the stale row without changing its logical credential -generation. - -The old key remains available for decryption through the documented application -rollback and backup-retention window. Rollback restores compatible application -behavior while both keys are still configured; it never removes key material -first, downgrades ciphertext to plaintext, or enables a provider-environment -fallback. Routine rotation does not re-encrypt short-lived authorization -attempts: new attempts use the current key, while old keys remain until attempts -at those versions expire and are deleted. Operators remove an old key only -after the database has no integration or attempt payloads at that version, all -replicas use the new ring, the rollback window has closed, and backups that -require the old key have expired or remain paired with a separately protected -copy of that key. Emergency retirement of a compromised key cancels and deletes -affected attempts and requires those users to restart authorization. - -The credential payload is opaque to Ecto query code and never appears in -session events, model mappings, changeset errors, exception inspection, -telemetry metadata, or client responses. Disconnecting an integration removes -its credential payload from the durable database row. Backup retention and -provider-side revocation remain operational concerns and are documented with -the deployment procedure. - -== Request-time resolution - -Kodo combines each accepted turn's preserved model identity and route snapshot -and resolves that provider-specific model specification through -`ReqLLM.model/1` before looking up a credential. The `provider` on the resulting -`LLMDB.Model` is canonical and must equal the selected route; provider text -derived from a stored model string is display data and cannot select a -credential. This RFD allows only `openai`, `openai_codex`, `anthropic`, and -`openrouter`. Unknown, malformed, unsupported, and route-incompatible models -fail before a provider request. - -For a new operation, Kodo selects the active integration for the resolved -provider. Activation affects only future resolution. Once an operation has -received its typed integration reference, that exact integration ID and -credential generation remain pinned through admission; switching the active -account cannot move an already admitted operation to different credentials. - -The provider-independent LLM boundary accepts the authenticated scope, resolved -model, and a typed non-secret integration reference containing integration and -provider identity. It fetches the referenced integration under that scope, -rechecks ownership and current generation, and requires exact equality between -the resolved model provider, reference provider, and stored integration provider -before admitting an operation. A forged or cross-user reference therefore -fails closed. This check applies equally to catalog aliases, inline model -specifications, and OpenRouter models whose underlying model vendor is OpenAI -or Anthropic. - -Only the scoped resolver decrypts stored payloads and creates the internal, -operation-local credential consumed by the ReqLLM adapter. Public generation -callbacks and their callers cannot supply a raw API key, OAuth token, or this -internal credential value. The adapter translates an API-key credential to -`:api_key` and a Codex credential to request-local OAuth options. Only the -current API key or OAuth access token and required decrypted account identifier -cross into ReqLLM; refresh tokens, expiry, generation, and rotation state remain -in Kodo. No request uses `System.put_env/2`, `Application.put_env/3`, ReqLLM's -global key store, or a shared OAuth file. - -Transport contract tests deliberately configure sentinel provider environment -keys, ReqLLM global credentials, and OAuth files while exercising each request -path. A request with a scoped integration must send only that integration's -operation-local credential. A request without one must fail before network -admission instead of selecting any sentinel credential. Redirect tests make -both same-origin and cross-origin destinations observable and assert that each -transport issues no follow-up request and forwards no authorization material. - -Status pages and turn preflight query only non-secret integration metadata and -batch all required role providers into one indexed query. Immediately before -each credential-bearing external operation, Kodo reads the current integration -or authorization-attempt state through its ownership index and decrypts the -required fields in the Phoenix process. An operation is one validation, -inference or streaming call, tool-call continuation, device poll or exchange, -or token refresh. Kodo does not hold a database transaction or row lock during -the external request. - -This adds a small bounded set of indexed reads per external operation and scales -with active provider calls rather than the number of Kodo replicas. Since -provider calls are orders of magnitude slower than the lookup and local AEAD -decryption, Kodo does not introduce a plaintext credential cache in a -`GenServer`, ETS, persistent terms, or session state. A future generation-aware -encrypted cache requires measured database pressure and a separate consistency -review because stale cache entries weaken immediate replacement and -disconnection semantics. - -The admission boundary is the final successful ownership, state, and generation -check for the operation-local decrypted payload. For a model call, Kodo rechecks -that generation while durably persisting the invocation start and billing -provenance before allowing the HTTP request to proceed. Device polling and -refresh use their claim and lease fencing at the same boundary. A missing -integration, a `disconnected` or -`reauthorization_required` connection, or an `invalid` validation returns a -domain error naming the provider and required user action without including -credential material. The session can accept a later turn after the user -reconnects the provider. Provider errors must not trigger fallback to a -differently billed integration unless model settings explicitly define such a -fallback in a future proposal. - -Each started invocation records non-secret billing provenance from this -resolved boundary: canonical provider, authentication type, and billing path -(`platform`, `subscription`, or `aggregator`). It never records credential -material. This provenance remains stable even if the integration or mapping is -later replaced. - -Once a provider operation is admitted, replacement, disconnection, or user -deletion does not alter it. The process may pause before transmission, then send -and persist a response with the billing provenance captured at admission -because Kodo cannot atomically coordinate database state with an external -network write. Each later provider request, including a tool-call continuation -or another role call in the same turn, resolves and seeks admission again, then -fails closed if the integration is unusable. A late validation or refresh result -remains generation-fenced and cannot restore or overwrite a disconnected -integration. - -Kodo classifies Req and ReqLLM failures into bounded domain errors before they -leave the LLM boundary. Session events, exception inspection, logs, telemetry, -and browser responses may contain only the provider, operation, bounded outcome -class, and actionable user guidance; they never contain raw provider bodies, -headers, request options, URLs with secrets, or inspected credential values. - -Model validation remains credential-independent. Provider capability checks -may resolve model metadata without making a billed request, while connection -validation and inference use the session owner's integration. - -== Refresh and multi-node coordination - -API keys do not refresh. Codex access tokens refresh shortly before expiry, -using the stored refresh token and OpenAI's token endpoint. A successful -refresh must return a new access token and valid expiry. It atomically writes -those values, retains the existing refresh token or account identifier when the -response omits either one, and replaces the refresh token when the response -rotates it. A different returned account identifier is a contract and billing- -identity violation: Kodo discards that response and requires reauthorization -rather than silently changing the linked account. - -Refresh is just-in-time, bounded work rather than a long-lived process per -integration. A request that encounters a near-expiry token starts the external -HTTP operation under Kodo's existing task supervisor after acquiring the -database lease. The task decrypts immediately before use, retains references -only for the bounded operation, and discards them afterward so they become -eligible for garbage collection. A task or node failure leaves durable -credential state unchanged and the expired lease available for takeover. - -Callers coordinate directly through the database; Kodo does not add a refresh -coordinator `GenServer`, a `DynamicSupervisor` child, or an in-memory timer per -integration. A process-local coordinator would not prevent another replica -from refreshing, while a cluster-wide process would require leader election -and still need durable fencing during failover. If proactive refresh becomes -necessary, a single supervised sweeper or durable job system may discover due -integrations, but it must invoke the same lease-protected refresh operation and -keep the database as the source of truth. - -Kodo admits one lease holder for an integration at a time. It uses a short -database-backed refresh lease, calculated from database time, so it does not -hold a database transaction or row lock across an external HTTP request. The -lease duration exceeds the hard refresh-request timeout plus a safety margin. -Other callers wait for a bounded interval and reload the integration; an -expired lease can be taken over, although a paused former holder can briefly -overlap the replacement after resuming. - -Every attempt captures the credential generation it read. A successful -response may atomically replace the encrypted payload and advance that -generation even if its lease expired while the task or node was paused, but -only if no successful refresh, replacement, reauthorization, or disconnection -has already advanced it. The first successful response wins; later responses -reload the stored result. User replacement, starting or completing -reauthorization, and disconnection always advance the generation and -irrevocably fence every old refresh response. A new authorization attempt -captures the post-advance integration generation. - -An `invalid_grant` or refresh identity mismatch records -`reauthorization_required` with a bounded refresh-specific reason after its -generation check succeeds, but does not advance the source credential -generation or erase the encrypted payload. This state is terminal for new -requests but provisional in refresh-outcome precedence: a successful response -already produced from that same generation may replace it and advance the -generation, even after an arbitrarily long process pause. A successful response -cannot replace reauthorization initiated or completed by the user, replacement, -or disconnection because those actions advance the generation. - -A stale-lease or takeover attempt that receives `invalid_grant` reloads and may -wait for a bounded interval before displaying reauthorization so a common late -success avoids UI churn. The wait is only an optimization and is never the -correctness boundary. Transient provider or network failures preserve the -credential, release or expire the lease, and return a retryable -provider-unavailable error. - -This protocol minimizes concurrent refresh but cannot make an external token -endpoint exactly once. If the provider rotates a refresh token and Kodo -permanently loses the successful response, the only safe recovery may be user -reauthorization. Kodo documents and tests this boundary rather than silently -retrying an ambiguously consumed token. - -== User interface and authorization - -Integration management lives at `/integrations` inside the existing -`:require_authenticated_user` LiveView session and browser pipeline. The route -requires login because every integration is user-owned and its status controls -that user's model requests. The normal authenticated-user boundary applies to -viewing status and to submitting, replacing, testing, reauthorizing, or -disconnecting a user-owned integration; integration management does not require -renewed sudo mode. Server-side handlers reload the integration through the -authenticated scope and retain the existing ownership, state, and generation -checks rather than trusting browser-supplied ownership or stale lifecycle data. - -An OAuth or device flow may complete only while the same user-owned attempt -remains active and its generation checks succeed. Cancelling such an attempt -also requires authenticated ownership. An explicit same-model execution-route -change additionally uses a clear billing confirmation so the user understands -which external account will be charged; the existing turn-boundary and -exact-model compatibility rules still apply. - -The page provides distinct actions for OpenAI API, ChatGPT Subscription, -Anthropic, and OpenRouter. It explains the billing identity before connection, -shows progress and expiry for device authorization, and provides actionable -states for missing credentials, invalid keys, and required reauthorization. It -does not present request-scoped quota or billing outcomes as integration state. -Those outcomes appear with retry and billing guidance on the affected session -or turn. The page never embeds raw scripts; device-flow progress uses normal -LiveView events and asynchronous server work. - -Session creation and model settings identify integrations by provider and -billing path. If a selected role lacks a connection, the UI links to the -integration page rather than instructing the operator to restart Kodo with an -environment variable. - -== Settings information architecture and visual direction - -The integration work establishes a shared settings experience rather than -adding another isolated generated form. Account and integration pages keep -their existing `/users/settings` and `/integrations` paths, but render inside -one settings shell with consistent navigation, page headings, content width, -and action placement. - -The visual direction uses a quiet neutral canvas, clear sectional navigation, -subtle separators, rounded surfaces, generous spacing, restrained accent -color, and controls sized for touch. These principles support settings without -introducing conversation, project, or composer chrome into the page. - -At desktop and tablet widths, settings appear as one framed workspace within -the authenticated application: a compact persistent rail lists Account and -Integrations, a subtle divider separates navigation from content, and the -selected page occupies a balanced detail pane. The frame may use a rounded -outer surface at larger widths but remains a normal deep-linkable page, not a -transient modal whose state disappears on refresh. A clear back or close action -returns to the user's prior application context. - -Kodo does not add Personal/Workspace switching, Billing, Usage, Secrets, or -other placeholder destinations. Only implemented settings are visible. If Kodo -later gains workspace-owned configuration, its ownership, authorization, and -navigation require a separate decision rather than overloading user-owned -integrations. - -On narrow phones the frame becomes edge-to-edge and the rail becomes horizontal -section navigation above the page; it must not create a second off-canvas menu -inside the existing application navigation. The content pane uses one column -without shrinking desktop cards into unreadable two-column forms. Focus order, -selected-state contrast, keyboard navigation, scroll containment, and touch -target size remain equivalent across layouts. - -The Account page groups email and password changes into separately titled -surfaces with concise security context. Its generated authentication behavior, -sudo-mode checks, form semantics, and confirmation flow do not change. The -Integrations page uses one card per connected or previously connected account. A -compact Add integration menu chooses the provider and opens a modal for a -user-visible account name and credential. Each card gives provider purpose, -billing path, connection status, and active state. Connected inactive accounts -offer an explicit Activate action; check access, replace, reconnect, and -disconnect always target the card's exact integration. - -Connected provider cards show connection state before access-validation state. -Successful and confirmed-invalid probes appear as the textual outcomes Valid -and Invalid, with green and red color as supplemental cues. Not checked and -Unable to verify remain neutral because neither is a verdict that the saved -credential is invalid. - -Connection forms open within the provider's page context rather than placing -four permanent secret inputs on the screen. Device authorization emphasizes -the OpenAI-owned verification destination, the one-time code, remaining time, -and a cancellable progress state. Because the short-lived code must be entered -at the provider, it is an intentional display exception and has an accessible -Copy action; Kodo removes it from the UI when the attempt completes, expires, -or is cancelled. Success and failure feedback stays attached to the affected -provider card and is also announced accessibly. Before submission, transient -loading must not shift unrelated cards or discard the browser-held API key; -after a successful submission, Kodo clears that input. - -== Interface sketches - -These sketches communicate hierarchy and responsive behavior, not exact copy, -dimensions, colors, or component styling. - -=== Desktop and tablet - -[source,text] ----- -+--------------------------------------------------------------------------+ -| <- Sessions Settings darwin67 | -+------------------+-------------------------------------------------------+ -| | | -| SETTINGS | Provider integrations | -| | Connect each billing identity used by your agents. | -| Account | | -| > Integrations | +-------------------------------------------------+ | -| | | ChatGPT Subscription (Beta) CONNECTED | | -| | | OpenAI Codex - ChatGPT plan billing | | -| | | Last checked 2 min ago [Test] [Reconnect] | | -| | +-------------------------------------------------+ | -| | | -| | +-------------------------------------------------+ | -| | | OpenAI API NOT CONNECTED | | -| | | Platform API usage and billing | | -| | | [Connect] | | -| | +-------------------------------------------------+ | -| | | -| | +----------------------+ +----------------------+ | -| | | Anthropic API | | OpenRouter | | -| | | NOT CONNECTED | | CONNECTED | | -| | | [Connect] | | [Test] [Replace] | | -| | +----------------------+ +----------------------+ | -| | | -+------------------+-------------------------------------------------------+ ----- - -The detail pane may use a two-column card row only when both cards remain -readable and actions do not wrap ambiguously. ChatGPT and OpenAI API remain -separate cards because their authentication, endpoint, model namespace, and -billing identity differ. - -=== Narrow mobile - -[source,text] ----- -+--------------------------------------+ -| <- Settings | -+--------------------------------------+ -| [ Account ] [ Integrations ] | -+--------------------------------------+ -| | -| Provider integrations | -| Connect providers used by agents. | -| | -| +--------------------------------+ | -| | ChatGPT Subscription (Beta) | | -| | CONNECTED | | -| | ChatGPT plan billing | | -| | | | -| | [Test] [Reconnect] | | -| +--------------------------------+ | -| | -| +--------------------------------+ | -| | OpenAI API - NOT CONNECTED | | -| | Platform API billing | | -| | [Connect] | | -| +--------------------------------+ | -| | -| +--------------------------------+ | -| | Anthropic API | | -| | NOT CONNECTED [Connect] | | -| +--------------------------------+ | -| | -| +--------------------------------+ | -| | OpenRouter | | -| | CONNECTED [Manage] | | -| +--------------------------------+ | -| | -+--------------------------------------+ ----- - -Cards become a single sequence on mobile. Section navigation remains visible -without horizontally scrolling provider content, and secondary actions may -collapse behind one labelled Manage action when width is constrained. - -=== ChatGPT device authorization - -[source,text] ----- -+-----------------------------------------------------------+ -| ChatGPT Subscription (Beta) | -| | -| 1. Open the OpenAI verification page: | -| | -| https://auth.openai.com/codex/device | -| | -| 2. Enter this one-time code: | -| | -| ABCD-EFGH [Copy] | -| | -| Waiting for OpenAI authorization... 12:41 left | -| [==============================>................] | -| | -| [Cancel] | -+-----------------------------------------------------------+ ----- - -The code is rendered as selectable text with a copy action in the real -interface. Status updates use a live region, the countdown is not the only -expiry cue, and cancelling returns the provider card to a stable disconnected -state. - -== Pre-release cutover - -Kodo has no production users or stored provider integrations to migrate. The -integration schema, request-local credential boundary, missing-integration UX, -and removal of ReqLLM's environment-key path therefore form one pre-release -cutover spanning Phases 1A and 1B. Phase 1A may deploy to pre-production with -provider traffic disabled; Phase 1B enables the first usable integration path -and missing-provider guidance. There is no deployment fallback, automatic -import, or implicit owner for an existing environment key. - -Development, evaluation, and opt-in live-provider runs require an explicit test -user whose encrypted integrations are provisioned through the Kodo context. -Ordinary tests use fake adapters plus scoped integration fixtures and non-secret -references without external provider access. Neither path adds environment -lookup, caller-supplied plaintext credentials, or owner inference to the -production adapter. - -At the end of this RFD, no LLM API key or OAuth token is read from deployment -configuration at boot or request time. The credential-encryption key ring is a -production-readiness requirement because encrypted database secrets need a -root of trust outside the database. Installations with a valid key ring but no -connected provider can boot and serve account and integration pages, but cannot -start a model turn until the user connects every provider required by the -selected role mapping. - -== Security and operations - -Kodo applies the following boundaries: - -* Provider secrets remain in the Phoenix control plane and are never sent to - runners, browsers after submission, or hosted runner environments. -* Provider endpoints and authorization endpoints are exact HTTPS allowlists in - code. Credential-bearing requests never follow redirects, and device - verification UI never navigates automatically to a provider-returned URL. -* Logs and exceptions redact API keys, bearer tokens, refresh tokens, device - codes, authorization codes, and encrypted payloads. -* Metrics use bounded provider, authentication-type, operation, and outcome - labels; user, account, integration, and token identifiers stay out of metric - labels. -* API-key submission and replacement, authorization start and completion, - cancellation, disconnection, validation outcomes, execution-route changes, - refresh outcomes, and required reauthorization produce security-relevant - audit logs without credential material. Audit records may contain internal - actor and integration identifiers for investigation, but those identifiers - never become metric labels. -* Phoenix parameter filtering covers every provider secret field before the - first credential form ships. Audit data excludes API keys, access and refresh - tokens, device and authorization codes, encrypted payloads, raw provider - responses, and secret-bearing URLs. -* Credential-derived hashes, suffixes, and fingerprints do not appear in the - database, UI, logs, telemetry, or audit records. If a future operational need - requires API-key correlation, a separate proposal must use a versioned, - domain-separated keyed HMAC restricted to internal access; an unkeyed hash or - OAuth-token fingerprint is never acceptable. -* Kodo minimizes plaintext credential references and does not retain them in - long-lived processes, caches, or unnecessary process messages. BEAM immutable - binaries, garbage collection, and HTTP client internals do not provide a - guarantee of immediate memory zeroization, so tests assert application-level - non-retention rather than physical erasure. -* Encryption-key rotation uses a distribute, activate, CAS-safe re-encrypt, and - retire sequence; the old key remains through application rollback and backup - retention. -* Disconnecting instructs the user how to revoke the credential at the - provider when Kodo cannot revoke it directly. The confirmation states that - disconnect prevents future Kodo requests but cannot guarantee cancellation - of an operation already admitted or sent to the provider or its associated - billing. - -Operational documentation covers initial encryption-key provisioning, backup -handling, rotation, provider revocation, device-flow failures, refresh failure -rates, and safe rollback across integration schema and encryption-key changes. -Encryption keys are backed up and access-controlled separately from database -backups. User deletion removes live database payloads but cannot selectively -erase ciphertext already present in retained database backups or write-ahead -logs; those copies remain governed by the documented backup expiry and key -retention policy. Production guidance restricts BEAM debugging and memory -inspection and protects or disables crash dumps, core dumps, and swap according -to the deployment environment. Guaranteed zeroization would require a separate -native or isolated secret-handling boundary and is outside this RFD. - -== Alternatives considered - -=== Continue deployment environment keys - -Environment keys are simple but preserve one billing identity for every user, -require operator involvement, and cannot support user-scoped OAuth refresh. -Because Kodo is not yet live, retaining them as a migration bridge adds billing -ambiguity without preserving production compatibility. - -=== Write credentials to runner environments - -This would let provider clients run near workspaces but expands the secret -boundary to every runner and subprocess. Kodo already performs inference in the -control plane, so this adds risk without a corresponding capability. - -=== Use ReqLLM global keys or OAuth files - -ReqLLM supports process-wide keys and file-backed OAuth refresh for local -applications. Those stores cannot safely distinguish concurrent Kodo users or -coordinate refresh across control-plane replicas. Kodo therefore owns the -database lifecycle and passes only request-local credentials to ReqLLM. - -=== Store provider-specific secret columns - -Separate API-key, access-token, and refresh-token columns make accidental -selection and logging easier and require schema changes for every credential -shape. A versioned encrypted payload with queryable non-secret metadata keeps -provider details inside the integration boundary. - -== Phased delivery - -Phases 0 through 3 are independently reviewable and deployable to -pre-production. Production launch requires Phase 4 as well as every preceding -phase. Detailed progress is tracked in -link:IMPLEMENTATION.org[RFD 5 implementation checklist]. - -=== Phase 0: Implement and verify the Codex contract - -Trace and reproduce the working Codex device flow in a bounded Kodo live spike -against the current ReqLLM `openai_codex` provider. Record the upstream public -OAuth client identity, scopes, device and token endpoints, PKCE and polling -rules, account identification, Kodo originator headers, required model -capabilities, token refresh, and restart recovery. Phase 0 defines the -production contract and regression diagnostics; it is not a gate for omitting -the required ChatGPT/Codex integration. - -=== Phase 1A: Establish the credential security foundation - -Add the user-owned integration schema, authenticated encryption and key -versioning, scoped context operations, parameter filtering, safe inspection, -fixed outbound endpoint policy, credential-free audit framework, typed -request-local credential boundary, and fail-closed resolution. Security tests -must prove ownership isolation and prevent secret egress to logs, browsers, -runners, telemetry, or redirected requests. This phase is deployable without a -credential UI; Kodo must not accept a credential or send a production provider -request until the complete foundation passes. - -=== Phase 1B: Add OpenAI API integration and settings - -Add the shared responsive settings shell, improve the existing Account -presentation without changing its behavior, and ship the authenticated -integration page with OpenAI Platform API-key connection first. Wire model -resolution, explicit live-test integrations, validation, lifecycle audit events, -baseline missing-provider guidance, and request-local ReqLLM options through -the Phase 1A boundary without a provider-key environment fallback. - -=== Phase 2: Add Anthropic and OpenRouter - -Reuse the API-key lifecycle for Anthropic and OpenRouter, add provider-specific -validation, errors, audit events, and missing-provider guidance, and verify -model-role mappings can use several providers in one session without sharing -credentials or billing paths. Allow several named accounts for each API-key -provider while enforcing and resolving only its explicitly active account. - -=== Phase 3: Add ChatGPT device authorization beta - -Add durable user-scoped authorization attempts, asynchronous polling, encrypted -OAuth persistence, refresh leases, rotated-token updates, reauthorization, and -the ChatGPT Subscription billing identity, settings and missing-provider UX, -audit events, and exact-model route changes. Require Phase 0's compatibility -suite to pass through the production path before shipping, retain the Beta -label, and treat later failures as regressions that leave affected integrations -unavailable while Kodo fixes the contract. - -=== Phase 4: Harden operations - -Complete operational hardening, exercise multi-node refresh and key rotation, -verify audit and telemetry completeness, and publish operator guidance. All -Phase 4 requirements are production-launch requirements even though they follow -provider implementation. The encryption key remains the only -integration-related boot secret. - -== Implementation - -Progress against this proposal is tracked in the -link:IMPLEMENTATION.org[RFD 5 implementation checklist]. diff --git a/rfd/README.md b/rfd/README.md deleted file mode 100644 index 9b5dec2..0000000 --- a/rfd/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# Kodo Requests for Discussion - -Requests for Discussion (RFDs) capture proposals early enough to shape them -through written review and preserve the reasoning behind project decisions. An -RFD is not authoritative merely because it exists; its `state` says how it -should be read. - -| RFD | Topic | -|---|---| -| [1: Bound control-plane database load](0001/README.adoc) | Keep heartbeat, recovery, ownership, and session-index database work proportional to live replicas and active sessions | -| [2: Extend Kodo to mobile and tablet clients](0002/README.adoc) | Start with a responsive PWA, handle disconnection gracefully, and preserve a path to native clients | -| [3: Define behavioral evaluation and release benchmarking](0003/README.adoc) | Separate role quality from multi-turn behavior, calibrate observable scoring, and benchmark frozen release candidates | -| [4: Introduce a full-screen terminal interface](0004/README.adoc) | Make Ratatui the default client, retain non-interactive runner hosting, and preserve reusable application semantics | -| [5: Store user-owned LLM provider integrations](0005/README.adoc) | Encrypt provider credentials, resolve them per model request, and support OpenAI, Anthropic, OpenRouter, and a ChatGPT/Codex Beta without boot-time LLM credentials | - -## Source format - -Each RFD lives at `rfd/NNNN/README.adoc`, where `NNNN` is a four-digit number. -The document starts with canonical AsciiDoc attributes and an unpadded title: - -```asciidoc -:authors: Name -:state: prediscussion -:discussion: -:labels: software, process - -= RFD 2 Example title -``` - -`authors` contains semicolon-separated owners. `discussion` contains the RFD's -pull-request URL once discussion starts. `labels` is a comma-separated set of -searchable topics. The document is the single source of truth for this metadata; -the index intentionally does not duplicate it. - -Implementation progress lives separately in `rfd/NNNN/IMPLEMENTATION.org`. The -RFD and checklist link to each other, keeping the design and decision record -stable while implementation tasks are checked off. - -## States - -- `prediscussion`: actively being written and not ready for broad review. -- `ideation`: a narrowly scoped topic or scratchpad without active revision. -- `discussion`: under active review in the linked pull request. -- `published`: discussion has converged and the RFD expresses project direction. -- `committed`: the proposal is fully implemented and describes current behavior. -- `abandoned`: deliberately not proceeding or otherwise retained only for history. - -The usual path is `prediscussion` or `ideation` to `discussion`, then -`published`, and eventually `committed`. `abandoned` is an off-ramp at any stage. -Implementation checklist progress does not determine the RFD's state. - -## Lifecycle - -Reserve the next unused four-digit number and create `rfd/NNNN/README.adoc` and -`rfd/NNNN/IMPLEMENTATION.org` on a branch. Cross-link the two documents. Use -`prediscussion` while writing or `ideation` for a topic placeholder. When the -document is ready for review, open a pull request, set the state to `discussion`, -and add that pull request as the discussion URL. - -Before merging a proposal that represents project direction, move it to -`published`. Once the described work is entirely implemented, update it to -`committed`. Material changes to a published or committed RFD go through a new -pull request and retain the original discussion link unless the RFD explicitly -documents a replacement. - -## Relationship to the MVP plan - -The [MVP plan](../docs/mvp.org) remains Kodo's delivery roadmap and acceptance -sequence. RFDs document durable design decisions, boundaries, and tradeoffs that -need focused discussion. An MVP milestone may link to an RFD without moving its -task checklist into the design document. - -## Shared principles - -- Session durability must not make recovery cost grow without bound. -- Database work should be proportional to live replicas and active sessions, - not historical sessions, completed coordinators, total users, or unrelated - event traffic. -- Ownership checks and recovery optimization must preserve fencing and the - documented failure-detection bound. -- User-owned collections are scoped in the database query rather than fetched - and filtered afterward. -- Protocol changes remain compatible across rolling control-plane and runner - upgrades unless an RFD explicitly defines a migration boundary. From 0fab2834ba26431844d10dbc439c99d6ca05ac5c Mon Sep 17 00:00:00 2001 From: "Darwin D. Wu" Date: Fri, 23 Oct 2026 18:35:36 -0700 Subject: [PATCH 3/3] docs(mvp): keep the engineering principles from the RFD index The shared principles listed in rfd/README.md apply to Kodo itself, so keep them in the MVP plan now that the RFDs live in chaba-dev/rfds. --- docs/mvp.org | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/mvp.org b/docs/mvp.org index 636a95e..6c6b7a5 100644 --- a/docs/mvp.org +++ b/docs/mvp.org @@ -76,6 +76,21 @@ The user can see each consequential action, stop an active turn, and inspect the resulting working-tree changes. Kodo reports what actually happened rather than relying on the model's description of its work. +* Engineering principles + +These hold across Kodo's [[https://chaba-rfds.pages.dev/?project=kodo][RFDs]]. + +- Session durability must not make recovery cost grow without bound. +- Database work should be proportional to live replicas and active sessions, + not historical sessions, completed coordinators, total users, or unrelated + event traffic. +- Ownership checks and recovery optimization must preserve fencing and the + documented failure-detection bound. +- User-owned collections are scoped in the database query rather than fetched + and filtered afterward. +- Protocol changes remain compatible across rolling control-plane and runner + upgrades unless an RFD explicitly defines a migration boundary. + * System architecture #+begin_example