diff --git a/deploy/org/README.md b/deploy/org/README.md index a89ee0335f..6ece69c938 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -298,6 +298,10 @@ because it has to become a different Linux user for every chat. It is built from until the machine confirms every delete. The log says so when it starts waiting (again after the 10th, 100th ... failed try) and once when it finishes. It deletes only the chats the person had when they were removed, so a chat made later by someone who joined again under the same handle is left alone. The operator does not repeat the removal. + The person also leaves People, whichever way they joined (a named invitation or an anonymous access link), and every share + others gave them on chats or workstreams is deleted, so none comes back if they join again. The link they came in by does + not reopen for someone else. Once their last chat is deleted the machine removes the person's own folder under `/chats/people` + if nothing else is in it. - **Limits.** `CODEAF_SESSIONHOST_MAX_RUNNING` chats at once (default 20) and `CODEAF_SESSIONHOST_MAX_PER_PERSON` per person (default 3). A chat counts while it has a process; a person at their limit can still make a chat but cannot start another and reads "You already have N chats running; stop one first." @@ -550,6 +554,43 @@ docker compose up -d codeaf sessionhost The people, their sign-ins, the invitations and the chats come back as they were. +**On Railway** the volumes are Railway's, so the `docker run` lines above do not apply. This is the recipe that was run, once, on an +idle organization: the two volumes that matter, `codeaf`'s `/data` and `sessionhost`'s `/chats`, were archived over `railway ssh`, and the +copy was restored into a scratch folder on a laptop. Nothing was ever restored over the live install. The archives hold password +hashes and sign-in sessions, so they are as private as `.env`: `umask 077` makes the files readable by you alone, and any folder you +unpack them into should be mode 700. + +```sh +umask 077 +railway ssh -s codeaf -- 'tar czf - -C /data . | base64 -w0' codeaf-data.tgz +railway ssh -s sessionhost -- 'tar czf - -C /chats . | base64 -w0' sessions-data.tgz +``` + +The `base64` keeps the archive intact through the ssh stream, and `/codeaf/factory/config.yaml --listen 127.0.0.1:18787`, stopped again afterwards). The restored server signed in the operator and +a person by password, refused a person who had been removed, showed the same people, bots, shares and policy revision as the live one, +had the same spend total, and its SQLite store passed `integrity_check`. Of the 579 files in the `sessionhost` archive, 576 had the +same sha256 as the live ones; the other three are mode-000 placeholders that the non-root checker could not read, and they are in the +archive. + +What was not done, so it is not claimed: + +- **The services were not stopped first.** `railway ssh` needs a running container, so the Compose recipe's "stop the writers" + step has no equivalent here. The copy was taken while nobody was working, with the SQLite and WAL files live. A copy taken while + people are working may not be consistent. +- **A restore onto a Railway volume.** Only the scratch restore above was run; how to put an archive back into a service's volume is + unproven. +- **Railway's own volume backups** were not used. +- Hosted chats were not served from the restored copy (the scratch server had no hosting settings), so only the files of + `sessionhost`'s archive were compared, not running chats. + Everything outside this checkout is pinned: the codeaf release that `CODEAF_BINARY_FROM=fetch` downloads (`CODEAF_RELEASE` and its two sha256 values at the top of `codeaf.Dockerfile`), the SWE-AF and PR-AF commits (`SWEAF_REF`, `PRAF_REF`) and the AgentField image (`AGENTFIELD_IMAGE`, tag and digest together in `agentfield.Dockerfile`). The default build does not download a codeaf at all: @@ -658,8 +699,8 @@ The same Dockerfiles run on Railway as one project: six services (seven with the the model stub, private networking between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds from this repository's source, on Railway's builders. The table below is the configuration by hand. It was followed from an empty project, with the keyless stub, and every service came up: see "Check it" below. (A Railway template needs images, not a -repository: `railway/make-template.sh` makes a draft one from the published images above, sessionhost included, and is a dry run -until those images exist.) +repository: `railway/make-template.sh` makes a draft one from the published images above, sessionhost included; see "The template +script, and the draft it makes" below for what it does and what is left for you.) **What you need:** a Railway account and the workspace that should own the project, and the Railway CLI (`railway`, version 5.x, signed in with `railway login`). The dashboard can do every step of the table, but "Check it" and the operator link below use the CLI. @@ -705,10 +746,17 @@ For real work, also set `GH_TOKEN=...` on `runner`, `swe-af` and `pr-af` (it let requests, as in "What you need"; the keyless test needs none). People's own GitHub access for hosted chats is not a variable: each person stores theirs on the server (see "Keys, spend and git"). -Volumes: Railway's default size is large (50 GB on the plan this was tried on), the dashboard and the CLI's `railway volume add` take the -default unless you size it, and **a volume can grow but never shrink**. Size it when you create it: 1 GB is plenty for `codeaf`, `agentfield` -and `sessionhost`, 512 MB for `runner` and `pr-af`. Reference variables (`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) are Railway's way of -naming another service; keep them as written. +Volumes: **Railway makes every volume 50 GB unless it is sized, and the CLI cannot size one.** `railway volume add` takes a mount +path and nothing else, and `railway volume update` takes only a mount path and a name, so six volumes made with the CLI (which is +what `make-template.sh` does) are 300 GB of billed storage. **A volume can grow but never shrink**, so start small: 1 GB is plenty for +`codeaf`, `agentfield`, `sessionhost` and `swe-af`, 512 MB for `runner` and `pr-af` (the sizes the production run used). + +The resize step, for a volume that is still empty: delete it (`railway volume delete --volume --yes`) and make it again +with a size through Railway's API, which takes `sizeMB`. The production run did exactly that, with Railway's MCP server +(`create-volume` with `sizeMB`), for all six volumes before anything was written to them. A volume that already holds data can only +grow: Railway's volumes documentation describes a live resize from the volume's settings in the dashboard (growth only, no downtime +unless the volume is full). That dashboard resize was not tried here. Reference variables (`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) +are Railway's way of naming another service; keep them as written. What a first install needs that the table does not show: @@ -785,6 +833,26 @@ curl -s "https:///v1/about" The first three answer for the whole stack's wiring: AgentField refuses an anonymous call, the sessionhost can keep chats apart on this kernel, and the public name serves over HTTPS. None of them makes a model call or a chat; those start once the organization is claimed. +### The template script, and the draft it makes + +`railway/make-template.sh` builds the same six services from the published images (it checks that they exist first) and turns the +project into a Railway template draft. With no argument it is a dry run that prints every Railway call; `--apply`, with +`RAILWAY_WORKSPACE` set to the workspace's id or name, makes them. Run `--apply` from a terminal: with no terminal on stdin the +Railway CLI reads a JSON patch from stdin and ignores the flags the script passes. `--apply` ran end to end on 2026-11-25 against +Railway CLI 5.71.0, except for its last call, `railway templates create`, which that run skipped on purpose. `railway/railway_scripts_test.sh` +runs it against a stub CLI that records its arguments, so the volume and environment calls are pinned. + +What it leaves for you: + +- **Every volume is 50 GB.** The CLI has no size option; see "Volumes" above for the resize step, and do it before first use. +- **`railway templates create` makes a DRAFT, not a published template.** Railway describes it as cloning the project into an + unpublished template that opens in the dashboard's template editor for cleanup before publishing. The script has no publish + call and never will. After it runs: open the draft in your workspace's template editor, mark `OPENROUTER_API_KEY` and `GH_TOKEN` + on the `codeaf` service as inputs people fill in, check the services and variables against the table above, and press Publish + only if you mean to put it in Railway's marketplace; otherwise leave it a draft. The project the script made only fed the draft, + so delete it once the draft exists (the script's closing note says the same). The production run skipped this call, so the + draft's contents were not looked at. + ## Known limits - The runner is a small Python host of the codeaf engine (`scripts/runner.py`), because `codeaf factory serve` @@ -800,6 +868,18 @@ kernel, and the public name serves over HTTPS. None of them makes a model call o no variable here, such as `loopback_trust` (always off for this team server; see "Claim the organization"), cannot be changed in this stack, and a hand edit of the file is replaced. - One replica of each service; no high availability. +- **A hosted chat's sandbox has a small toolbox.** The chats' machine is the `codeaf` image's runtime, which carries `python3` + (3.11 in the production run), `git`, `curl` and `openssh-client` and nothing else a project is likely to need: no `pip`, no + `pytest`, no `go`, no `node`, no `make`, no `gcc`, and a chat's Linux user is not root, so it cannot install them. A chat can work on + a project that needs only the standard library; the production run's first test project needed one third-party Python + package and its tests could not run at all. There is no setting for this. The tools come from the `apt-get install` line in the + runtime stage of `codeaf.Dockerfile`, and a different set means building your own image from it, which was not tried. +- **The factory services' model calls are not counted.** SWE-AF, PR-AF and the runner call OpenRouter directly with their own copy + of the key (`OPENROUTER_API_KEY` on each service), not through the organization's model door. Their spend is not in the + spend table, in anyone's My space or in a chat's or a person's limit, and the limits above do not stop them. In the production run + one SWE-AF job's own view said it cost `0.00027` while OpenRouter billed about $0.56 for it. To bound that spend, set a credit + limit on the key at OpenRouter (the run's key had one of $50), and give these services a key of their own if you want their + bill apart from the chats'. - **The network fence filters TCP by port.** A chat's commands may connect only to ports 443, 80, 22 and 9418 by default (`CODEAF_SESSIONHOST_CONNECT_PORTS`) and the ports used for the organization server's own address. Landlock has no rule for a destination address. Ports 80 and 443 can reach any host accessible from the chats' machine, including the internet, diff --git a/deploy/org/railway/make-template.sh b/deploy/org/railway/make-template.sh index 2247725bbc..4651e744b2 100755 --- a/deploy/org/railway/make-template.sh +++ b/deploy/org/railway/make-template.sh @@ -25,13 +25,16 @@ # (`codeaf sessionhost probe` in that service reports `uid+fence`). The person using the template still needs to supply # the model key input. # -# NOT YET RUN AGAINST RAILWAY: the images did not exist on Docker Hub when this was written. The calls are the Railway CLI's -# documented ones (`railway add --image`, `railway volume add`, `railway environment edit --service-config`, `railway -# templates create`); the first --apply is the first real test, and a service-by-service failure leaves a project you can -# delete (it is only the SOURCE of the draft; delete it once the draft exists). -# The deploy.limitOverride and deploy.healthcheckPath paths were read back from a live Railway project. Run --apply from -# a terminal. `railway environment edit --service-config ...` reads its patch from the command line only when stdin is a -# terminal. With non-terminal stdin, such as in CI or an agent, it reads a JSON patch from stdin and ignores those flags. +# RUN AGAINST RAILWAY: --apply ran end to end on 2026-11-25 against Railway CLI 5.71.0, and two calls had to change for +# the current CLI: `railway volume` takes the service as `railway volume --service add ...` (the ID, from the +# JSON `railway add` printed, never the name; `volume add --service` is an error and a name panics the CLI), and every +# `railway environment edit` needs `--message` (without it a terminal run stops at "Apply changes now? (Y/n)" and waits). +# railway_scripts_test.sh pins both calls against a stub CLI that records its arguments. Run --apply from a terminal: +# `railway environment edit --service-config ...` reads its patch from the command line only when stdin is a terminal. With +# non-terminal stdin, such as in CI or an agent, it reads a JSON patch from stdin and ignores those flags. +# Two things the CLI cannot do: it has no volume SIZE option (every volume comes out at Railway's default, 50 GB; resize each +# one in the dashboard, see README.md "On Railway"), and `railway templates create` makes a draft the owner still has to +# finish by hand. # shellcheck disable=SC2016 # the ${{...}} in single quotes are Railway expressions, not shell expansions set -euo pipefail @@ -71,7 +74,37 @@ rail() { local arg for arg in "$@"; do printf ' '; quote "$arg"; done printf '\n' - if [ "$APPLY" = 1 ]; then railway "$@"; fi + if [ "$APPLY" = 1 ]; then + if [ "$capture" = 1 ]; then + # Keep the JSON Railway prints on stdout (its prompts and progress stay on the terminal) to read an ID from it. + railway_out=$(railway "$@") + printf '%s\n' "$railway_out" + else + railway "$@" + fi + fi +} +capture=0 +railway_out="" + +# service_id is the ID Railway gave the service added last. `railway volume` needs the ID, not the name. +service_id="" + +# volume_add NAME MOUNT: a volume on the service added last. The current CLI wants the service ID before `add` +# (`railway volume --service add`); an older one took `railway volume add --service `, and is used when its help +# still lists that option. A dry run always prints the current form, so the plan does not depend on which CLI is installed. +volume_style="" +volume_add() { + local name="$1" mount="$2" help + if [ "$APPLY" = 1 ] && [ -z "$volume_style" ]; then + help=$(railway volume add --help 2>&1 || true) + case "$help" in *--service*) volume_style=old ;; *) volume_style=current ;; esac + fi + if [ "$volume_style" = old ]; then + rail volume add --service "$name" --mount-path "$mount" --json + else + rail volume --service "${service_id:-<$name service id>}" add --mount-path "$mount" --json + fi } # check_var NAME VALUE: refuses anything that would put a real value, or a smoke-test switch, in the template. @@ -97,7 +130,15 @@ service() { check_var "${pair%%=*}" "${pair#*=}" args+=(--variables "$pair") done + capture=1 rail add --service "$name" --image "$image" "${args[@]}" --json + capture=0 + if [ "$APPLY" = 1 ]; then + service_id=$(printf '%s\n' "$railway_out" | sed -n 's/.*"id" *: *"\([^"]*\)".*/\1/p' | head -n 1) + [ -n "$service_id" ] || { echo "could not read the ID of service $name from the output of 'railway add --json'" >&2; exit 4; } + else + service_id="" + fi } if [ "$APPLY" = 1 ]; then @@ -128,7 +169,7 @@ service agentfield "$AGENTFIELD_IMAGE" \ AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH=/data/agentfield.bolt \ AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true \ AGENTFIELD_TELEMETRY_ENABLED=false -rail volume add --service agentfield --mount-path /data --json +volume_add agentfield /data rail environment edit --service-config agentfield deploy.healthcheckPath /api/v1/health --message "agentfield health check" # --- codeaf: the organization server, the one service with a public domain. Holds the template's two inputs. -------------------------- @@ -145,7 +186,7 @@ service codeaf "$CODEAF_IMAGE" \ 'CODEAF_HOSTED_MODEL_KEY=${{OPENROUTER_API_KEY}}' \ OPENROUTER_API_KEY= \ GH_TOKEN= -rail volume add --service codeaf --mount-path /data --json +volume_add codeaf /data rail environment edit --service-config codeaf deploy.healthcheckPath /v1/about --message "codeaf health check" rail domain --service codeaf --port 8787 --json @@ -157,9 +198,9 @@ service sessionhost "$CODEAF_IMAGE" \ "CODEAF_SESSIONHOST_MODEL=$MODEL" \ CODEAF_SESSIONHOST_MAX_RUNNING=4 \ CODEAF_SESSIONHOST_MAX_PER_PERSON=2 -rail volume add --service sessionhost --mount-path /chats --json +volume_add sessionhost /chats rail environment edit --service-config sessionhost deploy.limitOverride.containers.cpu 1 \ - --service-config sessionhost deploy.limitOverride.containers.memoryBytes 1000000000 + --service-config sessionhost deploy.limitOverride.containers.memoryBytes 1000000000 --message "sessionhost limits" # Railway can resolve this reference once the sessionhost service exists. hosted_url='http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790' @@ -174,7 +215,7 @@ service runner "$CODEAF_IMAGE" \ "ORG_MODEL=$MODEL" \ 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ 'GH_TOKEN=${{codeaf.GH_TOKEN}}' -rail volume add --service runner --mount-path /data --json +volume_add runner /data # --- the reasoner nodes ---------------------------------------------------------------------------------------------------------------------- service swe-af "$SWE_AF_IMAGE" \ @@ -187,7 +228,7 @@ service swe-af "$SWE_AF_IMAGE" \ SWE_DEFAULT_MODEL=openrouter/deepseek/deepseek-v4-flash-0731 \ 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ 'GH_TOKEN=${{codeaf.GH_TOKEN}}' -rail volume add --service swe-af --mount-path /workspaces --json +volume_add swe-af /workspaces service pr-af "$PR_AF_IMAGE" \ NODE_ID=pr-af \ @@ -198,7 +239,7 @@ service pr-af "$PR_AF_IMAGE" \ PR_AF_MODEL=deepseek/deepseek-v4-flash-0731 \ 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ 'GH_TOKEN=${{codeaf.GH_TOKEN}}' -rail volume add --service pr-af --mount-path /workspaces --json +volume_add pr-af /workspaces # --- the draft. `templates create` clones the project into an UNPUBLISHED template; there is no publish call here. ----------------- rail templates create --json @@ -209,6 +250,9 @@ if [ "$APPLY" = 1 ]; then The draft template is in your workspace, unpublished. Open it in the dashboard's template editor and mark OPENROUTER_API_KEY and GH_TOKEN (on the codeaf service) as inputs people fill in. The source project "$PROJECT" only fed the draft: delete it. Never press Publish unless you mean to put this in the marketplace. + +Every volume came out at Railway's default size, 50 GB, because the CLI has no size option: resize them before first use +(deploy/org/README.md, "Railway", Volumes). NOTE else echo "# $calls calls. Variables checked: no literal secret, no smoke-only switch. Nothing was run." diff --git a/deploy/org/railway/railway_scripts_test.sh b/deploy/org/railway/railway_scripts_test.sh index c9727d69c4..ce07b9c3ab 100755 --- a/deploy/org/railway/railway_scripts_test.sh +++ b/deploy/org/railway/railway_scripts_test.sh @@ -57,7 +57,7 @@ sessionhost_variables() { } row 'make-template 2: sessionhost gets its role, data, shared secret, model and limits' sessionhost_variables row 'make-template 2: sessionhost mounts /chats' \ - grep -qE '^\+ railway volume add --service sessionhost --mount-path /chats( |$)' "$plan" + grep -qxF "+ railway volume --service '' add --mount-path /chats --json" "$plan" private_sessionhost() { [ -n "$sessionhost" ] && ! grep -Eq '^\+ railway domain .*--service sessionhost( |$)' "$plan" } @@ -85,6 +85,118 @@ template_excludes_smoke_switches() { } row 'make-template 5: no smoke-only switches enter the plan' template_excludes_smoke_switches +# --apply against a stub of the Railway CLI (5.7x) that records every call's arguments, one line per call with each argument +# in brackets, and refuses what that CLI refuses: `volume add --service` is an unknown option, `volume --service ` panics +# (only an ID works), and `environment edit` without --message stops at "Apply changes now? (Y/n)", where a terminal run waits +# forever. FAKE_RAILWAY_STYLE=old makes `volume add` take --service itself, as an older CLI did; FAKE_RAILWAY_NO_ID=1 makes +# `add` print no ID. +mkdir "$work/apply-bin" +cat >"$work/apply-bin/railway" <<'STUB' +#!/usr/bin/env bash +set -u +line="" +for a in "$@"; do line+="[$a]"; done +printf '%s\n' "$line" >>"$FAKE_RAILWAY_LOG" +case "${1:-}" in + whoami) exit 0 ;; + init) echo '{"id":"project-id","name":"stub"}' ;; + add) + name="" prev="" + for a in "$@"; do [ "$prev" = --service ] && name=$a; prev=$a; done + echo '> What do you need? Docker Image' >&2 + if [ "${FAKE_RAILWAY_NO_ID:-}" = 1 ]; then echo '{}'; else printf '{"id":"id-%s","name":"%s"}\n' "$name" "$name"; fi ;; + volume) + shift + parent="" + if [ "${1:-}" = --service ]; then parent=${2:-}; shift 2; fi + [ "${1:-}" = add ] || exit 64 + shift + for a in "$@"; do + if [ "$a" = --help ]; then + if [ "${FAKE_RAILWAY_STYLE:-current}" = old ]; then echo ' -s, --service Service'; fi + echo ' -m, --mount-path The mount path of the volume' + exit 0 + fi + done + if [ "${FAKE_RAILWAY_STYLE:-current}" != old ]; then + for a in "$@"; do + [ "$a" = --service ] && { echo "error: unexpected argument '--service' found" >&2; exit 2; } + done + case "$parent" in id-*) ;; *) echo "thread 'main' panicked: called Option::unwrap() on a None value" >&2; exit 101 ;; esac + fi + echo '{"id":"volume"}' ;; + environment) + shift + [ "${1:-}" = edit ] || exit 64 + shift + seen=0 + for a in "$@"; do if [ "$a" = --message ] || [ "$a" = -m ]; then seen=1; fi; done + [ "$seen" = 1 ] || { echo '? Apply changes now? (Y/n)' >&2; exit 99; } ;; + domain) echo '{"domain":"https://stub.example"}' ;; + *) echo '{}' ;; +esac +STUB +cat >"$work/apply-bin/docker" <<'STUB' +#!/bin/sh +exit 0 +STUB +chmod +x "$work/apply-bin/railway" "$work/apply-bin/docker" +mkdir "$work/tmp" + +apply_with() { + FAKE_RAILWAY_LOG=$work/calls + : >"$FAKE_RAILWAY_LOG" + status=0 + env "$@" FAKE_RAILWAY_LOG="$FAKE_RAILWAY_LOG" TMPDIR="$work/tmp" RAILWAY_WORKSPACE=stub-workspace \ + PATH="$work/apply-bin:$PATH" "$template" --apply >"$work/apply-out" 2>"$work/apply-err" || status=$? +} +apply_ok() { apply_with FAKE_RAILWAY_STYLE=current; [ "$status" = 0 ] && ! grep -q "ID of service" "$work/apply-err"; } +row 'make-template 6: --apply runs to the end against the current CLI' apply_ok + +volumes_by_id() { + apply_ok || return 1 + local want + for want in agentfield:/data codeaf:/data sessionhost:/chats runner:/data swe-af:/workspaces pr-af:/workspaces; do + local name=${want%%:*} mount=${want#*:} add vol + add=$(grep -nF "[add][--service][$name][--image]" "$FAKE_RAILWAY_LOG" | head -n 1 | cut -d: -f1) && + vol=$(grep -nxF "[volume][--service][id-$name][add][--mount-path][$mount][--json]" "$FAKE_RAILWAY_LOG" | head -n 1 | cut -d: -f1) && + [ "$add" -lt "$vol" ] || return 1 + done + [ "$(grep '^\[volume\]' "$FAKE_RAILWAY_LOG" | grep -vc '\[--help\]')" = 6 ] +} +row 'make-template 6: each volume is added with its service ID, after the service exists, and never as volume add --service' volumes_by_id + +limits_have_a_message() { + apply_ok && + grep -qxF '[environment][edit][--service-config][sessionhost][deploy.limitOverride.containers.cpu][1][--service-config][sessionhost][deploy.limitOverride.containers.memoryBytes][1000000000][--message][sessionhost limits]' "$FAKE_RAILWAY_LOG" +} +row 'make-template 6: the sessionhost limits edit carries --message, so a terminal run does not wait for a key' limits_have_a_message + +every_edit_has_a_message() { + apply_ok || return 1 + local edits messages + edits=$(grep -c '^\[environment\]\[edit\]' "$FAKE_RAILWAY_LOG") + messages=$(grep '^\[environment\]\[edit\]' "$FAKE_RAILWAY_LOG" | grep -c '\[--message\]') + [ "$edits" = 3 ] && [ "$messages" = 3 ] +} +row 'make-template 6: all three environment edits carry --message' every_edit_has_a_message + +older_cli_keeps_working() { + apply_with FAKE_RAILWAY_STYLE=old + [ "$status" = 0 ] && + [ "$(grep -c '^\[volume\]\[add\]\[--service\]' "$FAKE_RAILWAY_LOG")" = 6 ] && + grep -qxF '[volume][add][--service][sessionhost][--mount-path][/chats][--json]' "$FAKE_RAILWAY_LOG" && + ! grep -q '^\[volume\]\[--service\]' "$FAKE_RAILWAY_LOG" +} +row 'make-template 6: an older CLI whose volume add takes --service still gets that form' older_cli_keeps_working + +stops_without_an_id() { + apply_with FAKE_RAILWAY_NO_ID=1 + [ "$status" = 4 ] && grep -qF 'could not read the ID of service agentfield' "$work/apply-err" && + ! grep -q '^\[volume\]' "$FAKE_RAILWAY_LOG" +} +row 'make-template 6: an add that prints no service ID stops the script before any volume' stops_without_an_id + mkdir "$work/bin" cat >"$work/bin/railway" <<'FAKE' #!/bin/sh diff --git a/docs/changes/unreleased/2944-prod-run-fixes.md b/docs/changes/unreleased/2944-prod-run-fixes.md new file mode 100644 index 0000000000..ad3be156ad --- /dev/null +++ b/docs/changes/unreleased/2944-prod-run-fixes.md @@ -0,0 +1,13 @@ +--- +kind: fixed +title: Removing a person ends their place and grants on every join door; Railway script fits the CLI +pr: 2944 +surface: [factory, docs, build] +invalidates: + - "Removing a person who had joined by an anonymous access link left them in People with every grant they held, and a new link brought those grants back. Removal now takes them out of People and ends every grant they hold, on every join door, and a new link brings none of it back. The one thing unchanged is that the same still-open link admits them again as a new member with no grants." + - "Deleting the last chat of a removed person left their empty folder on the chats' host. The folder is now removed with the chat, only when nothing else is in it; folders left by earlier removals stay." + - "deploy/org/railway/make-template.sh failed on Railway CLI 5.71.0, because volume add no longer takes --service and the environment edit waited at a prompt without --message. It now adds each volume by the service's ID after the service exists and passes --message on all three edits; an older CLI still gets the older form." + - "The operator docs did not say that Railway volumes are 50 GB with no size flag, that templates create makes a draft, that a hosted chat's sandbox has no pip, pytest, go, node, make or gcc, or that SWE-AF, PR-AF and the runner call the model provider directly, outside the organization's spend table and limits. They now say each of these, and give a backup recipe for Railway." +--- + +Grants end by person, in the same removal that ends their chats. Links, invites and the password door admit people as before. diff --git a/docs/organizations.md b/docs/organizations.md index 43eef08067..75e5161f88 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -113,6 +113,9 @@ read along without acting as you. The server sends each person's verbs with every chat row, and the client only hides the controls it was not given. Taking a share away ends the guest's open window within a few seconds (`CODEAF_HOSTED_HEARTBEAT`, five by default). +When the operator removes a person from the organization, every share they hold on anyone's chat ends with them, whichever way +they joined (a named invitation or an anonymous access link), and they leave People. If they join again later, by a new link or +the old one, none of those shares comes back. **From a terminal.** The desktop app has no sharing buttons for chats yet, so the owner shares one with a request. The chat's name, `hs_...`, is in the owner's list; the share names a person by username and a role: @@ -340,8 +343,18 @@ It answers with an `access_token` the same way. - `local_sessions: refuse` is enforced on the server side only. No client acts on it yet. - Request framing and WebSocket upgrades through a front proxy were untested end to end. The test stack used no proxy. - The priced-model reservation path was read in the code and remains untested end to end. The test stub has no model price. -- The Railway template is made from the published images, which are not on Docker Hub yet, so the script that makes it has only - been dry-run. The by-hand Railway install in the operator README is the tested configuration, and it includes the sessionhost. +- The script that makes the Railway template (`deploy/org/railway/make-template.sh`) ran end to end against the published + images on Railway CLI 5.71.0, except its last call, `railway templates create`, which makes a draft that the owner still has + to finish in the dashboard and that was not looked at. Its volumes come out at Railway's default 50 GB because the CLI has no + size option. The operator README, "Railway", has the resize step, the draft and a backup recipe for Railway that was run once + and restored only into a scratch folder. +- A hosted chat's sandbox has `python3`, `git`, `curl` and `openssh-client`, and no `pip`, `pytest`, `go`, `node`, `make` or + `gcc`; a chat's user is not root and cannot install them. A project that needs more than the standard library cannot run its + tests in a hosted chat today, and there is no setting that changes it. +- SWE-AF, PR-AF and the runner call the model provider directly with their own copy of the key, not through the organization's model + door. Their spend is not in the spend table, in anyone's My space, or in any chat's or person's limit, and those limits do + not stop them. In one production-style run a factory job's own view said it cost `0.00027` while OpenRouter billed about $0.56 for + it. Put a credit limit on the key at the provider. - GitHub sign-in and invitation mail are optional and untested in the stack; a username and password is the default way in. - One replica of each service; no high availability. diff --git a/internal/factory/serve/invites.go b/internal/factory/serve/invites.go index 4f969ae2d4..d0f4dd6f53 100644 --- a/internal/factory/serve/invites.go +++ b/internal/factory/serve/invites.go @@ -656,7 +656,10 @@ func tokenHash(secret string) string { return hex.EncodeToString(sum[:]) } -// closeInvitesOf ends every invite that admitted handle; the list skips an ended invite. +// closeInvitesOf ends the standing of a removed person on every link that admitted them, in one save. A named +// invite carries the handle it admitted and is revoked, which the list skips. An anonymous access link carries +// none, so it cannot be found by handle and cannot be revoked (that would turn away the others who joined by it): +// the person's own use is marked removed instead. Either way the use stays spent, so no link reopens. func closeInvitesOf(path, handle string, now time.Time) error { if path == "" { return nil @@ -667,6 +670,7 @@ func closeInvitesOf(path, handle string, now time.Time) error { if t.Invite != nil && !t.Revoked && t.Invite.Handle != "" && factory.NormalizeHandle(t.Invite.Handle) == handle { t.TokenHash, t.Token, t.Revoked, t.RevokedAt = tokenHash(t.Token), "", true, now.UTC() } + t.EndMember(handle, now) } return rows, nil }) diff --git a/internal/factory/serve/members.go b/internal/factory/serve/members.go index 8e108e0871..123b81b628 100644 --- a/internal/factory/serve/members.go +++ b/internal/factory/serve/members.go @@ -38,7 +38,8 @@ func (h *Handler) memberList() []api.Member { continue } for _, joiner := range tok.Members() { - if joiner.Profile.Handle == "" { + // A joiner the operator removed (closeInvitesOf) keeps their spent use but is no longer a member. + if joiner.Profile.Handle == "" || !joiner.Removed.IsZero() { continue } m := take(joiner.Profile.Handle) diff --git a/internal/factory/serve/people_v2.go b/internal/factory/serve/people_v2.go index d0f452663f..4de50a9c27 100644 --- a/internal/factory/serve/people_v2.go +++ b/internal/factory/serve/people_v2.go @@ -207,6 +207,12 @@ func (h *Handler) operatorRevokePerson(w http.ResponseWriter, r *http.Request) { if h.failed(w, closeInvitesOf(h.config.TokensPath, handle, h.now())) { return } + // WHAT OTHERS GAVE THEM GOES TOO, whichever door they came in by: a grant left on someone's chat would apply again + // to anyone who later joins under the same handle (found on a production run, 2026-11-25). + ended, err := h.endGrantsOf(handle) + if h.failed(w, err) { + return + } // A person the operator removes leaves every team with their sign-ins, // and their workstreams go to an heir rather than keep a gone owner. if h.failed(w, h.leaveEveryTeam(r, handle)) { @@ -229,9 +235,20 @@ func (h *Handler) operatorRevokePerson(w http.ResponseWriter, r *http.Request) { if given > 0 { detail += fmt.Sprintf("; %d workstreams given to @%s", given, heir) } + if ended > 0 { + detail += fmt.Sprintf("; %d grants ended", ended) + } h.finish(w, h.operatorEvent(r, record.SessionsRevoked, "person:"+handle, detail)) } +// endGrantsOf deletes every grant that names a removed person and answers how many it deleted. +func (h *Handler) endGrantsOf(handle string) (int, error) { + if h.config.Store == nil { + return 0, nil + } + return h.config.Store.RemoveGrantsOfSubject("person", factory.NormalizeHandle(handle)) +} + // revokePerson ends sign-ins and runner credentials. Leaving the // organization also ends the person's bot credentials. func (h *Handler) revokePerson(handle string, leaving bool) error { diff --git a/internal/factory/serve/removal_link_joiners_test.go b/internal/factory/serve/removal_link_joiners_test.go new file mode 100644 index 0000000000..b81aa5cca4 --- /dev/null +++ b/internal/factory/serve/removal_link_joiners_test.go @@ -0,0 +1,282 @@ +package serve + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +// VALIDATION CONTRACT, written before the code it checks (found on a production run of the hosted organization: +// a person who joined by an anonymous access link and was then removed stayed in People as "away" and kept the +// grants others had given them): +// - Removing a person drops them from People and from the member list, and drops every grant they hold on +// anyone's chat, whichever door they joined by: a named invite, an anonymous link, or a GitHub sign-in. +// - Nobody else is touched: another person's grants on the same chat, and a joiner of the same multi-use link, +// stay exactly as they were. +// - A removed person's spent use stays spent: the link they came in by does not reopen for anyone else. Joining +// again, by a new link or by the old one, brings no old grants back. +// - A person who joined by a named invite is removed exactly as before: gone from People, the invite closed. + +// removalDoor is one way a person joins the organization. +type removalDoor struct { + name string + // link makes a fresh link as the operator and answers it. + link func(t *testing.T, rg *hostedRig) string + // after is the state the answer to a second sign-up through the same link names once its person is gone. + after string +} + +var removalDoors = []removalDoor{ + {"named invite", func(t *testing.T, rg *hostedRig) string { + t.Helper() + var made api.InviteMade + rg.do(t, "owner", http.MethodPost, "/v1/invites", -1, api.InviteNew{Email: "bob@acme.example"}, http.StatusCreated, &made) + return made.URL + }, "revoked"}, + {"anonymous link", func(t *testing.T, rg *hostedRig) string { return rg.anonymousLink(t, 1) }, "used_up"}, +} + +// anonymousLink is the README's own recipe, POST /v1/access/links, for up to uses people. +func (rg *hostedRig) anonymousLink(t *testing.T, uses int) string { + t.Helper() + var made struct { + Link api.AccessLink `json:"link"` + } + rg.do(t, "owner", http.MethodPost, "/v1/access/links", -1, api.CreateAccessLink{MaxUses: uses}, http.StatusCreated, &made) + if made.Link.URL == "" { + t.Fatal("the link carries no address") + } + return made.Link.URL +} + +// join signs username up through link and keeps their token. +func (rg *hostedRig) join(t *testing.T, link, username string) { + t.Helper() + out, code := rg.signUpAs(t, link, username) + if code != http.StatusOK || out.State != "joined" || out.AccessToken == "" { + t.Fatalf("%s did not join: %d %+v", username, code, out) + } + rg.tokens[username] = out.AccessToken +} + +// handlesOf reads who the organization lists, through the two routes that list people. +func (rg *hostedRig) handlesOf(t *testing.T) (people, members []string) { + t.Helper() + var list api.People + rg.do(t, "owner", http.MethodGet, "/v1/people", -1, nil, http.StatusOK, &list) + for _, p := range list.People { + people = append(people, p.Handle) + } + var all api.Members + rg.do(t, "owner", http.MethodGet, "/v1/members", -1, nil, http.StatusOK, &all) + for _, m := range all.Members { + members = append(members, m.Handle) + } + return people, members +} + +// holders lists who holds a grant on one chat, by handle and role, in the store. +func (rg *hostedRig) holders(t *testing.T, chat string) []string { + t.Helper() + grants, err := rg.st.GrantsOn(store.SessionKind, chat) + if err != nil { + t.Fatal(err) + } + var out []string + for _, g := range grants { + out = append(out, g.Subject.ID+":"+g.Role) + } + slices.Sort(out) + return out +} + +func (rg *hostedRig) remove(t *testing.T, handle string) { + t.Helper() + if w := rg.send("owner", http.MethodDelete, "/v1/people/"+handle+"/sessions", nil, nil); w.Code != http.StatusOK { + t.Fatalf("removing %s = %d %s", handle, w.Code, w.Body) + } +} + +// Contract items 1, 2, 3 and 4: through the real handlers and a real store, on both password doors. +func TestRemovingAJoinerEndsTheirPlaceAndEveryGrantWhicheverDoorTheyUsed(t *testing.T) { + for _, door := range removalDoors { + t.Run(door.name, func(t *testing.T) { + rg := newHostedRig(t) + link := door.link(t, rg) + rg.join(t, link, "bob") + chat := rg.create(t, "santosh") + other := rg.create(t, "mia") + hostedGrant(t, rg, "santosh", chat, "bob", "edit") + hostedGrant(t, rg, "santosh", chat, "bob", "view") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + hostedGrant(t, rg, "mia", other, "bob", "view") + + // Controls: before the removal bob is listed, holds the grants and reads the chat, so what is gone + // afterwards is the removal's doing. + if people, members := rg.handlesOf(t); !slices.Contains(people, "bob") || !slices.Contains(members, "bob") { + t.Fatalf("before the removal, bob is not listed: people %v, members %v", people, members) + } + if w := rg.send("bob", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Fatalf("before the removal, bob's read of the chat = %d %s", w.Code, w.Body) + } + if got, want := rg.holders(t, chat), []string{"abir:view", "bob:edit", "bob:view"}; !slices.Equal(got, want) { + t.Fatalf("before the removal, the chat's grants = %v, want %v", got, want) + } + + rg.remove(t, "bob") + + people, members := rg.handlesOf(t) + if slices.Contains(people, "bob") || slices.Contains(members, "bob") { + t.Errorf("after the removal, bob is still listed: people %v, members %v", people, members) + } + if held, err := rg.st.GrantsOfSubject("person", "bob"); err != nil || len(held) != 0 { + t.Errorf("after the removal, bob still holds grants: %+v, %v", held, err) + } + if got, want := rg.holders(t, chat), []string{"abir:view"}; !slices.Equal(got, want) { + t.Errorf("the chat's grants after the removal = %v, want %v", got, want) + } + if got := rg.holders(t, other); len(got) != 0 { + t.Errorf("mia's chat's grants after the removal = %v, want none", got) + } + if w := rg.send("abir", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Errorf("another guest's read of the chat after bob's removal = %d, want 200", w.Code) + } + // What the removal already did stays done. + if w := rg.send("bob", http.MethodGet, "/v1/me", nil, nil); w.Code != http.StatusUnauthorized { + t.Errorf("bob's token after the removal = %d, want 401", w.Code) + } + if w := rg.signIn(t, "bob"); w.Code != http.StatusUnauthorized { + t.Errorf("bob's password sign-in after the removal = %d, want 401", w.Code) + } + // The link does not reopen, and its answer to a second person is what it was. + if out, _ := rg.signUpAs(t, link, "carol"); out.State != door.after { + t.Errorf("a second sign-up through bob's link says %q, want %q", out.State, door.after) + } + }) + } +} + +// signUpAs joins by password through link, from loopback because the password door takes plain HTTP only there; +// the answer may be a refusal. +func (rg *hostedRig) signUpAs(t *testing.T, link, username string) (api.FactoryAccess, int) { + t.Helper() + body, _ := json.Marshal(api.FactoryAccessRequest{Link: link, Verb: "sign_up", Username: username, Password: pwAbir}) + r := httptest.NewRequest(http.MethodPost, "/v1/factory-access", strings.NewReader(string(body))) + r.RemoteAddr = "127.0.0.1:4000" + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + var out api.FactoryAccess + _ = json.Unmarshal(w.Body.Bytes(), &out) + return out, w.Code +} + +func (rg *hostedRig) signIn(t *testing.T, username string) *httptest.ResponseRecorder { + t.Helper() + body, _ := json.Marshal(api.PasswordSignIn{Username: username, Password: pwAbir}) + r := httptest.NewRequest(http.MethodPost, "/v1/auth/password", strings.NewReader(string(body))) + r.RemoteAddr = "127.0.0.1:4000" + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w +} + +// Contract item 2: a link that admits several people loses only the one removed. +func TestRemovingOneJoinerOfAMultiUseLinkLeavesTheOthersAndTheirGrants(t *testing.T) { + rg := newHostedRig(t) + link := rg.anonymousLink(t, 2) + rg.join(t, link, "bob") + rg.join(t, link, "carol") + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "bob", "edit") + hostedGrant(t, rg, "santosh", chat, "carol", "edit") + + rg.remove(t, "bob") + + if people, members := rg.handlesOf(t); slices.Contains(people, "bob") || slices.Contains(members, "bob") || + !slices.Contains(people, "carol") || !slices.Contains(members, "carol") { + t.Errorf("after bob's removal: people %v, members %v; want carol listed and bob not", people, members) + } + if got, want := rg.holders(t, chat), []string{"carol:edit"}; !slices.Equal(got, want) { + t.Errorf("the chat's grants after bob's removal = %v, want %v", got, want) + } + if w := rg.send("carol", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Errorf("carol's read of the chat after bob's removal = %d, want 200", w.Code) + } + // Bob's use stays spent: the link did not reopen for a third person. + if out, _ := rg.signUpAs(t, link, "dave"); out.State != "used_up" { + t.Errorf("a third sign-up through the two-person link says %q, want used_up", out.State) + } +} + +// Contract item 3, on the GitHub door: joining again by a new link brings no old grant back. +func TestARemovedGitHubJoinerDoesNotComeBackWithTheirGrants(t *testing.T) { + rg, g, _, chat := removedGitHubJoiner(t) + + // A new link joins him again, and he holds nothing he held before. + fresh := rg.anonymousLink(t, 1) + rg.tokens["bob"] = signInHandle(t, rg.h, g, &rg.now, "bob", gateOf(t, fresh)) + rg.wantBackWithoutGrants(t, chat) +} + +// Contract item 3, same door: the link they came in by still admits someone it already counted, as it always has, +// and that brings him back into People without any old grant. +func TestARemovedGitHubJoinerUsingTheOldLinkIsBackInPeopleWithoutGrants(t *testing.T) { + rg, g, gate, chat := removedGitHubJoiner(t) + + rg.tokens["bob"] = signInHandle(t, rg.h, g, &rg.now, "bob", gate) + rg.wantBackWithoutGrants(t, chat) +} + +// removedGitHubJoiner joins bob through an anonymous link by GitHub, gives him a grant on santosh's chat, removes him, +// and answers the scene. +func removedGitHubJoiner(t *testing.T) (*hostedRig, *fakeGitHub, string, string) { + t.Helper() + rg := newHostedRig(t) + g := &fakeGitHub{t: t} + rg.h.config.GitHubClientID, rg.h.config.GitHubHTTPClient = "client", g.client() + gate := gateOf(t, rg.anonymousLink(t, 3)) + rg.tokens["bob"] = signInHandle(t, rg.h, g, &rg.now, "bob", gate) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "bob", "edit") + if w := rg.send("bob", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Fatalf("before the removal, bob's read of the chat = %d %s", w.Code, w.Body) + } + rg.remove(t, "bob") + if people, _ := rg.handlesOf(t); slices.Contains(people, "bob") { + t.Fatalf("after the removal, bob is still listed: %v", people) + } + return rg, g, gate, chat +} + +func (rg *hostedRig) wantBackWithoutGrants(t *testing.T, chat string) { + t.Helper() + if people, _ := rg.handlesOf(t); !slices.Contains(people, "bob") { + t.Errorf("after joining again, bob is not listed: %v", people) + } + if held, err := rg.st.GrantsOfSubject("person", "bob"); err != nil || len(held) != 0 { + t.Errorf("joining again brought old grants back: %+v, %v", held, err) + } + if w := rg.send("bob", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Errorf("after joining again, bob's read of the old chat = %d %s, want 404 %q", w.Code, w.Body, hostNoSuchChat) + } +} + +// gateOf is the secret in a link's address, which GitHub sign-in presents as its gate. +func gateOf(t *testing.T, link string) string { + t.Helper() + parsed, err := url.Parse(link) + if err != nil { + t.Fatal(err) + } + fragment, _ := url.ParseQuery(parsed.Fragment) + return fragment.Get("token") +} diff --git a/internal/factory/store/grants.go b/internal/factory/store/grants.go index 37c96e1a5a..3e649e4de3 100644 --- a/internal/factory/store/grants.go +++ b/internal/factory/store/grants.go @@ -217,6 +217,25 @@ func (st *Store) RemoveGrantAtPolicy(id string, rev int) error { return st.removeGrant(id, &rev) } +// RemoveGrantsOfSubject deletes every grant that names one subject, lapsed ones +// included, in one transaction, and answers how many it deleted. It is what +// removing a person from the organization does to what others gave them: a +// grant left behind would apply again to anyone who later joins under the same +// handle. Like RemoveGrant it keeps nothing; the serve layer writes the record. +func (st *Store) RemoveGrantsOfSubject(kind, id string) (int, error) { + removed := 0 + err := st.wsTx(func(tx *sql.Tx) error { + res, err := tx.Exec(`DELETE FROM grants WHERE subject_kind = ? AND subject_id = ?`, kind, id) + if err != nil { + return err + } + n, err := res.RowsAffected() + removed = int(n) + return err + }) + return removed, err +} + // removeGrant deletes the row inside one transaction, first checking the // policy revision when one is given. func (st *Store) removeGrant(id string, rev *int) error { diff --git a/internal/factory/tokens/join_test.go b/internal/factory/tokens/join_test.go index c9ad859571..a323f5b08a 100644 --- a/internal/factory/tokens/join_test.go +++ b/internal/factory/tokens/join_test.go @@ -225,3 +225,78 @@ func TestPlainTokensAndOperatorClaimsAreNotHumanLinks(t *testing.T) { t.Fatalf("second handle on a plain token = %v", err) } } + +// VALIDATION CONTRACT for ending a person's standing on a link (a removed person who joined by an anonymous link was +// left in People, because nothing named them on the row): +// - The row stops counting that person as a member, but their use stays spent: it never reopens for someone else. +// - Nobody else on the row is touched, and a row written before Joiners existed (one person, named only by Profile) +// is ended the same way and survives a save and a load. +// - A person already counted who signs in through the same link again is back in, with nothing spent. +func TestEndingAMemberKeepsTheirUseSpent(t *testing.T) { + path := filepath.Join(t.TempDir(), "tokens.json") + legacy := `{"tokens":[{"access_link":true,"id":"tok_old","token":"s1","joined":"2026-10-02T00:00:00Z","profile":{"handle":"raj"}}]}` + if err := os.WriteFile(path, []byte(legacy), 0o600); err != nil { + t.Fatal(err) + } + rows, err := Load(path) + if err != nil { + t.Fatal(err) + } + if !rows[0].EndMember("RAJ", t0) || rows[0].EndMember("raj", t0) { + t.Fatal("ending a legacy row's one person must change it once, whatever the case of the handle") + } + if err := Save(path, rows); err != nil { + t.Fatal(err) + } + if rows, err = Load(path); err != nil { + t.Fatal(err) + } + got := rows[0].Members() + if len(got) != 1 || got[0].Removed.IsZero() || rows[0].Used() != 1 || rows[0].Remaining() != 0 || rows[0].Reason(t0) != "used_up" { + t.Fatalf("the ended legacy row = %+v (used %d, %s)", got, rows[0].Used(), rows[0].Reason(t0)) + } + + two := humanLink(t, path, 2, nil) + for _, name := range []string{"ann", "ben"} { + if _, err := Join(path, two.ID, who(name), t0); err != nil { + t.Fatal(err) + } + } + if err := Edit(path, func(rows []Token) ([]Token, error) { + for i := range rows { + rows[i].EndMember("ann", t0.Add(time.Hour)) + } + return rows, nil + }); err != nil { + t.Fatal(err) + } + rows, _ = Load(path) + var row Token + for _, r := range rows { + if r.ID == two.ID { + row = r + } + } + members := row.Members() + if len(members) != 2 || members[0].Removed.IsZero() || !members[1].Removed.IsZero() || row.Remaining() != 0 { + t.Fatalf("after ending ann: %+v, remaining %d", members, row.Remaining()) + } + if _, err := Join(path, two.ID, who("cat"), t0.Add(time.Hour)); !errors.Is(err, ErrUsedUp) { + t.Fatalf("the use ann gave up reopened the link: %v", err) + } + + // Ann signs in through the same link again: counted already, so nothing is spent, and she is back in. + if got, err := Join(path, two.ID, who("ann"), t0.Add(2*time.Hour)); err != nil || got.Consumed { + t.Fatalf("returning through the same link = %+v, %v", got, err) + } + rows, _ = Load(path) + for _, r := range rows { + if r.ID == two.ID { + for _, m := range r.Members() { + if !m.Removed.IsZero() { + t.Fatalf("%s is still marked removed after signing in again", m.Profile.Handle) + } + } + } + } +} diff --git a/internal/factory/tokens/tokens.go b/internal/factory/tokens/tokens.go index f405c5499d..3825c03a10 100644 --- a/internal/factory/tokens/tokens.go +++ b/internal/factory/tokens/tokens.go @@ -154,6 +154,31 @@ func Change(path, id string, change func(*Token) error) error { type Joiner struct { Profile Profile `json:"profile"` Joined time.Time `json:"joined"` + // Removed is when the operator removed this person from the organization. + // THE USE STAYS SPENT, so the link never reopens and the handle stays + // reserved, but the person no longer counts as a member. A person already + // counted who signs in through the same link again, as joinHuman has + // always let them, is back in and the mark is cleared. Zero for everyone + // who is still in. + Removed time.Time `json:"removed,omitzero"` +} + +// EndMember marks every use of this row that handle consumed as removed at +// now, and says whether anything changed. A row from before Joiners existed +// names its one person only through Profile, so that person is written down +// first, as joinHuman does before it adds the next. It serves a person who +// joined by an anonymous link, which carries no handle of its own to find. +func (t *Token) EndMember(handle string, now time.Time) bool { + members, ended := t.Members(), false + for i := range members { + if strings.EqualFold(members[i].Profile.Handle, handle) && members[i].Removed.IsZero() { + members[i].Removed, ended = now.UTC(), true + } + } + if ended { + t.Joiners = members + } + return ended } // MaxLinkPeople bounds an up-to-N human link. @@ -510,6 +535,8 @@ func joinHuman(row *Token, profile Profile, now time.Time) (Joined, error) { for k := range row.Joiners { if row.Joiners[k].Profile.Handle == profile.Handle { row.Joiners[k].Profile = profile + // Back in through the same link: removed no longer. + row.Joiners[k].Removed = time.Time{} } } return Joined{}, nil diff --git a/internal/manual/chat/inviting-people.md b/internal/manual/chat/inviting-people.md index 67e2aaeab3..b0dd9109ad 100644 --- a/internal/manual/chat/inviting-people.md +++ b/internal/manual/chat/inviting-people.md @@ -51,6 +51,8 @@ After joining through the link and signing in, a person lands on their organizat In the People table, a joined person's menu has **Remove from …**. Removing someone takes them off the People table, ends their sign-ins and stops their bots, takes them out of every team and every workstream, and gives the workstreams they owned to you. The tasks they owned are **offered to you to hand over**: they arrive in your **Handed to you**, marked as handed over by them, so nothing is left without an owner. +It works the same whichever way the person joined, a named invitation or an anonymous access link: they leave the People table either way, and every share others gave them on a chat or a workstream ends, so joining again later, by a new link or the old one, brings no share back. Their spent use of the link stays spent, so a link that admitted one person does not reopen for someone else. A person who joined by a link that admits several people leaves only themselves; the others stay. + ## Teams — a group you add to a workstream in one step **Teams in ** lists the organization's teams with **New team**. A team is a group of people you can add to a workstream in one step. Inviting someone with a team puts them in it when they join. diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 53228dee02..26c632ade6 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -202,6 +202,18 @@ Only if you shared the chat with a role that holds `run` (the `edit` and `full` If the server cannot be reached, the desktop window says ` is unreachable.` once, with **Try again**, and the chat stays where it is. If your sign-in is missing or has ended it says `Sign in to first.` In neither case does the app start a chat on your computer in its place: a hosted chat never falls back to running locally. A turn that was already running on the server goes on without you, and the conversation is there when the server answers again. +## what tools does a hosted chat have — python, git and curl, but no pip, pytest, go, node, make or a compiler, so my project's tests will not run + +A hosted chat's machine has `python3` (3.11 in the one organization this was checked on), `git`, `curl` and `openssh-client`. It has no `pip`, no `pytest`, no `go`, no `node`, no `make` and no compiler such as `gcc`, and a chat's Linux user is not root, so it cannot install them. A project that needs only the standard library works; one that needs a third-party Python package, a build step or another language's toolchain cannot run its tests there, and in the check the first test project failed at its first import for that reason. The chat can still read, edit and search the code, and use git through the organization's server. + +There is no setting that adds tools. The list is the packages installed in the runtime stage of `deploy/org/codeaf.Dockerfile`, so an operator who wants more builds the organization's own image from that file; that was not tried. If you need to run a project's tests, run them on your own computer in a personal chat, outside the organization's window. + +## do the background jobs count toward the organization's spend and limits — factory jobs call the model provider directly + +No. Hosted chats are metered because they call their model through the organization's server, which counts each call to the cent in My space and stops a chat or a person at their limit. The organization's background jobs do not go that way. The factory's code-writing service, its pull-request review service and the runner that hosts them each call the model provider directly with their own copy of the provider key. Their spend is not in the spend table, in anyone's My space or in any chat's or person's limit, and those limits do not stop them. In one run, a job's own view showed a cost of `0.00027` while the provider billed about $0.56 for it. + +To bound that spend, put a credit limit on the key at the provider, and give those services a key of their own if you want their bill apart from the chats'. Hosted chats are counted exactly as described in *what does a hosted chat cost and who pays*. + ## turn on chats on the server — for the operator Hosted chats are off by default. The operator turns them on by running the chats' machine beside the organization's server, in the organization's deployment (`deploy/org/README.md`, "Hosted chats"), and giving both the same long secret, which `./setup.sh` makes. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index d35b0952d3..b213657dc8 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3988,6 +3988,11 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"can a chat on the organization's server connect to other services on my network", "organization-hosted-sessions"}, {"can a hosted chat reach other machines on my company network", "organization-hosted-sessions"}, {"is there a disk or memory limit for each hosted chat", "organization-hosted-sessions"}, + {"why can't my hosted chat run pytest or pip install", "organization-hosted-sessions"}, + {"what tools does a hosted chat have installed", "organization-hosted-sessions"}, + {"does a factory job count toward the organization's spending limit", "organization-hosted-sessions"}, + {"why is the spend table lower than my openrouter bill", "organization-hosted-sessions"}, + {"what happens to the shares someone holds when I remove them from the organization", "inviting-people"}, {"what happens to a person's chats when I remove them while the chat machine is down", "organization-hosted-sessions"}, {"why does my chat say it is already making as many requests as it may at once", "organization-hosted-sessions"}, {"can a bot with view scope start a hosted chat", "organization-hosted-sessions"}, diff --git a/internal/sessionhost/api.go b/internal/sessionhost/api.go index cc5f2f1c6a..3026be83f5 100644 --- a/internal/sessionhost/api.go +++ b/internal/sessionhost/api.go @@ -13,10 +13,13 @@ import ( "net/http" "net/url" "os" + "path/filepath" "slices" "strings" "sync" "time" + + "golang.org/x/sys/unix" ) type refusal int @@ -413,5 +416,27 @@ func (s *supervisor) deleteSession(row sessionRow) bool { s.registry.sessions[row.ID] = row return false } - return s.removeLayout(row) == nil && s.registry.remove(row.ID, s.now().UTC()) == nil + if s.removeLayout(row) != nil || s.registry.remove(row.ID, s.now().UTC()) != nil { + return false + } + s.removeEmptyPersonFolder(row) + return true +} + +// removeEmptyPersonFolder takes away the folder that held a person's chats once the +// last of them is gone, so removing someone from the organization leaves no trace of +// their name on the volume (found on a production run: an empty p_ folder stayed +// behind). THE EMPTINESS TEST IS THE KERNEL'S: rmdir refuses a folder with anything in +// it, so a person's other chats, and anything this code does not know about, stay put. +// This runs under the supervisor's lock, as does every create, so a chat being made +// for the same person cannot find its parent folder gone halfway through. +func (s *supervisor) removeEmptyPersonFolder(row sessionRow) { + folders, err := layoutFor(s.cfg.Data, row.Person, row.ID) + if err != nil { + return + } + err = unix.Rmdir(filepath.Dir(folders.dir)) + if err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, unix.ENOTEMPTY) && !errors.Is(err, unix.EEXIST) { + s.log.Warn("could not remove a person's empty chat folder", "error", err) + } } diff --git a/internal/sessionhost/lifecycle_test.go b/internal/sessionhost/lifecycle_test.go index eb6ca3c5aa..5747fa4580 100644 --- a/internal/sessionhost/lifecycle_test.go +++ b/internal/sessionhost/lifecycle_test.go @@ -118,3 +118,60 @@ func TestC7_StopClearsTemporaryFilesAndKeepsWork(t *testing.T) { t.Fatal("delete did not quarantine the process identity") } } + +// VALIDATION CONTRACT for what deleting a chat leaves of the person's folder (found on a production run, where +// removing a person left an empty p_ folder behind): +// - Deleting a person's last chat takes the folder that held their chats with it, so their name is not left on the volume. +// - Deleting one of two chats leaves the folder, and the other chat, untouched. +// - A folder with anything else in it is never removed, and the delete still succeeds. +// - Another person's folder is never touched, and a person whose folder went can start a new chat. +func TestDeletingAPersonsLastChatRemovesTheirEmptyFolder(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + createChat(t, s, "alice", chatB) + createChat(t, s, "bob", chatC) + alice, _ := layoutFor(cfg.Data, "alice", chatA) + bob, _ := layoutFor(cfg.Data, "bob", chatC) + aliceFolder, bobFolder := filepath.Dir(alice.dir), filepath.Dir(bob.dir) + + if w := request(s, "DELETE", "/v1/sessions/"+chatA, cfg.Secret, "alice", ""); w.Code != 204 { + t.Fatalf("delete the first chat: %d %s", w.Code, w.Body) + } + if _, err := os.Lstat(aliceFolder); err != nil { + t.Fatalf("deleting one of two chats took the person's folder: %v", err) + } + if _, err := os.Lstat(filepath.Join(aliceFolder, chatB)); err != nil { + t.Fatalf("deleting one of two chats took the other: %v", err) + } + if w := request(s, "DELETE", "/v1/sessions/"+chatB, cfg.Secret, "alice", ""); w.Code != 204 { + t.Fatalf("delete the last chat: %d %s", w.Code, w.Body) + } + if _, err := os.Lstat(aliceFolder); !os.IsNotExist(err) { + t.Errorf("deleting the person's last chat left their folder: %v", err) + } + if _, err := os.Lstat(bobFolder); err != nil { + t.Errorf("another person's folder was touched: %v", err) + } + createChat(t, s, "alice", chatA) + if _, err := os.Lstat(alice.dir); err != nil { + t.Errorf("a person whose folder went could not start a new chat: %v", err) + } +} + +func TestAPersonFolderWithSomethingElseInItIsNotRemoved(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + l, _ := layoutFor(cfg.Data, "alice", chatA) + stray := filepath.Join(filepath.Dir(l.dir), "not-a-chat") + if err := os.WriteFile(stray, []byte("kept"), 0o600); err != nil { + t.Fatal(err) + } + if w := request(s, "DELETE", "/v1/sessions/"+chatA, cfg.Secret, "alice", ""); w.Code != 204 { + t.Fatalf("delete beside a stray file: %d %s", w.Code, w.Body) + } + if data, err := os.ReadFile(stray); err != nil || string(data) != "kept" { + t.Errorf("the folder with a stray file in it was removed: %q, %v", data, err) + } +}