From 14a84980eeac024c58a1ec7fdd0ab089cdfd11ab Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Fri, 20 Nov 2026 14:27:26 -0800 Subject: [PATCH] Telemetry can count gstack's own use on Capy, opt-in and kept out of public numbers (GST-3311) (#4576) Agent-driven Capy sessions still send no telemetry. If the owner's `preferences.yaml` holds `telemetry_capy: anonymous`, each skill run sends one anonymous row labelled `source=capy`, or `source=gt` from Garry's own machines. Why: we couldn't see our own gstack use on Capy, and if we had sent it, it would have been counted as real use. Nothing to do yet: nothing changes until the owner adds that line, and the ingest change ships in a separate deploy. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-skill-end | 11 +- bin/gstack-telemetry-log | 10 +- bin/gstack-telemetry-sync | 3 +- bin/gstack-telemetry-tier | 47 ++++++ changelog.d/capy-telemetry-opt-in.md | 1 + docs/capy-install.md | 3 +- docs/model-policy.md | 5 +- docs/privacy.md | 10 +- docs/unattended.md | 5 +- lib/agent-model.ts | 5 +- supabase/functions/telemetry-ingest/index.ts | 5 +- test/agent-model.test.ts | 6 + test/next-telemetry-fields.test.ts | 9 +- test/supabase-telemetry-schema.test.ts | 1 + test/telemetry-capy.test.ts | 148 +++++++++++++++++++ 15 files changed, 250 insertions(+), 19 deletions(-) create mode 100755 bin/gstack-telemetry-tier create mode 100644 changelog.d/capy-telemetry-opt-in.md create mode 100644 test/telemetry-capy.test.ts diff --git a/bin/gstack-skill-end b/bin/gstack-skill-end index 2e38cb461..9b0007eed 100755 --- a/bin/gstack-skill-end +++ b/bin/gstack-skill-end @@ -46,11 +46,13 @@ _GH="$_gstack_sr_root" _TEL=$("$_BIN/gstack-config" get telemetry 2>/dev/null || echo off) # Plan B1: an unattended session writes no usage, sends no telemetry and never # drains or pushes the artifacts queue, whatever the inherited settings say. The -# upgrade offer it skipped at start becomes one line here, read from the +# one exception is gstack's own use on Capy: the owner's preferences file can +# opt Capy sessions in at the anonymous tier (gstack-telemetry-tier --capy). +# The upgrade offer it skipped at start becomes one line here, read from the # update-check cache (no network) so the parent can act on it. _SESSION_KIND=$("$_BIN/gstack-session-kind" 2>/dev/null || echo "interactive") if [ "$_SESSION_KIND" = "unattended" ]; then - _TEL="off" + _TEL=$("$_BIN/gstack-telemetry-tier" --capy 2>/dev/null || echo off) _CACHED_UPD=$(head -1 "$_GH/last-update-check" 2>/dev/null | tr -cd 'A-Za-z0-9._+ ' || true) case "$_CACHED_UPD" in UPGRADE_AVAILABLE*) echo "UPGRADE_AVAILABLE: $(printf '%s\n' "$_CACHED_UPD" | awk '{ print $3 (NF >= 4 ? " (main at " $4 ")" : "") }'); run /gstack-upgrade" @@ -79,8 +81,9 @@ if [ "$_SESSION_KIND" != "unattended" ]; then "$_BIN/gstack-brain-sync" --once 2>/dev/null || true fi -# Local analytics (gated on telemetry setting). -if [ "$_TEL" != "off" ]; then +# Local analytics (gated on telemetry setting; an opted-in Capy session sends +# its one telemetry row below and still records no usage of its own). +if [ "$_TEL" != "off" ] && [ "$_SESSION_KIND" != "unattended" ]; then echo '{"skill":"'"$SKILL_NAME"'","duration_s":"'"$_TEL_DUR"'","outcome":"'"$OUTCOME"'","browse":"'"$USED_BROWSE"'","session":"'"$SESSION_ID"'","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"}' >> "$_GH/analytics/skill-usage.jsonl" 2>/dev/null || true fi diff --git a/bin/gstack-telemetry-log b/bin/gstack-telemetry-log index 53a3af394..63bf660f6 100755 --- a/bin/gstack-telemetry-log +++ b/bin/gstack-telemetry-log @@ -94,17 +94,21 @@ while [ $# -gt 0 ]; do done # Source: flag > GSTACK_TELEMETRY_SOURCE > an eval run (the eval harness sets -# EVALS_RUN_ID or GSTACK_EVAL_DIR) > CI > live. An explicit value always wins, -# so CI=true never relabels a row a test marked source=test. +# EVALS_RUN_ID or GSTACK_EVAL_DIR) > CI > Capy (GSTACK_CAPY=1, gstack's own +# use on Capy: capy, or gt from the owner's preferences file, never free text) +# > live. An explicit value always wins, so CI=true never relabels a row a test +# marked source=test, and an eval lane on Capy stays eval. if [ -z "$SOURCE" ]; then if [ -n "${GSTACK_TELEMETRY_SOURCE:-}" ]; then SOURCE="$GSTACK_TELEMETRY_SOURCE" elif [ -n "${EVALS_RUN_ID:-}" ] || [ -n "${GSTACK_EVAL_DIR:-}" ]; then SOURCE="eval" elif [ "${CI:-}" = "true" ]; then SOURCE="ci" + elif [ "${GSTACK_CAPY:-}" = "1" ]; then SOURCE="$("$GSTACK_DIR/bin/gstack-telemetry-tier" --source 2>/dev/null || echo capy)" else SOURCE="live"; fi fi # ─── Read telemetry tier ───────────────────────────────────── -TIER="$("$CONFIG_CMD" get telemetry 2>/dev/null || true)" +# gstack-telemetry-tier adds the Capy opt-in to this machine's setting. +TIER="$("$GSTACK_DIR/bin/gstack-telemetry-tier" 2>/dev/null || "$CONFIG_CMD" get telemetry 2>/dev/null || true)" TIER="${TIER:-off}" # Validate tier diff --git a/bin/gstack-telemetry-sync b/bin/gstack-telemetry-sync index 92bb14b1d..7fee88392 100755 --- a/bin/gstack-telemetry-sync +++ b/bin/gstack-telemetry-sync @@ -45,7 +45,8 @@ if [ -f "$RATE_FILE" ]; then fi # ─── Read tier ─────────────────────────────────────────────── -TIER="$("$CONFIG_CMD" get telemetry 2>/dev/null || true)" +# gstack-telemetry-tier adds the Capy opt-in to this machine's setting. +TIER="$("$GSTACK_DIR/bin/gstack-telemetry-tier" 2>/dev/null || "$CONFIG_CMD" get telemetry 2>/dev/null || true)" TIER="${TIER:-off}" [ "$TIER" = "off" ] && exit 0 diff --git a/bin/gstack-telemetry-tier b/bin/gstack-telemetry-tier new file mode 100755 index 000000000..02117f3a3 --- /dev/null +++ b/bin/gstack-telemetry-tier @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# gstack-telemetry-tier — the tier this session's telemetry goes out at, and +# the label a Capy session's rows carry. +# +# gstack-telemetry-tier → off | anonymous | community +# gstack-telemetry-tier --capy → the Capy opt-in alone: anonymous | off +# gstack-telemetry-tier --source → the Capy label: capy | gt +# +# A Capy session (GSTACK_CAPY=1) is opted in only by the owner's preferences +# file (GSTACK_PREFERENCES_FILE, beside the Capy skill's SKILL.md) holding +# exactly one `telemetry_capy: anonymous` line. It then sends at the anonymous +# tier whatever this machine's `telemetry` setting says. Only anonymous: +# community's installation_id is a stable device id, and Capy's consent rules +# one out (docs/privacy.md). No file, no line, two lines, another value or a +# file over 4 KB is off. Without the opt-in this prints the machine's setting. +# Unattended sessions stay silent unless opted in: gstack-skill-end asks --capy. +# +# gstack-telemetry-log labels a Capy session's rows from a fixed list: +# `telemetry_capy_source: gt` (gstack's maintainer's own machines) gives gt, +# and anything else, a missing line included, gives capy. + +# pref KEY → the value of the file's one `KEY:` line, empty when there is not exactly one. +pref() { + local f="${GSTACK_PREFERENCES_FILE:-}" bom lines + [ "${GSTACK_CAPY:-}" = "1" ] && [ -n "$f" ] && [ -f "$f" ] || return 0 + [ "$(wc -c < "$f" 2>/dev/null || echo 4097)" -le 4096 ] || return 0 + bom=$(printf '\357\273\277') + lines=$(LC_ALL=C sed -e "1s/^$bom//" "$f" 2>/dev/null | tr -d '\r' | grep -E "^$1:" || true) + [ -n "$lines" ] && [ "$(printf '%s\n' "$lines" | wc -l | tr -d ' ')" = 1 ] || return 0 + printf '%s' "${lines#"$1":}" | sed -e 's/[[:space:]]#.*$//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e "s/^\([\"']\)\(.*\)\1\$/\2/" +} + +if [ "${1:-}" = "--source" ]; then + case "$(pref telemetry_capy_source)" in gt) echo gt ;; *) echo capy ;; esac + exit 0 +fi +capy=off +[ "$(pref telemetry_capy)" = anonymous ] && capy=anonymous +if [ "${1:-}" = "--capy" ] || [ "$capy" != off ]; then + echo "$capy" + exit 0 +fi +tier=$("$(dirname "$0")/gstack-config" get telemetry 2>/dev/null || true) +case "$tier" in + anonymous|community) echo "$tier" ;; + *) echo off ;; +esac diff --git a/changelog.d/capy-telemetry-opt-in.md b/changelog.d/capy-telemetry-opt-in.md new file mode 100644 index 000000000..17a6be8f1 --- /dev/null +++ b/changelog.d/capy-telemetry-opt-in.md @@ -0,0 +1 @@ +**gstack's own use on Capy can be counted, and is kept out of real-use numbers.** Agent-driven sessions on Capy still send no telemetry by default. When the owner's `preferences.yaml` beside the Capy gstack skill holds `telemetry_capy: anonymous`, each skill run there sends one row at the anonymous tier (no device ID, even on a machine set to `community`), labelled `source=capy`, or `source=gt` with `telemetry_capy_source: gt`. Eval and CI labels still win on Capy, unattended sessions elsewhere are unchanged, the ingest function accepts both labels, and the public dashboard's views count only `live` rows. `bin/gstack-telemetry-tier` is the one place that reads these settings. diff --git a/docs/capy-install.md b/docs/capy-install.md index df3aeaac0..234c27fd9 100644 --- a/docs/capy-install.md +++ b/docs/capy-install.md @@ -538,7 +538,8 @@ When the session starts from the Drive skill (a bootstrapper outside the checkout), the file also exports `GSTACK_PREFERENCES_FILE`, the path of `preferences.yaml` beside that skill's SKILL.md, which the `GSTACK_LAUNCH` line leaves out; `gstack-models resolve --role agent` reads it -([your model preference](model-policy.md#your-model-preference)). +([your model preference](model-policy.md#your-model-preference)), and +`gstack-telemetry-tier` reads its Capy telemetry opt-in ([privacy](privacy.md)). The file is part of the ok verdict: a passing run that cannot write it exits 1 with `gstack: fail launch-file — could not write the launch file ; fix: make writable, or set GSTACK_STATE_ROOT to a writable directory diff --git a/docs/model-policy.md b/docs/model-policy.md index 5e9a30621..b2b03e22a 100644 --- a/docs/model-policy.md +++ b/docs/model-policy.md @@ -169,7 +169,10 @@ A value gstack can't use stops only the agent role, naming the file and the fix. **On Capy.** Each cloud machine starts fresh, so config.yaml does not carry over. Keep the preference in `preferences.yaml` next to the gstack skill's SKILL.md in your Drive: one `agent_model: ` line, with `#` comments -allowed (any other key is ignored with a warning). The session start puts the +allowed. The file may also hold `telemetry_capy: anonymous`, which opts gstack's +own Capy sessions in to anonymous telemetry, and `telemetry_capy_source: gt`, +which labels those rows `gt` ([privacy](privacy.md)); any other key is ignored +with a warning. The session start puts the file's path in the launch file as `GSTACK_PREFERENCES_FILE` and gstack reads it where it is: nothing is copied, and `--check` never writes the skill folder. Agents write that file only when you ask them to remember a preference. To change or clear it for diff --git a/docs/privacy.md b/docs/privacy.md index 1e5808714..e72273d6a 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -38,8 +38,16 @@ no, and `gstack-config set telemetry off` turns it off at any time. `other`) and the version you came from. `--check` and unattended sessions send nothing. - `source` is set to `ci` under CI and `eval` inside gstack's eval runs, - so lab traffic stays out of real-use numbers. A duration gstack can't + so lab traffic stays out of real-use numbers. gstack's own use on Capy is + labelled `capy` (or `gt`, below) and kept out of them too. A duration gstack can't measure is sent empty instead of 0. +- **On Capy:** sessions an agent drives there send nothing unless the owner's + `preferences.yaml` beside the Capy gstack skill holds the line + `telemetry_capy: anonymous`. Then each skill run sends one row at the + `anonymous` tier (no device ID, even on a machine set to `community`), + labelled `capy`. Any other value, or two such lines, is off. A second line, + `telemetry_capy_source: gt`, labels the rows `gt` instead (gstack's + maintainer's own machines); any other label is `capy`. - **What's never sent:** code, file paths, repo names, branch names, prompts, or any other content you write. - **What stays on your machine:** opted in, each run is also logged to diff --git a/docs/unattended.md b/docs/unattended.md index 9d3371752..48ea722a3 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -34,7 +34,10 @@ drives still sets `GSTACK_SESSION_KIND=unattended` itself. onboarding tips and routing blocks are suppressed exactly as they are for `spawned`. An unanswered consent is `off`. - **No publishing or sync, enforced at the writers.** Usage analytics are not - written (`TELEMETRY_WRITE: skipped (unattended session)`), the artifacts + written (`TELEMETRY_WRITE: skipped (unattended session)`; the one exception + is a Capy session the owner opted in with `telemetry_capy: anonymous`, which + sends one anonymous row per skill run labelled `capy` (or `gt`), see + [privacy](privacy.md)), the artifacts repo is neither pulled nor pushed (`ARTIFACTS_SYNC: skipped (unattended session; mode= queue= retained)`), the sync spool is not fed (`gstack-brain-enqueue` is a no-op, and `gstack-review-log` says `review-log: diff --git a/lib/agent-model.ts b/lib/agent-model.ts index 5f2526c98..d32c2fddc 100644 --- a/lib/agent-model.ts +++ b/lib/agent-model.ts @@ -14,6 +14,8 @@ import { readConfigKeyWithRoot, type StateRootEnv } from './state-root'; export const AGENT_MODEL_KEY = 'agent_model' as const; export const PREFERENCES_FILE_MAX_BYTES = 4096; +/** Other keys gstack reads from the preferences file: bin/gstack-telemetry-tier reads the telemetry ones. */ +const OTHER_PREFERENCE_KEYS = new Set(['telemetry_capy', 'telemetry_capy_source']); const DOCS = 'https://github.com/garrytan/gstack/blob/main/docs/model-policy.md#your-model-preference'; /** Family names a preference may use. When gstack's tier catalog lists a family, its entry here is the same model (test/agent-model.test.ts). */ @@ -94,7 +96,7 @@ function invalid(value: string, where: string, repair: string[]): AgentModelErro ); } -/** Read agent_model from a preferences file: `key: value` lines, # comments, at most 4 KB. Unknown keys warn; a duplicate agent_model is an error. */ +/** Read agent_model from a preferences file: `key: value` lines, # comments, at most 4 KB. Keys gstack reads elsewhere pass silently, unknown keys warn; a duplicate agent_model is an error. */ export function readPreferencesFile(file: string): { value: string | null; warnings: string[] } { let text: string; try { @@ -114,6 +116,7 @@ export function readPreferencesFile(file: string): { value: string | null; warni if (trimmed === '' || trimmed.startsWith('#')) return; const m = /^([a-z][a-z0-9_]*):(.*)$/.exec(line); if (!m) { warnings.push(`${file}:${i + 1} is not a 'key: value' line; ignored`); return; } + if (OTHER_PREFERENCE_KEYS.has(m[1])) return; if (m[1] !== AGENT_MODEL_KEY) { warnings.push(`${file}:${i + 1} sets '${sanitize(m[1])}', which gstack does not read from preferences; ignored`); return; } if (value !== null) throw new AgentModelError(`${file} sets agent_model twice`, 'keep one agent_model line', [`edit ${file}`]); value = m[2].replace(/\s#.*$/, '').trim().replace(/^(["'])(.*)\1$/, '$2'); diff --git a/supabase/functions/telemetry-ingest/index.ts b/supabase/functions/telemetry-ingest/index.ts index 40d0a9cae..de6f018be 100644 --- a/supabase/functions/telemetry-ingest/index.ts +++ b/supabase/functions/telemetry-ingest/index.ts @@ -79,9 +79,10 @@ function normalizeOutcome(outcome: unknown) { } // bin/gstack-telemetry-log writes source from --source or -// GSTACK_TELEMETRY_SOURCE (default "live"). Keep it so test and eval traffic +// GSTACK_TELEMETRY_SOURCE (default "live"). Keep it so test, eval, CI and +// gstack's own use on Capy ("capy", or "gt" from its maintainer's machines) // can be told apart from real use; anything unexpected is "other", never "live". -const SOURCES = ["live", "test", "eval", "ci"]; +const SOURCES = ["live", "test", "eval", "ci", "capy", "gt"]; function normalizeSource(source: unknown): string { if (source === undefined || source === null || source === "") return "live"; return SOURCES.includes(String(source)) ? String(source) : "other"; diff --git a/test/agent-model.test.ts b/test/agent-model.test.ts index b973425ae..4b4417bc3 100644 --- a/test/agent-model.test.ts +++ b/test/agent-model.test.ts @@ -168,6 +168,12 @@ describe('the preferences file', () => { expect(() => readPreferencesFile(f)).toThrow(/sets agent_model twice/); }); + test('the telemetry keys are read by gstack-telemetry-tier, so they pass without a warning', () => { + const f = path.join(tmp(), 'preferences.yaml'); + fs.writeFileSync(f, 'agent_model: opus\ntelemetry_capy: anonymous\ntelemetry_capy_source: gt\n'); + expect(readPreferencesFile(f)).toEqual({ value: 'opus', warnings: [] }); + }); + test('CRLF line endings, a byte-order mark and a trailing comment still read the value', () => { const f = path.join(tmp(), 'preferences.yaml'); fs.writeFileSync(f, '\ufeff# owner preferences\r\nagent_model: opus # my pick\r\n'); diff --git a/test/next-telemetry-fields.test.ts b/test/next-telemetry-fields.test.ts index 2fa557b6a..942c272e3 100644 --- a/test/next-telemetry-fields.test.ts +++ b/test/next-telemetry-fields.test.ts @@ -65,13 +65,14 @@ describe.skipIf(process.platform === 'win32')('gstack-telemetry-log next fields' expect([b.harness_session_id, b.from_version]).toEqual([null, null]); }); - test('source: flag > GSTACK_TELEMETRY_SOURCE > eval run > CI > live, so CI never relabels a test row', () => { + test('source: flag > GSTACK_TELEMETRY_SOURCE > eval run > CI > Capy > live, so CI never relabels a test row', () => { run('gstack-telemetry-log', ['--outcome', 'success', '--source', 'test'], { CI: 'true', EVALS_RUN_ID: 'r1' }); run('gstack-telemetry-log', ['--outcome', 'success'], { CI: 'true', GSTACK_TELEMETRY_SOURCE: 'test' }); - run('gstack-telemetry-log', ['--outcome', 'success'], { CI: 'true', EVALS_RUN_ID: 'r1' }); - run('gstack-telemetry-log', ['--outcome', 'success'], { CI: 'true' }); + run('gstack-telemetry-log', ['--outcome', 'success'], { CI: 'true', EVALS_RUN_ID: 'r1', GSTACK_CAPY: '1' }); + run('gstack-telemetry-log', ['--outcome', 'success'], { CI: 'true', GSTACK_CAPY: '1' }); + run('gstack-telemetry-log', ['--outcome', 'success'], { GSTACK_CAPY: '1' }); run('gstack-telemetry-log', ['--outcome', 'success']); - expect(events().map(e => e.source)).toEqual(['test', 'test', 'eval', 'ci', 'live']); + expect(events().map(e => e.source)).toEqual(['test', 'test', 'eval', 'ci', 'capy', 'live']); }); }); diff --git a/test/supabase-telemetry-schema.test.ts b/test/supabase-telemetry-schema.test.ts index 62544085f..8629aada3 100644 --- a/test/supabase-telemetry-schema.test.ts +++ b/test/supabase-telemetry-schema.test.ts @@ -41,6 +41,7 @@ describe('telemetry-ingest accepts what the client sends', () => { test('ingest stores source, so test and eval traffic stay separable', () => { expect(INGEST).toContain('source: normalizeSource(event.source)'); + expect(INGEST).toContain('const SOURCES = ["live", "test", "eval", "ci", "capy", "gt"];'); }); test('ingest writes with the service role key, the only write path once 008 drops the anon policies', () => { diff --git a/test/telemetry-capy.test.ts b/test/telemetry-capy.test.ts new file mode 100644 index 000000000..e89f6c479 --- /dev/null +++ b/test/telemetry-capy.test.ts @@ -0,0 +1,148 @@ +/** Capy's own gstack use (GST-3311): an unattended Capy session sends + * telemetry only when the owner's preferences file opts it in, always at the + * anonymous tier and labelled source=capy unless an eval or CI label wins. + * Network is stubbed; nothing leaves the box. */ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { execSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const BIN = path.join(ROOT, 'bin'); +let tmp: string; +let prefs: string; + +function run(cmd: string, extra: Record = {}): string { + return execSync(`{ ${cmd}\n} | cat; exit "\${PIPESTATUS[0]}"`, { + shell: '/bin/bash', + cwd: tmp, + env: { + ...process.env as Record, + HOME: path.join(tmp, 'home'), GSTACK_HOME: tmp, GSTACK_STATE_ROOT: tmp, GSTACK_STATE_DIR: tmp, + GSTACK_DIR: ROOT, GSTACK_SUPABASE_URL: 'https://telemetry.fixture.invalid', GSTACK_SUPABASE_ANON_KEY: 'fixture', + GSTACK_TEST_CAPTURE: path.join(tmp, 'sent'), + GSTACK_SESSION_KIND: 'unattended', GSTACK_CAPY: '1', GSTACK_PREFERENCES_FILE: prefs, + CI: '', GSTACK_TELEMETRY_SOURCE: '', EVALS_RUN_ID: '', GSTACK_EVAL_DIR: '', + PATH: `${path.join(tmp, 'bin')}:${process.env.PATH}`, + ...extra, + }, + encoding: 'utf-8', + timeout: 20_000, + }).trim(); +} +function skillEnd(extra: Record = {}) { + return run(`${BIN}/gstack-skill-end --skill review --outcome success --session-id 123-capy --tel-start 1`, extra); +} +function sent(): any[] { + const f = path.join(tmp, 'sent'); + if (!fs.existsSync(f)) return []; + return fs.readFileSync(f, 'utf-8').split('\n').filter(Boolean).flatMap(b => JSON.parse(b)); +} +function writePrefs(text: string) { fs.writeFileSync(prefs, text); } + +beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-capytel-')); + prefs = path.join(tmp, 'preferences.yaml'); + fs.mkdirSync(path.join(tmp, 'home')); + fs.mkdirSync(path.join(tmp, 'bin')); + fs.mkdirSync(path.join(tmp, 'analytics')); + fs.writeFileSync(path.join(tmp, 'bin', 'curl'), `#!/bin/sh +out='' +while [ "$#" -gt 0 ]; do + case "$1" in + -o) shift; out="$1" ;; + @*) cat "\${1#@}" >> "$GSTACK_TEST_CAPTURE"; printf '\\n' >> "$GSTACK_TEST_CAPTURE" ;; + esac + shift +done +[ -z "$out" ] || printf '{"inserted":1}' > "$out" +printf 200 +`, { mode: 0o755 }); + writePrefs('agent_model: opus\ntelemetry_capy: anonymous # GST-3311\n'); +}); +afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); }); + +describe.skipIf(process.platform === 'win32')('Capy telemetry opt-in', () => { + test('an opted-in Capy session sends exactly one anonymous row labelled capy, even on a community machine', () => { + run(`${BIN}/gstack-config set telemetry community`, { GSTACK_SESSION_KIND: 'interactive' }); + skillEnd(); + const rows = sent(); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ skill: 'review', outcome: 'success', source: 'capy' }); + expect(rows[0]).not.toHaveProperty('installation_id'); + expect(fs.existsSync(path.join(tmp, 'installation-id'))).toBe(false); + }); + + test('without exactly one telemetry_capy: anonymous line a Capy session sends nothing', () => { + skillEnd(); + expect(sent()).toHaveLength(1); + for (const text of ['agent_model: opus\n', 'telemetry_capy: off\n', 'telemetry_capy: community\n', 'telemetry_capy: yes\n', + 'telemetry_capy: anonymous\ntelemetry_capy: anonymous\n', ' telemetry_capy: anonymous\n']) { + fs.rmSync(path.join(tmp, 'sent'), { force: true }); + fs.rmSync(path.join(tmp, 'analytics'), { recursive: true, force: true }); fs.mkdirSync(path.join(tmp, 'analytics')); + writePrefs(text); + skillEnd(); + expect([text, sent()]).toEqual([text, []]); + } + fs.rmSync(prefs); + skillEnd(); + expect(sent()).toEqual([]); + }); + + test('an eval run and CI keep their own labels on Capy', () => { + skillEnd({ EVALS_RUN_ID: 'r1', CI: 'true' }); + expect(sent().map(e => e.source)).toEqual(['eval']); + fs.rmSync(path.join(tmp, 'sent')); + fs.rmSync(path.join(tmp, 'analytics'), { recursive: true, force: true }); fs.mkdirSync(path.join(tmp, 'analytics')); + skillEnd({ CI: 'true' }); + expect(sent().map(e => e.source)).toEqual(['ci']); + }); + + test('telemetry_capy_source: gt labels the row gt; eval and CI still win over it', () => { + writePrefs('telemetry_capy: anonymous\ntelemetry_capy_source: gt\n'); + skillEnd(); + expect(sent().map(e => [e.source, e.installation_id])).toEqual([['gt', undefined]]); + for (const [extra, label] of [[{ EVALS_RUN_ID: 'r1' }, 'eval'], [{ GSTACK_EVAL_DIR: tmp }, 'eval'], [{ CI: 'true' }, 'ci']] as const) { + fs.rmSync(path.join(tmp, 'sent')); + fs.rmSync(path.join(tmp, 'analytics'), { recursive: true, force: true }); fs.mkdirSync(path.join(tmp, 'analytics')); + skillEnd(extra); + expect(sent().map(e => e.source)).toEqual([label]); + } + }); + + test('the label is a fixed-list pick: anything but one gt line falls back to capy', () => { + for (const label of ['live', 'GT', 'gt-x', 'other', '', 'gt\ntelemetry_capy_source: gt']) { + fs.rmSync(path.join(tmp, 'sent'), { force: true }); + fs.rmSync(path.join(tmp, 'analytics'), { recursive: true, force: true }); fs.mkdirSync(path.join(tmp, 'analytics')); + writePrefs(`telemetry_capy: anonymous\ntelemetry_capy_source: ${label}\n`); + skillEnd(); + expect([label, sent().map(e => e.source)]).toEqual([label, ['capy']]); + } + }); + + test('an unattended session outside Capy still sends nothing, whatever the preferences file or machine tier says', () => { + run(`${BIN}/gstack-config set telemetry anonymous`, { GSTACK_SESSION_KIND: 'interactive' }); + skillEnd({ GSTACK_CAPY: '' }); + expect(sent()).toEqual([]); + expect(fs.existsSync(path.join(tmp, 'analytics', 'skill-usage.jsonl'))).toBe(false); + expect(skillEnd({ GSTACK_CAPY: '' })).toContain('ARTIFACTS_SYNC: skipped (unattended session)'); + }); + + 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' }); + expect([tier('--capy'), tier()]).toEqual(['anonymous', 'anonymous']); + expect([tier('--capy', { GSTACK_CAPY: '' }), tier('', { GSTACK_CAPY: '' })]).toEqual(['off', 'community']); + writePrefs('telemetry_capy: "anonymous"\r\n'); + expect(tier('--capy')).toBe('anonymous'); + writePrefs('telemetry_capy: anonymous\n' + '#'.repeat(4096)); + expect([tier('--capy'), tier()]).toEqual(['off', 'community']); + }); + + test('outside an unattended session the label is still capy under GSTACK_CAPY=1', () => { + run(`${BIN}/gstack-config set telemetry anonymous`, { GSTACK_SESSION_KIND: 'interactive' }); + run(`${BIN}/gstack-telemetry-log --skill qa --outcome success --session-id 9-capy`, { GSTACK_PREFERENCES_FILE: '' }); + expect(sent().map(e => e.source)).toEqual(['capy']); + }); +});