From 431cdc83cba7a58131ccb5a6911e16900f41aaa4 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Mon, 16 Nov 2026 07:52:12 -0800 Subject: [PATCH] fix(container): one WIP branch per run and folder, setup chain records failed, lifetime read as decimal Two folders sharing a remote no longer force-push over each other's triple-c/wip/; the folder is part of the branch name (sanitised, check-ref-format validated, hash fallback). A setup chain that dies with the setup still running records failed so the idle stop is not blocked. TRIPLEC_MAX_LIFETIME_MINUTES 00 means no cap and 08 means 8. The run record is written after the agent-token block. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 36 +++--- app/src-tauri/src/docker/aws_mode_tests.rs | 132 ++++++++++++++++++++- container/entrypoint.sh | 25 +++- container/triple-c-idle-watch | 8 +- container/triple-c-wip-push | 35 ++++-- 5 files changed, 202 insertions(+), 34 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b8eb873..c054d3f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -405,22 +405,28 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li start, and `triple-c-wip-push` skips scratch. Switching EFS → Hybrid/Ephemeral keeps `workspace_access_point_id` (store-owned) until "Remove AWS resources" with discard deletes both access points. On - TERM the hook pushes unsaved work to the run's `triple-c/wip/` branch via a temporary index - (the user's index is untouched; needs the task definition's `stopTimeout` raised, 120 s) unless the - stop marker says the app handled it. **One WIP branch per task run:** `aws_prepare_run` writes - `/run/triple-c/run-id` (`-`, task id from ECS task metadata) and - `start-epoch` at the very start; `/run/triple-c` is root 0711 (the stop guard keeps that mode — at - 0700 `claude` could not read the run id). Later pushes force (`+`) only that branch, and a tree equal - to `/run/triple-c/wip-last/` (claude-owned dir, written after a successful push) is skipped; - no usable run id (Docker) keeps the per-push stamp. **Setup script** (`TRIPLEC_SETUP_SCRIPT`, unset - before the snapshot like `TRIPLEC_FILES`): written to `/run/triple-c-setup/script` (root 0755 dir; - root opens `log` and hands the descriptor over, so claude writes nothing there), run as `claude`, - `bash -e`, stdin `/dev/null`, `timeout -k 10 1800`, chained after the background clone's `done` in - the same background subshell; `status` is `running` from the start until `ok` / `failed `. - `triple-c-workspace-status` (python, no secrets) prints `{clone:{done,repos},setup:{state,code,tail}}`. + TERM the hook pushes unsaved work to the run's `triple-c/wip/-` branch via a + temporary index (the user's index is untouched; needs the task definition's `stopTimeout` raised, + 120 s) unless the stop marker says the app handled it. + **One WIP branch per task run and folder:** `aws_prepare_run` (right after the agent-token block) + writes `/run/triple-c/run-id` (`-`, task id from ECS task metadata) + and `start-epoch`; `/run/triple-c` is root 0711 (the stop guard keeps that mode — at 0700 `claude` + could not read the run id). The folder is sanitised to `[A-Za-z0-9._-]` and the ref checked with + `git check-ref-format`; later pushes force (`+`) only that run's own branch, and a tree equal to + `/run/triple-c/wip-last/` (claude-owned dir, written after a successful push) is skipped. + No usable run id (Docker) keeps a per-push `-`, never forced. + **Setup script** (`TRIPLEC_SETUP_SCRIPT`, unset before the snapshot like `TRIPLEC_FILES`): written + to `/run/triple-c-setup/script` (root 0755 dir; root opens `log` and hands the descriptor over, so + claude writes nothing there), run as `claude`, `bash -e`, stdin `/dev/null`, + `timeout -k 10 1800`, chained after the background clone's `done` in the same background + subshell; `status` is `running` from the start until `ok` / `failed ` (a chain that dies + early writes `failed`, so the idle stop is never blocked). `triple-c-workspace-status` (python, + no secrets) prints `{clone:{done,repos},setup:{state,code,tail}}`. **Lifetime cap** (`TRIPLEC_MAX_LIFETIME_MINUTES`, advisory — sudo can kill it): the idle watcher - (started when idle stop *or* the cap is set) pushes best effort, records `lifetime` and TERMs; the - hook exits 76 (`aws::tasks::LIFETIME_EXIT_CODE` → `StopKind::LifetimeCap` → `lifetime` toast). The idle watcher runs as root under a supervisor and signals the + (started when idle stop *or* a non-zero cap is set) pushes best effort, records `lifetime` and + sends TERM; the hook exits 76 (`aws::tasks::LIFETIME_EXIT_CODE` → `StopKind::LifetimeCap` → + `lifetime` toast). + The idle watcher runs as root under a supervisor and signals the entrypoint's own PID (not PID 1, which is docker-init), so idle and ECS stops share one trap. Idle = the agent's `last_activity_unix` older than N minutes (open-but-silent attaches/tunnels don't count; requests with `X-Triple-C-Background: 1` — the auth bridge's and the file viewer's polls — never do), diff --git a/app/src-tauri/src/docker/aws_mode_tests.rs b/app/src-tauri/src/docker/aws_mode_tests.rs index 2c9ccc2..f51d84f 100644 --- a/app/src-tauri/src/docker/aws_mode_tests.rs +++ b/app/src-tauri/src/docker/aws_mode_tests.rs @@ -667,7 +667,10 @@ fn wip_push_pushes_the_whole_tree_and_leaves_the_repo_as_it_was() { assert_eq!(refs.len(), 1, "{refs:?}"); let name = refs[0].trim_start_matches("refs/heads/triple-c/wip/"); assert!( - name.len() == 15 && name.as_bytes()[8] == b'-' && name.chars().filter(|c| c.is_ascii_digit()).count() == 14, + name.len() == 20 + && name.as_bytes()[8] == b'-' + && name[..15].chars().filter(|c| c.is_ascii_digit()).count() == 14 + && name.ends_with("-proj"), "{name}" ); let r = &refs[0]; @@ -1410,6 +1413,12 @@ fn docker_mode_never_reaches_the_aws_blocks() { assert!( ENTRYPOINT.find("unset TRIPLEC_SETUP_SCRIPT").unwrap() < ENTRYPOINT.find("# >>> agent_token").unwrap() ); + // The run record is made after the agent-token block (its children must + // not inherit TRIPLEC_AGENT_TOKEN) and before anything that can push. + let prepare = ENTRYPOINT.find("then aws_prepare_run; fi").expect("aws_prepare_run call"); + assert!(prepare > ENTRYPOINT.find("# <<< agent_token").unwrap()); + assert!(prepare < ENTRYPOINT.find("trap stop_keepalive TERM INT HUP").unwrap()); + assert!(prepare < ENTRYPOINT.find("\nstart_agent\n").unwrap()); // The setup runs in the clone's background chain, never in the agent's way. assert!(block(ENTRYPOINT, "aws_repos").contains("aws_run_setup")); } @@ -1679,6 +1688,8 @@ fn lifetime_cap_not_reached_keeps_the_workspace_up() { assert_eq!(none.status.code(), Some(2), "{}", text(&none)); let zero = w.lifetime_cmd(target.id(), "0", 30).output().unwrap(); assert_eq!(zero.status.code(), Some(2), "0 is no cap: {}", text(&zero)); + let zeros = w.lifetime_cmd(target.id(), "00", 30).output().unwrap(); + assert_eq!(zeros.status.code(), Some(2), "00 is no cap either: {}", text(&zeros)); } #[test] @@ -1732,7 +1743,7 @@ fn wip_pushes_in_one_run_update_one_branch_and_skip_an_unchanged_tree() { fs::write(repo.join("a.txt"), "one").unwrap(); let out = wip_push_in_run(&ws, Some(run_id)); assert!(out.status.success(), "{}", text(&out)); - let branch = format!("refs/heads/triple-c/wip/{run_id}"); + let branch = format!("refs/heads/triple-c/wip/{run_id}-proj"); assert_eq!(wip_refs(&remote), [branch.clone()]); let first = git(&remote, &["rev-parse", &branch]); assert_eq!(git(&remote, &["show", &format!("{branch}:a.txt")]), "one"); @@ -1783,7 +1794,7 @@ fn wip_push_without_a_usable_run_id_keeps_the_per_push_stamp() { let refs = wip_refs(&remote); assert_eq!(refs.len(), 1, "{refs:?}"); let name = refs[0].trim_start_matches("refs/heads/triple-c/wip/"); - assert!(name.len() == 15 && name.as_bytes()[8] == b'-', "{run_id:?}: {name}"); + assert!(name.len() == 20 && name.as_bytes()[8] == b'-' && name.ends_with("-proj"), "{run_id:?}: {name}"); } } @@ -1857,3 +1868,118 @@ fn workspace_status_reports_clone_and_setup_and_survives_missing_files() { fs::create_dir(setup.join("log")).unwrap(); assert_eq!(workspace_status(&clone, &setup)["setup"]["tail"], serde_json::json!([])); } + +#[test] +fn lifetime_cap_reads_leading_zeros_as_decimal() { + // `08` is 8 minutes, not a bad octal number. + let w = Watch::new(); + let mut target = fake_entrypoint(w.tmp.path()); + let out = run_watch_for(w.lifetime_cmd(target.id(), "08", 8 * 60 + 1), 20).expect("it stops at 8 minutes"); + target.wait().unwrap(); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(w.tmp.path().join("reason")).unwrap().trim(), "lifetime"); + let w = Watch::new(); + let mut target = fake_entrypoint(w.tmp.path()); + let ran = run_watch_for(w.lifetime_cmd(target.id(), "08", 7 * 60), 3); + target.kill().ok(); + target.wait().ok(); + assert!(ran.is_none(), "7 of 8 minutes: {:?}", ran.map(|o| text(&o))); +} + +#[test] +fn a_setup_chain_that_dies_early_records_failed_so_the_idle_stop_is_not_blocked() { + // The chain ends abnormally while the status still says `running`. + let tmp = tempfile::tempdir().unwrap(); + let blocks = aws_run_blocks(tmp.path(), &["aws_env", "aws_run", "aws_repos"]); + let script = format!( + "{blocks}\n\ + aws_run_setup() {{ exit 9; }}\n\ + triplec_setup_script='echo hi'\n\ + aws_prepare_run\n\ + start_clone_repos '[]' \"$STATUS\"\n\ + wait\n" + ); + let out = bash(&script, &[], &[("STATUS", tmp.path().join("clone").to_str().unwrap())], &[]); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(tmp.path().join("setup/status")).unwrap(), "failed\n"); + + // Killed (TERM) while the clone is still running: `done` and `failed`. + let tmp = tempfile::tempdir().unwrap(); + let blocks = aws_run_blocks(tmp.path(), &["aws_env", "aws_run", "aws_repos"]); + let pid = tmp.path().join("inner.pid"); + let script = format!( + "{blocks}\n\ + clone_repos() {{ sleep 30 >/dev/null 2>&1 & s=$!; echo \"$BASHPID $s\" > '{p}'; wait $s; }}\n\ + triplec_setup_script='echo hi'\n\ + aws_prepare_run\n\ + start_clone_repos '[]' \"$STATUS\"\n\ + chain=$!\n\ + while [ ! -s '{p}' ]; do sleep 0.1; done\n\ + kill -TERM \"$chain\" $(cat '{p}')\n\ + wait\n", + p = pid.display() + ); + let started = std::time::Instant::now(); + let out = bash(&script, &[], &[("STATUS", tmp.path().join("clone").to_str().unwrap())], &[]); + assert!(out.status.success(), "{}", text(&out)); + assert!(started.elapsed() < std::time::Duration::from_secs(20)); + assert!(tmp.path().join("clone/done").exists()); + assert_eq!(fs::read_to_string(tmp.path().join("setup/status")).unwrap(), "failed\n"); + // A finished setup's status is left alone by the trap. + let tmp = tempfile::tempdir().unwrap(); + let out = run_setup(tmp.path(), "true\n", "1800"); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(tmp.path().join("setup/status")).unwrap(), "ok\n"); +} + +#[test] +fn each_folder_in_a_run_has_its_own_wip_branch_even_on_one_remote() { + let tmp = tempfile::tempdir().unwrap(); + let (ws, api, remote) = workspace_with_clone(tmp.path()); + // A second clone of the same bare remote, under a folder name git refs + // cannot carry as is. + git(&ws, &["clone", "-q", remote.to_str().unwrap(), "we b@x"]); + let web = ws.join("we b@x"); + git(&web, &["config", "user.name", "Dev"]); + git(&web, &["config", "user.email", "dev@example.invalid"]); + let run_id = "20261115-093000-0123abcd"; + fs::write(api.join("a.txt"), "api-1").unwrap(); + fs::write(web.join("a.txt"), "web-1").unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + let api_ref = format!("refs/heads/triple-c/wip/{run_id}-proj"); + let web_ref = format!("refs/heads/triple-c/wip/{run_id}-we_b_x"); + let mut refs = wip_refs(&remote); + refs.sort(); + assert_eq!(refs, [api_ref.clone(), web_ref.clone()]); + assert_eq!(git(&remote, &["show", &format!("{api_ref}:a.txt")]), "api-1"); + assert_eq!(git(&remote, &["show", &format!("{web_ref}:a.txt")]), "web-1"); + let web_first = git(&remote, &["rev-parse", &web_ref]); + + // A second push changes only api: its branch moves, web's is skipped. + fs::write(api.join("a.txt"), "api-2").unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + assert!(text(&out).contains("we b@x: unchanged since the last push"), "{}", text(&out)); + assert_eq!(git(&remote, &["show", &format!("{api_ref}:a.txt")]), "api-2"); + assert_eq!(git(&remote, &["rev-parse", &web_ref]), web_first); + assert_eq!(wip_refs(&remote).len(), 2); +} + +#[test] +fn a_folder_name_no_ref_can_carry_falls_back_to_a_hash() { + let tmp = tempfile::tempdir().unwrap(); + let (ws, _, remote) = workspace_with_clone(tmp.path()); + git(&ws, &["clone", "-q", remote.to_str().unwrap(), "a..b.lock"]); + let repo = ws.join("a..b.lock"); + git(&repo, &["config", "user.name", "Dev"]); + git(&repo, &["config", "user.email", "dev@example.invalid"]); + fs::write(repo.join("x"), "x").unwrap(); + let run_id = "20261115-093000-local"; + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + let refs = wip_refs(&remote); + assert_eq!(refs.len(), 1, "{refs:?}"); + let suffix = refs[0].strip_prefix(&format!("refs/heads/triple-c/wip/{run_id}-")).unwrap(); + assert!(suffix.len() == 12 && suffix.chars().all(|c| c.is_ascii_hexdigit()), "{suffix}"); +} diff --git a/container/entrypoint.sh b/container/entrypoint.sh index 299e2fc..7182bf3 100644 --- a/container/entrypoint.sh +++ b/container/entrypoint.sh @@ -122,15 +122,16 @@ fi # <<< aws_env # ── AWS: this run's record, and the setup script's files ─────────────────── -# aws_prepare_run, as root at the very start of an AWS task: +# aws_prepare_run, as root at the start of an AWS task (just after the +# agent-token block): # /run/triple-c root, 0711 — users may open a file they know the # name of, never list it (the stop marker in it is # 0600; the stop guard and the idle watcher keep the # mode); # /run/triple-c/run-id `-` (task id # from the ECS task metadata, else `local`), 0644 — -# triple-c-wip-push names this run's one WIP branch -# after it (triple-c/wip/); +# triple-c-wip-push names this run's WIP branches +# after it (triple-c/wip/-); # /run/triple-c/start-epoch the start in Unix seconds, for the idle watcher's # lifetime cap (TRIPLEC_MAX_LIFETIME_MINUTES); # /run/triple-c/wip-last 0700, owned by `claude`: triple-c-wip-push (run as @@ -198,6 +199,13 @@ aws_prepare_run() { triplec_setup_script= } +# The setup chain ended without a verdict: record a failure (no code). +aws_setup_abandoned() { + [ "$(head -n 1 "$triplec_setup_dir/status" 2>/dev/null)" = running ] || return 0 + printf 'failed\n' > "$triplec_setup_dir/status.tmp" && mv -f "$triplec_setup_dir/status.tmp" "$triplec_setup_dir/status" + echo "entrypoint: the setup script did not finish — recorded as failed" +} + # Runs the setup script, if there is one (see above). Never fails. aws_run_setup() { local dir="$triplec_setup_dir" rc state @@ -214,7 +222,6 @@ aws_run_setup() { return 0 } # <<< aws_run -if [ "$triplec_aws" = 1 ]; then aws_prepare_run; fi # ── triple-c-agent token: off the environment before anything else runs ─── # The agent (started at the very end, see start_agent) authenticates every @@ -259,6 +266,9 @@ if [ -n "${TRIPLEC_AGENT_TOKEN_FILE:-}" ]; then mapfile -d '' agent_env < <(env -u PWD -u OLDPWD -u SHLVL -u _ -0) fi # <<< agent_token +# After the token block, so nothing aws_prepare_run starts (the metadata curl) +# inherits TRIPLEC_AGENT_TOKEN; before anything that can push. +if [ "$triplec_aws" = 1 ]; then aws_prepare_run; fi # ── UID/GID remapping ────────────────────────────────────────────────────── # Match the container's claude user to the host user's UID/GID so that @@ -879,6 +889,11 @@ start_clone_repos() { mkdir -m 755 "$status_dir" || status_dir="" ( trap '' HUP + # Should this chain end early (an error, a signal) with the setup + # still marked `running`, say `failed`: the idle watcher counts a + # running setup as busy and would otherwise never stop the workspace. + trap 'aws_setup_abandoned' EXIT + trap 'exit 143' TERM ( # `done` however the clone ends (an error, a signal), or the idle # watcher would count it as still running forever. @@ -1425,7 +1440,7 @@ stop_keepalive() { exit "${triplec_exit_status:-0}" } trap stop_keepalive TERM INT HUP -if [ "$triplec_aws" = 1 ] && { [ -n "${TRIPLEC_IDLE_STOP_MINUTES:-}" ] || [ "${TRIPLEC_MAX_LIFETIME_MINUTES:-0}" != 0 ]; }; then +if [ "$triplec_aws" = 1 ] && { [ -n "${TRIPLEC_IDLE_STOP_MINUTES:-}" ] || [ -n "${TRIPLEC_MAX_LIFETIME_MINUTES//0/}" ]; }; then start_idle_watch "${TRIPLEC_IDLE_STOP_MINUTES:-}" "$$" fi # Repos are cloned in the background from here on — see clone_repos — and the diff --git a/container/triple-c-idle-watch b/container/triple-c-idle-watch index 22e7037..bc6f13d 100755 --- a/container/triple-c-idle-watch +++ b/container/triple-c-idle-watch @@ -192,11 +192,15 @@ check() { case "$minutes" in '') ;; - *[!0-9]*|0) echo "triple-c-idle-watch: TRIPLEC_IDLE_STOP_MINUTES must be a positive integer" >&2; exit 2 ;; + *[!0-9]*) echo "triple-c-idle-watch: TRIPLEC_IDLE_STOP_MINUTES must be a positive integer" >&2; exit 2 ;; + *) minutes=$((10#$minutes)) + [ "$minutes" -gt 0 ] || { echo "triple-c-idle-watch: TRIPLEC_IDLE_STOP_MINUTES must be a positive integer" >&2; exit 2; } ;; esac case "$lifetime" in - ''|0) lifetime="" ;; + '') ;; *[!0-9]*) echo "triple-c-idle-watch: TRIPLEC_MAX_LIFETIME_MINUTES must be a whole number of minutes" >&2; exit 2 ;; + # Decimal even with leading zeros (`08` is 8); 0, 00, … mean no cap. + *) lifetime=$((10#$lifetime)); [ "$lifetime" -gt 0 ] || lifetime="" ;; esac if [ "${1:-}" = "--check" ]; then diff --git a/container/triple-c-wip-push b/container/triple-c-wip-push index 2c80dc2..d8e8bb4 100755 --- a/container/triple-c-wip-push +++ b/container/triple-c-wip-push @@ -5,18 +5,23 @@ # directly under /workspace whose working tree is dirty or which holds commits # no remote has, push a snapshot of the *whole* working tree (tracked changes, # staged or not, and untracked files .gitignore does not exclude) to -# refs/heads/triple-c/wip/ on the repo's remote. +# refs/heads/triple-c/wip/- on the repo's remote. # -# One branch per task run (phase 6, Q9): is the entrypoint's -# /run/triple-c/run-id, `-`. +# One branch per task run and folder (phase 6, Q9; ruling R4 — two folders +# can share a remote, so the folder is part of the name): is the +# entrypoint's /run/triple-c/run-id, `-`; is the folder name with everything outside +# [A-Za-z0-9._-] made `_`, cut to 64 characters, or — when the ref still is +# not valid (`git check-ref-format`: `..`, a `.lock` end, …) — the first 12 +# hex digits of the folder name's SHA-256. # Later pushes in the same run move that branch (a forced push — the branch is # Triple-C's alone, and each WIP commit sits on the user's HEAD, not on the # last WIP commit), and a push whose tree equals the one last pushed for that # folder in this run is skipped: the tree is recorded after each successful # push in /run/triple-c/wip-last/ (made for `claude` by the # entrypoint). Without a usable run id (Docker, or a run that recorded none) -# every push gets its own refs/heads/triple-c/wip/, never -# forced. +# every push gets its own refs/heads/triple-c/wip/-, +# never forced. # # It never touches the user's index, HEAD, branches or working tree: the # snapshot is built in a temporary index (GIT_INDEX_FILE) seeded from a copy of @@ -74,17 +79,28 @@ shopt -s dotglob nullglob stamp=$(date -u +%Y%m%d-%H%M%S) failed=0 -# This run's branch, when the entrypoint recorded a well-formed run id; the -# per-push stamp otherwise. Only our own per-run branch is ever force-pushed. +# This run's id, when the entrypoint recorded a well-formed one; the per-push +# stamp otherwise. Only our own per-run branches are ever force-pushed. run_id=$(head -n 1 "$run_id_file" 2>/dev/null) if [[ "$run_id" =~ ^[0-9]{8}-[0-9]{6}-[A-Za-z0-9]{1,32}$ ]]; then - ref="refs/heads/triple-c/wip/$run_id" + ref_base="refs/heads/triple-c/wip/$run_id" force=+ else - ref="refs/heads/triple-c/wip/$stamp" + ref_base="refs/heads/triple-c/wip/$stamp" force= fi +# The WIP ref for folder $1: -, or -. +wip_ref() { + local safe r + safe=$(printf '%s' "$1" | LC_ALL=C tr -c 'A-Za-z0-9._-' '_' | cut -c 1-64) + r="$ref_base-$safe" + if [ -z "$safe" ] || ! git check-ref-format "$r"; then + r="$ref_base-$(printf '%s' "$1" | sha256sum | cut -c 1-12)" + fi + printf '%s' "$r" +} + # The remote to push to: the branch's upstream remote, else origin, else the # only remote. Empty when there is none. pick_remote() { @@ -198,6 +214,7 @@ for dir in "$root"/*/; do exit 0 fi + ref=$(wip_ref "$folder") if [ "$dirty" = true ]; then msg="Triple-C WIP ($reason) of $branch at $stamp UTC" if [ -n "$head" ]; then