diff --git a/.github/workflows/review.yml b/.github/workflows/review.yml index 11620af..6789682 100644 --- a/.github/workflows/review.yml +++ b/.github/workflows/review.yml @@ -19,6 +19,10 @@ on: description: Codex session this run continues; one per PR, or per branch for pushes, by default. type: string default: "" + session-ref-prefix: + description: Store session snapshots under `refs//` instead of Actions artifacts; empty keeps artifacts, for example `agent-sessions`. + type: string + default: "" broker: description: Service that exchanges the job's OIDC token for an installation token of the App and relays webhooks. type: string @@ -94,6 +98,7 @@ jobs: codex-auth: ${{ secrets.codex-auth }} service-tier: ${{ inputs.service-tier }} session-key: ${{ inputs.session-key }} + session-ref-prefix: ${{ inputs.session-ref-prefix }} broker: ${{ inputs.broker }} encrypt-snapshots: ${{ inputs.encrypt-snapshots }} shared-uv-cache: ${{ inputs.shared-uv-cache }} diff --git a/README.md b/README.md index e976c67..47058d5 100644 --- a/README.md +++ b/README.md @@ -105,13 +105,15 @@ Each run seeds the webhook that started it into its event stream in the same sha - Completed checks on the reviewed head wake a review that waits for CI; the review's own check runs and suites never do. - The review decides when a pull request is safe to merge, using CI results it trusts and running the checks that matter when CI is missing or flaky. It leaves work that is still moving, such as recent pushes or an open draft, to the author. The action merges only when the verdict says so and the head has not moved since. -The tool and stop hooks record consumed context locally. The action checkpoints these receipts with the review session after publishing the checks, PR review and reactions successfully. Session snapshots are Actions artifacts shared across trigger refs. When no artifact exists, the action can resume from a legacy cache visible to the trigger. Queued runs fetch the current PR head and skip consumed activity only when that head also has a saved publication checkpoint. Receiving an event alone never marks it consumed, and a forked review starts its own checkpoint. Receipt deduplication is independent of the transport: the action neither saves a replay cursor nor sends `Last-Event-ID`. +The tool and stop hooks record consumed context locally. The action checkpoints these receipts with the review session after publishing the checks, PR review and reactions successfully. Session snapshots are Actions artifacts shared across trigger refs, or custom git refs when `session-ref-prefix` is set (see below). When no artifact exists, the action can resume from a legacy cache visible to the trigger. Queued runs fetch the current PR head and skip consumed activity only when that head also has a saved publication checkpoint. Receiving an event alone never marks it consumed, and a forked review starts its own checkpoint. Receipt deduplication is independent of the transport: the action neither saves a replay cursor nor sends `Last-Event-ID`. -New session snapshots expire after 1 day by default. When using the reusable workflow, set the repository Actions variable `REVIEW_SESSION_RETENTION_DAYS` to a positive whole number of days to keep them longer. Direct action callers can set `session-retention-days`. GitHub caps the requested retention at the repository limit. Invalid values warn and fall back to 1 day. +New session artifacts expire after 1 day by default. When using the reusable workflow, set the repository Actions variable `REVIEW_SESSION_RETENTION_DAYS` to a positive whole number of days to keep them longer. Direct action callers can set `session-retention-days`. GitHub caps the requested retention at the repository limit. Invalid values warn and fall back to 1 day. + +In a private repository, setting `session-ref-prefix` (for example `agent-sessions`) moves session snapshots from Actions artifacts to custom git refs at `refs/agent-sessions/`. Each changed snapshot appends a commit that contains the complete session as raw files: rollouts are split into 16 MiB chunks with a manifest of paths, sizes and SHA-256 digests, and the next run reassembles and verifies them before Codex resumes. Nothing is pruned, so earlier tool output stays available to search on later runs. Restore reads the ref at depth 1; when the ref is absent the action falls back to an artifact, then the legacy cache. These are not branches: pushing a custom ref does not trigger `push` workflows, but anyone with read access to the repository can fetch it. Git must resolve both fetch and push to the checked repository’s HTTPS URL. The action checks repository visibility before restoring and again before saving; this cannot protect snapshots already pushed if you later make the repository public. Do not make a repository containing these snapshots public. `encrypt-snapshots` is not supported in this mode yet, and `session-retention-days` applies only to artifact snapshots. Ref history grows with every save; changing the prefix starts a new namespace while leaving the old refs untouched. Removing the input switches back to artifact storage. The next run restores the latest available artifact or legacy cache, and starts fresh if both have expired. Progress saved only in the ref stays there. To shorten retention for `agent-debug-events`, set the repository Actions variable `REVIEW_DEBUG_RETENTION_DAYS` to a positive whole number of days (for example, `7`). Direct action callers can set the `debug-retention-days` input. An invalid value skips the debug upload. -Session saves clear reasoning bodies from superseded context windows in an archive-only copy. Every saved thread keeps its required compaction checkpoint, guardian state and later records, including parent history still needed by an earlier fork. The cleanup keeps record identities, byte offsets and ordinals intact by replacing removed bodies with JSON whitespace; compressed artifacts shrink while uncompressed file lengths stay the same. Histories without a proven boundary stay intact. Old reasoning is no longer available for rewind or transcript inspection after restoring a cleaned snapshot. The running session and separately archived debug events are unchanged. +Artifact saves clear reasoning bodies from superseded context windows in an archive-only copy. Every saved thread keeps its required compaction checkpoint, guardian state and later records, including parent history still needed by an earlier fork. The cleanup keeps record identities, byte offsets and ordinals intact by replacing removed bodies with JSON whitespace; compressed artifacts shrink while uncompressed file lengths stay the same. Histories without a proven boundary stay intact. Old reasoning is no longer available for rewind or transcript inspection after restoring a cleaned snapshot. The running session and separately archived debug events are unchanged. Anyone with read access to the repository can download its session and debug artifacts, which contain Codex conversations and tool output. Set `encrypt-snapshots` to have the action encrypt each artifact with AES-256-GCM; it is off by default, and needs a broker that serves `/snapshot-key`. The key comes from the broker, which derives it from the repository's numeric ID and its own secret: renaming the repository, reinstalling the App, or switching the provider or the model leaves older snapshots readable, while another repository's key cannot open them. If the current session fails authentication, the run stops before extraction. Restore the original key or delete the unreadable snapshot to resume reviews. A child review can start fresh if it cannot restore the parent session. Snapshots saved before encryption restore as they were, and the next save of that session replaces the plaintext one, which pruning then removes like any older snapshot; archives under the pre-rename `code-review-session-*` name remain downloadable until retention expires. To remove one sooner, delete the plaintext artifact from its workflow run after verifying the replacement. Restores follow the archive's own marker rather than the input, so turning `encrypt-snapshots` off stops new encryption without stranding what an earlier run encrypted. [GitHub artifact access](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/download-workflow-artifacts) diff --git a/action.yml b/action.yml index 57562af..58af16b 100644 --- a/action.yml +++ b/action.yml @@ -35,6 +35,9 @@ inputs: default: "1" session-key: description: Codex session this review continues; one per PR, or per branch for pushes, by default. + session-ref-prefix: + description: Store session snapshots under `refs//` in this repository instead of Actions artifacts. Empty keeps artifacts; for example `agent-sessions`. The ref namespace is configurable through this prefix. + default: "" service-tier: description: Provider service tier for reviews, such as `ultrafast` where the model advertises it; `default` or empty sends none. setup: @@ -84,6 +87,21 @@ runs: done ) >> "$RUNNER_TEMP/token.err" 2>&1 & echo "TOKEN_PID=$!" >> "$GITHUB_ENV" + - name: Validate the session storage mode + if: steps.app-token.outputs.skip != 'true' && inputs.session-ref-prefix != '' + shell: bash + env: + ENCRYPT_SNAPSHOTS: ${{ inputs.encrypt-snapshots }} + GH_CONFIG_DIR: ${{ runner.temp }}/gh + run: | + encryption=$(printf '%s' "$ENCRYPT_SNAPSHOTS" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]') + case "$encryption" in + true) echo "::error::encrypt-snapshots is not supported with session-ref-prefix yet"; exit 1 ;; + false) ;; + *) echo "::error::encrypt-snapshots must be true or false"; exit 1 ;; + esac + bash "$GITHUB_ACTION_PATH/scripts/require-private-session-repo.sh" + - name: Resolve the review target if: steps.app-token.outputs.skip != 'true' shell: bash @@ -177,9 +195,32 @@ runs: with: bun-version: ${{ inputs.bun-version }} + - name: Find the session snapshot ref + id: ref-snapshot + if: steps.app-token.outputs.skip != 'true' && (inputs.session-ref-prefix != '' && env.SKIP != 'true') + shell: bash + env: + SESSION_REF_PREFIX: ${{ inputs.session-ref-prefix }} + SESSION_REF_REMOTE: '' + SESSION_REF_TOKEN: '' + GH_CONFIG_DIR: ${{ runner.temp }}/gh + run: bash "$GITHUB_ACTION_PATH/scripts/session-ref.sh" find "$SESSION_KEY" + + - name: Restore the session snapshot from its ref + id: restore-session-ref + if: steps.app-token.outputs.skip != 'true' && (steps.ref-snapshot.outputs.commit) + shell: bash + env: + SESSION_REF_PREFIX: ${{ inputs.session-ref-prefix }} + SESSION_REF_REMOTE: '' + SESSION_REF_TOKEN: '' + GH_CONFIG_DIR: ${{ runner.temp }}/gh + run: bash "$GITHUB_ACTION_PATH/scripts/session-ref.sh" restore "$SESSION_KEY" "$CODEX_HOME" + - name: Find codex session snapshot id: snapshot - if: steps.app-token.outputs.skip != 'true' && (env.SKIP != 'true') + # When the ref is absent, fall back to a snapshot saved before this storage moved out of artifacts. + if: steps.app-token.outputs.skip != 'true' && (env.SKIP != 'true' && (!steps.ref-snapshot.outputs.commit && (inputs.session-ref-prefix == '' || steps.ref-snapshot.outcome == 'success'))) shell: bash env: GH_TOKEN: ${{ github.token }} @@ -344,9 +385,47 @@ runs: bash "$GITHUB_ACTION_PATH/scripts/subscribe.sh" >> "$RUNNER_TEMP/sse.err" 2>&1 & echo "SSE_PID=$!" >> "$GITHUB_ENV" + - name: Find the session to fork in refs + id: fork-ref-snapshot + if: steps.app-token.outputs.skip != 'true' && (inputs.session-ref-prefix != '' && steps.check.outputs.fork-key && !steps.snapshot.outputs.id && !steps.ref-snapshot.outputs.commit && !steps.session-cache.outputs.cache-matched-key && env.SKIP != 'true') + shell: bash + env: + SESSION_REF_PREFIX: ${{ inputs.session-ref-prefix }} + SESSION_REF_REMOTE: '' + SESSION_REF_TOKEN: '' + GH_CONFIG_DIR: ${{ runner.temp }}/gh + FORK_KEY: ${{ steps.check.outputs.fork-key }} + run: bash "$GITHUB_ACTION_PATH/scripts/session-ref.sh" find "$FORK_KEY" + + - name: Restore the session to fork from its ref + id: restore-fork-ref + if: steps.app-token.outputs.skip != 'true' && (steps.fork-ref-snapshot.outputs.commit) + continue-on-error: true + shell: bash + env: + SESSION_REF_PREFIX: ${{ inputs.session-ref-prefix }} + SESSION_REF_REMOTE: '' + SESSION_REF_TOKEN: '' + GH_CONFIG_DIR: ${{ runner.temp }}/gh + FORK_KEY: ${{ steps.check.outputs.fork-key }} + run: bash "$GITHUB_ACTION_PATH/scripts/session-ref.sh" restore "$FORK_KEY" "$CODEX_HOME/fork" + + - name: Verify the session to fork from its ref + id: verify-fork-ref + if: steps.app-token.outputs.skip != 'true' && (steps.restore-fork-ref.outcome == 'success') + shell: bash + run: | + if [ -d "$CODEX_HOME/fork/sessions" ] && [ -s "$CODEX_HOME/fork/last-thread-id" ]; then + echo "restored=true" >> "$GITHUB_OUTPUT" + else + rm -rf "$CODEX_HOME/fork" + echo "::warning::Could not restore the session to fork. This review starts without it." + fi + - name: Find the session to fork id: fork-snapshot - if: steps.app-token.outputs.skip != 'true' && (steps.check.outputs.fork-key && !steps.snapshot.outputs.id && !steps.session-cache.outputs.cache-matched-key && env.SKIP != 'true') + # When the fork's ref is absent, fall back to a snapshot saved before this storage moved out of artifacts. + if: steps.app-token.outputs.skip != 'true' && (steps.check.outputs.fork-key && !steps.snapshot.outputs.id && !steps.session-cache.outputs.cache-matched-key && !steps.fork-ref-snapshot.outputs.commit && (inputs.session-ref-prefix == '' || steps.fork-ref-snapshot.outcome == 'success') && env.SKIP != 'true') shell: bash env: GH_TOKEN: ${{ github.token }} @@ -524,7 +603,7 @@ runs: # Only the optional CI-name lookup uses this token; the reviewer keeps the App identity. REVIEW_ACTIONS_TOKEN: ${{ github.token }} # Without the empty-string fallback, a failed restore check sets FORK_KEY to "false", which run-review.sh treats as a session key. - FORK_KEY: ${{ ((steps.decrypt-fork.outputs.restored == 'true' || steps.verify-fork.outputs.restored == 'true') && steps.check.outputs.fork-key) || '' }} + FORK_KEY: ${{ ((steps.decrypt-fork.outputs.restored == 'true' || steps.verify-fork.outputs.restored == 'true' || steps.verify-fork-ref.outputs.restored == 'true') && steps.check.outputs.fork-key) || '' }} JOB_CHECK_RUN_ID: ${{ job.check_run_id }} TRIGGER_SENDER: ${{ github.event.sender.login || 'unknown' }} TRIGGER_TYPE: ${{ github.event.sender.type || 'unknown' }} @@ -585,7 +664,7 @@ runs: - name: Archive codex session id: encrypt-session - if: steps.app-token.outputs.skip != 'true' && (env.SKIP != 'true' || env.RECORDED_SKIP == 'true') + if: steps.app-token.outputs.skip != 'true' && (inputs.session-ref-prefix == '' && (env.SKIP != 'true' || env.RECORDED_SKIP == 'true')) # Losing the key must not fail a review that is already published; the older snapshot stays restore-able. continue-on-error: true shell: bash @@ -603,9 +682,25 @@ runs: bash "$GITHUB_ACTION_PATH/scripts/snapshot.sh" save "$RUNNER_TEMP/snapshot.bin" "$CODEX_HOME" printf 'retention-days=%s\n' "$retention_days" >> "$GITHUB_OUTPUT" + - name: Save the session snapshot to its ref + id: save-session-ref + if: steps.app-token.outputs.skip != 'true' && (inputs.session-ref-prefix != '' && (env.SKIP != 'true' || env.RECORDED_SKIP == 'true')) + # An append failure must not discard a completed review. + continue-on-error: true + shell: bash + env: + SESSION_REF_PREFIX: ${{ inputs.session-ref-prefix }} + SESSION_REF_REMOTE: '' + SESSION_REF_TOKEN: '' + SESSION_REF_BASE: ${{ steps.restore-session-ref.outputs.commit }} + GH_CONFIG_DIR: ${{ runner.temp }}/gh + run: | + bash "$GITHUB_ACTION_PATH/scripts/require-private-session-repo.sh" && + bash "$GITHUB_ACTION_PATH/scripts/session-ref.sh" save "$SESSION_KEY" + - name: Save codex session id: save-session - if: steps.app-token.outputs.skip != 'true' && (steps.encrypt-session.outcome == 'success') + if: steps.app-token.outputs.skip != 'true' && (inputs.session-ref-prefix == '' && steps.encrypt-session.outcome == 'success') # An upload failure must not discard a completed review. continue-on-error: true uses: actions/upload-artifact@v7 @@ -618,7 +713,7 @@ runs: retention-days: ${{ steps.encrypt-session.outputs.retention-days }} - name: Drop older session snapshots - if: steps.app-token.outputs.skip != 'true' && (steps.save-session.outputs.artifact-id) + if: steps.app-token.outputs.skip != 'true' && (inputs.session-ref-prefix == '' && steps.save-session.outputs.artifact-id) continue-on-error: true shell: bash env: @@ -640,6 +735,7 @@ runs: env: GH_CONFIG_DIR: ${{ runner.temp }}/gh SNAPSHOT_ID: ${{ steps.save-session.outputs.artifact-id }} + SAVED_REF: ${{ steps.save-session-ref.outputs.commit }} run: | [ -n "$CODEX_HOME" ] || exit 0 opened=$(if [ -f "$RUNNER_TEMP/forked-prs" ]; then cat "$RUNNER_TEMP/forked-prs"; fi) || exit 1 @@ -649,7 +745,10 @@ runs: # A draft this run opened can only fork the session it was written into; drafts an earlier run left pending were already waiting after a save. if [ -n "$(printf '%s' "$opened" | sed '/^$/d')" ]; then listed=false - [ -z "$SNAPSHOT_ID" ] || listed=$(GH_TOKEN=${{ github.token }} bash "$GITHUB_ACTION_PATH/scripts/retry.sh" gh api "repos/${{ github.repository }}/actions/artifacts/$SNAPSHOT_ID" --jq '.expired == false' { const setup = fixture(), decrypt = step("Extract the session to fork"); const output = join(setup.dir, "github-output"), fork = join(setup.dir, "fork"); const key = step("Run codex review").env.FORK_KEY; - expect(key).toBe(`\${{ ((steps.${decrypt.id}.outputs.restored == 'true' || steps.verify-fork.outputs.restored == 'true') && steps.check.outputs.fork-key) || '' }}`); + expect(key).toBe(`\${{ ((steps.${decrypt.id}.outputs.restored == 'true' || steps.verify-fork.outputs.restored == 'true' || steps.verify-fork-ref.outputs.restored == 'true') && steps.check.outputs.fork-key) || '' }}`); writeFileSync(output, ""); mkdirSync(fork); writeFileSync(join(fork, "snapshot.bin"), "unreadable archive"); diff --git a/scripts/require-private-session-repo.sh b/scripts/require-private-session-repo.sh new file mode 100644 index 0000000..0a92645 --- /dev/null +++ b/scripts/require-private-session-repo.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail + +# A custom ref is not an access-control boundary. Use the refreshed App credential. +if ! visibility=$(GH_TOKEN= GITHUB_TOKEN= gh api --hostname github.com "repos/${GITHUB_REPOSITORY:?}" --jq '.visibility') || [ "$visibility" != private ]; then + echo "::error::session-ref-prefix requires a verified private repository because snapshots are unencrypted." >&2 + exit 1 +fi diff --git a/scripts/session-ref-visibility.test.ts b/scripts/session-ref-visibility.test.ts new file mode 100644 index 0000000..4b3585e --- /dev/null +++ b/scripts/session-ref-visibility.test.ts @@ -0,0 +1,32 @@ +import { expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +test("session refs require verified private visibility and the refreshed App credential", () => { + const root = mkdtempSync(join(tmpdir(), "session-ref-visibility-")); + try { + writeFileSync(join(root, "gh"), [ + "#!/usr/bin/env bash", + '[[ "$*" == "api --hostname github.com repos/test/repo --jq .visibility" ]] || exit 99', + '[[ -z "$GH_TOKEN" && -z "$GITHUB_TOKEN" ]] || exit 99', + 'printf "%s\\n" "$VISIBILITY"', + 'exit "$API_EXIT"', + "", + ].join("\n"), { mode: 0o700 }); + for (const [visibility, apiExit, expected] of [ + ["private", "0", 0], ["public", "0", 1], ["internal", "0", 1], ["", "0", 1], ["private", "1", 1], + ] as const) { + const result = spawnSync("bash", [join(import.meta.dir, "require-private-session-repo.sh")], { + env: { ...process.env, PATH: `${root}:${process.env.PATH}`, GITHUB_REPOSITORY: "test/repo", + GH_TOKEN: "ignored", GITHUB_TOKEN: "ignored", VISIBILITY: visibility, API_EXIT: apiExit }, + encoding: "utf8", + }); + expect(result.status).toBe(expected); + if (expected) expect(result.stderr).toContain("requires a verified private repository"); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/session-ref.sh b/scripts/session-ref.sh new file mode 100755 index 0000000..a30243a --- /dev/null +++ b/scripts/session-ref.sh @@ -0,0 +1,236 @@ +#!/usr/bin/env bash +# Store session snapshots under refs// so they never consume Actions artifact storage. +# Each changed snapshot appends a commit containing the complete session. +# Usage: session-ref.sh find | restore | save +set -euo pipefail + +: "${SESSION_REF_PREFIX:?Set session-ref-prefix to the ref namespace, for example agent-sessions}" +: "${MODEL_NAME:?MODEL_NAME is required to key a session ref}" +case "$SESSION_REF_PREFIX" in + refs|refs/*|heads|heads/*|tags|tags/*|*'{'*|*'}'*) + echo "::error::session-ref-prefix must be a plain ref namespace such as agent-sessions" >&2; exit 1 ;; +esac +git check-ref-format "refs/$SESSION_REF_PREFIX/snapshot" || { echo "::error::Invalid session-ref-prefix" >&2; exit 1; } +command -v jq >/dev/null || { echo "::error::jq is required"; exit 1; } + +chunk_bytes=${SESSION_REF_CHUNK_BYTES:-16777216} +remote=${SESSION_REF_REMOTE:-https://github.com/${GITHUB_REPOSITORY:?}.git} +hash_stream() { + if command -v sha256sum >/dev/null; then sha256sum | cut -d' ' -f1 + else shasum -a 256 | cut -d' ' -f1 + fi +} +key_hash() { printf '%s\0%s' "$MODEL_NAME" "$1" | hash_stream; } +ref_for() { printf 'refs/%s/%s' "$SESSION_REF_PREFIX" "$(key_hash "$1")"; } + +git_ref() { + # gh reads the renewed installation token from GH_CONFIG_DIR on each request. + GH_TOKEN=${SESSION_REF_TOKEN:-} GITHUB_TOKEN= GIT_TERMINAL_PROMPT=0 command git \ + -c credential.https://github.com.helper= -c 'credential.https://github.com.helper=!gh auth git-credential' "$@" +} + +digest() { + hash_stream < "$1" +} + +bytes() { wc -c < "$1" | tr -d ' '; } + +emit() { + if [ -n "${GITHUB_OUTPUT:-}" ]; then printf '%s\n' "$@" >> "$GITHUB_OUTPUT"; else printf '%s\n' "$@"; fi +} + +tmpdir() { mktemp -d "${TMPDIR:-/tmp}/session-ref.XXXXXX"; } +cleanup="" + +# Write manifest.json and chunks for the snapshot under codir into tree. +build_tree() { + local codir=$1 work=$2 tree=$2/tree LC_ALL=C + local files=() file name + if [ -d "$codir/sessions" ]; then + find "$codir/sessions" -type f -print0 | sort -z > "$work/files" + while IFS= read -r -d '' file; do files+=("$file"); done < "$work/files" + fi + for name in last-thread-id check-runs.jsonl; do [ ! -f "$codir/$name" ] || files+=("$codir/$name"); done + + [ "${#files[@]}" -gt 0 ] || { echo "::error::No session files to save"; return 1; } + local entries=() rel hash path_hash size chunk chunk_size chunk_hash + for file in "${files[@]}"; do + rel=${file#"$codir"/} + path_hash=$(printf '%s' "$rel" | hash_stream) + mkdir -p "$tree/chunks/$path_hash" + split -b "$chunk_bytes" -d -a 6 "$file" "$tree/chunks/$path_hash/" + # Derive the manifest from the captured bytes even if the source changed during the save. + local chunks=() + size=0 + for chunk in "$tree/chunks/$path_hash"/*; do + [ -f "$chunk" ] || continue + chunk_size=$(bytes "$chunk") + chunk_hash=$(digest "$chunk") + size=$((size + chunk_size)) + chunks+=("$(printf '{"path":"%s","size":%s,"sha256":"%s"}' "${chunk#"$tree"/}" "$chunk_size" "$chunk_hash")") + done + if [ "$size" -gt 0 ]; then hash=$(cat "$tree/chunks/$path_hash"/* | hash_stream) + else hash=$(hash_stream < /dev/null) + fi + entries+=("$(printf '{"path":%s,"size":%s,"sha256":"%s","chunks":[%s]}' \ + "$(printf '%s' "$rel" | jq -Rs .)" "$size" "$hash" "$(IFS=,; printf '%s' "${chunks[*]:-}")")") + done + { + printf '{"version":1,"model":%s,"files":[' "$(printf '%s' "$MODEL_NAME" | jq -R .)" + local first=1 entry + for entry in "${entries[@]}"; do + [ "$first" = 1 ] || printf ',' + printf '%s' "$entry"; first=0 + done + printf ']}\n' + } > "$tree/manifest.json" +} + +# ls-remote patterns also match suffixes. Only an exact match identifies this session. +lookup_tip() { + require_snapshot_url ls-remote --get-url "$remote" || return 1 + git_ref ls-remote "$remote" "$1" | awk -v want="$1" '$2 == want { print $1 }' +} + +# Git can inherit URL rewrites and additional push destinations on a self-hosted runner. +require_snapshot_url() { + local resolved + resolved=$(git_ref "$@") || return 1 + [ "$resolved" = "$remote" ] || { echo "::error::Git resolved a different session snapshot destination" >&2; return 1; } +} + +# Fetch by object ID so a concurrent ref change cannot substitute another commit. +prepare() { + local work=$1 ref=$2 tip + tip=$(lookup_tip "$ref") || return 1 + git_ref init -q --template= "$work" || return 1 + git_ref -C "$work" config core.autocrlf false || return 1 + git_ref -C "$work" remote add origin "$remote" || return 1 + [ -n "$tip" ] || return 3 + require_snapshot_url -C "$work" remote get-url --all origin || return 1 + git_ref -C "$work" fetch -q --no-tags --depth 1 origin "$tip" || return 1 +} + +restore_files() { + local work=$1 dest=$2 manifest=$work/manifest.json + local entries entry path hash size chunk chunk_size chunk_hash actual temporary + jq -e '.version == 1 and (.files | type == "array")' "$manifest" >/dev/null \ + || { echo "::error::Unsupported session snapshot manifest"; return 1; } + entries=$(jq -c '.files[]' "$manifest") || { echo "::error::Unreadable session snapshot manifest"; return 1; } + while IFS= read -r entry; do + [ -n "$entry" ] || continue + IFS= read -r -d '' path < <(jq -j '.path, "\u0000"' <<<"$entry") || return 1 + hash=$(jq -r .sha256 <<<"$entry"); size=$(jq -r .size <<<"$entry") + if [ "$path" = "null" ] || [ "$hash" = "null" ] || [ "$size" = "null" ]; then + echo "::error::Malformed session snapshot manifest entry"; return 1 + fi + # A snapshot may only restore the files Codex itself keeps; config, auth and hooks must not come from it. + case "$path" in + sessions/*|last-thread-id|check-runs.jsonl) ;; + *) echo "::error::Unsafe session snapshot path: $path"; return 1 ;; + esac + case "$path" in + ""|/*|..|../*|*/../*|*/..) echo "::error::Unsafe session snapshot path: $path"; return 1 ;; + esac + [[ "$path" != */* ]] || mkdir -p "$dest/${path%/*}" + : > "$dest/$path" + while IFS=$'\t' read -r chunk chunk_size chunk_hash; do + [ -n "$chunk" ] || continue + case "$chunk" in + chunks/*) ;; + *) echo "::error::Unsafe session snapshot chunk: $chunk"; return 1 ;; + esac + case "$chunk" in *..*) echo "::error::Unsafe session snapshot chunk: $chunk"; return 1 ;; esac + temporary=$(mktemp "${work}/chunk.XXXXXX") + if ! git_ref -C "$work" cat-file blob "FETCH_HEAD:$chunk" > "$temporary"; then + rm -f "$temporary"; echo "::error::Missing session snapshot chunk: $chunk"; return 1 + fi + if [ "$(bytes "$temporary")" != "$chunk_size" ] || [ "$(digest "$temporary")" != "$chunk_hash" ]; then + rm -f "$temporary"; echo "::error::Corrupt session snapshot chunk: $chunk"; return 1 + fi + cat "$temporary" >> "$dest/$path"; rm -f "$temporary" + done <<< "$(jq -r '.chunks[] | [.path, (.size | tostring), .sha256] | @tsv' <<<"$entry")" + [ "$(bytes "$dest/$path")" = "$size" ] || { echo "::error::Session snapshot size mismatch for $path"; return 1; } + actual=$(digest "$dest/$path") + [ "$actual" = "$hash" ] || { echo "::error::Session snapshot digest mismatch for $path"; return 1; } + done <<< "$entries" +} + +restore() { + local key=$1 dest=$2 ref work rc staging + ref=$(ref_for "$key"); work=$(tmpdir); cleanup=$work; trap 'rm -rf "$cleanup"' EXIT + if prepare "$work" "$ref"; then rc=0; else rc=$?; fi + if [ "$rc" = 3 ]; then echo "::error::The session ref $ref disappeared before it could be restored"; return 1; fi + [ "$rc" = 0 ] || return "$rc" + git_ref -C "$work" show FETCH_HEAD:manifest.json > "$work/manifest.json" + # Verify the whole snapshot in a private tree; a partial restore must not leave receipts beside the session. + staging=$work/restore; mkdir -p "$staging" + restore_files "$work" "$staging" + [ -e "$staging/sessions" ] || [ -e "$staging/last-thread-id" ] || [ -e "$staging/check-runs.jsonl" ] \ + || { echo "::error::The session snapshot $ref is empty"; return 1; } + mkdir -p "$dest"; cp -R "$staging"/. "$dest"/ + emit "commit=$(git_ref -C "$work" rev-parse FETCH_HEAD)" + echo "Restored $ref into $dest" +} + +save() { + local key=$1 ref tree work attempt expected candidate tip rc + ref=$(ref_for "$key"); work=$(tmpdir); tree=$work/tree; mkdir -p "$tree" + cleanup=$work; trap 'rm -rf "$cleanup"' EXIT + build_tree "$CODEX_HOME" "$work" + # The snapshot belongs to the state this run restored. Never replace a newer ref with older state. + expected=${SESSION_REF_BASE:-} + candidate="" + for attempt in 1 2 3 4 5; do + rm -rf "$work/repo"; mkdir -p "$work/repo" + if prepare "$work/repo" "$ref"; then rc=0; else rc=$?; fi + [ "$rc" = 3 ] || [ "$rc" = 0 ] || return "$rc" + if [ "$rc" = 3 ]; then + [ -z "$expected" ] || { echo "::warning::The session ref disappeared after it was restored; keeping the saved snapshot."; emit "saved=false"; return 0; } + else + tip=$(git_ref -C "$work/repo" rev-parse FETCH_HEAD) + # A push can succeed even when its response is lost; accept our own commit as the new tip. + if [ -n "$candidate" ] && [ "$tip" = "$candidate" ]; then + emit "saved=true" "commit=$tip" "ref=$ref"; echo "Saved $ref at $tip"; return 0 + fi + if [ "$tip" != "$expected" ]; then + echo "::warning::The session ref advanced during this run; keeping the newer snapshot." + emit "saved=false"; return 0 + fi + git_ref -C "$work/repo" update-ref HEAD "$tip" + fi + cp -R "$tree"/. "$work/repo"/ + # Stage all snapshot bytes, including paths global ignore rules or clean filters would change. + GIT_ATTR_NOSYSTEM=1 git_ref -C "$work/repo" -c core.attributesFile=/dev/null add --force --all + if git_ref -C "$work/repo" diff --cached --quiet; then + candidate=$(git_ref -C "$work/repo" rev-parse HEAD) + emit "saved=true" "commit=$candidate" "ref=$ref"; echo "Session snapshot already at $candidate"; return 0 + fi + git_ref -C "$work/repo" -c user.name=muspi-merol-review -c user.email=review@promplate.dev \ + commit -q -m "session snapshot ${GITHUB_RUN_ID:-local}-${GITHUB_RUN_ATTEMPT:-1}" + candidate=$(git_ref -C "$work/repo" rev-parse HEAD) + # A literal push refspec can resolve to a branch with the same suffix. A pattern maps the sole local snapshot ref exactly. + git_ref -C "$work/repo" update-ref "$ref" "$candidate" + require_snapshot_url -C "$work/repo" remote get-url --push --all origin || return 1 + if git_ref -C "$work/repo" push -q --force-with-lease="$ref:$expected" origin "refs/$SESSION_REF_PREFIX/*:refs/$SESSION_REF_PREFIX/*"; then + emit "saved=true" "commit=$candidate" "ref=$ref"; echo "Saved $ref at $candidate"; return 0 + fi + echo "::notice::Retrying session snapshot push after a transient failure." + done + echo "::error::Could not append the session snapshot to $ref" + return 1 +} + +find_ref() { + local ref sha + ref=$(ref_for "$1") + sha=$(lookup_tip "$ref") || { echo "::error::Could not query the session ref $ref" >&2; return 1; } + [ -z "$sha" ] || emit "ref=$ref" "commit=$sha" +} + +case ${1:?usage: session-ref.sh find|restore|save [dir]} in + find) find_ref "$2" ;; + restore) restore "$2" "$3" ;; + save) save "$2" ;; + *) echo "usage: session-ref.sh find|restore|save [dir]" >&2; exit 64 ;; +esac diff --git a/scripts/session-ref.test.ts b/scripts/session-ref.test.ts new file mode 100644 index 0000000..429c341 --- /dev/null +++ b/scripts/session-ref.test.ts @@ -0,0 +1,202 @@ +import { afterEach, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const directories: string[] = []; +afterEach(() => directories.splice(0).forEach(path => rmSync(path, { recursive: true, force: true }))); +const script = join(import.meta.dir, "session-ref.sh"); +const git = (args: string[], cwd?: string) => spawnSync("git", args, { cwd, encoding: "utf8" }); +const key = (model: string, session: string) => createHash("sha256").update(`${model}\0${session}`).digest("hex"); +const run = (args: string[], env: Record) => spawnSync("bash", [script, ...args], { env: { ...process.env, ...env }, encoding: "utf8" }); + +function fixture() { + const root = mkdtempSync(join(tmpdir(), "session-ref-")); directories.push(root); + const remote = join(root, "remote.git"); + expect(git(["init", "--bare", "-q", remote]).status).toBe(0); + const home = join(root, "home"), sessions = join(home, "sessions/2026/11/30"); + mkdirSync(sessions, { recursive: true }); + writeFileSync(join(home, "last-thread-id"), "thread-1\n"); + writeFileSync(join(home, "check-runs.jsonl"), '{"sha":"head"}\n'); + const rollout = join(sessions, "rollout-2026-11-30T00-00-00-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa.jsonl"); + writeFileSync(rollout, "line one\nline two with tool output\n"); + writeFileSync(join(sessions, "empty.jsonl"), ""); + const env = { + SESSION_REF_PREFIX: "agent-sessions", MODEL_NAME: "test-model", SESSION_REF_REMOTE: remote, + SESSION_REF_CHUNK_BYTES: "8", CODEX_HOME: home, GITHUB_REPOSITORY: "rb-hq/test", GITHUB_OUTPUT: join(root, "out"), + }; + return { root, remote, home, rollout, env, ref: `refs/agent-sessions/${key("test-model", "session-1")}` }; +} + +function restoreTo(f: ReturnType, name: string) { + const destination = join(f.root, name); + mkdirSync(destination, { recursive: true }); + const result = run(["restore", "session-1", destination], f.env); + expect(result.status).toBe(0); + return destination; +} + +test("appends a complete snapshot and restores its exact bytes", () => { + const f = fixture(); + const save = run(["save", "session-1"], f.env); + expect(save.status).toBe(0); + expect(readFileSync(join(f.root, "out"), "utf8")).toContain("saved=true"); + + const find = run(["find", "session-1"], { ...f.env, GITHUB_OUTPUT: join(f.root, "find") }); + expect(find.status).toBe(0); + expect(readFileSync(join(f.root, "find"), "utf8")).toContain(`ref=${f.ref}`); + + const restored = restoreTo(f, "restore"); + for (const path of ["last-thread-id", "check-runs.jsonl", "sessions/2026/11/30/rollout-2026-11-30T00-00-00-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa.jsonl", "sessions/2026/11/30/empty.jsonl"]) { + expect(readFileSync(join(restored, path))).toEqual(readFileSync(join(f.home, path))); + } + expect(statSync(join(restored, "sessions/2026/11/30/empty.jsonl")).size).toBe(0); +}); + +const commitIn = (f: ReturnType, name = "out") => readFileSync(join(f.root, name), "utf8").match(/commit=([0-9a-f]+)/)![1]; + +test("appends another commit and keeps the previous history", () => { + const f = fixture(); + expect(run(["save", "session-1"], f.env).status).toBe(0); + const first = commitIn(f); + appendFileSync(f.rollout, "line three\n"); + expect(run(["save", "session-1"], { ...f.env, SESSION_REF_BASE: first }).status).toBe(0); + const count = git(["--git-dir", f.remote, "rev-list", "--count", f.ref]); + expect(count.stdout.trim()).toBe("2"); + const restored = restoreTo(f, "restore"); + expect(readFileSync(join(restored, "sessions/2026/11/30/rollout-2026-11-30T00-00-00-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa.jsonl"), "utf8")).toContain("line three"); +}); + +test("does not append a commit when the snapshot is unchanged", () => { + const f = fixture(); + expect(run(["save", "session-1"], f.env).status).toBe(0); + const first = commitIn(f); + expect(run(["save", "session-1"], { ...f.env, SESSION_REF_BASE: first }).status).toBe(0); + const count = git(["--git-dir", f.remote, "rev-list", "--count", f.ref]); + expect(count.stdout.trim()).toBe("1"); +}); + +test("reports a missing ref without failing", () => { + const f = fixture(); + const find = run(["find", "missing"], { ...f.env, GITHUB_OUTPUT: join(f.root, "missing") }); + expect(find.status).toBe(0); + expect(() => readFileSync(join(f.root, "missing"))).toThrow(); +}); + +function publishManifest(f: ReturnType, manifest: string, chunks: Record) { + const work = join(f.root, "publish"); + mkdirSync(work, { recursive: true }); + expect(git(["init", "-q"], work).status).toBe(0); + expect(git(["remote", "add", "origin", f.remote], work).status).toBe(0); + writeFileSync(join(work, "manifest.json"), manifest); + for (const [path, body] of Object.entries(chunks)) { + mkdirSync(join(work, path, ".."), { recursive: true }); + writeFileSync(join(work, path), body); + } + expect(git(["add", "-A"], work).status).toBe(0); + expect(git(["-c", "user.name=probe", "-c", "user.email=probe@example.com", "commit", "-q", "-m", "probe"], work).status).toBe(0); + expect(git(["push", "-q", "origin", `HEAD:${f.ref}`], work).status).toBe(0); +} + +test("refuses to restore a path outside the destination", () => { + const f = fixture(); + const hash = createHash("sha256").update("x").digest("hex"); + publishManifest(f, JSON.stringify({ + version: 1, + files: [{ path: "../escape", size: 1, sha256: hash, chunks: [{ path: "chunks/x/0", size: 1, sha256: hash }] }], + }), { "chunks/x/0": "x" }); + const destination = join(f.root, "safe"); + mkdirSync(destination, { recursive: true }); + const restore = run(["restore", "session-1", destination], f.env); + expect(restore.status).not.toBe(0); + expect(() => statSync(join(f.root, "escape"))).toThrow(); +}); + +test("refuses to restore a corrupt manifest", () => { + const f = fixture(); + publishManifest(f, "{not json", {}); + const destination = join(f.root, "corrupt"); + mkdirSync(destination, { recursive: true }); + expect(run(["restore", "session-1", destination], f.env).status).not.toBe(0); +}); + +test("refuses to append over a ref that advanced since the restore", () => { + const f = fixture(); + expect(run(["save", "session-1"], f.env).status).toBe(0); + const first = commitIn(f); + appendFileSync(f.rollout, "second\n"); + expect(run(["save", "session-1"], { ...f.env, SESSION_REF_BASE: first }).status).toBe(0); + appendFileSync(f.rollout, "third\n"); + const result = run(["save", "session-1"], { ...f.env, SESSION_REF_BASE: first, GITHUB_OUTPUT: join(f.root, "stale") }); + expect(result.status).toBe(0); + expect(readFileSync(join(f.root, "stale"), "utf8")).toContain("saved=false"); + expect(git(["--git-dir", f.remote, "rev-list", "--count", f.ref]).stdout.trim()).toBe("2"); +}); + +test("rejects reserved and invalid ref namespaces before lookup", () => { + const f = fixture(); + for (const prefix of ["heads", "tags", "history.lock", ".private/history"]) { + expect(run(["find", "session-1"], { ...f.env, SESSION_REF_PREFIX: prefix }).status).not.toBe(0); + } +}); + +test("a branch sharing the ref's suffix leaves the session available for its first save", () => { + const f = fixture(); + expect(run(["save", "session-1"], f.env).status).toBe(0); + const first = commitIn(f); + expect(git(["--git-dir", f.remote, "update-ref", `refs/heads/${f.ref}`, first]).status).toBe(0); + expect(git(["--git-dir", f.remote, "update-ref", "-d", f.ref]).status).toBe(0); + expect(run(["restore", "session-1", join(f.root, "missing")], f.env).status).not.toBe(0); + appendFileSync(f.rollout, "fresh session\n"); + expect(run(["save", "session-1"], f.env).status).toBe(0); + expect(git(["--git-dir", f.remote, "show-ref", "--verify", f.ref]).status).toBe(0); + expect(git(["--git-dir", f.remote, "rev-parse", `refs/heads/${f.ref}`]).stdout.trim()).toBe(first); +}); + +test("the restored commit is the base when the ref advanced after lookup", () => { + const f = fixture(); + expect(run(["save", "session-1"], f.env).status).toBe(0); + expect(run(["find", "session-1"], { ...f.env, GITHUB_OUTPUT: join(f.root, "lookup") }).status).toBe(0); + appendFileSync(f.rollout, "review from another run\n"); + const second = { ...f.env, SESSION_REF_BASE: commitIn(f, "lookup"), GITHUB_OUTPUT: join(f.root, "second") }; + expect(run(["save", "session-1"], second).status).toBe(0); + const dir = join(f.root, "restored"); + expect(run(["restore", "session-1", dir], { ...f.env, GITHUB_OUTPUT: join(f.root, "restore-output") }).status).toBe(0); + expect(commitIn(f, "restore-output")).toBe(commitIn(f, "second")); + appendFileSync(join(dir, "check-runs.jsonl"), '{"sha":"published"}\n'); + expect(run(["save", "session-1"], { ...f.env, CODEX_HOME: dir, SESSION_REF_BASE: commitIn(f, "restore-output") }).status).toBe(0); + expect(git(["--git-dir", f.remote, "rev-list", "--count", f.ref]).stdout.trim()).toBe("3"); +}); + +test("global Git settings preserve manifest paths and chunk bytes", () => { + const f = fixture(); + const excludes = join(f.root, "ignore"), attributes = join(f.root, "attributes"); + writeFileSync(excludes, "manifest.json\n"); + writeFileSync(attributes, "* text eol=lf\n"); + const path = "sessions/tool\\output\n"; + writeFileSync(join(f.home, path), "first\r\nsecond\r\n"); + const env = { + ...f.env, GIT_CONFIG_COUNT: "2", GIT_CONFIG_KEY_0: "core.excludesFile", GIT_CONFIG_VALUE_0: excludes, + GIT_CONFIG_KEY_1: "core.attributesFile", GIT_CONFIG_VALUE_1: attributes, + }; + expect(run(["save", "session-1"], env).status).toBe(0); + const dir = restoreTo(f, "restored"); + expect(readFileSync(join(dir, path))).toEqual(readFileSync(join(f.home, path))); +}); + +test("a snapshot save stops when Git reports an additional push destination", () => { + const f = fixture(); + const realGit = Bun.which("git")!; + writeFileSync(join(f.root, "git"), `#!/bin/sh +case " $* " in + *" remote get-url --push --all origin "*) printf '%s\\n' "$SESSION_REF_REMOTE" "unexpected-destination" ;; + *) exec "$FIXTURE_GIT" "$@" ;; +esac +`, { mode: 0o700 }); + const save = run(["save", "session-1"], { ...f.env, PATH: `${f.root}:${process.env.PATH}`, FIXTURE_GIT: realGit }); + expect(save.status).toBe(1); + expect(save.stderr).toContain("Git resolved a different session snapshot destination"); + expect(git(["--git-dir", f.remote, "for-each-ref", f.ref]).stdout).toBe(""); +});