diff --git a/bin/gstack-skill-end b/bin/gstack-skill-end index 9b0007eed..d03a04aa1 100755 --- a/bin/gstack-skill-end +++ b/bin/gstack-skill-end @@ -118,10 +118,13 @@ if [ "$_TEL" != "off" ] && [ -x "$_BIN/gstack-telemetry-log" ]; then fi fi ;; esac + # error_class: an error run's exit reason, from exit_reason's own fixed list. + _ERR_CLASS="" + [ "$OUTCOME" = error ] && case "$EXIT_REASON" in blocked|tool_error|test_failed|context_limit|gave_up) _ERR_CLASS="$EXIT_REASON" ;; esac "$_BIN/gstack-telemetry-log" \ --skill "$SKILL_NAME" --duration "$_TEL_DUR" --outcome "$OUTCOME" \ --used-browse "$USED_BROWSE" --session-id "$SESSION_ID" \ - --error-message "$ERROR_MESSAGE" --failed-step "$FAILED_STEP" \ + --error-class "$_ERR_CLASS" --error-message "$ERROR_MESSAGE" --failed-step "$FAILED_STEP" \ --host "$_HOST" --routing "$_ROUTING" --harness-session "$_HSESS" \ --exit-reason "$EXIT_REASON" --invoked "$INVOKED" --model-family "$MODEL_FAMILY" --checks "$CHECKS" 2>/dev/null & fi diff --git a/bin/gstack-telemetry-log b/bin/gstack-telemetry-log index 63bf660f6..7bd859a23 100755 --- a/bin/gstack-telemetry-log +++ b/bin/gstack-telemetry-log @@ -123,6 +123,17 @@ if [ "$TIER" = "off" ]; then exit 0 fi +# One row per onboarding step and outcome per install a day: setup sends its step on +# every run, so anything rerunning ./setup in a loop repeated it hundreds of times an hour. +# The day's marker is claimed with noclobber (O_EXCL), so concurrent runs send it once. +if [ "$EVENT_TYPE" = "onboarding" ]; then + OB_NAME="$(printf '%s' "$SKILL" | tr -cd 'A-Za-z0-9_-')--$(printf '%s' "$OUTCOME" | tr -cd 'A-Za-z0-9_-')" + OB_MARKER="$ANALYTICS_DIR/.onboarding-$OB_NAME-$(date -u +%Y-%m-%d)" + mkdir -p "$ANALYTICS_DIR" 2>/dev/null + ( set -C; : > "$OB_MARKER" ) 2>/dev/null || exit 0 # best-effort: another run already recorded this step today + for _ob in "$ANALYTICS_DIR"/.onboarding-"$OB_NAME"-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]; do [ "$_ob" = "$OB_MARKER" ] || rm -f "$_ob"; done +fi + # ─── Finalize stale .pending markers ──────────────────────── # Each session gets its own .pending-$SESSION_ID file to avoid races # between concurrent sessions. Finalize any that don't match our session. diff --git a/bin/gstack-telemetry-tier b/bin/gstack-telemetry-tier index 02117f3a3..4d6ed35de 100755 --- a/bin/gstack-telemetry-tier +++ b/bin/gstack-telemetry-tier @@ -40,6 +40,17 @@ if [ "${1:-}" = "--capy" ] || [ "$capy" != off ]; then echo "$capy" exit 0 fi +# On a Capy install (gstack-capy-install's state file in this checkout's git +# dir) only the opt-in above sends: a shell that never sourced the launch file, +# such as a /ship reader subagent's, is off, never the machine setting. Both +# the logical and the physical root count: a host directory that links only +# bin/ (Codex, Factory, OpenCode, Cursor, Kiro) resolves to the checkout -P. +for _root in "$(cd "$(dirname "$0")/.." 2>/dev/null && pwd)" "$(cd -P "$(dirname "$0")/.." 2>/dev/null && pwd)"; do + if [ -n "$_root" ] && [ -f "$(git -C "$_root" rev-parse --absolute-git-dir 2>/dev/null)/gstack-capy-install.state" ]; then + echo off + exit 0 + fi +done tier=$("$(dirname "$0")/gstack-config" get telemetry 2>/dev/null || true) case "$tier" in anonymous|community) echo "$tier" ;; diff --git a/changelog.d/telemetry-env-fixes-batch-b.md b/changelog.d/telemetry-env-fixes-batch-b.md new file mode 100644 index 000000000..2fc8fe7b1 --- /dev/null +++ b/changelog.d/telemetry-env-fixes-batch-b.md @@ -0,0 +1,4 @@ +--- +important: security +--- +**On a Capy install, only the owner's opt-in sends telemetry.** A shell that never sourced the launch file, such as a /ship reader subagent's or a Codex skill's that reaches gstack through a linked `bin/`, used to fall back to the machine's telemetry setting and send rows labelled `live`; it now sends nothing, as docs/privacy.md already says. Error runs now fill `error_class` from their exit reason (the same fixed list), and each onboarding step and outcome is sent at most once a day per install, so a loop that reruns `./setup` no longer floods the counts. Test runs strip the launch file's preferences-file and loadout variables and the Claude plugin state root, and the ship test fixture drops every launch marker even when `bun test` runs outside the checkout, so a fixture can no longer read the owner's real approvals or preferences. diff --git a/scripts/harness-pins/scripts/lib/shard-engine.ts.json b/scripts/harness-pins/scripts/lib/shard-engine.ts.json index 7aafbeeb6..aba0c41b3 100644 --- a/scripts/harness-pins/scripts/lib/shard-engine.ts.json +++ b/scripts/harness-pins/scripts/lib/shard-engine.ts.json @@ -1 +1 @@ -{"blob":"8ee2872d038520d3d3d958d25fd18cf6609ffa69","since":6,"nonBehavioral":"createShardSandbox writes the .gstack-test-fixture marker into the shard state dir beside tmp/ (GST-1695); with it test-setup.ts keeps the shard TMPDIR exactly as main hands it, so no case sees a different temp layout, input or verdict, and tmp/ stays empty for the bootstrap retention scope"} +{"blob":"77f0039e555cf695bdda02e123b4d6af6d378682","since":6,"nonBehavioral":"CAPY_LAUNCH_MARKERS gains GSTACK_PREFERENCES_FILE and GSTACK_LOADOUT_SKILL_ROOT, which the shard sandbox strips from fixture children; CI never sets either, so no case there sees a different input or verdict, and a Capy machine stops leaking the owner's settings into fixtures"} diff --git a/scripts/lib/shard-engine.ts b/scripts/lib/shard-engine.ts index 8ee2872d0..77f0039e5 100644 --- a/scripts/lib/shard-engine.ts +++ b/scripts/lib/shard-engine.ts @@ -597,7 +597,7 @@ export function createShardSandbox( * child a shard spawns, so fixtures would see an unattended Capy session they * never set up (GSTA-99); each fixture sets its own session kind. */ -export const CAPY_LAUNCH_MARKERS = ['GSTACK_SESSION_KIND', 'GSTACK_CAPY', 'GSTACK_EPHEMERAL', 'GSTACK_INSTALL_VERDICT'] as const; +export const CAPY_LAUNCH_MARKERS = ['GSTACK_SESSION_KIND', 'GSTACK_CAPY', 'GSTACK_EPHEMERAL', 'GSTACK_INSTALL_VERDICT', 'GSTACK_PREFERENCES_FILE', 'GSTACK_LOADOUT_SKILL_ROOT'] as const; /** * Asynchronous best-effort backstop removal: a SIGKILLed shard can leave a diff --git a/test-setup.ts b/test-setup.ts index e19d10d8d..d8bbac3b9 100644 --- a/test-setup.ts +++ b/test-setup.ts @@ -23,7 +23,7 @@ import { FIXTURE_MARKER } from './lib/fixture-marker'; import { CAPY_LAUNCH_MARKERS } from './scripts/lib/shard-engine'; // State-root hermeticity (docs/state-root.md). Tests isolate state with -// GSTACK_HOME, but GSTACK_STATE_ROOT and GSTACK_STATE_DIR outrank or join it +// GSTACK_HOME, but GSTACK_STATE_ROOT, GSTACK_STATE_DIR and CLAUDE_PLUGIN_DATA outrank or join it // in the chain, so an ambient value from the parent shell would redirect // every test's state. Strip them before any test module loads. The merged // privacy keys also read $HOME/.gstack; point that second root at a @@ -36,6 +36,8 @@ for (const name of ['GSTACK_STATE_ROOT', 'GSTACK_STATE_DIR']) { delete process.env[name]; process.stderr.write(`test-setup: stripped inherited ${name}; tests isolate state via GSTACK_HOME\n`); } +// The chain's plugin link (CLAUDE_PLUGIN_DATA) goes too; no test runs as a Claude plugin. +delete process.env.CLAUDE_PLUGIN_DATA; // The Capy installer's launch markers (GSTA-99, GSTA-104): a focused `bun test` // run from a shell that sourced the launch file would hand every product child // an unattended Capy session it never set up. The shard engine strips the same diff --git a/test/helpers/ship-bin-fixture.ts b/test/helpers/ship-bin-fixture.ts index f2b72df06..c023bdba6 100644 --- a/test/helpers/ship-bin-fixture.ts +++ b/test/helpers/ship-bin-fixture.ts @@ -8,6 +8,7 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import { CAPY_LAUNCH_MARKERS } from '../../scripts/lib/shard-engine'; const ROOT = path.resolve(import.meta.dir, '..', '..'); export const PREFLIGHT = path.join(ROOT, 'bin', 'gstack-ship-preflight'); @@ -56,7 +57,8 @@ export function shipFixture(base: Record = {}, feat: Record { const installer = fs.readFileSync(path.join(ROOT, 'bin/gstack-capy-install'), 'utf8'); expect(installer).toContain('LAUNCH_FILE="${VERDICT%.json}.env"'); expect(installer).toContain('chmod 0600 "$tmp"'); - for (const name of CAPY_LAUNCH_MARKERS) expect(installer, name).toMatch(new RegExp(`^\\s*echo "export ${name}=`, 'm')); + for (const name of CAPY_LAUNCH_MARKERS) expect(installer, name).toMatch(new RegExp(`echo "export ${name}=`)); // Both directions: every `export NAME=` line the launch file writes is either a marker the shard // sandbox and the test preload strip, or GSTACK_STATE_ROOT, which they keep on purpose (GSTA-99). - // The PATH prepend is a separate `case` line this regex ignores; PATH is kept too. - const exported = [...installer.matchAll(/^\s*echo "export ([A-Z_]+)=/gm)].map(m => m[1]).sort(); + // The PATH prepend is a separate `case` line this regex ignores; PATH is kept too. Not anchored to the line + // start: the preferences file and the loadout root are written by conditional lines (GSTA-666). + const exported = [...installer.matchAll(/echo "export ([A-Z_]+)=/g)].map(m => m[1]).sort(); expect(exported).toEqual([...CAPY_LAUNCH_MARKERS, 'GSTACK_STATE_ROOT'].sort()); expect(installer).toContain('echo "GSTACK_LAUNCH_FILE: $LAUNCH_FILE"'); for (const file of ['ship/sections/documentation.md', 'document-release/SKILL.md', 'autoplan/DRIVER.md', 'capy/skill/gstack/SKILL.md']) { diff --git a/test/next-telemetry-fields.test.ts b/test/next-telemetry-fields.test.ts index 942c272e3..623021a94 100644 --- a/test/next-telemetry-fields.test.ts +++ b/test/next-telemetry-fields.test.ts @@ -122,6 +122,13 @@ describe.skipIf(process.platform === 'win32')('gstack-skill-end next fields', () expect(e.harness_session_id).not.toBe('aaaaaaaaaaaaaaaa'); }, 30_000); + test('an error run sends its exit reason as error_class, from the same fixed list; other runs and reasons send none', async () => { + const end = (outcome: string, reason: string) => run('gstack-skill-end', ['--skill', 'qa', '--outcome', outcome, '--session-id', '99-1', '--exit-reason', reason]); + end('error', 'test_failed'); end('error', 'made_up'); end('error', 'completed'); end('success', 'tool_error'); + const rows = await eventually(4); + expect(rows.map(e => e.error_class)).toEqual(['test_failed', null, null, null]); + }); + test('an unknown start time sends a null duration, not 0', async () => { const out = run('gstack-skill-end', ['--skill', 'qa', '--outcome', 'success', '--session-id', '99-1']); expect(out).toContain('duration_s=unknown'); diff --git a/test/state-root-config-merge.test.ts b/test/state-root-config-merge.test.ts index d6a1a25e5..302de2258 100644 --- a/test/state-root-config-merge.test.ts +++ b/test/state-root-config-merge.test.ts @@ -12,6 +12,8 @@ import * as os from 'os'; import * as path from 'path'; import { readConfigKey } from '../lib/state-root'; import { repoPolicyTier, repoPolicyTierBatch } from '../lib/gbrain-repo-policy-client'; +import { CAPY_LAUNCH_MARKERS } from '../scripts/lib/shard-engine'; +import { shipFixture } from './helpers/ship-bin-fixture'; const ROOT = path.resolve(import.meta.dir, '..'); const CONFIG = path.join(ROOT, 'bin', 'gstack-config'); @@ -164,6 +166,39 @@ describe('test preload hermeticity', () => { expect(r.stderr.match(/test-setup: stripped/g)?.length).toBe(2); }); + test('bun test strips every variable the Capy launch file exports and the plugin state root (GSTA-666)', () => { + const exported = [...fs.readFileSync(path.join(ROOT, 'bin', 'gstack-capy-install'), 'utf-8').matchAll(/echo "export (GSTACK_[A-Z_]+)=/g)].map(m => m[1]); + expect(exported).toEqual(expect.arrayContaining(['GSTACK_STATE_ROOT', 'GSTACK_CAPY', 'GSTACK_PREFERENCES_FILE', 'GSTACK_LOADOUT_SKILL_ROOT'])); + const leaked = [...new Set([...exported, 'CLAUDE_PLUGIN_DATA'])].filter(k => k !== 'GSTACK_HOME'); + const probe = path.join(tmp, 'launch-probe.test.ts'); + fs.writeFileSync(probe, [ + "import { test, expect } from 'bun:test';", + "import { resolveStateRoot } from '" + path.join(ROOT, 'lib', 'state-root.ts').replace(/\\/g, '/') + "';", + "test('probe', () => {", + ` expect(${JSON.stringify(leaked)}.filter(k => process.env[k] !== undefined)).toEqual([]);`, + " expect(resolveStateRoot()).toBe(process.env.GSTACK_HOME);", + "});", + ].join('\n')); + const r = spawnSync('bun', ['test', '--preload', path.join(ROOT, 'test-setup.ts'), probe], { + cwd: tmp, + env: { ...env, ...Object.fromEntries(leaked.map(k => [k, path.join(tmp, 'real-root')])), GSTACK_HOME: resolved, CLAUDE_PLUGIN_ROOT: path.join(tmp, 'plugins', 'gstack') }, + encoding: 'utf-8', + timeout: 60_000, + }); + expect([r.status, r.stderr.match(/\(fail\)|error:.*$/gm)], r.stderr).toEqual([0, null]); + }); + + test.skipIf(process.platform === 'win32')('the ship bin fixture hands its children no launch marker, even without the preload (GSTA-666)', () => { + const saved = Object.fromEntries(CAPY_LAUNCH_MARKERS.map(k => [k, process.env[k]])); + for (const k of CAPY_LAUNCH_MARKERS) process.env[k] = 'leaked'; + let f: ReturnType; + try { f = shipFixture(); } finally { for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } } + try { + const r = f.run(process.execPath, ['-e', `console.log(${JSON.stringify(CAPY_LAUNCH_MARKERS)}.filter(k => process.env[k] === 'leaked').join(','))`]); + expect(r.stdout.trim()).toBe(''); + } finally { f.cleanup(); } + }); + test('bun test strips an inherited live-brain URL, so a temp-HOME gbrain child never sees it (#3466)', () => { const live = path.join(tmp, 'live-gbrain'); fs.mkdirSync(live, { recursive: true }); diff --git a/test/telemetry-capy.test.ts b/test/telemetry-capy.test.ts index e89f6c479..baee3b37c 100644 --- a/test/telemetry-capy.test.ts +++ b/test/telemetry-capy.test.ts @@ -129,6 +129,39 @@ describe.skipIf(process.platform === 'win32')('Capy telemetry opt-in', () => { expect(skillEnd({ GSTACK_CAPY: '' })).toContain('ARTIFACTS_SYNC: skipped (unattended session)'); }); + test('a shell on a Capy install that never sourced the launch file (a reader subagent) sends nothing, whatever the machine tier', () => { + const install = path.join(tmp, 'install'); + fs.mkdirSync(install); + execSync('git init -q', { cwd: install, timeout: 20_000 }); + fs.symlinkSync(BIN, path.join(install, 'bin')); + fs.copyFileSync(path.join(ROOT, 'VERSION'), path.join(install, 'VERSION')); + run(`${BIN}/gstack-config set telemetry community`, { GSTACK_SESSION_KIND: 'interactive' }); + const reader = { GSTACK_DIR: install, GSTACK_SESSION_KIND: 'interactive', GSTACK_CAPY: '' }; + const end = () => run(`${install}/bin/gstack-skill-end --skill plan-ceo-review --outcome success --session-id 123-reader --tel-start 1`, reader); + end(); + expect(sent().filter(e => e.v === 1).map(e => e.source)).toEqual(['live']); + fs.rmSync(path.join(tmp, 'sent')); + fs.rmSync(path.join(tmp, 'analytics'), { recursive: true, force: true }); fs.mkdirSync(path.join(tmp, 'analytics')); + fs.writeFileSync(path.join(install, '.git', 'gstack-capy-install.state'), 'fixture\n'); + end(); + expect(sent()).toEqual([]); + expect(run(`${install}/bin/gstack-telemetry-tier`, reader)).toBe('off'); + expect(run(`${install}/bin/gstack-telemetry-tier`, { GSTACK_DIR: install })).toBe('anonymous'); + }); + + test('a host directory that links only bin/ to a Capy install (Codex) still sees the install and sends nothing', () => { + const install = path.join(tmp, 'install'); + fs.mkdirSync(path.join(install, 'bin'), { recursive: true }); + execSync('git init -q', { cwd: install, timeout: 20_000 }); + for (const f of fs.readdirSync(BIN)) fs.symlinkSync(path.join(BIN, f), path.join(install, 'bin', f)); + fs.writeFileSync(path.join(install, '.git', 'gstack-capy-install.state'), 'fixture\n'); + const host = path.join(tmp, 'codex-skill'); + fs.mkdirSync(host); + fs.symlinkSync(path.join(install, 'bin'), path.join(host, 'bin')); + run(`${BIN}/gstack-config set telemetry community`, { GSTACK_SESSION_KIND: 'interactive' }); + expect(run(`${host}/bin/gstack-telemetry-tier`, { GSTACK_SESSION_KIND: 'interactive', GSTACK_CAPY: '' })).toBe('off'); + }); + test('gstack-telemetry-tier prints the Capy opt-in alone with --capy, else the machine setting', () => { const tier = (args = '', extra: Record = {}) => run(`${path.join(BIN, 'gstack-telemetry-tier')} ${args}`, extra); run(`${BIN}/gstack-config set telemetry community`, { GSTACK_SESSION_KIND: 'interactive' }); diff --git a/test/telemetry.test.ts b/test/telemetry.test.ts index 2b0a28b84..fa7fbef17 100644 --- a/test/telemetry.test.ts +++ b/test/telemetry.test.ts @@ -395,6 +395,29 @@ describe('.pending marker', () => { expect(events[0].outcome).toBe('chromium-install'); }); + test('each onboarding step is recorded at most once a day, however often setup reruns', () => { + setConfig('telemetry', 'community'); + for (let i = 0; i < 3; i++) run(`${BIN}/gstack-telemetry-log --event-type onboarding --skill _setup_playwright --outcome chromium-install --no-sweep`); + run(`${BIN}/gstack-telemetry-log --event-type onboarding --skill _setup_welcome --outcome shown --no-sweep`); + run(`${BIN}/gstack-telemetry-log --event-type onboarding --skill _setup_welcome --outcome shown --no-sweep`); + expect(parseJsonl().map(e => e.skill)).toEqual(['_setup_playwright', '_setup_welcome']); + }); + + test('a different onboarding outcome for the same step on the same day is still recorded', () => { + setConfig('telemetry', 'community'); + run(`${BIN}/gstack-telemetry-log --event-type onboarding --skill _setup_playwright --outcome chromium-install --no-sweep`); + run(`${BIN}/gstack-telemetry-log --event-type onboarding --skill _setup_playwright --outcome deps-missing --no-sweep`); + run(`${BIN}/gstack-telemetry-log --event-type onboarding --skill _setup_playwright --outcome deps-missing --no-sweep`); + expect(parseJsonl().map(e => e.outcome)).toEqual(['chromium-install', 'deps-missing']); + }); + + test('concurrent setup runs record an onboarding step once', () => { + setConfig('telemetry', 'community'); + const one = `${BIN}/gstack-telemetry-log --event-type onboarding --skill _setup_playwright --outcome chromium-install --no-sweep`; + run(`for i in $(seq 1 24); do ${one} & done; wait`); + expect(parseJsonl().map(e => e.outcome)).toEqual(['chromium-install']); + }); + test('finalizes stale .pending from another session as outcome:unknown', () => { setConfig('telemetry', 'anonymous');