Remove the /cso security audit skill, since a plain audit request finds more (#4833)

/cso is gone: the skill, its native helper programs, scanner images, CI
jobs, docs and the rest of its tests. Upgrading removes gstack's own
`/cso` entries and old helper files, and leaves a skill of your own
named `cso` alone.

Why: on 52 real security advisories, plainly asking the agent to audit
the code caught more than /cso (13 vs 7 on particle-1; 12 vs 8 of 51 on
Claude Opus 5.5, within the margin of error).

To do: nothing. Optional cleanup of old scanner images and reports is in
the changelog entry.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/outside-voice#1 reader=outside-voice
Review-Finding: p1/outside-voice#2 reader=outside-voice
Review-Finding: p1/adversarial-native#1 reader=adversarial-native
Review-Finding: p1/adversarial-native#2 reader=adversarial-native
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-25 21:59:08 +00:00
1 parent fd7e8c7b36
commit 2fae1d78d6
207 files changed
+387 -32001

No files matched your search

-91
View File
@@ -1,91 +0,0 @@
param(
[Parameter(Mandatory = $true)][string]$RepoRoot,
[string]$OutputPath,
[string]$LockOutputPath,
[string]$CoreSha256,
[Parameter(Mandatory = $true)][string]$GitExePath,
[switch]$CheckOnly
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$stagedOutput = $null
$stagedLockOutput = $null
$gitItem = Get-Item -LiteralPath ([System.IO.Path]::GetFullPath($GitExePath)) -Force
if ($gitItem.PSIsContainer -or ($gitItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -or
-not $gitItem.Name.Equals('git.exe', [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'CSO Windows build requires the resolved regular git.exe used by setup.'
}
$resolvedGit = $gitItem.FullName
if (-not $CheckOnly) {
if (-not $OutputPath -or -not $LockOutputPath -or $CoreSha256 -notmatch '^[a-f0-9]{64}$') { throw 'Normal CSO Windows builds require staged outputs and a lowercase SHA-256 core binding.' }
$resolvedRepo = (Get-Item -LiteralPath $RepoRoot -Force).FullName
$binRoot = [System.IO.Path]::GetFullPath((Join-Path $resolvedRepo 'bin')).TrimEnd('\')
function Resolve-StagedOutput([string]$Value, [string]$ExpectedName) {
$resolved = [System.IO.Path]::GetFullPath($Value)
$parent = [System.IO.Path]::GetDirectoryName($resolved)
$parentItem = Get-Item -LiteralPath $parent -Force
$directParent = [System.IO.Path]::GetDirectoryName($parent)
if ([System.IO.Path]::GetFileName($resolved) -cne $ExpectedName -or
[System.IO.Path]::GetFileName($parent) -notlike '.gstack-cso-stage.*' -or
-not $directParent.Equals($binRoot, [System.StringComparison]::OrdinalIgnoreCase) -or
($parentItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
throw 'CSO Windows native output must be a direct, non-reparse staging directory under the repository bin directory.'
}
return $resolved
}
$stagedOutput = Resolve-StagedOutput $OutputPath 'gstack-cso-launcher.exe'
$stagedLockOutput = Resolve-StagedOutput $LockOutputPath 'gstack-cso-publish-lock.exe'
}
# Use the installed MSVC toolchain, not a Bun-hosted launcher or downloaded
# compiler. This works from Git Bash without a preconfigured Developer Prompt.
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
if (-not (Test-Path -LiteralPath $vswhere -PathType Leaf)) {
throw 'CSO Windows build requires Visual Studio 2022 Build Tools with the Desktop development with C++ workload.'
}
$installation = & $vswhere -latest -products '*' -version '[17.0,)' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if ($LASTEXITCODE -ne 0 -or -not $installation) {
throw 'CSO Windows build requires the Visual Studio 2022 MSVC x64 toolchain and Windows SDK.'
}
$devShell = Join-Path ([string]$installation) 'Common7\Tools\Launch-VsDevShell.ps1'
if (-not (Test-Path -LiteralPath $devShell -PathType Leaf)) { throw 'MSVC Developer PowerShell initialization is unavailable.' }
& $devShell -Arch amd64 -HostArch amd64 -SkipAutomaticLocation | Out-Null
$compiler = (Get-Command cl.exe -ErrorAction Stop).Source
$installationPrefix = [System.IO.Path]::GetFullPath([string]$installation).TrimEnd('\') + '\'
if (-not [System.IO.Path]::GetFullPath($compiler).StartsWith($installationPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'MSVC initialization selected a compiler outside the discovered Visual Studio installation.'
}
$temporary = Join-Path ([System.IO.Path]::GetTempPath()) ('gstack-cso-msvc-' + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $temporary | Out-Null
try {
if ($CheckOnly) {
$source = Join-Path $temporary 'probe.c'
$output = Join-Path $temporary 'probe.exe'
Set-Content -LiteralPath $source -Encoding Ascii -NoNewline -Value 'int main(void) { return 0; }'
$object = Join-Path $temporary 'probe.obj'
# /wd5105: the Windows SDK's own winbase.h raises C5105 ("macro expansion
# producing 'defined' has undefined behavior"), which /WX turns into
# error C2220 inside a system header (#3015). Only that diagnostic is off.
& $compiler /nologo /std:c11 /W4 /WX /wd5105 /O2 /MT /GS /guard:cf /D_CRT_SECURE_NO_WARNINGS "/Fo$object" "/Fe$output" $source /link /DYNAMICBASE /NXCOMPAT /HIGHENTROPYVA
if ($LASTEXITCODE -ne 0) { throw "Native CSO Windows compiler probe failed ($LASTEXITCODE)." }
if (-not (Test-Path -LiteralPath $output -PathType Leaf)) { throw 'Native CSO Windows compiler probe was not produced.' }
} else {
$binding = Join-Path $temporary 'core-binding.h'
$gitLiteral = $resolvedGit.Replace('\', '\\').Replace('"', '\"')
Set-Content -LiteralPath $binding -Encoding Ascii -Value "#define GSTACK_CSO_CORE_SHA256 `"$CoreSha256`"`n#define GSTACK_CSO_GIT_PATH L`"$gitLiteral`""
$builds = @(
@{ Source = (Join-Path $RepoRoot 'lib\cso\launcher-windows.c'); Output = [string]$stagedOutput; Object = 'launcher.obj'; Binding = $true },
@{ Source = (Join-Path $RepoRoot 'lib\cso\publish-lock.c'); Output = [string]$stagedLockOutput; Object = 'publish-lock.obj'; Binding = $false }
)
foreach ($build in $builds) {
$object = Join-Path $temporary $build.Object
$forcedInclude = if ($build.Binding) { "/FI$binding" } else { @() }
& $compiler /nologo /std:c11 /W4 /WX /wd5105 /O2 /MT /GS /guard:cf /D_CRT_SECURE_NO_WARNINGS $forcedInclude "/Fo$object" "/Fe$($build.Output)" $build.Source /link /DYNAMICBASE /NXCOMPAT /HIGHENTROPYVA
if ($LASTEXITCODE -ne 0) { throw "Native CSO Windows helper compilation failed ($LASTEXITCODE)." }
if (-not (Test-Path -LiteralPath $build.Output -PathType Leaf)) { throw 'Native CSO Windows output was not produced.' }
}
}
} finally {
Remove-Item -LiteralPath $temporary -Recurse -Force
}
-437
View File
@@ -1,437 +0,0 @@
#!/usr/bin/env bash
set -eu
GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac
CSO_BUILD_ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
cd "$CSO_BUILD_ROOT"
umask 077
BUN_CMD="${BUN_CMD:-bun}"
CSO_CC="${CSO_CC:-cc}"
CSO_EXE=""
case "$(uname -s)" in
MINGW*|MSYS*|CYGWIN*|Windows_NT) CSO_EXE=".exe" ;;
esac
CSO_FINAL_CORE="$CSO_BUILD_ROOT/bin/gstack-cso-core$CSO_EXE"
CSO_FINAL_LAUNCHER="$CSO_BUILD_ROOT/bin/gstack-cso-launcher$CSO_EXE"
CSO_FINAL_WATCHDOG="$CSO_BUILD_ROOT/bin/gstack-cso-watchdog"
CSO_FINAL_GENERATION="$CSO_BUILD_ROOT/bin/.gstack-cso-generation"
# Build-result record read by setup's summary and gstack-doctor (#3071).
CSO_RESULT_FILE="$CSO_BUILD_ROOT/bin/.gstack-cso-build-result"
CSO_RESULT_RECORDING=0
CSO_RESULT_STAGE=build
CSO_REVISION=""
CSO_PREVIOUS_INSTALLED=""
CSO_STAGE=""
CSO_PUBLISHING=0
CSO_COMMITTED=0
CSO_OLD_COHERENT=0
CSO_OLD_LAUNCHER_MOVED=0
CSO_OLD_CORE_MOVED=0
CSO_OLD_WATCHDOG_MOVED=0
CSO_OLD_GENERATION_MOVED=0
CSO_NEW_LAUNCHER_INSTALLED=0
CSO_NEW_CORE_INSTALLED=0
CSO_NEW_WATCHDOG_INSTALLED=0
CSO_NEW_GENERATION_INSTALLED=0
CSO_EVALUATION_UNIT=""
cso_checkpoint() {
[ "${GSTACK_CSO_BUILD_TESTING:-0}" = 1 ] || return 0
if [ "${GSTACK_CSO_BUILD_TEST_FAIL_AFTER:-}" = "$1" ]; then
echo "Injected CSO build failure after $1" >&2
exit 86
fi
if [ "${GSTACK_CSO_BUILD_TEST_KILL_AFTER:-}" = "$1" ]; then
kill -KILL "$$"
fi
if [ "${GSTACK_CSO_BUILD_TEST_REMOVE_LOCKER_AFTER:-}" = "$1" ]; then
rm -f "$CSO_STAGE_LOCKER"
fi
}
cso_record_field() { sed -n "s/^$1=//p" "$CSO_RESULT_FILE" 2>/dev/null | head -1; }
# One record per run: result (ok/failed), stage (build/publish), reason, this
# checkout's revision, the revision of the CSO generation still installed, and
# whether that launcher is usable. A SIGKILL leaves the last "interrupted" entry.
cso_write_result() {
launcher=no
if cso_valid_artifact "$CSO_FINAL_LAUNCHER" && cso_valid_artifact "$CSO_FINAL_CORE"; then launcher=yes; fi
installed=""
if [ "$1" = ok ]; then installed=$CSO_REVISION
elif [ "$launcher" = yes ]; then installed=${CSO_PREVIOUS_INSTALLED:-an earlier build}; fi
# Written in place: publication's signal tests count on mv moving artifacts only.
printf 'result=%s\nstage=%s\nreason=%s\nrevision=%s\ninstalled=%s\nlauncher=%s\ndiagnostic=%s\n' \
"$1" "$2" "$3" "$CSO_REVISION" "$installed" "$launcher" "${GSTACK_CSO_BUILD_LOG:-the scripts/build-cso.sh output}" > "$CSO_RESULT_FILE" || true
}
cso_restore_previous() {
rollback_ok=1
# A public launcher is removed before any supporting artifact is restored.
if [ "$CSO_NEW_LAUNCHER_INSTALLED" -eq 1 ]; then rm -f "$CSO_FINAL_LAUNCHER" || rollback_ok=0; fi
if [ "$CSO_NEW_CORE_INSTALLED" -eq 1 ]; then rm -f "$CSO_FINAL_CORE" || rollback_ok=0; fi
if [ -z "$CSO_EXE" ] && [ "$CSO_NEW_WATCHDOG_INSTALLED" -eq 1 ]; then rm -f "$CSO_FINAL_WATCHDOG" || rollback_ok=0; fi
if [ "$CSO_NEW_GENERATION_INSTALLED" -eq 1 ];then rm -f "$CSO_FINAL_GENERATION"||rollback_ok=0;fi
if [ "$CSO_OLD_CORE_MOVED" -eq 1 ]; then
if [ "${GSTACK_CSO_BUILD_TESTING:-0}" = 1 ] && [ "${GSTACK_CSO_BUILD_TEST_FAIL_RESTORE:-}" = core ];then rollback_ok=0
elif cso_present "$CSO_STAGE/previous/core";then cso_move "$CSO_STAGE/previous/core" "$CSO_FINAL_CORE" || rollback_ok=0
elif ! cso_valid_artifact "$CSO_FINAL_CORE";then rollback_ok=0;fi
fi
if [ -z "$CSO_EXE" ] && [ "$CSO_OLD_WATCHDOG_MOVED" -eq 1 ]; then
if cso_present "$CSO_STAGE/previous/watchdog";then cso_move "$CSO_STAGE/previous/watchdog" "$CSO_FINAL_WATCHDOG" || rollback_ok=0
elif ! cso_valid_artifact "$CSO_FINAL_WATCHDOG";then rollback_ok=0;fi
fi
if [ "$CSO_OLD_GENERATION_MOVED" -eq 1 ];then
if cso_present "$CSO_STAGE/previous/generation";then cso_move "$CSO_STAGE/previous/generation" "$CSO_FINAL_GENERATION"||rollback_ok=0
elif ! cso_valid_generation "$CSO_FINAL_GENERATION";then rollback_ok=0;fi
fi
# Restore the old launcher last, and only beside the complete old support set.
if [ "$CSO_OLD_LAUNCHER_MOVED" -eq 1 ]; then
if [ "$rollback_ok" -eq 1 ] && [ "$CSO_OLD_COHERENT" -eq 1 ]; then
if cso_present "$CSO_STAGE/previous/launcher";then cso_move "$CSO_STAGE/previous/launcher" "$CSO_FINAL_LAUNCHER" || rollback_ok=0
elif ! cso_valid_artifact "$CSO_FINAL_LAUNCHER";then rollback_ok=0;fi
else
rollback_ok=0
fi
fi
if [ "$rollback_ok" -ne 1 ]; then
rm -f "$CSO_FINAL_LAUNCHER"
: > "$CSO_STAGE/.retain-recovery"
echo "CSO build rollback was incomplete; the public launcher is withheld and recovery files remain in $CSO_STAGE" >&2
return 1
fi
return 0
}
cso_cleanup() {
status=$1
trap - EXIT
trap '' HUP INT TERM
set +e
cleanup_stage=1
if [ "$CSO_PUBLISHING" -eq 1 ] && [ "$CSO_COMMITTED" -ne 1 ]; then
if ! cso_restore_previous; then status=1; cleanup_stage=0; fi
fi
if [ "$cleanup_stage" -eq 1 ] && [ -n "$CSO_STAGE" ] && [ ! -f "$CSO_STAGE/.retain-recovery" ]; then rm -rf "$CSO_STAGE"; fi
if [ -n "$CSO_EVALUATION_UNIT" ]; then rm -rf "$CSO_EVALUATION_UNIT"; fi
if [ "$CSO_RESULT_RECORDING" -eq 1 ]; then
if [ "$status" -eq 0 ] && [ "$CSO_COMMITTED" -eq 1 ]; then cso_write_result ok publish committed
else cso_write_result failed "$CSO_RESULT_STAGE" "exit $status"; fi
fi
exit "$status"
}
trap 'cso_cleanup $?' EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
cso_valid_artifact() { [ -f "$1" ] && [ ! -L "$1" ] && [ -x "$1" ]; }
cso_present() { [ -e "$1" ] || [ -L "$1" ]; }
cso_valid_generation() {
[ -f "$1" ]&&[ ! -L "$1" ]||return 1
generation_size="$(wc -c < "$1" 2>/dev/null||true)"
generation_size="${generation_size//[[:space:]]/}"
[ "$generation_size" = 65 ]||return 1
generation="$(cat "$1" 2>/dev/null)";[ "${#generation}" -eq 64 ]||return 1
case "$generation" in *[!a-f0-9]*) return 1;;esac
}
cso_move() {
move_attempts=0
while ! mv "$1" "$2";do
move_attempts=$((move_attempts+1))
if [ -z "$CSO_EXE" ] || [ "$move_attempts" -ge 50 ];then return 1;fi
sleep .02
done
}
cso_sign_macos_artifact() {
artifact=$1
hardened=$2
if [ "$(uname -m)" = arm64 ]; then
sig_end="$(otool -l "$artifact" 2>/dev/null | awk '/LC_CODE_SIGNATURE/{f=1} f&&/dataoff/{o=$2} f&&/datasize/{print o+$2; exit}')"
file_size="$(stat -f%z "$artifact" 2>/dev/null || true)"
if [ -n "$sig_end" ] && [ -n "$file_size" ] && [ "$sig_end" -gt 0 ] 2>/dev/null && [ "$sig_end" -lt "$file_size" ] 2>/dev/null; then
truncated="$CSO_STAGE/.codesign-truncated"
head -c "$sig_end" "$artifact" > "$truncated"
cat "$truncated" > "$artifact"
rm -f "$truncated"
chmod +x "$artifact"
fi
fi
codesign --remove-signature "$artifact" 2>/dev/null || true
if [ "$hardened" -eq 1 ]; then codesign --force --sign - --options runtime "$artifact"
else codesign --force --sign - "$artifact"; fi
codesign --verify --strict "$artifact"
if [ "$hardened" -eq 1 ]; then codesign -d --verbose=4 "$artifact" 2>&1 | grep -q 'runtime'; fi
}
cso_sha256() {
if [ -x /usr/bin/sha256sum ];then digest="$(/usr/bin/sha256sum "$1")";digest=${digest%% *}
elif [ -x /usr/bin/shasum ];then digest="$(/usr/bin/shasum -a 256 "$1")";digest=${digest%% *}
else echo 'CSO build requires sha256sum or shasum to bind the native launcher to its core.' >&2;return 1;fi
case "$digest" in *[!a-f0-9]*|'') echo 'CSO build received an invalid core SHA-256 digest.' >&2;return 1;;esac
[ "${#digest}" -eq 64 ] || { echo 'CSO build received an invalid core SHA-256 digest.' >&2;return 1; }
printf '%s\n' "$digest"
}
# Bun's compile-time switches stop configuration discovery in the audited
# working directory before the helper can apply its own policy.
cso_compile_bun() {
"$BUN_CMD" build --compile \
--no-compile-autoload-dotenv \
--no-compile-autoload-bunfig \
--no-compile-autoload-tsconfig \
--no-compile-autoload-package-json \
"$1" "${@:3}" --outfile "$2"
chmod +x "$2"
}
cso_compile_watchdog() {
"$CSO_CC" -std=c11 -D_POSIX_C_SOURCE=200809L -O2 -Wall -Wextra \
lib/cso/watchdog.c -o "$1"
chmod +x "$1"
}
cso_compile_posix_launcher() {
CSO_LAUNCHER_FLAGS=""
case "$(uname -s)" in
Linux) CSO_LAUNCHER_FLAGS="-static" ;;
# Local ad-hoc signatures do not distinguish the launcher from another
# ad-hoc dylib. This section makes dyld prune DYLD_* before constructors.
Darwin) CSO_LAUNCHER_FLAGS="-Wl,-sectcreate,__RESTRICT,__restrict,/dev/null" ;;
esac
# shellcheck disable=SC2086 -- the optional platform flags are fixed literals.
"$CSO_CC" -std=c11 -D_POSIX_C_SOURCE=200809L -O2 -Wall -Wextra $CSO_LAUNCHER_FLAGS \
"-DGSTACK_CSO_CORE_SHA256=\"$2\"" lib/cso/launcher.c -o "$1"
}
# An evaluation candidate embeds a cso-eval-* runtime catalog in a private
# five-artifact producer unit outside this checkout. It never touches bin/, and
# its .gstack-cso-evaluation manifest marks it evaluation-only for setup.
cso_build_evaluation_candidate() {
[ "$#" -eq 4 ] && [ "$1" = --evaluation-candidate ] && [ "$3" = --output ] || {
echo 'Usage: build-cso.sh --evaluation-candidate <cso-eval-catalog.json> --output <new-directory>' >&2;return 64; }
[ -z "$CSO_EXE" ] || { echo 'CSO evaluation candidates are built only on Linux and macOS.' >&2;return 69; }
command -v "$CSO_CC" >/dev/null 2>&1 || { echo 'CSO build requires a C compiler (cc/clang/gcc) for the trusted launcher and watchdog.' >&2;return 1; }
candidate_catalog=$2
[ -f "$candidate_catalog" ] && [ ! -L "$candidate_catalog" ] || { echo 'CSO evaluation catalog must be one regular file.' >&2;return 66; }
candidate_parent="$(cd "$(dirname "$4")" 2>/dev/null && pwd -P)" || { echo 'CSO evaluation output parent must be an existing directory.' >&2;return 73; }
candidate_output="$candidate_parent/$(basename "$4")"
if cso_present "$candidate_output";then echo 'CSO evaluation output must be a new directory.' >&2;return 73;fi
case "$candidate_output/" in "$CSO_BUILD_ROOT"/*) echo 'CSO evaluation output must be outside the gstack checkout, where setup and distribution never look.' >&2;return 73;;esac
candidate_revision="$(grep -o '"revision": *"cso-eval-[0-9]\{1,\}-[a-f0-9]\{12\}"' "$candidate_catalog" | head -n 1 | sed 's/.*"\(cso-eval-[^"]*\)"$/\1/' || true)"
[ -n "$candidate_revision" ] || { echo 'CSO evaluation candidates require a cso-eval-<runId>-<sha12> catalog revision.' >&2;return 65; }
CSO_STAGE="$(mktemp -d "${TMPDIR:-/tmp}/gstack-cso-evaluation.XXXXXX")"
CSO_EVALUATION_UNIT="$(mktemp -d "$candidate_parent/.gstack-cso-evaluation.XXXXXX")"
source_root="$CSO_STAGE/source"
mkdir -m 700 "$source_root" "$source_root/test"
cp -R lib scripts "$source_root/"
cp -R test/helpers "$source_root/test/"
cp "$candidate_catalog" "$source_root/lib/cso/runtime-catalog.json"
(cd "$source_root" && "$BUN_CMD" --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" scripts/cso-runtime-promotion.ts check-evaluation lib/cso/runtime-catalog.json)
(cd "$source_root" && cso_compile_bun lib/cso/cli.ts "$CSO_EVALUATION_UNIT/gstack-cso-core" lib/cso/search-worker.ts)
(cd "$source_root" && cso_compile_bun scripts/cso-eval-producer.ts "$CSO_EVALUATION_UNIT/cso-eval-producer")
cso_compile_watchdog "$CSO_EVALUATION_UNIT/gstack-cso-watchdog"
if [ "$(uname -s)" = Darwin ]; then
cso_sign_macos_artifact "$CSO_EVALUATION_UNIT/gstack-cso-core" 0
cso_sign_macos_artifact "$CSO_EVALUATION_UNIT/gstack-cso-watchdog" 0
fi
candidate_core_sha256="$(cso_sha256 "$CSO_EVALUATION_UNIT/gstack-cso-core")"
cso_compile_posix_launcher "$CSO_EVALUATION_UNIT/gstack-cso-launcher" "$candidate_core_sha256"
chmod +x "$CSO_EVALUATION_UNIT/gstack-cso-launcher"
if [ "$(uname -s)" = Darwin ];then cso_sign_macos_artifact "$CSO_EVALUATION_UNIT/gstack-cso-launcher" 1;fi
printf '%s\n' "$candidate_core_sha256" > "$CSO_EVALUATION_UNIT/.gstack-cso-generation"
printf '{"schemaVersion":1,"evaluationOnly":true,"runtimeCatalogRevision":"%s","runtimeCatalogSha256":"%s","coreSha256":"%s"}\n' \
"$candidate_revision" "$(cso_sha256 "$source_root/lib/cso/runtime-catalog.json")" "$candidate_core_sha256" \
> "$CSO_EVALUATION_UNIT/.gstack-cso-evaluation"
for artifact in gstack-cso-core gstack-cso-launcher gstack-cso-watchdog cso-eval-producer;do
cso_valid_artifact "$CSO_EVALUATION_UNIT/$artifact" || { echo "Evaluation $artifact is not one executable regular file." >&2;return 1; }
done
cso_valid_generation "$CSO_EVALUATION_UNIT/.gstack-cso-generation" || { echo 'Evaluation generation manifest is invalid.' >&2;return 1; }
[ "$(cso_sha256 "$CSO_EVALUATION_UNIT/gstack-cso-core")" = "$candidate_core_sha256" ] || { echo 'Evaluation core changed after launcher binding.' >&2;return 1; }
"$CSO_EVALUATION_UNIT/gstack-cso-launcher" --version >/dev/null
chmod 0555 "$CSO_EVALUATION_UNIT"/gstack-cso-core "$CSO_EVALUATION_UNIT"/gstack-cso-launcher "$CSO_EVALUATION_UNIT"/gstack-cso-watchdog "$CSO_EVALUATION_UNIT"/cso-eval-producer
chmod 0444 "$CSO_EVALUATION_UNIT/.gstack-cso-generation" "$CSO_EVALUATION_UNIT/.gstack-cso-evaluation"
chmod 0755 "$CSO_EVALUATION_UNIT"
mv "$CSO_EVALUATION_UNIT" "$candidate_output"
CSO_EVALUATION_UNIT=""
printf '{"output":"%s","revision":"%s","evaluationOnly":true}\n' "$candidate_output" "$candidate_revision"
}
cso_publish_locked() {
[ "${GSTACK_CSO_PUBLISH_LOCKED:-}" = 1 ] || { echo 'CSO publication requires the native publisher lock.' >&2;return 73; }
[ "$#" -eq 1 ] && [ -d "$1" ] && [ ! -L "$1" ] || { echo 'CSO publication stage is invalid.' >&2;return 69; }
CSO_STAGE="$(cd "$1" && pwd -P)"
case "$CSO_STAGE" in "$CSO_BUILD_ROOT"/bin/.gstack-cso-stage.*) ;; *) echo 'CSO publication stage escaped the trusted bin directory.' >&2;return 69;;esac
CSO_STAGE_CORE="$CSO_STAGE/gstack-cso-core$CSO_EXE"
CSO_STAGE_LAUNCHER="$CSO_STAGE/gstack-cso-launcher$CSO_EXE"
CSO_STAGE_WATCHDOG="$CSO_STAGE/gstack-cso-watchdog"
CSO_STAGE_GENERATION="$CSO_STAGE/.gstack-cso-generation"
cso_valid_artifact "$CSO_STAGE_CORE" || { echo 'Staged CSO core is not one executable regular file.' >&2;return 1; }
cso_valid_artifact "$CSO_STAGE_LAUNCHER" || { echo 'Staged CSO launcher is not one executable regular file.' >&2;return 1; }
if [ -z "$CSO_EXE" ];then cso_valid_artifact "$CSO_STAGE_WATCHDOG" || { echo 'Staged CSO watchdog is not one executable regular file.' >&2;return 1; };fi
cso_valid_generation "$CSO_STAGE_GENERATION"||{ echo 'Staged CSO generation manifest is invalid.' >&2;return 1; }
old_present=0
for artifact in "$CSO_FINAL_LAUNCHER" "$CSO_FINAL_CORE";do
if cso_present "$artifact";then cso_valid_artifact "$artifact" || { echo 'Existing CSO artifacts contain an unsafe file.' >&2;return 1; };old_present=$((old_present+1));fi
done
if [ -z "$CSO_EXE" ]&&cso_present "$CSO_FINAL_WATCHDOG";then cso_valid_artifact "$CSO_FINAL_WATCHDOG" || { echo 'Existing CSO artifacts contain an unsafe file.' >&2;return 1; };old_present=$((old_present+1));fi
if cso_present "$CSO_FINAL_GENERATION";then cso_valid_generation "$CSO_FINAL_GENERATION"||{ echo 'Existing CSO generation manifest is unsafe.' >&2;return 1; };old_present=$((old_present+1));fi
expected=3;[ -n "$CSO_EXE" ]||expected=4
if [ "$old_present" -eq "$expected" ];then CSO_OLD_COHERENT=1;fi
CSO_PUBLISHING=1
# Ignored signals remain ignored in mv children. SIGKILL is handled by the
# launcher-first withdrawal and launcher-last commit order.
trap '' HUP INT TERM
if cso_present "$CSO_FINAL_LAUNCHER";then
CSO_OLD_LAUNCHER_MOVED=1
cso_move "$CSO_FINAL_LAUNCHER" "$CSO_STAGE/previous/launcher"
cso_checkpoint withdraw-launcher
fi
if cso_present "$CSO_FINAL_CORE";then CSO_OLD_CORE_MOVED=1;cso_move "$CSO_FINAL_CORE" "$CSO_STAGE/previous/core";fi
if [ -z "$CSO_EXE" ]&&cso_present "$CSO_FINAL_WATCHDOG";then CSO_OLD_WATCHDOG_MOVED=1;cso_move "$CSO_FINAL_WATCHDOG" "$CSO_STAGE/previous/watchdog";fi
if cso_present "$CSO_FINAL_GENERATION";then CSO_OLD_GENERATION_MOVED=1;cso_move "$CSO_FINAL_GENERATION" "$CSO_STAGE/previous/generation";fi
CSO_NEW_CORE_INSTALLED=1
cso_move "$CSO_STAGE_CORE" "$CSO_FINAL_CORE"
cso_checkpoint publish-core
if [ -z "$CSO_EXE" ];then
CSO_NEW_WATCHDOG_INSTALLED=1
cso_move "$CSO_STAGE_WATCHDOG" "$CSO_FINAL_WATCHDOG"
cso_checkpoint publish-watchdog
fi
CSO_NEW_GENERATION_INSTALLED=1
cso_move "$CSO_STAGE_GENERATION" "$CSO_FINAL_GENERATION"
cso_checkpoint before-publish-launcher
CSO_NEW_LAUNCHER_INSTALLED=1
cso_move "$CSO_STAGE_LAUNCHER" "$CSO_FINAL_LAUNCHER"
cso_checkpoint publish-launcher
CSO_COMMITTED=1
}
cso_start_result() {
CSO_RESULT_RECORDING=1
CSO_RESULT_STAGE=$1
CSO_REVISION="$(head -1 "$CSO_BUILD_ROOT/VERSION" 2>/dev/null | tr -cd '0-9A-Za-z.+-')"
revision_sha="$(git -C "$CSO_BUILD_ROOT" rev-parse --short=12 HEAD 2>/dev/null | tr -cd '0-9a-f')"
CSO_REVISION="${CSO_REVISION:-unknown}${revision_sha:+ ($revision_sha)}"
CSO_PREVIOUS_INSTALLED="$(cso_record_field installed)"
}
if [ "${1:-}" = __publish_locked ];then
shift
cso_start_result publish
cso_publish_locked "$@"
exit 0
fi
if [ "${1:-}" = --evaluation-candidate ];then
cso_build_evaluation_candidate "$@"
exit 0
fi
[ "$#" -eq 0 ] || { echo 'Usage: build-cso.sh [--evaluation-candidate <cso-eval-catalog.json> --output <new-directory>]' >&2;exit 64; }
cso_start_result build
cso_write_result failed build interrupted
# Distribution builds embed only the committed catalog, never an evaluation one.
if [ -f lib/cso/runtime-catalog.json ] && grep -q '"revision": *"cso-eval-' lib/cso/runtime-catalog.json;then
echo 'lib/cso/runtime-catalog.json is an evaluation-only catalog; distribution builds refuse it. Restore the committed catalog.' >&2
exit 65
fi
# This entrypoint can be run directly. Once it may publish a CSO generation,
# the previous whole-build completion proof no longer describes all outputs.
rm -f "$CSO_BUILD_ROOT/browse/dist/.build-complete"
if ! command -v "$CSO_CC" >/dev/null 2>&1 && [ -z "$CSO_EXE" ]; then
echo 'CSO build requires a C compiler (cc/clang/gcc) for the trusted launcher and watchdog.' >&2
exit 1
fi
if [ "$(uname -s)" = Darwin ] && ! command -v codesign >/dev/null 2>&1; then
echo 'CSO build requires macOS codesign so staged artifacts can be verified before publication.' >&2
exit 1
fi
CSO_STAGE="$(mktemp -d "$CSO_BUILD_ROOT/bin/.gstack-cso-stage.XXXXXX")"
CSO_STAGE_CORE="$CSO_STAGE/gstack-cso-core$CSO_EXE"
CSO_STAGE_LAUNCHER="$CSO_STAGE/gstack-cso-launcher$CSO_EXE"
CSO_STAGE_WATCHDOG="$CSO_STAGE/gstack-cso-watchdog"
CSO_STAGE_GENERATION="$CSO_STAGE/.gstack-cso-generation"
CSO_STAGE_LOCKER="$CSO_STAGE/gstack-cso-publish-lock$CSO_EXE"
mkdir -m 700 "$CSO_STAGE/previous"
if [ -n "$CSO_EXE" ];then : > "$CSO_STAGE/.gstack-cso-generation.lock";fi
# These are compile-time switches. Bun otherwise discovers configuration in
# the audited working directory before the helper can apply its own policy.
cso_compile_bun lib/cso/cli.ts "$CSO_STAGE_CORE" lib/cso/search-worker.ts
cso_checkpoint core
# POSIX process groups are required by the detached watchdog. Windows keeps
# comprehensive execution unavailable instead of substituting a weaker timer.
if [ -z "$CSO_EXE" ]; then
cso_compile_watchdog "$CSO_STAGE_WATCHDOG"
cso_checkpoint watchdog
fi
if [ "$(uname -s)" = Darwin ]; then
cso_sign_macos_artifact "$CSO_STAGE_CORE" 0
cso_sign_macos_artifact "$CSO_STAGE_WATCHDOG" 0
fi
CSO_CORE_SHA256="$(cso_sha256 "$CSO_STAGE_CORE")"
printf '%s\n' "$CSO_CORE_SHA256" > "$CSO_STAGE_GENERATION"
if [ -n "$CSO_EXE" ];then
# PowerShell 7 first: Windows PowerShell 5.1 can crash outright (#3071).
CSO_POWERSHELL="$(command -v pwsh 2>/dev/null || command -v powershell.exe 2>/dev/null || true)"
if [ -z "$CSO_POWERSHELL" ]||! command -v cygpath >/dev/null 2>&1;then
echo 'CSO Windows build requires Git Bash and PowerShell (pwsh or Windows PowerShell) with MSVC Build Tools.' >&2;exit 1
fi
CSO_WINDOWS_GIT="$(type -P git 2>/dev/null || true)"
[ -n "$CSO_WINDOWS_GIT" ] && [ -f "$CSO_WINDOWS_GIT" ] || { echo 'CSO Windows build requires the Git for Windows git.exe selected by Git Bash.' >&2;exit 1; }
"$CSO_POWERSHELL" -NoProfile -NonInteractive -ExecutionPolicy Bypass \
-File "$(cygpath -w "$CSO_BUILD_ROOT/scripts/build-cso-windows.ps1")" \
-RepoRoot "$(cygpath -w "$CSO_BUILD_ROOT")" \
-OutputPath "$(cygpath -w "$CSO_STAGE_LAUNCHER")" \
-LockOutputPath "$(cygpath -w "$CSO_STAGE_LOCKER")" \
-CoreSha256 "$CSO_CORE_SHA256" \
-GitExePath "$(cygpath -aw "$CSO_WINDOWS_GIT")"
else
cso_compile_posix_launcher "$CSO_STAGE_LAUNCHER" "$CSO_CORE_SHA256"
"$CSO_CC" -std=c11 -D_POSIX_C_SOURCE=200809L -O2 -Wall -Wextra lib/cso/publish-lock.c -o "$CSO_STAGE_LOCKER"
fi
chmod +x "$CSO_STAGE_LAUNCHER" "$CSO_STAGE_LOCKER"
cso_checkpoint launcher
cso_checkpoint publish-lock
if [ "$(uname -s)" = Darwin ];then cso_sign_macos_artifact "$CSO_STAGE_LAUNCHER" 1;fi
cso_valid_artifact "$CSO_STAGE_CORE" || { echo 'Staged CSO core is not one executable regular file.' >&2; exit 1; }
cso_valid_artifact "$CSO_STAGE_LAUNCHER" || { echo 'Staged CSO launcher is not one executable regular file.' >&2; exit 1; }
cso_valid_artifact "$CSO_STAGE_LOCKER" || { echo 'Staged CSO publisher lock is not one executable regular file.' >&2; exit 1; }
if [ -z "$CSO_EXE" ]; then cso_valid_artifact "$CSO_STAGE_WATCHDOG" || { echo 'Staged CSO watchdog is not one executable regular file.' >&2; exit 1; }; fi
cso_valid_generation "$CSO_STAGE_GENERATION"||{ echo 'Staged CSO generation manifest is invalid.' >&2;exit 1; }
[ "$(cso_sha256 "$CSO_STAGE_CORE")" = "$CSO_CORE_SHA256" ] || { echo 'Staged CSO core changed after launcher binding.' >&2;exit 1; }
"$CSO_STAGE_LAUNCHER" --version >/dev/null
cso_checkpoint validated
if [ -n "$CSO_EXE" ];then
[ -f /usr/bin/bash.exe ] || { echo 'CSO publication requires the Git Bash executable.' >&2;exit 1; }
CSO_PUBLISH_SHELL="$(cygpath -aw /usr/bin/bash.exe)"
else
case "${BASH:-}" in /*) CSO_PUBLISH_SHELL=$BASH;; *) echo 'CSO publication requires an absolute Bash executable.' >&2;exit 1;;esac
fi
cso_valid_artifact "$CSO_STAGE_LOCKER" || { echo 'Staged CSO publisher lock is not one executable regular file.' >&2; exit 1; }
CSO_RESULT_STAGE=publish
cso_write_result failed publish interrupted
cso_checkpoint before-exec
# From here the locked child owns the stage: its own EXIT trap restores and
# cleans it. Git Bash's exec of a native program may not replace this shell,
# so this trap must not be armed under the running child (#3071). If the exec
# itself fails, clean up here.
set +e
shopt -s execfail
trap - EXIT
exec "$CSO_STAGE_LOCKER" "$CSO_BUILD_ROOT/bin" "$CSO_PUBLISH_SHELL" "$CSO_BUILD_ROOT/scripts/build-cso.sh" __publish_locked "$CSO_STAGE"
cso_exec_status=$?
echo "CSO publication could not start $CSO_STAGE_LOCKER (exit $cso_exec_status)." >&2
cso_cleanup "$cso_exec_status"
-21
View File
@@ -10,10 +10,6 @@ BUILD_STAMP="$ROOT/browse/dist/.build-complete"
BUILD_STAMP_TMP="$BUILD_STAMP.tmp.$$"
# Setup trusts this stamp as proof that the selected multi-binary build completed.
# CSO is optional: a failed CSO build or publish is reported and recorded in
# bin/.gstack-cso-build-result, and the rest of the build still completes (#3071).
# GSTACK_STRICT_BUILD=1 (CI) makes a CSO failure fatal. Setup may explicitly omit
# CSO after its host capability probe, while still publishing the general build.
# Invalidate before touching output so an interrupted build cannot hide staleness.
rm -f "$BUILD_STAMP" "$BUILD_STAMP_TMP"
@@ -55,23 +51,6 @@ fi
"$BUN_CMD" build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig design/src/cli.ts --outfile design/dist/design
"$BUN_CMD" build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig make-pdf/src/cli.ts --outfile make-pdf/dist/pdf
"$BUN_CMD" build --compile --no-compile-autoload-dotenv --no-compile-autoload-bunfig bin/gstack-global-discover.ts --outfile bin/gstack-global-discover
if [ "${GSTACK_SETUP_RUNNING:-0}" = "1" ] && [ "${GSTACK_SETUP_SKIP_CSO_BUILD:-0}" = "1" ]; then
# Setup removes these before invoking us too. Repeat here so the setup-private
# escape hatch can never publish a completion stamp beside stale trusted code.
rm -f bin/gstack-cso-launcher bin/gstack-cso-launcher.exe \
bin/gstack-cso-core bin/gstack-cso-core.exe bin/gstack-cso-watchdog \
bin/.gstack-cso-generation bin/.gstack-cso-generation.lock
else
CSO_BUILD_LOG_FILE="$ROOT/bin/.gstack-cso-build.log"
if ! (set -o pipefail; GSTACK_CSO_BUILD_LOG="$CSO_BUILD_LOG_FILE" BUN_CMD="$BUN_CMD" bash scripts/build-cso.sh 2>&1 | tee "$CSO_BUILD_LOG_FILE"); then
cso_stage="$(sed -n 's/^stage=//p' bin/.gstack-cso-build-result 2>/dev/null | head -1)"
if [ "${GSTACK_STRICT_BUILD:-0}" = "1" ]; then
echo "CSO ${cso_stage:-build} failed and GSTACK_STRICT_BUILD=1 makes it fatal. Log: $CSO_BUILD_LOG_FILE" >&2
exit 1
fi
echo "CSO unavailable: the ${cso_stage:-build} step failed; the rest of the build continues. Log: $CSO_BUILD_LOG_FILE. Retry: cd $ROOT && bun run build:cso" >&2
fi
fi
bash browse/scripts/build-node-server.sh
bash scripts/write-version-files.sh browse/dist/.version design/dist/.version make-pdf/dist/.version
chmod +x browse/dist/browse browse/dist/find-browse design/dist/design make-pdf/dist/pdf bin/gstack-global-discover
-69
View File
@@ -1,69 +0,0 @@
/** Redaction of the producer's provider output and error text before a receipt binds them. */
import { join } from 'node:path';
import { readBoundedStable } from '../lib/cso/bounded-file';
import { CsoError, MAX_OUTPUT } from '../lib/cso/contracts';
import { redactFindingSpans, scan } from '../lib/redact-engine';
/**
* Identifiers the CSO helper emits by schema, which the redactor's PII shapes misread: `<epoch ms>-<hex>` run and
* replay IDs and the 13-digit epoch in them (pii.phone.e164), `cso-eval-<runId>-<sha12>` catalog revisions,
* `<tool>-<hex16>-<hex16>` artifact IDs, and hex finding, review and content IDs (pii.wallet).
*/
const HELPER_ID = /(?<![A-Za-z0-9])(?:\d{13}-[a-f0-9]{16}|cso-eval-\d{1,20}-[a-f0-9]{12}|(?:[a-z]+-)+[a-f0-9]{16}-[a-f0-9]{16}|[a-f0-9]{16,64})(?![A-Za-z0-9])/g;
export interface OutputRedaction {
/** The text as a receipt may bind it. */
text: string;
/** Matched rule IDs with their counts, e.g. `pii.phone.e164×2`; never the matched text. */
rules: string[];
/** True when a credential-class (`secret`) rule matched: the text must be withheld, not span-redacted. */
secret: boolean;
}
const tally = (ids: string[]): string[] => {
const counts = new Map<string, number>();
for (const id of ids) counts.set(id, (counts.get(id) ?? 0) + 1);
return [...counts].sort(([left], [right]) => left < right ? -1 : 1).map(([id, count]) => `${id}×${count}`);
};
const ASSIGNMENT = /^\s*(?:export\s+)?[A-Za-z_][\w.-]*\s*[=:]\s*["']?([^\s"'#]{8,})/;
/**
* Values assigned to credential-shaped names (the env.kv rule) in the cell's verified source, such as a planted
* canary. Quoted without its name, such a value reads as prose to every rule, so the output check matches it exactly.
*/
export function sourceCredentialValues(root: string, paths: string[]): string[] {
const values = new Set<string>();
for (const path of paths) {
if (path === '.git' || path.startsWith('.git/')) continue;
const contents = readBoundedStable(join(root, ...path.split('/')), 2 * 1024 * 1024, 'Producer source file');
if (contents.includes(0)) continue;
const text = contents.toString('utf8'), lines = text.split('\n');
for (const finding of scan(text, { maxBytes: 2 * 1024 * 1024 }).findings) {
const value = finding.id === 'env.kv' ? ASSIGNMENT.exec(lines[finding.line - 1] ?? '')?.[1] : undefined;
if (value) values.add(value);
}
}
return [...values];
}
/**
* Credential classes are judged on the unmasked text, so masking can never hide one. Only when none matched are the
* helper's identifiers set aside and the remaining PII, internal, legal and hygiene spans replaced in place.
*/
export function redactProducerText(value: string, sourceCredentials: string[] = []): OutputRedaction {
const findings = scan(value, { maxBytes: MAX_OUTPUT });
if (findings.oversize) throw new CsoError('REDACTION_FAILED', 'Producer output withheld because it exceeds the redaction limit');
const secretIds = findings.findings.filter(finding => finding.category === 'secret').map(finding => finding.id);
for (const credential of sourceCredentials) secretIds.push(...Array(value.split(credential).length - 1).fill('source.env.kv'));
if (secretIds.length) return { text: '', rules: tally(secretIds), secret: true };
const identifiers: string[] = [];
const letters = (index: number): string => (index >= 26 ? letters(Math.floor(index / 26) - 1) : '') + String.fromCharCode(97 + (index % 26));
const masked = value.replace(HELPER_ID, match => `GSTACKHELPERID${letters(identifiers.push(match) - 1)}Z`);
const masking = scan(masked, { maxBytes: MAX_OUTPUT }).findings;
const redacted = redactFindingSpans(masked, { maxBytes: MAX_OUTPUT });
if (redacted === null) throw new CsoError('REDACTION_FAILED', 'Producer output withheld because redaction could not safely locate every span');
const indexOf = (code: string): number => [...code].reduce((total, char) => total * 26 + char.charCodeAt(0) - 96, 0) - 1;
const text = redacted.replace(/GSTACKHELPERID([a-z]+)Z/g, (whole, code: string) => identifiers[indexOf(code)] ?? whole);
return { text, rules: tally(masking.map(finding => finding.id)), secret: false };
}
-714
View File
@@ -1,714 +0,0 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/** Generic producer runner. Compile this file before moving it to a clean producer host. */
import * as fs from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { readBoundedStable } from '../lib/cso/bounded-file';
import { CsoError } from '../lib/cso/contracts';
import { EMPTY_GLOBAL_GIT_CONFIG, executable, redact } from '../lib/cso/process';
import { atomicWriteSync } from '../lib/fs-atomic';
import { redactProducerText, sourceCredentialValues, type OutputRedaction } from './cso-eval-output-redaction';
import { resolveClaudeCommand } from '../lib/claude-bin';
import runtimeCatalog from '../lib/cso/runtime-catalog.json';
import scannerCatalog from '../lib/cso/scanner-images/catalog.json';
import { ClaudeAdapter } from '../test/helpers/providers/claude';
import { GptAdapter } from '../test/helpers/providers/gpt';
import { GeminiAdapter, prepareGeminiProducerState, removeGeminiProducerState } from '../test/helpers/providers/gemini';
import { PRICING } from '../test/helpers/pricing';
import type { ProviderAdapter, RunOpts, RunResult } from '../test/helpers/providers/types';
import {
PRODUCER_PLATFORMS,
producerHostPlatform,
producerInputHash,
producerArtifactInventoryHash,
producerInstallationIdentityHash,
producerProviderIdentityHash,
producerReceiptHash,
sha256,
type ProducerExecution,
type ProducerHost,
type ProducerInput,
type ProducerArtifactInventory,
type ProducerInstallationIdentity,
type ProducerProviderIdentity,
type ProducerReceipt,
type ProducerSourceEntry,
} from './cso-eval-protocol';
const HEX = /^[a-f0-9]{64}$/;
const GENERATION_MANIFEST_BYTES = 65;
const INPUT_LIMIT = 4 * 1024 * 1024;
const OUTPUT_LIMIT = 32 * 1024 * 1024;
const ARTIFACT_FILE_LIMIT = 32 * 1024 * 1024;
const ARTIFACT_TOTAL_LIMIT = 128 * 1024 * 1024;
const ARTIFACT_COUNT_LIMIT = 4096;
/**
* `/cso --budget` bounds the helper run: it accepts evidence until its deadline (start + budget) and `finish` writes the
* report after it. A user's agent is never killed at the budget, so the provider gets the budget, the agent's time
* before `start`, and the reporting time after the deadline. Matches the evaluator's frozen `graceSeconds`.
*/
export const PRODUCER_REPORTING_GRACE_SECONDS = 300;
export function producerProviderTimeoutMs(budgetSeconds: number): number {
return (budgetSeconds + PRODUCER_REPORTING_GRACE_SECONDS) * 1000;
}
function inside(parent: string, child: string): boolean {
const path = relative(parent, child);
return path === '' || (!path.startsWith(`..${sep}`) && path !== '..' && !isAbsolute(path));
}
function sourceError(path: string, rule: string): Error {
return new Error(`INVALID_PRODUCER_SOURCE: ${JSON.stringify(path.length > 200 ? `${path.slice(0, 200)}...` : path)} ${rule}`);
}
function regularFile(path: string, relativePath: string): fs.Stats {
const stat = fs.lstatSync(path);
if (!stat.isFile() || stat.isSymbolicLink()) throw sourceError(relativePath, 'is not a regular file');
if (stat.nlink !== 1) throw sourceError(relativePath, `has ${stat.nlink} hard links; expected 1`);
return stat;
}
function safeDirectory(path: string): void {
const stat = fs.lstatSync(path);
if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(path) !== path) throw new Error('NON_ISOLATED_PRODUCER_LAYOUT');
}
function assertIsolatedLayout(controlPath: string, receiptPath: string): { jobRoot: string; sourceRoot: string } {
const jobRoot = dirname(controlPath), producerRoot = dirname(jobRoot), sourceRoot = join(jobRoot, 'source');
safeDirectory(producerRoot); safeDirectory(jobRoot); safeDirectory(sourceRoot);
if (basename(jobRoot) !== 'job' || basename(controlPath) !== 'producer-input.json') throw new Error('NON_ISOLATED_PRODUCER_LAYOUT');
if (JSON.stringify(fs.readdirSync(producerRoot).sort()) !== JSON.stringify(['job'])) throw new Error('NON_ISOLATED_PRODUCER_LAYOUT');
if (JSON.stringify(fs.readdirSync(jobRoot).sort()) !== JSON.stringify(['producer-input.json', 'source'])) throw new Error('NON_ISOLATED_PRODUCER_LAYOUT');
if (inside(producerRoot, receiptPath)) throw new Error('NON_ISOLATED_PRODUCER_LAYOUT');
return { jobRoot, sourceRoot };
}
function assertReceiptDestination(path: string): void {
const parent = dirname(path), stat = fs.lstatSync(parent);
if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(parent) !== parent || fs.existsSync(path)) throw new Error('UNSAFE_RECEIPT_DESTINATION');
}
function walk(root: string, directory = root): string[] {
const output: string[] = [];
for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
const full = join(directory, entry.name), relativePath = relative(root, full).split(sep).join('/');
if (directory === root && entry.name === '.git') {
if (!entry.isDirectory() || entry.isSymbolicLink() || fs.realpathSync(join(root, '.git')) !== join(root, '.git')) throw sourceError('.git', 'is not a real directory');
continue;
}
if (entry.isSymbolicLink()) throw sourceError(relativePath, 'is a symbolic link');
if (entry.isDirectory()) output.push(...walk(root, full));
else if (entry.isFile()) output.push(relativePath);
else throw sourceError(relativePath, 'is not a regular file or directory');
}
return output.sort();
}
function validateSource(root: string, entries: ProducerSourceEntry[], expectedHash: string): void {
const seen = new Set<string>();
for (const entry of entries) {
if (!entry || typeof entry.path !== 'string' || !entry.path || entry.path.includes('\\') || entry.path.startsWith('/') || entry.path.split('/').some(part => !part || part === '.' || part === '..') || seen.has(entry.path) || !HEX.test(entry.sha256) || !Number.isSafeInteger(entry.bytes) || entry.bytes < 0) throw new Error('INVALID_PRODUCER_INPUT');
seen.add(entry.path);
}
const actualPaths = walk(root), actual = new Set(actualPaths);
const expectedPaths = entries.map(entry => entry.path).sort(), expected = new Set(expectedPaths);
const firstMismatch = [
...actualPaths.filter(path => !expected.has(path)).map(path => [path, 'is not in the expected source listing']),
...expectedPaths.filter(path => !actual.has(path)).map(path => [path, 'is missing from the source']),
].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)[0];
if (firstMismatch) throw sourceError(firstMismatch[0], firstMismatch[1]);
const hashed: Array<[string, string]> = [];
for (const entry of [...entries].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)) {
const path = resolve(root, ...entry.path.split('/'));
if (!inside(root, path)) throw sourceError(entry.path, 'resolves outside the source root');
const stat = regularFile(path, entry.path);
const contents = readBoundedStable(path, 2 * 1024 * 1024, 'Producer source file');
if (stat.size !== entry.bytes || contents.byteLength !== entry.bytes) throw sourceError(entry.path, `is ${contents.byteLength} bytes; expected ${entry.bytes}`);
if (sha256(contents) !== entry.sha256) throw sourceError(entry.path, 'does not match its expected sha256');
hashed.push([entry.path, entry.sha256]);
}
if (sha256(JSON.stringify(hashed)) !== expectedHash) throw sourceError('.', 'listing does not match the cell sourceHash');
}
/** Seal the one-cell source copy before a provider starts. Production producers are macOS/Linux only. */
export function sealProducerSource(root: string): void {
if (process.platform === 'win32') return;
const directories: string[] = [];
const files: string[] = [];
const visit = (directory: string): void => {
const directoryStat = fs.lstatSync(directory);
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) throw sourceError(relative(root, directory) || '.', 'is not a real directory');
directories.push(directory);
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const full = join(directory, entry.name);
if (entry.isSymbolicLink()) throw sourceError(relative(root, full), 'is a symbolic link');
if (entry.isDirectory()) visit(full);
else if (entry.isFile()) files.push(full);
else throw sourceError(relative(root, full), 'is not a regular file or directory');
}
};
visit(root);
for (const file of files) fs.chmodSync(file, 0o444);
// Children first so traversal stays available while modes are changed.
for (const directory of directories.reverse()) fs.chmodSync(directory, 0o555);
assertProducerSourceSealed(root);
}
export function assertProducerSourceSealed(root: string): void {
if (process.platform === 'win32') return;
const visit = (directory: string): void => {
const modeError = (path: string, rule: string) => new Error(`PRODUCER_CHANGED_SOURCE_MODE: ${JSON.stringify(relative(root, path) || '.')} ${rule}`);
const directoryStat = fs.lstatSync(directory);
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) throw modeError(directory, 'is not a real directory');
if ((directoryStat.mode & 0o777) !== 0o555) throw modeError(directory, `has mode ${(directoryStat.mode & 0o777).toString(8)}; expected 555`);
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const full = join(directory, entry.name), stat = fs.lstatSync(full);
if (entry.isSymbolicLink()) throw modeError(full, 'is a symbolic link');
if (entry.isDirectory()) visit(full);
else if (!entry.isFile()) throw modeError(full, 'is not a regular file or directory');
else if ((stat.mode & 0o777) !== 0o444) throw modeError(full, `has mode ${(stat.mode & 0o777).toString(8)}; expected 444`);
}
};
visit(root);
}
function emptyArtifactInventory(): ProducerArtifactInventory {
const base = { schemaVersion: 1 as const, root: 'security/cso' as const, entries: [], totalBytes: 0 };
return { ...base, identityHash: producerArtifactInventoryHash(base) };
}
/** A whole path component that is one of the helper's own identifiers: `<epoch ms>-<hex>` run and replay IDs, retired runs, hex artifact IDs with an optional lowercase-word prefix (`gitleaks-<hex>-<hex>.json`), and dependency-closure files (`<finding id>-before|after-<plan hash>.json`). */
const HELPER_ID_COMPONENT = /^(?:\d{13}-[a-f0-9]{16}|\.retired-\d{13}-[a-f0-9]{16}-[a-f0-9]{32}|(?:[a-z]+-)*[a-f0-9]{16,64}(?:-[a-f0-9]{16})*(?:\.[a-z]+)?|(?:[a-f0-9]{32}){1,2}-(?:before|after)-[a-f0-9]{16}\.json)$/;
/**
* Helper artifact paths are `<repoId>/<runId>/...` plus the helper's public-cache/ and legacy-imports/. Components that
* are wholly a helper identifier are checked by shape, because the secret redactor reads them as data (a 13-digit epoch
* as a phone number, some 32-hex IDs as wallets). Every other component (fixed helper names, and source paths mirrored
* under snapshot/ and readable/) still goes through the redactor.
*/
export function assertProducerArtifactPath(relativePath: string): void {
const parts = relativePath.split('/');
const reject = (rule: string): never => { throw new Error(`INVALID_PRODUCER_ARTIFACTS: ${rule}`); };
if (!relativePath || relativePath.length > 1024) reject('an artifact path is empty or longer than 1024 bytes');
if (!/^[A-Za-z0-9._/-]+$/.test(relativePath) || parts.some(part => !part || part === '.' || part === '..')) reject('an artifact path has a component outside [A-Za-z0-9._-]');
const inRun = /^[a-f0-9]{24}$/.test(parts[0]) && /^(?:\d{13}-[a-f0-9]{16}|\.retired-\d{13}-[a-f0-9]{16}-[a-f0-9]{32})$/.test(parts[1] ?? '');
if (parts.length < 2 || !(inRun ? parts.length >= 3 : ['public-cache', 'legacy-imports'].includes(parts[0]))) reject('an artifact lies outside <repoId>/<runId>/, public-cache/ and legacy-imports/');
const schemaId = (part: string, index: number) => index === 0 ? /^[a-f0-9]{24}$/.test(part) : HELPER_ID_COMPONENT.test(part);
for (const [index, part] of parts.entries()) {
if (schemaId(part, index)) continue;
let clean: boolean;
try { clean = redact(part) === part; } catch { clean = false; }
if (!clean) {
const parent = parts.slice(0, index).map((item, at) => schemaId(item, at) ? 'ID' : item).join('/');
throw new CsoError('REDACTION_FAILED', `artifact path component ${index + 1} under ${JSON.stringify(parent)} looks like a secret; the component is withheld`);
}
}
}
export function inventoryProducerArtifacts(helperHome: string): ProducerArtifactInventory {
const security = join(helperHome, 'security'), artifactRoot = join(security, 'cso');
for (const directory of [security, artifactRoot]) {
let stat: fs.Stats;
try { stat = fs.lstatSync(directory); }
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return emptyArtifactInventory(); throw error; }
if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(directory) !== directory) throw new Error('INVALID_PRODUCER_ARTIFACTS');
}
const entries: ProducerSourceEntry[] = [];
let totalBytes = 0, visited = 0;
const visit = (directory: string, depth: number): void => {
if (depth > 32 || ++visited > ARTIFACT_COUNT_LIMIT * 2) throw new Error('INVALID_PRODUCER_ARTIFACTS');
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const full = join(directory, entry.name);
if (++visited > ARTIFACT_COUNT_LIMIT * 2) throw new Error('INVALID_PRODUCER_ARTIFACTS');
if (entry.isSymbolicLink()) throw new Error('INVALID_PRODUCER_ARTIFACTS');
if (entry.isDirectory()) { visit(full, depth + 1); continue; }
if (!entry.isFile() || entries.length >= ARTIFACT_COUNT_LIMIT) throw new Error('INVALID_PRODUCER_ARTIFACTS');
const relativePath = relative(artifactRoot, full).split(sep).join('/');
assertProducerArtifactPath(relativePath);
const contents = readBoundedStable(full, ARTIFACT_FILE_LIMIT, 'Producer artifact');
totalBytes += contents.byteLength;
if (totalBytes > ARTIFACT_TOTAL_LIMIT) throw new Error('PRODUCER_ARTIFACTS_TOO_LARGE');
entries.push({ path: relativePath, sha256: sha256(contents), bytes: contents.byteLength });
}
};
visit(artifactRoot, 0);
entries.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
const base = { schemaVersion: 1 as const, root: 'security/cso' as const, entries, totalBytes };
return { ...base, identityHash: producerArtifactInventoryHash(base) };
}
function repositoryIdentity(root: string): string {
const nullPath = process.platform === 'win32' ? 'NUL' : '/dev/null';
const env = { PATH: process.env.PATH ?? '', LANG: 'C', LC_ALL: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: EMPTY_GLOBAL_GIT_CONFIG, GIT_ATTR_NOSYSTEM: '1', GIT_OPTIONAL_LOCKS: '0' };
const git = executable('git');
const config = readBoundedStable(join(root, '.git', 'config'), 1024 * 1024, 'Producer Git configuration').toString('utf8');
if (/^\s*\[\s*include(?:if)?(?=[\s."\]])/im.test(config)) throw sourceError('.git/config', 'contains an include directive');
const common = ['-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false', '-c', `core.hooksPath=${nullPath}`, '-c', `core.attributesFile=${nullPath}`, '-c', `core.excludesFile=${nullPath}`, '-c', 'core.pager=cat', '-C', root];
const read = (args: string[]) => execFileSync(git, [...common, ...args], { env, encoding: 'utf8', timeout: 10_000, maxBuffer: 1024 * 1024 });
return sha256(JSON.stringify({ config: sha256(config), head: read(['rev-parse', '--verify', 'HEAD']).trim(), branch: read(['symbolic-ref', '--short', 'HEAD']).trim(), status: read(['status', '--porcelain=v2', '--untracked-files=all']) }));
}
const INPUT_FIELDS = 'cellRef,execution,schemaVersion,skill,source';
const EXECUTION_FIELDS = 'budgetSeconds,host,mode,model,skillHash,sourceHash';
/** The input has exactly the opaque fields: no case, variant, version, or repetition can ride along. */
function validateInput(input: ProducerInput): void {
const execution = input?.execution;
if (!input || typeof input !== 'object' || Object.keys(input).sort().join(',') !== INPUT_FIELDS || input.schemaVersion !== 2 || !HEX.test(input.cellRef) ||
typeof input.skill !== 'string' || Buffer.byteLength(input.skill) > INPUT_LIMIT || !Array.isArray(input.source) ||
!execution || typeof execution !== 'object' || Object.keys(execution).filter(key => key !== 'platform').sort().join(',') !== EXECUTION_FIELDS ||
!['daily', 'comprehensive'].includes(execution.mode) || typeof execution.model !== 'string' || !execution.model || !['claude', 'codex', 'gemini'].includes(execution.host) ||
!Number.isInteger(execution.budgetSeconds) || execution.budgetSeconds <= 60 || execution.budgetSeconds > 3600 || !HEX.test(execution.sourceHash) || !HEX.test(execution.skillHash) ||
('platform' in execution && !PRODUCER_PLATFORMS.includes(execution.platform!))) throw new Error('INVALID_PRODUCER_INPUT');
if (execution.platform !== undefined && execution.platform !== producerHostPlatform()) throw new Error('UNMATCHED_PRODUCER_PLATFORM');
}
export interface ProducerHelperBinding {
producer: string;
launcher: string;
core: string;
watchdog: string;
generation: string;
}
function boundExecutable(path: string): void {
const stat = fs.lstatSync(path);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || fs.realpathSync(path) !== path ||
(process.platform !== 'win32' && ((stat.mode & 0o111) === 0 || (stat.mode & 0o6000) !== 0))) throw new Error('INVALID_PRODUCER_HELPER');
}
function readGenerationManifest(path: string): string {
const bytes = readBoundedStable(path, GENERATION_MANIFEST_BYTES, 'Producer helper generation manifest');
const value = bytes.toString('utf8');
if (bytes.byteLength !== GENERATION_MANIFEST_BYTES || !/^[a-f0-9]{64}\n$/.test(value)) {
throw new Error('INVALID_PRODUCER_GENERATION');
}
return value.slice(0, -1);
}
function boundGenerationManifest(path: string): void {
const stat = fs.lstatSync(path);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || fs.realpathSync(path) !== path ||
stat.size !== GENERATION_MANIFEST_BYTES || (process.platform !== 'win32' && ((stat.mode & 0o444) === 0 || (stat.mode & 0o6111) !== 0))) {
throw new Error('INVALID_PRODUCER_HELPER');
}
readGenerationManifest(path);
}
function writableByProducer(path: string): boolean {
try { fs.accessSync(path, fs.constants.W_OK); return true; }
catch { return false; }
}
/** Production bundles must remain immutable to the unprivileged producing agent. */
export function validateProductionProducerInstallation(binding: ProducerHelperBinding, producerExecutable = process.execPath): void {
if (typeof process.getuid === 'function' && process.getuid() === 0) throw new Error('ROOT_PRODUCER_UNSUPPORTED');
if (producerExecutable !== binding.producer || !isAbsolute(producerExecutable) || resolve(producerExecutable) !== producerExecutable || dirname(producerExecutable) !== dirname(binding.launcher)) {
throw new Error('INVALID_PRODUCER_HELPER');
}
const executables = [producerExecutable, binding.launcher, binding.core, binding.watchdog];
for (const path of executables) boundExecutable(path);
boundGenerationManifest(binding.generation);
const files = [...executables, binding.generation];
const directories: string[] = [];
for (let current = dirname(producerExecutable);;) {
directories.push(current);
const parent = dirname(current);
if (parent === current) break;
current = parent;
}
for (const path of directories) {
const stat = fs.lstatSync(path);
if (!stat.isDirectory() || stat.isSymbolicLink() || fs.realpathSync(path) !== path) throw new Error('INVALID_PRODUCER_HELPER');
}
if ([...files, ...directories].some(writableByProducer)) throw new Error('WRITABLE_PRODUCER_INSTALLATION');
if (process.platform !== 'win32') {
for (const path of [...files, ...directories]) {
const stat = fs.lstatSync(path);
if (stat.uid !== 0 || (stat.mode & 0o022) !== 0) throw new Error('UNTRUSTED_PRODUCER_INSTALLATION');
}
}
}
export function resolveProducerHelperBinding(
sourceRoot: string,
stateRoot: string,
testLauncherPath?: string,
): ProducerHelperBinding {
if (process.platform === 'win32' && testLauncherPath === undefined) throw new Error('UNSUPPORTED_PRODUCER_PLATFORM');
const executableSuffix = process.platform === 'win32' ? '.exe' : '';
const launcher = testLauncherPath ?? join(dirname(process.execPath), `gstack-cso-launcher${executableSuffix}`);
if (!isAbsolute(launcher) || resolve(launcher) !== launcher || basename(launcher) !== `gstack-cso-launcher${executableSuffix}`) {
throw new Error('INVALID_PRODUCER_HELPER');
}
const directory = dirname(launcher);
if (inside(sourceRoot, directory) || inside(directory, sourceRoot) || inside(stateRoot, directory) || inside(directory, stateRoot)) {
throw new Error('INVALID_PRODUCER_HELPER');
}
const binding = {
producer: testLauncherPath === undefined ? process.execPath : join(dirname(launcher), `cso-eval-producer${executableSuffix}`),
launcher,
core: join(directory, `gstack-cso-core${executableSuffix}`),
watchdog: join(directory, `gstack-cso-watchdog${executableSuffix}`),
generation: join(directory, '.gstack-cso-generation'),
};
try {
boundExecutable(binding.producer);
boundExecutable(binding.launcher);
boundExecutable(binding.core);
boundExecutable(binding.watchdog);
boundGenerationManifest(binding.generation);
} catch {
throw new Error('INVALID_PRODUCER_HELPER');
}
// The explicit path exists solely for source-level unit tests. The production
// CLI has no override and enforces an unprivileged, nonwritable installation.
if (testLauncherPath === undefined) validateProductionProducerInstallation(binding);
return binding;
}
const PRODUCER_ARTIFACT_LIMIT = 512 * 1024 * 1024;
function artifactIdentity(path: string): { sha256: string; bytes: number } {
const named = fs.lstatSync(path);
if (!named.isFile() || named.isSymbolicLink() || named.nlink !== 1 || named.size <= 0 || named.size > PRODUCER_ARTIFACT_LIMIT) {
throw new Error('INVALID_PRODUCER_INSTALLATION');
}
let descriptor: number | undefined;
try {
descriptor = fs.openSync(path, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
const opened = fs.fstatSync(descriptor);
if (!opened.isFile() || opened.nlink !== 1 || opened.dev !== named.dev || opened.ino !== named.ino || opened.mode !== named.mode || opened.size !== named.size) {
throw new Error('PRODUCER_INSTALLATION_RACE');
}
const hash = createHash('sha256'), buffer = Buffer.allocUnsafe(1024 * 1024);
let bytes = 0;
for (;;) {
const count = fs.readSync(descriptor, buffer, 0, buffer.length, null);
if (count === 0) break;
bytes += count;
if (bytes > PRODUCER_ARTIFACT_LIMIT) throw new Error('INVALID_PRODUCER_INSTALLATION');
hash.update(buffer.subarray(0, count));
}
const after = fs.fstatSync(descriptor), current = fs.lstatSync(path);
if (bytes !== opened.size || !current.isFile() || current.isSymbolicLink() || current.nlink !== 1 || current.dev !== opened.dev || current.ino !== opened.ino || current.mode !== opened.mode || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs) {
throw new Error('PRODUCER_INSTALLATION_RACE');
}
return { sha256: hash.digest('hex'), bytes };
} finally {
if (descriptor !== undefined) fs.closeSync(descriptor);
}
}
function generationIdentity(path: string, core: { sha256: string; bytes: number }): ProducerInstallationIdentity['generation'] {
const manifest = artifactIdentity(path);
const coreSha256 = readGenerationManifest(path);
if (manifest.bytes !== GENERATION_MANIFEST_BYTES || manifest.sha256 !== sha256(`${coreSha256}\n`)) {
throw new Error('PRODUCER_INSTALLATION_RACE');
}
if (coreSha256 !== core.sha256) throw new Error('PRODUCER_HELPER_GENERATION_MISMATCH');
return { coreSha256, manifest };
}
export function producerInstallationIdentity(binding: ProducerHelperBinding): ProducerInstallationIdentity {
const core = artifactIdentity(binding.core);
const withoutHash: Omit<ProducerInstallationIdentity, 'identityHash'> = {
schemaVersion: 1,
producer: artifactIdentity(binding.producer),
launcher: artifactIdentity(binding.launcher),
core,
watchdog: artifactIdentity(binding.watchdog),
generation: generationIdentity(binding.generation, core),
embeddedCatalogs: {
runtimeRevision: runtimeCatalog.revision,
runtimeBuildRevision: runtimeCatalog.buildRevision,
runtimeSha256: sha256(JSON.stringify(runtimeCatalog)),
scannerRevision: scannerCatalog.revision,
scannerSha256: sha256(JSON.stringify(scannerCatalog)),
},
};
return { ...withoutHash, identityHash: producerInstallationIdentityHash(withoutHash) };
}
export const PRODUCER_PROVIDER_POLICY: Record<ProducerHost, { family: ProducerProviderIdentity['family']; policyRevision: string; version: string }> = {
claude: { family: 'claude', policyRevision: 'claude-2.1.263-cso-v2', version: '2.1.263 (Claude Code)' },
codex: { family: 'gpt', policyRevision: 'codex-0.153.4-cso-v3-generation', version: 'codex-cli 0.153.4' },
gemini: { family: 'gemini', policyRevision: 'gemini-0.59.0-cso-v1', version: '0.59.0' },
};
function validateProviderIdentity(identity: ProducerProviderIdentity, family: ProducerProviderIdentity['family']): ProducerProviderIdentity {
if (!identity || identity.schemaVersion !== 1 || identity.family !== family || !identity.policyRevision || !identity.version ||
!Array.isArray(identity.argsPrefix) || identity.argsPrefix.some(value => typeof value !== 'string' || value.includes('\0')) ||
!identity.executable || !HEX.test(identity.executable.sha256) || !Number.isSafeInteger(identity.executable.bytes) || identity.executable.bytes <= 0 ||
!HEX.test(identity.identityHash)) throw new Error('INVALID_PRODUCER_PROVIDER_IDENTITY');
const { identityHash, ...withoutHash } = identity;
if (producerProviderIdentityHash(withoutHash) !== identityHash) throw new Error('INVALID_PRODUCER_PROVIDER_IDENTITY');
return identity;
}
export interface ProducerProviderResolution {
identity: ProducerProviderIdentity;
command: { executable: string; argsPrefix: string[] };
}
export function resolveProducerProviderIdentity(host: ProducerHost, stateRoot: string): ProducerProviderResolution {
const policy = PRODUCER_PROVIDER_POLICY[host];
const resolved = host === 'claude'
? resolveClaudeCommand()
: { command: executable(host === 'codex' ? 'codex' : 'gemini'), argsPrefix: [] as string[] };
if (!resolved) throw new Error('PRODUCER_UNAVAILABLE: provider CLI not found');
const command = fs.realpathSync(resolved.command);
const versionOutput = execFileSync(resolved.command, [...resolved.argsPrefix, '--version'], {
cwd: dirname(command),
env: { PATH: process.env.PATH ?? '', HOME: stateRoot, LANG: 'C', LC_ALL: 'C', TZ: 'UTC' },
encoding: 'utf8', timeout: 10_000, maxBuffer: 64 * 1024,
}).trim();
if (policy.version !== versionOutput || redact(versionOutput) !== versionOutput) throw new Error('UNQUALIFIED_PRODUCER_PROVIDER_VERSION');
const withoutHash: Omit<ProducerProviderIdentity, 'identityHash'> = {
schemaVersion: 1,
family: policy.family,
policyRevision: policy.policyRevision,
executable: artifactIdentity(command),
argsPrefix: [...resolved.argsPrefix],
version: versionOutput,
};
return {
identity: { ...withoutHash, identityHash: producerProviderIdentityHash(withoutHash) },
command: { executable: command, argsPrefix: [...resolved.argsPrefix] },
};
}
function promptFor(cell: ProducerExecution, skill: string, sourceRoot: string, helper: ProducerHelperBinding): string {
const invocation = `/cso${cell.mode === 'comprehensive' ? ' --comprehensive' : ''} --budget ${cell.budgetSeconds}`;
const sourceAccess = cell.host === 'codex'
? 'The Codex permission profile grants read-only access to exactly that immutable snapshot so the trusted helper can read it. Use only the trusted helper to inspect or act on source; direct provider file or shell access is outside this evaluation policy.'
: 'The application snapshot is available to the producing agent only through the trusted helper.';
const sourceLocation = `The neutral current working directory contains no application source. The application repository at ${sourceRoot} is your entire source scope. ${sourceAccess}`;
return `You are the producing agent in a matched security evaluation. ${sourceLocation} The only trusted gstack-cso for this run is the absolute launcher path ${JSON.stringify(helper.launcher)}. Interpret every \`gstack-cso\` command in the skill as that exact path; do not discover or invoke another helper through PATH. Do not inspect parent directories, process metadata, evaluation control files, sibling jobs, alternative source variants, expected labels, or evaluator assertions. Follow the exact CSO skill instructions below and perform this invocation: ${invocation}\n\nDo not ask questions. Leave the application branch unchanged. End with the normal CSO report. Producer statements are claims that an independent evaluator will challenge; never infer private assertions or call a result tested without the helper evidence required by the skill.\n\n<exact-cso-skill sha256="${cell.skillHash}">\n${skill}\n</exact-cso-skill>\n`;
}
export function adapterFor(host: ProducerHost): ProviderAdapter {
return host === 'claude' ? new ClaudeAdapter() : host === 'codex' ? new GptAdapter() : new GeminiAdapter();
}
function writeExclusiveAtomic(path: string, value: unknown): void {
const parent = dirname(path);
const stat = fs.lstatSync(parent);
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('UNSAFE_RECEIPT_DESTINATION');
try { atomicWriteSync(path, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, noReplace: true }); }
catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new Error('RECEIPT_EXISTS'); throw error; }
}
/**
* Redact both channels, and both concatenation orders, before a receipt can bind them. A credential-class match
* anywhere withholds the output and fails the run, naming the rules. PII, internal, legal and hygiene matches are
* replaced in place and leave the run's status alone: scoring reads the helper's report, the evaluator scans the
* receipt for its canaries separately, and the helper's own identifiers are not personal data. `sourceCredentials` are
* the source's credential-name values (see sourceCredentialValues), matched exactly because no rule sees them bare.
*/
export function sanitizeProducerRun(run: RunResult, sourceCredentials: string[] = []): RunResult {
if (typeof run.output !== 'string' || (run.error && typeof run.error.reason !== 'string')) {
throw new CsoError('REDACTION_FAILED', 'Producer output withheld because it was not valid text');
}
const reason = run.error?.reason ?? '';
let views: OutputRedaction[];
try {
views = [run.output, reason, run.output + reason, reason + run.output].map(view => redactProducerText(view, sourceCredentials));
} catch {
throw new CsoError('REDACTION_FAILED', 'Producer output withheld because redaction could not safely inspect it');
}
const secret = views.find(view => view.secret);
if (secret) {
return {
...run,
output: '[sensitive producer output redacted]',
error: { code: run.error?.code ?? 'unknown', reason: `Sensitive producer output or error withheld: credential-class rule ${secret.rules.join(', ')}` },
};
}
const [output, error] = views;
return { ...run, output: output.text, ...(run.error ? { error: { ...run.error, reason: error.text } } : {}) };
}
export function producerFailureMessage(error: unknown): string {
if (error instanceof CsoError && error.code === 'REDACTION_FAILED') return 'REDACTION_FAILED: producer payload withheld';
const message = error instanceof Error ? error.message : 'CSO producer failed';
try { return redact(message); }
catch { return 'REDACTION_FAILED: producer error withheld'; }
}
/** A post-run check failed: the receipt records it as a failed cell with no output or artifacts, keeping the run's usage. */
export function producerIntegrityFailure(error: unknown): { code: string; reason: string } {
if (error instanceof CsoError) {
let reason: string;
try { reason = redact(error.message); } catch { reason = 'detail withheld'; }
return { code: error.code, reason };
}
const message = producerFailureMessage(error);
const named = error instanceof Error && !(error as NodeJS.ErrnoException).code ? /^([A-Z][A-Z0-9_]+)(?::\s*([\s\S]*))?$/.exec(message) : null;
return named ? { code: named[1], reason: named[2] || named[1] } : { code: 'PRODUCER_POST_RUN_CHECK_FAILED', reason: message };
}
export async function runProducerCell(inputPath: string, receiptPath: string, options: {
adapter?: ProviderAdapter;
paidExecutionAuthorized: boolean;
/** Unit tests run this source file through Bun; production always uses the adjacent compiled bundle. */
testHelperLauncherPath?: string;
/** Unit tests never execute a provider CLI; production always measures the reviewed binary. */
testProviderIdentity?: ProducerProviderIdentity;
/** Test-only exact command paired with testProviderIdentity. */
testProviderCommand?: { executable: string; argsPrefix: string[] };
}): Promise<ProducerReceipt> {
if (!options.paidExecutionAuthorized) throw new Error('PAID_EXECUTION_NOT_AUTHORIZED');
const controlPath = resolve(inputPath);
const receipt = resolve(receiptPath);
const { jobRoot, sourceRoot } = assertIsolatedLayout(controlPath, receipt);
assertReceiptDestination(receipt);
const bytes = readBoundedStable(controlPath, INPUT_LIMIT, 'Producer input');
let input: ProducerInput;
try { input = JSON.parse(bytes.toString('utf8')); } catch { throw new Error('INVALID_PRODUCER_INPUT'); }
validateInput(input);
const cell = input.execution;
if (basename(receipt) !== `${input.cellRef}.json`) throw new Error('UNMATCHED_RECEIPT_DESTINATION');
if (sha256(input.skill) !== cell.skillHash) throw new Error('INVALID_PRODUCER_SKILL');
validateSource(sourceRoot, input.source, cell.sourceHash);
sealProducerSource(sourceRoot);
validateSource(sourceRoot, input.source, cell.sourceHash);
const sourceCredentials = sourceCredentialValues(sourceRoot, input.source.map(entry => entry.path));
const originalRepositoryIdentity = repositoryIdentity(sourceRoot);
const stateRoot = join(jobRoot, 'state');
const helperHome = join(stateRoot, 'cso-home');
const helper = resolveProducerHelperBinding(sourceRoot, stateRoot, options.testHelperLauncherPath);
const installationIdentity = producerInstallationIdentity(helper);
const adapter = options.adapter ?? adapterFor(cell.host);
if ((cell.host === 'codex' ? 'gpt' : cell.host) !== adapter.family) throw new Error('UNMATCHED_PRODUCER_ADAPTER');
fs.mkdirSync(stateRoot, { recursive: false, mode: 0o700 });
fs.mkdirSync(helperHome, { recursive: false, mode: 0o700 });
const provider = options.testProviderIdentity
? {
identity: validateProviderIdentity(options.testProviderIdentity, adapter.family),
command: options.testProviderCommand ?? { executable: process.execPath, argsPrefix: [] },
}
: resolveProducerProviderIdentity(cell.host, stateRoot);
const providerIdentity = provider.identity;
const runOptions = {
prompt: promptFor(cell, input.skill, sourceRoot, helper),
workdir: stateRoot,
timeoutMs: producerProviderTimeoutMs(cell.budgetSeconds),
model: cell.model,
csoProducer: {
stateDirectory: stateRoot,
sourceDirectory: sourceRoot,
helperLauncher: helper.launcher,
helperGeneration: helper.generation,
providerCommand: provider.command,
},
} satisfies RunOpts;
const availability = await adapter.available(runOptions);
if (!availability.ok) throw new Error(`PRODUCER_UNAVAILABLE: ${availability.reason ?? cell.host}`);
const inputHash = producerInputHash(input);
// Load the opaque metadata into memory, then remove it before starting the
// agent. A clean producer host exposes only source + installed product bits.
fs.unlinkSync(controlPath);
const previousHome = process.env.GSTACK_HOME;
const previousSessionKind = process.env.GSTACK_SESSION_KIND;
const previousHeadless = process.env.GSTACK_HEADLESS;
process.env.GSTACK_HOME = helperHome;
process.env.GSTACK_SESSION_KIND = 'spawned';
process.env.GSTACK_HEADLESS = '1';
const startedAt = new Date().toISOString();
let run: RunResult;
try {
if (cell.host === 'gemini') prepareGeminiProducerState(stateRoot, helper.launcher);
run = await adapter.run(runOptions);
} finally {
try {
if (cell.host === 'gemini') removeGeminiProducerState(stateRoot);
} finally {
if (previousHome === undefined) delete process.env.GSTACK_HOME; else process.env.GSTACK_HOME = previousHome;
if (previousSessionKind === undefined) delete process.env.GSTACK_SESSION_KIND; else process.env.GSTACK_SESSION_KIND = previousSessionKind;
if (previousHeadless === undefined) delete process.env.GSTACK_HEADLESS; else process.env.GSTACK_HEADLESS = previousHeadless;
}
}
const finishedAt = new Date().toISOString();
let artifacts = emptyArtifactInventory();
let integrityFailure: { code: string; reason: string } | undefined;
let check = '';
try {
check = 'helper installation';
const installationAfter = producerInstallationIdentity(helper);
if (installationAfter.identityHash !== installationIdentity.identityHash) {
throw new Error('PRODUCER_HELPER_GENERATION_CHANGED: installed helper identity changed during the run');
}
check = 'provider installation';
const providerAfter = artifactIdentity(provider.command.executable);
if (providerAfter.sha256 !== providerIdentity.executable.sha256 || providerAfter.bytes !== providerIdentity.executable.bytes) {
throw new Error('PRODUCER_PROVIDER_INSTALLATION_RACE: provider executable changed during the run');
}
check = 'source modes';
assertProducerSourceSealed(sourceRoot);
check = 'source content';
validateSource(sourceRoot, input.source, cell.sourceHash);
check = 'source Git state';
if (repositoryIdentity(sourceRoot) !== originalRepositoryIdentity) throw new Error('PRODUCER_CHANGED_SOURCE: Git HEAD, branch, config or status changed during the run');
check = 'artifact inventory';
artifacts = inventoryProducerArtifacts(helperHome);
check = 'output size';
const outputBytes = typeof run.output === 'string' ? Buffer.byteLength(run.output) : 0;
if (outputBytes > OUTPUT_LIMIT) throw new Error(`PRODUCER_OUTPUT_TOO_LARGE: output is ${outputBytes} bytes; the limit is ${OUTPUT_LIMIT}`);
} catch (error) {
const failure = producerIntegrityFailure(error);
integrityFailure = { code: failure.code, reason: `${check} check: ${failure.reason}${run.error ? `; the provider run also failed (${run.error.code})` : ''}` };
artifacts = emptyArtifactInventory();
}
if (!integrityFailure) {
run = sanitizeProducerRun(run, sourceCredentials);
if(!run.error&&!run.output.trim())run={...run,error:{code:'unknown',reason:'empty output from provider CLI (exit 0)'}};
}
const tokensReported = run.tokens.input > 0 || run.tokens.output > 0 || (run.tokens.cached ?? 0) > 0;
const estimatedCostUSD = tokensReported && PRICING[run.modelUsed] ? adapter.estimateCost(run.tokens, run.modelUsed) : null;
const failure = integrityFailure ?? run.error, output = integrityFailure ? '' : run.output;
const withoutHash: Omit<ProducerReceipt, 'receiptHash'> = {
schemaVersion: 2,
cellRef: input.cellRef,
inputHash,
installationIdentity,
providerIdentity,
artifacts,
startedAt,
finishedAt,
status: failure ? 'failed' : 'succeeded',
requestedModel: cell.model,
modelUsed: run.modelUsed,
modelIdentitySource: run.modelUsed === cell.model ? 'requested_pin' : 'provider_reported',
durationMs: run.durationMs,
firstUsefulResultMs: null,
toolCalls: run.toolCalls,
...(run.toolTimeline ? { toolTimeline: run.toolTimeline } : {}),
output,
outputHash: sha256(output),
usage: {
inputTokens: tokensReported ? run.tokens.input : null,
outputTokens: tokensReported ? run.tokens.output : null,
cachedTokens: tokensReported && run.tokens.cached !== undefined ? run.tokens.cached : null,
estimatedCostUSD,
},
...(failure ? { error: failure } : {}),
};
const result = { ...withoutHash, receiptHash: producerReceiptHash(withoutHash) };
writeExclusiveAtomic(receipt, result);
return result;
}
async function cli(args: string[]): Promise<void> {
if (args.length !== 4 || args[0] !== 'run' || args[3] !== '--execute-paid') throw new Error('Usage: cso-eval-producer run <consumable-input.json> <new-receipt.json> --execute-paid');
if (process.env.CSO_EVAL_PAID !== '1') throw new Error('PAID_EXECUTION_NOT_AUTHORIZED: also set CSO_EVAL_PAID=1 on the isolated producer host');
const receipt = await runProducerCell(args[1], args[2], { paidExecutionAuthorized: true });
console.log(JSON.stringify({ cellRef: receipt.cellRef, status: receipt.status, durationMs: receipt.durationMs, receiptHash: receipt.receiptHash }));
}
if (import.meta.main) {
cli(process.argv.slice(2)).catch(error => { console.error(producerFailureMessage(error)); process.exitCode = 1; });
}
-189
View File
@@ -1,189 +0,0 @@
import { createHash } from 'node:crypto';
export type ProducerHost = 'claude' | 'codex' | 'gemini';
export type ProducerVersion = 'v2' | 'v3';
export type ProducerMode = 'daily' | 'comprehensive';
export type ProducerStack = 'node' | 'bun' | 'python' | 'rails';
export type ProducerVariant = 'vulnerable' | 'fixed';
export type ProducerPlatform = 'linux/amd64' | 'linux/arm64';
export const PRODUCER_PLATFORMS: readonly ProducerPlatform[] = ['linux/amd64', 'linux/arm64'];
export interface ProducerCell {
id: string;
caseId: string;
stack: ProducerStack;
variant: ProducerVariant;
version: ProducerVersion;
mode: ProducerMode;
repetition: 1 | 2 | 3;
model: string;
host: ProducerHost;
budgetSeconds: number;
sourceHash: string;
skillHash: string;
/** Release and baseline cells pin the native producer platform; full-profile cells omit it. */
platform?: ProducerPlatform;
}
export interface ProducerSourceEntry {
path: string;
sha256: string;
bytes: number;
}
/**
* Only what a producer needs to run one cell. It never names the corpus case,
* variant, version, or repetition: an agent that can read its own control file
* or receipt still cannot tell which answer it is being graded against.
*/
export interface ProducerExecution {
mode: ProducerMode;
model: string;
host: ProducerHost;
budgetSeconds: number;
sourceHash: string;
skillHash: string;
platform?: ProducerPlatform;
}
/**
* This control file is consumed before a producing agent starts. It must never
* be placed inside the application repository or retained on the producer.
*/
export interface ProducerInput {
schemaVersion: 2;
/** The opaque matrix cell id; only the trusted evaluator maps it back to a cell. */
cellRef: string;
/** Exact canonical portable payload: root SKILL.md plus its manifest-listed sections. */
skill: string;
source: ProducerSourceEntry[];
execution: ProducerExecution;
}
export function producerExecution(cell: ProducerCell): ProducerExecution {
return {
mode: cell.mode, model: cell.model, host: cell.host, budgetSeconds: cell.budgetSeconds,
sourceHash: cell.sourceHash, skillHash: cell.skillHash, ...(cell.platform === undefined ? {} : { platform: cell.platform }),
};
}
export interface ProducerArtifactIdentity {
sha256: string;
bytes: number;
}
export interface ProducerInstallationIdentity {
schemaVersion: 1;
producer: ProducerArtifactIdentity;
launcher: ProducerArtifactIdentity;
core: ProducerArtifactIdentity;
watchdog: ProducerArtifactIdentity;
/** The adjacent manifest is exactly `<coreSha256>\n`; bind both its bytes and declaration. */
generation: {
coreSha256: string;
manifest: ProducerArtifactIdentity;
};
embeddedCatalogs: {
runtimeRevision: string;
runtimeBuildRevision: string;
runtimeSha256: string;
scannerRevision: string;
scannerSha256: string;
};
identityHash: string;
}
export interface ProducerProviderIdentity {
schemaVersion: 1;
family: 'claude' | 'gpt' | 'gemini';
policyRevision: string;
executable: ProducerArtifactIdentity;
argsPrefix: string[];
version: string;
identityHash: string;
}
export interface ProducerArtifactInventory {
schemaVersion: 1;
root: 'security/cso';
/** Sorted safe paths relative to root within the retained helper home. */
entries: ProducerSourceEntry[];
totalBytes: number;
identityHash: string;
}
export interface ProducerReceipt {
schemaVersion: 2;
/** The opaque cell id from the consumed input; bound together with inputHash. */
cellRef: string;
inputHash: string;
installationIdentity: ProducerInstallationIdentity;
providerIdentity: ProducerProviderIdentity;
artifacts: ProducerArtifactInventory;
startedAt: string;
finishedAt: string;
status: 'succeeded' | 'failed';
requestedModel: string;
modelUsed: string;
/** Provider-reported when it differs; otherwise the exact CLI model pin. */
modelIdentitySource: 'provider_reported' | 'requested_pin';
durationMs: number;
firstUsefulResultMs: null;
toolCalls: number;
/** Content-free tool timeline (name, offset, thread) for diagnosing overruns; absent when the adapter has none. */
toolTimeline?: Array<{ atMs: number; endMs?: number; tool: string; agent: 'main' | 'subagent' }>;
output: string;
outputHash: string;
usage: {
/** CLI/provider-reported tokens. Null means the adapter did not report usage. */
inputTokens: number | null;
outputTokens: number | null;
cachedTokens: number | null;
/** Pricing-table estimate, not a host-billed amount. */
estimatedCostUSD: number | null;
};
error?: { code: string; reason: string };
receiptHash: string;
}
/**
* Compact trusted index; raw output remains in the separately retained receipt.
* Collection adds the matrix cell that the receipt's cellRef names.
*/
export type ProducerReceiptIndex = Omit<ProducerReceipt, 'output' | 'error' | 'toolTimeline'> & {
cell: ProducerCell;
error?: { code: string };
};
export const sha256 = (value: string | Buffer): string => createHash('sha256').update(value).digest('hex');
/** The native platform this producer process runs on, or null when no CSO runtime platform matches it. */
export function producerHostPlatform(platform: string = process.platform, arch: string = process.arch): ProducerPlatform | null {
if (platform !== 'linux') return null;
return arch === 'x64' ? 'linux/amd64' : arch === 'arm64' ? 'linux/arm64' : null;
}
export function producerInputHash(input: ProducerInput): string {
return sha256(JSON.stringify(input));
}
export function producerReceiptHash(receipt: Omit<ProducerReceipt, 'receiptHash'>): string {
return sha256(JSON.stringify(receipt));
}
export function producerInstallationIdentityHash(identity: Omit<ProducerInstallationIdentity, 'identityHash'>): string {
if (!identity.generation || !identity.generation.manifest || identity.generation.coreSha256 !== identity.core.sha256 ||
identity.generation.manifest.bytes !== 65 ||
identity.generation.manifest.sha256 !== sha256(`${identity.generation.coreSha256}\n`)) {
throw new Error('INVALID_PRODUCER_GENERATION_IDENTITY');
}
return sha256(JSON.stringify(identity));
}
export function producerProviderIdentityHash(identity: Omit<ProducerProviderIdentity, 'identityHash'>): string {
return sha256(JSON.stringify(identity));
}
export function producerArtifactInventoryHash(inventory: Omit<ProducerArtifactInventory, 'identityHash'>): string {
return sha256(JSON.stringify(inventory));
}
-161
View File
@@ -1,161 +0,0 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/** Trusted CI input validation. Qualification evidence is handled separately. */
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
export const CSO_RUNTIME_PLATFORMS = ['linux/amd64', 'linux/arm64'] as const;
export const CSO_RUNTIME_STACKS = ['node', 'bun', 'python', 'rails', 'postgresql'] as const;
export type CsoRuntimeBuildPlatform = typeof CSO_RUNTIME_PLATFORMS[number];
export type CsoRuntimeBuildStack = typeof CSO_RUNTIME_STACKS[number];
const IMAGE = /^[a-z0-9.-]+(?::[0-9]+)?\/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/;
const TAGGED_IMAGE = /^[a-z0-9.-]+(?::[0-9]+)?\/[a-z0-9][a-z0-9._/-]*:[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
const RELEASE_TAG = /:v?\d+\.\d+\.\d+(?:[._-][A-Za-z0-9._-]*)?$/;
const TWO_PART_RELEASE_TAG = /:v?\d+\.\d+(?:\.\d+)?(?:[._-][A-Za-z0-9._-]*)?$/;
const REVISION = /^[a-z0-9][a-z0-9._-]{0,100}$/;
const REQUIRED_VERSIONS: Record<CsoRuntimeBuildStack, string[]> = {
node: ['node', 'npm', 'cso-preparation'],
// oven/bun exposes a Bun-backed `node` fallback, not a real Node release.
// Recording a Node version here would make package engine admission unsound.
bun: ['bun', 'cso-preparation'],
python: ['python', 'uv', 'cso-preparation'],
rails: ['ruby', 'bundler', 'cso-preparation'],
postgresql: ['postgresql'],
};
export interface ImageBuildRow {
inputRevision: string;
profileId: string;
runtimeId: string;
stack: CsoRuntimeBuildStack;
platform: CsoRuntimeBuildPlatform;
arch: 'amd64' | 'arm64';
runner: 'ubuntu-24.04' | 'ubuntu-24.04-arm';
baseSource: string;
baseIndexImage: string;
baseImage: string;
uvSource: string;
uvIndexImage: string;
uvImage: string;
sbomGeneratorSource: string;
sbomGeneratorIndexImage: string;
sbomGeneratorImage: string;
versions: Record<string, string>;
}
function record(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
function repositoryOfPinned(image: string): string {
return image.slice(0, image.lastIndexOf('@'));
}
function repositoryOfTag(image: string): string {
const slash = image.lastIndexOf('/');
const colon = image.lastIndexOf(':');
if (colon <= slash) throw new Error('INVALID_SOURCE_REFERENCE');
return image.slice(0, colon);
}
function assertPinnedFamily(source: unknown, indexImage: unknown, images: unknown, label: string, releaseTag = RELEASE_TAG): Record<CsoRuntimeBuildPlatform, string> {
if (typeof source !== 'string' || !TAGGED_IMAGE.test(source)) throw new Error(`INVALID_${label}_SOURCE`);
if (!releaseTag.test(source)) throw new Error(`FLOATING_${label}_SOURCE: ${source} must name an exact release version, not a moving major, minor or alias tag`);
if (typeof indexImage !== 'string' || !IMAGE.test(indexImage)) throw new Error(`UNPINNED_${label}_INDEX`);
if (!record(images)) throw new Error(`MISSING_${label}_IMAGES`);
const repository = repositoryOfTag(source);
if (repositoryOfPinned(indexImage) !== repository) throw new Error(`MISMATCHED_${label}_REPOSITORY`);
const pinned = {} as Record<CsoRuntimeBuildPlatform, string>;
for (const platform of CSO_RUNTIME_PLATFORMS) {
const image = images[platform];
if (typeof image !== 'string' || !IMAGE.test(image)) throw new Error(`UNPINNED_${label}_IMAGE: ${platform}`);
if (repositoryOfPinned(image) !== repository) throw new Error(`MISMATCHED_${label}_REPOSITORY`);
pinned[platform] = image;
}
if (pinned['linux/amd64'] === pinned['linux/arm64']) throw new Error(`DUPLICATE_${label}_PLATFORM_MANIFEST`);
return pinned;
}
/** Every declared stack must have both native platform manifests. */
export function imageBuildMatrix(input: unknown): { include: ImageBuildRow[] } {
if (!record(input)) throw new Error('INVALID_BUILD_INPUTS');
if (input.schemaVersion !== 1 || input.helperAbi !== 3) throw new Error('INCOMPATIBLE_BUILD_INPUTS');
if (input.state !== 'reviewed') throw new Error('MISSING_REVIEWED_BUILD_INPUTS: review pinned images and exact tool versions before staging publication.');
if (typeof input.revision !== 'string' || !REVISION.test(input.revision)) throw new Error('INVALID_BUILD_INPUT_REVISION');
if (typeof input.reviewedAt !== 'string' || !Number.isFinite(Date.parse(input.reviewedAt))) throw new Error('MISSING_BUILD_INPUT_REVIEW');
if (typeof input.reviewMethod !== 'string' || input.reviewMethod.length < 40 || input.reviewMethod.length > 500) throw new Error('MISSING_BUILD_INPUT_REVIEW');
if (!record(input.sbomGenerator)) throw new Error('UNPINNED_SBOM_GENERATOR');
const sbomImages = assertPinnedFamily(
input.sbomGenerator.source,
input.sbomGenerator.indexImage,
input.sbomGenerator.images,
'SBOM_GENERATOR',
);
if (!Array.isArray(input.profiles) || input.profiles.length !== CSO_RUNTIME_STACKS.length) throw new Error('INCOMPLETE_STACK_MATRIX');
const rows: ImageBuildRow[] = [];
const seenStacks = new Set<string>();
const seenProfileIds = new Set<string>();
for (const raw of input.profiles) {
if (!record(raw)) throw new Error('INVALID_PROFILE');
const { id, stack, source, indexImage, baseImages, versions } = raw;
if (typeof id !== 'string' || !REVISION.test(id) || seenProfileIds.has(id)) throw new Error('INVALID_PROFILE_ID');
seenProfileIds.add(id);
if (typeof stack !== 'string' || !CSO_RUNTIME_STACKS.includes(stack as CsoRuntimeBuildStack) || seenStacks.has(stack)) throw new Error('INVALID_STACK');
seenStacks.add(stack);
const typedStack = stack as CsoRuntimeBuildStack;
const bases = assertPinnedFamily(source, indexImage, baseImages, 'BASE', typedStack === 'postgresql' ? TWO_PART_RELEASE_TAG : RELEASE_TAG);
if (!record(versions)) throw new Error('MISSING_TOOL_VERSIONS');
const exactVersion = (value: unknown) => typeof value === 'string' &&
(typedStack === 'postgresql'
? /^\d+\.\d+(?:\.\d+)?(?:[.+_-][A-Za-z0-9.-]+)?$/
: /^\d+\.\d+\.\d+(?:[.+_-][A-Za-z0-9.-]+)?$/).test(value);
const expectedKeys = [...REQUIRED_VERSIONS[typedStack]].sort();
const suppliedKeys = Object.keys(versions).sort();
if (expectedKeys.join(',') !== suppliedKeys.join(',') || expectedKeys.some(key => !exactVersion(versions[key]))) throw new Error('UNPINNED_TOOL_VERSION');
if (typedStack !== 'postgresql' && versions['cso-preparation'] !== '1.0.0') throw new Error('INCOMPATIBLE_PREPARATION_HELPER');
let uvImages = {} as Record<CsoRuntimeBuildPlatform, string>;
if (typedStack === 'python') uvImages = assertPinnedFamily(raw.uvSource, raw.uvIndexImage, raw.uvImages, 'UV');
else if (raw.uvSource !== undefined || raw.uvIndexImage !== undefined || raw.uvImages !== undefined) throw new Error('UNEXPECTED_UV_IMAGE');
for (const platform of CSO_RUNTIME_PLATFORMS) {
const arch = platform === 'linux/amd64' ? 'amd64' : 'arm64';
rows.push({
inputRevision: input.revision,
profileId: id,
runtimeId: `${id}-${arch}`,
stack: typedStack,
platform,
arch,
runner: arch === 'amd64' ? 'ubuntu-24.04' : 'ubuntu-24.04-arm',
baseSource: source as string,
baseIndexImage: indexImage as string,
baseImage: bases[platform],
uvSource: typedStack === 'python' ? raw.uvSource as string : '',
uvIndexImage: typedStack === 'python' ? raw.uvIndexImage as string : '',
uvImage: typedStack === 'python' ? uvImages[platform] : '',
sbomGeneratorSource: input.sbomGenerator.source as string,
sbomGeneratorIndexImage: input.sbomGenerator.indexImage as string,
sbomGeneratorImage: sbomImages[platform],
versions: versions as Record<string, string>,
});
}
}
return { include: rows };
}
export function committedImageBuildMatrix(): { include: ImageBuildRow[] } {
const file = resolve(import.meta.dir, '../lib/cso/images/build-inputs.json');
return imageBuildMatrix(JSON.parse(readFileSync(file, 'utf8')));
}
if (import.meta.main) {
try {
if (process.argv.length !== 2) throw new Error('No arguments accepted; build inputs come from the reviewed repository file.');
process.stdout.write(JSON.stringify(committedImageBuildMatrix()) + '\n');
} catch (error) {
process.stderr.write((error instanceof Error ? error.message : 'INVALID_BUILD_INPUTS') + '\n');
process.exitCode = 1;
}
}
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
* Requalification triggers: the inputs a runtime qualification was measured
* under. A promoted catalog records them; a catalog whose recorded triggers
* differ from the current source is older than its inputs and must be
* requalified (or its runtimes withdrawn) before it ships.
*/
import { spawnSync } from '../lib/spawn-sync';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { canonical, sha256 } from '../lib/cso/contracts';
import { ISOLATION_POLICY_HASH } from '../lib/cso/docker';
import { CSO_HELPER_ABI, isEvaluationRuntimeCatalog, type RequalificationTriggers, type RuntimeCatalog } from '../lib/cso/runtime-catalog';
const ROOT = path.resolve(import.meta.dir, '..');
/** Compiled into every runtime image as gstack-cso-verifier and gstack-cso-preparation. */
export const IMAGE_HELPER_ENTRYPOINTS = ['lib/cso/verifier.ts', 'lib/cso/preparation-container.ts'] as const;
export const IMAGE_CONTEXT = 'lib/cso/images';
/** Image-context files that describe qualification rather than enter an image; build-inputs.json is its own trigger. */
const IMAGE_CONTEXT_EXCLUDED = new Set(['README.md', 'qualification.json', 'build-inputs.json']);
/** Every repository file whose bytes enter a runtime image: the helpers' import closure plus the image build context. */
export async function imageSourceFiles(root = ROOT): Promise<string[]> {
const build = await Bun.build({ entrypoints: IMAGE_HELPER_ENTRYPOINTS.map(entry => path.join(root, entry)), target: 'bun', metafile: true });
if (!build.success || !build.metafile) throw new Error('REQUALIFICATION_SOURCE_CLOSURE_FAILED');
// Bun reports metafile inputs relative to the process working directory, not to the entrypoints.
const closure = Object.keys(build.metafile.inputs).map(input => path.relative(root, path.resolve(process.cwd(), input)).split(path.sep).join('/'));
if (closure.some(file => file.startsWith('..') || file.includes('node_modules/'))) throw new Error('REQUALIFICATION_SOURCE_OUTSIDE_REPOSITORY');
const context = fs.readdirSync(path.join(root, IMAGE_CONTEXT), { withFileTypes: true })
.filter(entry => entry.isFile() && !IMAGE_CONTEXT_EXCLUDED.has(entry.name))
.map(entry => `${IMAGE_CONTEXT}/${entry.name}`);
return [...new Set([...closure, ...context])].sort();
}
/**
* Digest of every image source byte. A compiled helper's leading `#!` line never
* runs inside the image, so it is hashed as absent; every other byte counts.
* `legacy` hashes the shebang too, the rule staging runs recorded before this normalization (through run 39325583697).
*/
function preparationSha256(root: string, files: string[], legacy = false): string {
const helpers = new Set<string>(IMAGE_HELPER_ENTRYPOINTS);
return sha256(canonical(files.map(file => {
const bytes = fs.readFileSync(path.join(root, file));
if (legacy || !helpers.has(file) || bytes[0] !== 0x23 || bytes[1] !== 0x21) return [file, sha256(bytes)];
const newline = bytes.indexOf(0x0a);
return [file, sha256(newline === -1 ? Buffer.alloc(0) : bytes.subarray(newline + 1))];
})));
}
/** preparationSha256 of a committed tree under the current rule and the legacy rule. */
export async function committedPreparation(commit: string, root = ROOT): Promise<{ current: string; legacy: string }> {
if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error('INVALID_STAGED_COMMIT');
const archive = spawnSync('git', ['-C', root, 'archive', '--format=tar', commit], { timeout: 60_000, maxBuffer: 512 * 1024 * 1024 });
if (archive.status !== 0) throw new Error(`STAGED_COMMIT_UNAVAILABLE: ${commit} is not in this checkout; fetch full history`);
const tree = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-staged-source-'));
try {
const extract = spawnSync('tar', ['-x', '-C', tree], { input: archive.stdout, timeout: 60_000 });
if (extract.status !== 0) throw new Error('STAGED_COMMIT_UNAVAILABLE: archive extraction failed');
const files = await imageSourceFiles(tree);
return { current: preparationSha256(tree, files), legacy: preparationSha256(tree, files, true) };
} finally {
fs.rmSync(tree, { recursive: true, force: true });
}
}
export async function requalificationTriggers(root = ROOT): Promise<RequalificationTriggers> {
const files = await imageSourceFiles(root);
const buildInputs = JSON.parse(fs.readFileSync(path.join(root, IMAGE_CONTEXT, 'build-inputs.json'), 'utf8'));
if (typeof buildInputs?.revision !== 'string' || !buildInputs.revision) throw new Error('INVALID_BUILD_INPUTS_REVISION');
return {
helperAbi: CSO_HELPER_ABI,
isolationPolicyHash: ISOLATION_POLICY_HASH,
preparationSha256: preparationSha256(root, files),
buildInputsRevision: buildInputs.revision,
};
}
/** Names of the triggers that changed since the catalog's runtimes were qualified; empty when nothing is promoted. */
export function staleRequalificationTriggers(catalog: RuntimeCatalog, current: RequalificationTriggers): string[] {
if (isEvaluationRuntimeCatalog(catalog) || catalog.runtimes.length === 0) return [];
const recorded = catalog.promotion?.requalification;
if (!recorded) return Object.keys(current).sort();
return (Object.keys(current) as Array<keyof RequalificationTriggers>).filter(key => recorded[key] !== current[key]).sort();
}
if (import.meta.main) {
try {
const [command, file, ...rest] = process.argv.slice(2);
if (command === 'triggers' && file === undefined) {
process.stdout.write(JSON.stringify(await requalificationTriggers(), null, 2) + '\n');
} else if (command === 'check' && file && rest.length === 0) {
const stale = staleRequalificationTriggers(JSON.parse(fs.readFileSync(path.resolve(file), 'utf8')), await requalificationTriggers());
if (stale.length) throw new Error(`STALE_RUNTIME_QUALIFICATION: ${stale.join(', ')} changed since qualification; requalify the runtimes or withdraw them from the catalog`);
process.stdout.write('REQUALIFICATION CURRENT\n');
} else throw new Error('Usage: cso-requalification.ts triggers | check <runtime-catalog.json>');
} catch (error) {
process.stderr.write((error instanceof Error ? error.message : 'REQUALIFICATION_CHECK_FAILED') + '\n');
process.exitCode = 1;
}
}
-392
View File
@@ -1,392 +0,0 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/** Generate a reviewable catalog candidate from authenticated qualification statements. */
import * as fs from 'node:fs';
import * as path from 'node:path';
import { canonical, sha256 as sha256Hex } from '../lib/cso/contracts';
import committedCatalog from '../lib/cso/runtime-catalog.json';
import buildInputs from '../lib/cso/images/build-inputs.json';
import {
CSO_HELPER_ABI,
EVALUATION_REVISION_PREFIX,
isEvaluationRuntimeCatalog,
validRequalificationTriggers,
type RequalificationTriggers,
type QualifiedRuntime,
type RuntimeCatalog,
type RuntimeQualification,
validateRuntimeCatalog,
} from '../lib/cso/runtime-catalog';
import { ISOLATION_POLICY_HASH } from '../lib/cso/docker';
import { imageBuildMatrix, type ImageBuildRow } from './cso-image-matrix';
import { committedPreparation, requalificationTriggers, staleRequalificationTriggers } from './cso-requalification';
const DIGEST = /^sha256:[a-f0-9]{64}$/;
const WORKFLOW = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/actions\/runs\/[0-9]+$/;
const OUTPUT_IMAGE = /^ghcr\.io\/garrytan\/gstack\/cso-staging\/(node|bun|python|rails|postgresql)-(amd64|arm64)@sha256:[a-f0-9]{64}$/;
const MAX_EVIDENCE_FILES = 10;
const MAX_EVIDENCE_BYTES = 1024 * 1024;
export interface RuntimeQualificationStatement {
schemaVersion: 1;
helperAbi: 3;
state: 'qualified';
buildRevision: string;
runtimeId: string;
stack: ImageBuildRow['stack'];
platform: ImageBuildRow['platform'];
image: string;
versions: Record<string, string>;
sourceCommit: string;
workflow: string;
qualifiedAt: string;
sbomDigest: string;
provenanceDigest: string;
checks: Record<string, true>;
}
function sha256(value: string | Buffer): string {
return `sha256:${sha256Hex(value)}`;
}
function versionsKey(value: Record<string, string>): string {
return canonical(value);
}
export function requiredChecks(stack: ImageBuildRow['stack']): string[] {
if (stack === 'postgresql') return [
'containmentPassed', 'coldStartPassed', 'multiDatabasePassed', 'readinessPassed',
'secretCanaryPassed', 'watchdogCleanupPassed',
].sort();
const common = [
'accuracyGatesPassed', 'acquisitionPublicOnlyPassed', 'coldStartPassed', 'containmentPassed',
'heldOutRepairPassed', 'offlineLifecyclePassed', 'positiveNegativeAssertionsPassed',
'secretCanaryPassed', 'watchdogCleanupPassed',
];
return stack === 'rails'
? [...common, 'nativeExtensionsPassed', 'railsPostgresqlPassed', 'railsSqlitePassed'].sort()
: common.sort();
}
function qualification(statement: RuntimeQualificationStatement): RuntimeQualification {
if (statement.stack === 'postgresql') return {
kind: 'postgresql',
sourceCommit: statement.sourceCommit,
workflow: statement.workflow,
sbomDigest: statement.sbomDigest,
provenanceDigest: statement.provenanceDigest,
verifiedProvenance: true,
containmentPassed: true,
coldStartPassed: true,
multiDatabasePassed: true,
readinessPassed: true,
};
return {
kind: 'application',
sourceCommit: statement.sourceCommit,
workflow: statement.workflow,
sbomDigest: statement.sbomDigest,
provenanceDigest: statement.provenanceDigest,
verifiedProvenance: true,
containmentPassed: true,
coldStartPassed: true,
positiveNegativeAssertionsPassed: true,
heldOutRepairPassed: true,
};
}
function validateStatement(raw: unknown, row: ImageBuildRow): RuntimeQualificationStatement {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('INVALID_QUALIFICATION_STATEMENT');
const statement = raw as RuntimeQualificationStatement;
const expectedFields = [
'buildRevision', 'checks', 'helperAbi', 'image', 'platform', 'provenanceDigest',
'qualifiedAt', 'runtimeId', 'sbomDigest', 'schemaVersion', 'sourceCommit', 'stack',
'state', 'versions', 'workflow',
];
if (canonical(Object.keys(statement).sort()) !== canonical(expectedFields.sort())) throw new Error('INVALID_QUALIFICATION_STATEMENT_FIELDS');
if (statement.schemaVersion !== 1 || statement.helperAbi !== CSO_HELPER_ABI || statement.state !== 'qualified') throw new Error('UNQUALIFIED_RUNTIME_EVIDENCE');
if (statement.buildRevision !== row.inputRevision || statement.runtimeId !== row.runtimeId ||
statement.stack !== row.stack || statement.platform !== row.platform ||
versionsKey(statement.versions) !== versionsKey(row.versions)) throw new Error(`QUALIFICATION_BUILD_MISMATCH: ${row.runtimeId}`);
if (!OUTPUT_IMAGE.test(statement.image) || !statement.image.includes(`/${row.stack}-${row.arch}@`)) throw new Error(`INVALID_QUALIFIED_IMAGE: ${row.runtimeId}`);
if (!/^[a-f0-9]{40}$/.test(statement.sourceCommit) || !WORKFLOW.test(statement.workflow) ||
!Number.isFinite(Date.parse(statement.qualifiedAt)) || !DIGEST.test(statement.sbomDigest) ||
!DIGEST.test(statement.provenanceDigest)) throw new Error(`MISSING_QUALIFICATION_PROVENANCE: ${row.runtimeId}`);
if (!statement.checks || typeof statement.checks !== 'object' || Array.isArray(statement.checks)) throw new Error(`MISSING_RELEASE_GATES: ${row.runtimeId}`);
const expected = requiredChecks(row.stack);
const actual = Object.keys(statement.checks).sort();
if (canonical(actual) !== canonical(expected) || actual.some(key => statement.checks[key] !== true)) throw new Error(`MISSING_RELEASE_GATES: ${row.runtimeId}`);
return statement;
}
/** The committed (never evaluation-only) catalog and the reviewed build matrix it must describe. */
function reviewedMatrix(currentValue: unknown, inputValue: unknown): { current: RuntimeCatalog; rows: ImageBuildRow[] } {
validateRuntimeCatalog(currentValue);
const current = currentValue as RuntimeCatalog;
if (isEvaluationRuntimeCatalog(current)) throw new Error('EVALUATION_CATALOG_NOT_PROMOTABLE');
return { current, rows: profilesMatchingRows(current, inputValue) };
}
function profilesMatchingRows(current: RuntimeCatalog, inputValue: unknown): ImageBuildRow[] {
const rows = imageBuildMatrix(inputValue).include;
if (!current.profiles || current.buildRevision !== rows[0].inputRevision) throw new Error('CATALOG_BUILD_REVISION_MISMATCH');
const profiles = new Map(current.profiles.map(profile => [profile.id, profile]));
if (profiles.size !== rows.length) throw new Error('CATALOG_PROFILE_MATRIX_MISMATCH');
for (const row of rows) {
const profile = profiles.get(row.runtimeId);
if (!profile || profile.stack !== row.stack || profile.platform !== row.platform ||
versionsKey(profile.versions) !== versionsKey(row.versions)) throw new Error(`CATALOG_PROFILE_MATRIX_MISMATCH: ${row.runtimeId}`);
}
return rows;
}
/** The candidate build's gate: a valid evaluation-only catalog for the reviewed build inputs. */
export function validateEvaluationCandidate(catalogValue: unknown, inputValue: unknown): RuntimeCatalog {
validateRuntimeCatalog(catalogValue);
const catalog = catalogValue as RuntimeCatalog;
if (!isEvaluationRuntimeCatalog(catalog)) throw new Error('NOT_AN_EVALUATION_CATALOG');
const rows = profilesMatchingRows(catalog, inputValue);
for (const row of rows) {
const runtime = catalog.runtimes.find(item => item.id === row.runtimeId);
if (!runtime || !OUTPUT_IMAGE.test(runtime.image) || !runtime.image.includes(`/${row.stack}-${row.arch}@`)) throw new Error(`INVALID_QUALIFIED_IMAGE: ${row.runtimeId}`);
}
return catalog;
}
function matchRows(rows: ImageBuildRow[], values: unknown[]): Array<[ImageBuildRow, unknown]> {
if (values.length !== rows.length) throw new Error('INCOMPLETE_QUALIFICATION_MATRIX');
const byId = new Map<string, unknown>();
for (const value of values) {
const id = (value as any)?.runtimeId;
if (typeof id !== 'string' || byId.has(id)) throw new Error('DUPLICATE_QUALIFICATION_STATEMENT');
byId.set(id, value);
}
return rows.map(row => {
if (!byId.has(row.runtimeId)) throw new Error(`MISSING_QUALIFICATION_STATEMENT: ${row.runtimeId}`);
return [row, byId.get(row.runtimeId)];
});
}
const STAGED_FIELDS = [
'buildRevision', 'helperAbi', 'image', 'platform', 'provenanceDigest', 'qualification', 'runtimeId',
'sbomDigest', 'schemaVersion', 'sourceCommit', 'stack', 'state', 'verifiedProvenance', 'versions', 'workflow',
].sort();
/**
* Build an evaluation-only catalog from one staging run's staged-image.json
* records. It measures no release gate: every runtime is an
* evaluation_candidate, and setup, distribution builds and promotion refuse it.
*/
export function evaluationCandidateCatalog(currentValue: unknown, inputValue: unknown, stagedValues: unknown[], createdAt: string): RuntimeCatalog {
const { current, rows } = reviewedMatrix(currentValue, inputValue);
if (!Number.isFinite(Date.parse(createdAt))) throw new Error('INVALID_EVALUATION_TIME');
const staged = matchRows(rows, stagedValues).map(([row, value]) => {
const record = value as RuntimeQualificationStatement;
if (!record || typeof record !== 'object' || canonical(Object.keys(record).sort()) !== canonical(STAGED_FIELDS) ||
record.schemaVersion !== 1 || record.helperAbi !== CSO_HELPER_ABI || (record.state as string) !== 'staged' || (record as any).verifiedProvenance !== true) throw new Error(`INVALID_STAGED_RUNTIME: ${row.runtimeId}`);
if (record.buildRevision !== row.inputRevision || record.stack !== row.stack || record.platform !== row.platform ||
versionsKey(record.versions) !== versionsKey(row.versions)) throw new Error(`QUALIFICATION_BUILD_MISMATCH: ${row.runtimeId}`);
if (!OUTPUT_IMAGE.test(record.image) || !record.image.includes(`/${row.stack}-${row.arch}@`)) throw new Error(`INVALID_QUALIFIED_IMAGE: ${row.runtimeId}`);
if (!/^[a-f0-9]{40}$/.test(record.sourceCommit) || !WORKFLOW.test(record.workflow) || !DIGEST.test(record.sbomDigest) ||
!DIGEST.test(record.provenanceDigest)) throw new Error(`MISSING_QUALIFICATION_PROVENANCE: ${row.runtimeId}`);
return record;
});
if (new Set(staged.map(item => item.sourceCommit)).size !== 1 || new Set(staged.map(item => item.workflow)).size !== 1) throw new Error('SPLIT_STAGING_RUN');
const { sourceCommit, workflow } = staged[0];
const runtimes: QualifiedRuntime[] = staged.map(record => ({
id: record.runtimeId,
stack: record.stack,
platform: record.platform,
state: 'evaluation_candidate',
image: record.image,
entrypoint: '/opt/cso/entrypoint',
helperAbi: CSO_HELPER_ABI,
versions: record.versions,
policyVersion: 'cso-isolation-v1',
qualifiedAt: createdAt,
qualification: { kind: 'evaluation', sourceCommit, workflow, sbomDigest: record.sbomDigest, provenanceDigest: record.provenanceDigest, verifiedProvenance: true },
}));
const candidate: RuntimeCatalog = {
schemaVersion: 1,
revision: `${EVALUATION_REVISION_PREFIX}${workflow.slice(workflow.lastIndexOf('/') + 1)}-${sourceCommit.slice(0, 12)}`,
previousRevision: current.revision,
helperAbi: CSO_HELPER_ABI,
buildRevision: current.buildRevision,
profiles: current.profiles,
evaluation: { sourceCommit, workflow, evidenceDigest: sha256(canonical(runtimes)) },
runtimes,
};
validateRuntimeCatalog(candidate);
return candidate;
}
export function catalogPromotionCandidate(
currentValue: unknown,
inputValue: unknown,
evidenceValues: unknown[],
/** Measured by the staging run at sourceCommit (scripts/cso-requalification.ts triggers). */
requalification: RequalificationTriggers,
): RuntimeCatalog {
const { current, rows } = reviewedMatrix(currentValue, inputValue);
if (!validRequalificationTriggers(requalification, current.buildRevision)) throw new Error('INVALID_REQUALIFICATION_TRIGGERS');
if (requalification.isolationPolicyHash !== ISOLATION_POLICY_HASH) throw new Error('STALE_RUNTIME_QUALIFICATION: isolationPolicyHash');
const statements = matchRows(rows, evidenceValues).map(([row, value]) => validateStatement(value, row));
const sourceCommits = new Set(statements.map(item => item.sourceCommit));
const workflows = new Set(statements.map(item => item.workflow));
if (sourceCommits.size !== 1 || workflows.size !== 1) throw new Error('SPLIT_QUALIFICATION_RUN');
const sourceCommit = statements[0].sourceCommit;
const workflow = statements[0].workflow;
const runId = workflow.slice(workflow.lastIndexOf('/') + 1);
const runtimes: QualifiedRuntime[] = statements.map(statement => ({
id: statement.runtimeId,
stack: statement.stack,
platform: statement.platform,
state: 'qualified',
image: statement.image,
entrypoint: '/opt/cso/entrypoint',
helperAbi: CSO_HELPER_ABI,
versions: statement.versions,
policyVersion: 'cso-isolation-v1',
qualifiedAt: statement.qualifiedAt,
qualification: qualification(statement),
}));
const qualificationEvidenceDigest = sha256(canonical(statements));
const evidenceDigest = sha256(canonical(runtimes));
const candidate: RuntimeCatalog = {
schemaVersion: 1,
revision: `cso-v3-${runId}-${sourceCommit.slice(0, 12)}`,
previousRevision: current.revision,
helperAbi: CSO_HELPER_ABI,
buildRevision: current.buildRevision,
profiles: current.profiles,
promotion: {
sourceCommit, workflow, evidenceDigest, qualificationEvidenceDigest,
requalification: {
helperAbi: requalification.helperAbi,
isolationPolicyHash: requalification.isolationPolicyHash,
preparationSha256: requalification.preparationSha256,
buildInputsRevision: requalification.buildInputsRevision,
},
},
runtimes,
};
validateRuntimeCatalog(candidate);
return candidate;
}
/**
* The release contract: the promotion candidate, refused when any trigger moved since the staged commit.
* A recorded preparationSha256 that differs from the current one is re-measured at the staged commit in
* `source`, so a staging record made under the legacy rule compares under the current rule.
*/
export async function releaseCandidate(
evidenceValues: unknown[],
recorded: RequalificationTriggers,
current: RequalificationTriggers,
source?: string,
): Promise<RuntimeCatalog> {
let candidate = catalogPromotionCandidate(committedCatalog, buildInputs, evidenceValues, recorded);
if (recorded.preparationSha256 !== current.preparationSha256) {
const staged = await committedPreparation(candidate.promotion!.sourceCommit, source);
if (recorded.preparationSha256 !== staged.current && recorded.preparationSha256 !== staged.legacy) {
throw new Error('REQUALIFICATION_TRIGGERS_MISMATCH: preparationSha256 was not measured at the staged commit');
}
candidate = catalogPromotionCandidate(committedCatalog, buildInputs, evidenceValues, { ...recorded, preparationSha256: staged.current });
}
const stale = staleRequalificationTriggers(candidate, current);
if (stale.length) throw new Error(`STALE_RUNTIME_QUALIFICATION: ${stale.join(', ')} changed since the staged commit; re-stage and requalify`);
return candidate;
}
/** A promotion may only replace the exact catalog revision it was generated from. */
export function validateRuntimeCatalogTransition(currentValue: unknown, proposedValue: unknown): void {
validateRuntimeCatalog(currentValue);
validateRuntimeCatalog(proposedValue);
const current = currentValue as RuntimeCatalog;
const proposed = proposedValue as RuntimeCatalog;
if (isEvaluationRuntimeCatalog(current) || isEvaluationRuntimeCatalog(proposed)) throw new Error('EVALUATION_CATALOG_NOT_PROMOTABLE');
if (!proposed.promotion || proposed.runtimes.length === 0) throw new Error('UNQUALIFIED_RUNTIME_CATALOG_PROMOTION');
if (proposed.revision === current.revision || proposed.previousRevision !== current.revision) {
throw new Error('RUNTIME_CATALOG_BASE_REVISION_MISMATCH');
}
if (proposed.buildRevision !== current.buildRevision ||
canonical(proposed.profiles) !== canonical(current.profiles)) {
throw new Error('RUNTIME_CATALOG_PROFILE_TRANSITION_MISMATCH');
}
}
function collectEvidence(root: string, name = 'qualified-runtime.json'): unknown[] {
const absolute = path.resolve(root);
const rootStat = fs.lstatSync(absolute);
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error('UNSAFE_EVIDENCE_ROOT');
const files: string[] = [];
const visit = (directory: string, depth: number): void => {
if (depth > 4) throw new Error('EVIDENCE_TREE_TOO_DEEP');
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const file = path.join(directory, entry.name);
if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) throw new Error('UNSAFE_EVIDENCE_ENTRY');
if (entry.isDirectory()) visit(file, depth + 1);
else if (entry.name === name) files.push(file);
if (files.length > MAX_EVIDENCE_FILES) throw new Error('TOO_MANY_QUALIFICATION_STATEMENTS');
}
};
visit(absolute, 0);
return files.sort().map(file => {
const before = fs.lstatSync(file);
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > MAX_EVIDENCE_BYTES) throw new Error('UNSAFE_QUALIFICATION_STATEMENT');
const body = fs.readFileSync(file, 'utf8');
const after = fs.lstatSync(file);
if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size ||
before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new Error('QUALIFICATION_EVIDENCE_RACE');
try { return JSON.parse(body); } catch { throw new Error('INVALID_QUALIFICATION_STATEMENT'); }
});
}
function readCatalogArtifact(file: string): unknown {
const absolute = path.resolve(file);
const before = fs.lstatSync(absolute);
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size <= 0 || before.size > MAX_EVIDENCE_BYTES) {
throw new Error('UNSAFE_RUNTIME_CATALOG_ARTIFACT');
}
const body = fs.readFileSync(absolute, 'utf8');
const after = fs.lstatSync(absolute);
if (before.dev !== after.dev || before.ino !== after.ino || before.mode !== after.mode ||
before.nlink !== after.nlink || before.size !== after.size || before.mtimeMs !== after.mtimeMs ||
before.ctimeMs !== after.ctimeMs) throw new Error('RUNTIME_CATALOG_ARTIFACT_RACE');
try { return JSON.parse(body); } catch { throw new Error('INVALID_RUNTIME_CATALOG_ARTIFACT'); }
}
if (import.meta.main) {
try {
const args = process.argv.slice(2);
if (args[0] === 'check-evaluation') {
if (args.length !== 2) throw new Error('Usage: cso-runtime-promotion.ts check-evaluation <cso-eval-catalog>');
const catalog = validateEvaluationCandidate(readCatalogArtifact(args[1]), buildInputs);
process.stdout.write(`EVALUATION-ONLY ${catalog.revision}\n`);
} else if (args[0] === 'evaluation-candidate') {
if (![5, 7].includes(args.length) || args[1] !== '--staged-root' || args[3] !== '--output' || (args.length === 7 && args[5] !== '--created-at')) {
throw new Error('Usage: cso-runtime-promotion.ts evaluation-candidate --staged-root <directory> --output <new-file> [--created-at <ISO time>]');
}
const candidate = evaluationCandidateCatalog(committedCatalog, buildInputs, collectEvidence(args[2], 'staged-image.json'), args[6] ?? new Date().toISOString());
const output = path.resolve(args[4]);
fs.writeFileSync(output, JSON.stringify(candidate, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
process.stdout.write(`${output}\n`);
} else if (args[0] === 'validate-transition') {
if (args.length !== 3) throw new Error('Usage: cso-runtime-promotion.ts validate-transition <current-catalog> <proposed-catalog>');
validateRuntimeCatalogTransition(readCatalogArtifact(args[1]), readCatalogArtifact(args[2]));
process.stdout.write('VALID TRANSITION\n');
} else {
if (args.length !== 4 || args[0] !== '--evidence-root' || args[2] !== '--output') {
throw new Error('Usage: cso-runtime-promotion.ts --evidence-root <directory> --output <new-file>');
}
const triggers = collectEvidence(args[1], 'requalification.json');
if (triggers.length !== 1) throw new Error('MISSING_REQUALIFICATION_TRIGGERS');
const candidate = await releaseCandidate(collectEvidence(args[1]), triggers[0] as RequalificationTriggers, await requalificationTriggers());
const output = path.resolve(args[3]);
fs.writeFileSync(output, JSON.stringify(candidate, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
process.stdout.write(`${output}\n`);
}
} catch (error) {
process.stderr.write((error instanceof Error ? error.message : 'RUNTIME_PROMOTION_FAILED') + '\n');
process.exitCode = 1;
}
}
+5 -3
View File
@@ -15,10 +15,12 @@ const SKIP = new Set(['node_modules', '.git', 'dist']);
* install's gstack-owned entry. investigate was cut after a no-gain eval and
* its source is gone (GST-1717). verify is now build-check (#4593): the old
* name hid Claude Code's built-in /verify, so an upgrade removes gstack's old
* entry and leaves a user's own verify skill. setup and gstack-relink read the same list
* from GSTACK_RETIRED_SKILLS in bin/gstack-install-registry.sh.
* entry and leaves a user's own verify skill. cso was cut after a plain security
* audit request found more than it did (GST-3920), and its source is gone.
* setup and gstack-relink read the same list from GSTACK_RETIRED_SKILLS in
* bin/gstack-install-registry.sh.
*/
export const RETIRED_SKILLS = ['investigate', 'verify'];
export const RETIRED_SKILLS = ['investigate', 'verify', 'cso'];
/**
* Old skill name → new name. A user's disabled_skills entry under the old name
-2
View File
@@ -320,7 +320,6 @@
"test/claude-code-windows-job.test.ts": 3224,
"test/claude-md-size.test.ts": 56,
"test/claude-overlay-models.test.ts": 135,
"test/claude-producer-stream.test.ts": 83,
"test/claude-provider-keychain.test.ts": 234,
"test/claude-usage.test.ts": 7535,
"test/codex-carve-fixture.test.ts": 4262,
@@ -337,7 +336,6 @@
"test/cost-known.test.ts": 349,
"test/coverage-audit.test.ts": 8774,
"test/crew-move-layout.test.ts": 60,
"test/cso-requalification.test.ts": 160,
"test/declared-annotation.test.ts": 58,
"test/defensive-review-framing.test.ts": 50,
"test/dependency-security.test.ts": 154,
-2
View File
@@ -475,7 +475,6 @@
"test/claude-overlay-setup-lifecycle.test.ts": 21834,
"test/claude-overlay-setup-project.test.ts": 18207,
"test/claude-overlay-setup-recovery.test.ts": 24508,
"test/claude-producer-stream.test.ts": 3553,
"test/claude-provider-keychain.test.ts": 72,
"test/claude-usage.test.ts": 660,
"test/code-intelligence-cli.test.ts": 733,
@@ -522,7 +521,6 @@
"test/credential-rejection.test.ts": 283,
"test/crew-move-layout.test.ts": 15,
"test/crew-skills-on-capy.test.ts": 1042,
"test/cso-requalification.test.ts": 2885,
"test/decision-trail.test.ts": 554,
"test/declared-annotation.test.ts": 17,
"test/default-base.test.ts": 4360,
@@ -1 +1 @@
{"blob":"b88614aba91757dc9cd096e2333533de3bd57efe","since":8}
{"blob":"d2421bef3e56bc1c9e18d1730992c1e1ad864716","since":8,"nonBehavioral":"Removes the deleted /cso cases and test file from the paid case and PR-profile lists; no remaining case's selection, trials or verdict changes"}
@@ -1 +1 @@
{"blob":"10f92d323fc94589f184ad00fd1228f1372b5470","since":8,"nonBehavioral":"Removes the four deleted /cso workflows from the PR-profile path list; no remaining case's selection, trials or verdict changes"}
{"blob":"10f92d323fc94589f184ad00fd1228f1372b5470","since":8,"nonBehavioral":"Removes the deleted /cso cases and test file from the paid case and PR-profile lists; no remaining case's selection, trials or verdict changes"}
-3
View File
@@ -71,9 +71,6 @@ export const CASE_TEST_NAMES: Record<string, string> = {
'plan-review-report': '/plan-eng-review writes GSTACK REVIEW REPORT to plan file',
'auq-format-gate': "/plan-ceo-review's first AskUserQuestion is a compliant decision brief (7/7 + substance)",
'autoplan-dual-voice': 'both Claude + Codex voices produce output in Phase 1 (within timeout)',
'cso-full-audit': '/cso persists supported tenant-boundary findings with redacted evidence',
'cso-diff-mode': '/cso --diff records its base and investigates changed security paths',
'cso-infra-scope': '/cso --infra finds an attacker-to-credential execution path',
'plan-ceo-review-plan-mode': 'first terminal outcome is asked (Step 0 fires before any plan write)',
'plan-eng-review-artifact': 'an interactive review writes one QA test plan about the reviewed change',
};
-1
View File
@@ -85,7 +85,6 @@ const DESTRUCTIVE_PATTERNS: RegExp[] = [
* inherently high-stakes.
*/
const ONE_WAY_SKILL_CATEGORIES = new Set<string>([
'cso:approval', // security-audit findings
'land-and-deploy:approval', // anything /land-and-deploy asks
]);
-2
View File
@@ -9,7 +9,6 @@
"test/skill-e2e-bws.test.ts": 74261,
"test/skill-e2e-context-skills.test.ts": 1000,
"test/skill-e2e-coverage-audit.test.ts": 65669,
"test/skill-e2e-cso.test.ts": 229620,
"test/skill-e2e-deploy.test.ts#benchmark-workflow": 120646,
"test/skill-e2e-deploy.test.ts#canary-workflow": 42804,
"test/skill-e2e-deploy.test.ts#land-and-deploy-first-run": 103709,
@@ -135,7 +134,6 @@
"test/skill-e2e-bws.test.ts": 1000,
"test/skill-e2e-context-skills.test.ts": 144874,
"test/skill-e2e-coverage-audit.test.ts": 1000,
"test/skill-e2e-cso.test.ts": 303949,
"test/skill-e2e-design-model-smoke.test.ts": 90000,
"test/skill-e2e-design.test.ts": 817000,
"test/skill-e2e-design.test.ts#design-consultation-core": 173162,
-20
View File
@@ -479,26 +479,6 @@ export const QUESTIONS = {
description: "No CI ran on this head — merge it anyway?",
},
// -----------------------------------------------------------------------
// /cso — security audit
// -----------------------------------------------------------------------
'cso-global-scan-approval': {
id: 'cso-global-scan-approval',
skill: 'cso',
category: 'approval',
door_type: 'one-way',
options: ['accept', 'deny'],
description: "Run a global security scan? (Scans files outside this branch.)",
},
'cso-finding-fix': {
id: 'cso-finding-fix',
skill: 'cso',
category: 'approval',
door_type: 'one-way',
options: ['fix-now', 'defer', 'accept-risk'],
description: "Security finding — fix, defer to TODOs, or accept the risk?",
},
// -----------------------------------------------------------------------
// /gstack-upgrade — version upgrade
// -----------------------------------------------------------------------
-1
View File
@@ -47,7 +47,6 @@ const skillSaveMap: Record<string, SkillSaveMeta> = {
'plan-devex-review': { slugPrefix: 'devex-reviews', title: 'Devex Review', tag: 'devex-review' },
'retro': { slugPrefix: 'retros', title: 'Retro', tag: 'retro' },
'ship': { slugPrefix: 'releases', title: 'Release', tag: 'release' },
'cso': { slugPrefix: 'security-audits', title: 'Security Audit', tag: 'security-audit' },
'design-consultation': { slugPrefix: 'design-systems', title: 'Design System', tag: 'design-system' },
};
@@ -18,6 +18,6 @@ If you are looping on the same diagnostic, same file, or failed fix variants, ST
//
// Skills by tier:
// T1: browse, setup-cookies, benchmark
// T2: cso, retro, doc-release, setup-deploy, canary, checkpoint, health
// T2: retro, doc-release, setup-deploy, canary, checkpoint, health
// T3: autoplan, codex, design-consult, office-hours, ceo/design/eng-review
// T4: ship, review, qa, qa-only, design-review, land-deploy
+1 -1
View File
@@ -3,7 +3,7 @@
*
* {{REDACT_TAXONOMY_TABLE}} → markdown table of the 3-tier taxonomy,
* derived from lib/redact-patterns so /spec
* and /cso never drift from the engine.
* never drifts from the engine.
* {{REDACT_INVOCATION_BLOCK:<sink>}} → the canonical scan-at-sink bash + prose
* for one enforcement point. <sink> is a
* hyphenated label: pre-codex, pre-archive,
+1 -5
View File
@@ -6,7 +6,6 @@
* sibling's. These resolvers render that rule once:
*
* {{SIDEWAYS_SWEEP}} review Step 4: sweep + the forced-CRITICAL list
* {{SIDEWAYS_SWEEP:cso}} /cso Phase 12: the sibling sweep only (D2: nothing else)
* {{FLAKE_FIX_NUMBER:review}} a test-only flake fix needs P(fail | regression) before and after
*
* `undeclaredBehaviorLines()` is the Scope Check addition the plan-completion
@@ -24,10 +23,7 @@ export function forcedCriticalPhrase(): string {
return 'data loss, a trust-boundary bypass or uncapped spend';
}
export function generateSidewaysSweep(_ctx: TemplateContext, args?: string[]): string {
if (args?.[0] === 'cso') {
return 'After supporting a finding, grep its pattern at every other in-scope ingress, command and call site; severity follows the worst sibling.';
}
export function generateSidewaysSweep(_ctx: TemplateContext, _args?: string[]): string {
return `**Sideways sweep (every finding; reads code OUTSIDE the diff).** Grep the finding's pattern at every other ingress, command and call site, Read each match and rate severity on the worst sibling; a new enum value, status, tier or type constant is traced through every consumer the same way (checklist: Sideways sweep). ${forcedCriticalPhrase().replace(/^d/, 'D')} is forced CRITICAL: no lane, specialist, dedup or saved decision downgrades it. Keep findings anchored to changed code.`;
}
-1
View File
@@ -59,5 +59,4 @@ sudo install -T -o root -g root -m 4755 "${chrome%/*}/chrome_sandbox" "${chrome%
bun run vendor:xterm
bash browse/scripts/build-node-server.sh
bun run build:gates
bun run build:cso
} >/dev/null