From 515244505ac313c48a717608f3af08b0d499f0c6 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sat, 21 Nov 2026 08:56:50 -0800 Subject: [PATCH] /plan-tune's dream cycle now logs each send of your typed answers to Anthropic (#4617) (#4621) `gstack-distill-free-text`, which /plan-tune's dream cycle runs, now writes an entry to gstack's send log (`gstack-egress list`) before it sends your typed answers to Anthropic, and sends nothing if it can't write that entry. Why: the README promises that every off-machine send is logged, and this was the one sender that skipped it. Reported by @robbiesierra in #4617. Nothing to do: these sends now show up in `gstack-egress list`. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ARCHITECTURE.md | 2 +- bin/gstack-distill-free-text | 39 +++++++- .../plan-tune-distill-logs-anthropic-sends.md | 1 + docs/CONTRIBUTOR_REFERENCE.md | 11 ++- test/distill-free-text.test.ts | 74 ++++++++++++++ test/egress-receipt-wiring.test.ts | 98 +++++++++++++++++-- 6 files changed, 209 insertions(+), 16 deletions(-) create mode 100644 changelog.d/plan-tune-distill-logs-anthropic-sends.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b9f5518e7..bcc549ab5 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -205,7 +205,7 @@ The browser registry (Chrome, Chromium, Brave, Edge, Windows-only Opera and Oper Every enumerated gstack-initiated off-machine sink writes a hash-chained, tamper-evident receipt to `~/.gstack/security/egress.jsonl` BEFORE the send — `writeReceipt` in `lib/egress-receipt.ts` for TypeScript callers, `_receipted_curl` / `_receipted_git` from `bin/gstack-egress-lib.sh` for shell scripts. Receipts record a sha256 of the exact bytes sent when the caller owns them (subprocess-owned sends like git pushes record `sha256: null`); they never store the body. -Failure polarity is per-class and pinned by tests. Sensitive sinks are fail-closed: brain-sync pushes, memory-ingest, gbrain-sync, telemetry, ngrok tunnel starts, mcp-verify, supabase-provision, and the Memorable bridge's per-prompt `memorable-recall` hand-off (a prompt handed to a local vendor binary; see [docs/memorable-workflow-memory.md](docs/memorable-workflow-memory.md)) refuse to send if the receipt can't be written (each refusal prints problem + cause + fix). User-facing sinks fail open with a stderr warning — the design binary's OpenAI calls, update-check, the read-only dashboards, and git-class receipts proceed even when the receipt write failed, so a fail-open send can go unrecorded (warned, by design). The new-sink scanner in `test/egress-receipt-wiring.test.ts` fails CI when an off-machine sink ships unwired; its only exemptions are enumerated with reasons (user-directed page fetches, reachability probes, install-doc strings, skill prose). +Failure polarity is per-class and pinned by tests. Sensitive sinks are fail-closed: brain-sync pushes, memory-ingest, gbrain-sync, telemetry, ngrok tunnel starts, mcp-verify, supabase-provision, /plan-tune's dream-cycle send of the user's typed answers to Anthropic (`distill-free-text`), and the Memorable bridge's per-prompt `memorable-recall` hand-off (a prompt handed to a local vendor binary; see [docs/memorable-workflow-memory.md](docs/memorable-workflow-memory.md)) refuse to send if the receipt can't be written (each refusal prints problem + cause + fix). User-facing sinks fail open with a stderr warning — the design binary's OpenAI calls, update-check, the read-only dashboards, and git-class receipts proceed even when the receipt write failed, so a fail-open send can go unrecorded (warned, by design). The new-sink scanner in `test/egress-receipt-wiring.test.ts` fails CI when an off-machine sink ships unwired, including a model-provider SDK request or a file that loads a provider SDK or calls a provider API host without a receipt; its only exemptions are enumerated with reasons (user-directed page fetches, reachability probes, install-doc strings, skill prose, developer-invoked test and eval tooling). Inspect the ledger with `bin/gstack-egress`: `list` (what gstack attempted to send), `verify` (recompute the chain, exit 3 on tamper), `grants` (the standing consent settings and how to revoke each). `verify` detects in-place edits, reordering, and mid-chain deletion; it does NOT detect tail-truncation, whole-file re-fabrication, or deletion of the ledger itself — guarding against the same-machine, same-user actor who owns the file is out of scope for a forensic log. Threat model: the ledger is forensic observability of ATTEMPTED egress — it records what gstack tried to send so accidents are auditable; it is not an exfiltration control. diff --git a/bin/gstack-distill-free-text b/bin/gstack-distill-free-text index 2c4f50f67..18abfed8a 100755 --- a/bin/gstack-distill-free-text +++ b/bin/gstack-distill-free-text @@ -197,9 +197,11 @@ fi RESULT=$(EVENTS_JSON="$EVENTS_JSON" DISTILL_PROMPT="$DISTILL_PROMPT" \ PROPOSAL_FILE_PATH="$PROPOSAL_FILE" LOG_FILE_PATH="$LOG_FILE" \ ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \ + GSTACK_EGRESS_LIB="$ROOT_DIR/lib/egress-receipt.ts" GSTACK_SECURITY_DIR="$GSTACK_HOME/security" \ bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" --cwd "$ROOT_DIR" -e ' const fs = require("fs"); const Anthropic = require("@anthropic-ai/sdk").default; + const { writeReceipt, writeOutcome } = require(process.env.GSTACK_EGRESS_LIB); const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); const events = JSON.parse(process.env.EVENTS_JSON); @@ -215,11 +217,38 @@ RESULT=$(EVENTS_JSON="$EVENTS_JSON" DISTILL_PROMPT="$DISTILL_PROMPT" \ const distillModel = process.env.GSTACK_EVAL_MODEL_DISTILL || process.env.GSTACK_EVAL_MODEL || "claude-haiku-4-5-20251001"; - const resp = await client.messages.create({ - model: distillModel, - max_tokens: 4096, - messages: [{ role: "user", content: prompt }], - }); + + // Egress receipt BEFORE the send, fail-closed: the typed answers of the + // user leave the machine here, and skipping one distill costs nothing (the + // events stay undistilled for the next run). The SDK builds the request + // body, so the receipt is content-free with sha256 null. + let receipt; + try { + receipt = writeReceipt({ + sink: "distill-free-text", + host: new URL(client.baseURL).host, + payloadClass: "plan-tune-free-text count=" + events.length + " prompt_bytes=" + Buffer.byteLength(prompt) + " (request body built by the Anthropic SDK)", + bytes: 0, + sha256: null, + consent: "user ran the /plan-tune dream cycle (gstack-distill-free-text) with ANTHROPIC_API_KEY set", + }); + } catch (e) { + process.stderr.write("gstack: distill-free-text NOT sent: EGRESS_RECEIPT_FAILED (" + (e && e.message ? e.message : e) + "). Fix: chmod -R u+w " + process.env.GSTACK_SECURITY_DIR + " (or check GSTACK_HOME). gstack records everything it ATTEMPTS to send off-machine; see gstack-egress.\n"); + process.exit(3); + } + + let resp; + try { + resp = await client.messages.create({ + model: distillModel, + max_tokens: 4096, + messages: [{ role: "user", content: prompt }], + }); + } catch (e) { + try { writeOutcome({ receipt: receipt.id, status: "error:" + (e && e.status ? e.status : "transport") }); } catch {} + throw e; + } + try { writeOutcome({ receipt: receipt.id, status: "ok" }); } catch {} const text = resp.content.map((b) => (b.type === "text" ? b.text : "")).join(""); diff --git a/changelog.d/plan-tune-distill-logs-anthropic-sends.md b/changelog.d/plan-tune-distill-logs-anthropic-sends.md new file mode 100644 index 000000000..6f69db187 --- /dev/null +++ b/changelog.d/plan-tune-distill-logs-anthropic-sends.md @@ -0,0 +1 @@ +**/plan-tune's dream cycle now logs each send of your typed answers to Anthropic.** `gstack-distill-free-text` was the one off-machine sender missing from `gstack-egress list`; it now writes its entry first, holding no answer text, and sends nothing if it can't. The off-machine send test also fails on any new model-provider call that skips the log. Reported by @robbiesierra in #4617. diff --git a/docs/CONTRIBUTOR_REFERENCE.md b/docs/CONTRIBUTOR_REFERENCE.md index 67b601729..9f3b35051 100644 --- a/docs/CONTRIBUTOR_REFERENCE.md +++ b/docs/CONTRIBUTOR_REFERENCE.md @@ -48,14 +48,17 @@ send off the machine MUST write a hash-chained receipt to `writeReceipt` from `lib/egress-receipt.ts`; shell scripts source `bin/gstack-egress-lib.sh` and use `_receipted_curl` / `_receipted_git`. Failure polarity is per-class: fail-closed for sensitive sinks (brain-sync, memory-ingest, -gbrain-sync, telemetry, ngrok tunnels, mcp-verify, supabase-provision, and the -Memorable bridge's per-prompt memorable-recall hand-off), fail-open +gbrain-sync, telemetry, ngrok tunnels, mcp-verify, supabase-provision, the +/plan-tune dream-cycle distiller (distill-free-text), and the Memorable bridge's per-prompt memorable-recall hand-off), fail-open + stderr warning for user-facing ones (design OpenAI and Gemini calls, update-check, dashboards, git-class ops). The new-sink scanner in `test/egress-receipt-wiring.test.ts` fails CI on an unreceipted `curl` / -`git push` / `fetch` to a non-loopback host unless the file carries a reasoned +`git push` / `fetch` to a non-loopback host, or on a model-provider SDK request +or a file that loads a provider SDK or calls a provider API host with no +receipt, unless the file carries a reasoned entry in its `SCANNER_EXEMPT` list (user-directed page fetches, reachability -probes, instruction strings, skill prose) — if you add a new off-machine sink, +probes, instruction strings, skill prose, developer-invoked test and eval +tooling) — if you add a new off-machine sink, wire it through the helpers and add it to the enumerated sink list. `aside exec` (a gstack-composed prompt sent to Aside's agent) is a fail-open user-facing sink: skills call it through the `_aside_exec` wrapper that diff --git a/test/distill-free-text.test.ts b/test/distill-free-text.test.ts index b2d543cf8..e092ca3bd 100644 --- a/test/distill-free-text.test.ts +++ b/test/distill-free-text.test.ts @@ -205,3 +205,77 @@ describe('--background', () => { expect(r.stdout).toMatch(/DISTILL_SPAWNED: pid=\d+/); }); }); + +// ---------------------------------------------------------------------- +// Egress receipt (#4617): the typed answers leave the machine, so the +// send writes a receipt first, fail-closed. A local stand-in for the +// Anthropic API (ANTHROPIC_BASE_URL) records what the ledger held when +// the request arrived. +// ---------------------------------------------------------------------- + +describe('egress receipt', () => { + const ledgerPath = () => path.join(stateRoot, 'security', 'egress.jsonl'); + const ledgerRecords = (): Array> => + fs.existsSync(ledgerPath()) + ? fs.readFileSync(ledgerPath(), 'utf-8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)) + : []; + + async function distillAgainstStub(): Promise<{ status: number; stderr: string; requests: Array>> }> { + const requests: Array>> = []; + const server = Bun.serve({ + port: 0, + hostname: '127.0.0.1', + async fetch(req) { + await req.text(); + requests.push(ledgerRecords()); + return Response.json({ + id: 'msg_stub', type: 'message', role: 'assistant', model: 'stub', + content: [{ type: 'text', text: '{"proposals": []}' }], + stop_reason: 'end_turn', usage: { input_tokens: 10, output_tokens: 5 }, + }); + }, + }); + try { + const proc = Bun.spawn({ + cmd: [BIN], + env: makeEnv({ ANTHROPIC_API_KEY: 'test-key', ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}` }), + cwd: fixtureCwd, + stdout: 'pipe', + stderr: 'pipe', + timeout: 30_000, + }); + const [status, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]); + return { status, stderr, requests }; + } finally { + server.stop(true); + } + } + + test('writes a content-free distill-free-text receipt before the model call', async () => { + writeAuqOtherEvent('please never ask me about design review on typo fixes'); + const r = await distillAgainstStub(); + expect(r.status, r.stderr).toBe(0); + expect(r.requests.length).toBe(1); + const atSend = r.requests[0].filter((rec) => rec.type === 'egress' && rec.sink === 'distill-free-text'); + expect(atSend.length).toBe(1); + expect(atSend[0].host).toMatch(/^127\.0\.0\.1:\d+$/); + expect(atSend[0].payload_class).toContain('count=1'); + expect(atSend[0].sha256).toBeNull(); + const ledger = fs.readFileSync(ledgerPath(), 'utf-8'); + expect(ledger).not.toContain('typo fixes'); + expect(ledger).not.toContain('test-key'); + expect(ledgerRecords().some((rec) => rec.type === 'outcome')).toBe(true); + }); + + test('refuses the send when the receipt cannot be written (fail-closed)', async () => { + writeAuqOtherEvent('ship small PRs please'); + fs.writeFileSync(path.join(stateRoot, 'security'), 'not a directory'); + const r = await distillAgainstStub(); + expect(r.status).not.toBe(0); + expect(r.stderr).toContain('EGRESS_RECEIPT_FAILED'); + expect(r.requests.length).toBe(0); + const log = fs.readFileSync(path.join(stateRoot, 'projects', cwdSlug, 'question-log.jsonl'), 'utf-8'); + expect(log).not.toContain('distilled_at'); + }); +}); + diff --git a/test/egress-receipt-wiring.test.ts b/test/egress-receipt-wiring.test.ts index 30ded9710..adb32b989 100644 --- a/test/egress-receipt-wiring.test.ts +++ b/test/egress-receipt-wiring.test.ts @@ -60,6 +60,10 @@ const POLARITY: Record = { // an unrecorded hand-off of user content is the thing the ledger exists to // prevent, so it fails closed ("no receipt, no send"). 'memorable-recall': 'fail-closed', + // distill-free-text (#4617): /plan-tune's dream cycle sends the answers the + // user typed to Anthropic. Skipping one distill costs nothing (the events + // stay undistilled for the next run), so no receipt, no send. + 'distill-free-text': 'fail-closed', // fail-open: user-facing operations that must not die over an audit-log // hiccup; they warn on stderr and proceed. 'design-openai': 'fail-open', @@ -111,6 +115,9 @@ const MODULE_SINKS = [ // refs/pull//head for squashes on its base, to skip commits it already // holds; PR numbers leave the machine, sink 'sealed-guard' (fail-open). 'lib/sealed-guard.ts', + // #4617: a bash entry whose inline bun script sends the user's typed + // /plan-tune answers to Anthropic through the SDK; sink 'distill-free-text'. + 'bin/gstack-distill-free-text', ]; /** Shell sinks: must source the shared lib; every network op receipted. */ @@ -181,6 +188,10 @@ const SCANNER_EXEMPT: Record = { 'developer-invoked read-only measurement (GSTA-49 T0): git fetch of gstack\'s own origin by SHA (old PR heads and tested merge commits) so past PR gates can be replayed; a download only, no gstack or user state leaves the machine', 'scripts/windows-held-install-fixture.sh': 'CI-only fixture for the Windows Setup E2E held-install jobs: fetches one pinned release commit of gstack\'s own public repo from the workflow checkout\'s origin (a download only) and pushes to a bare repo under $RUNNER_TEMP; never runs on a user machine, and no gstack or user state leaves the runner', + 'scripts/judge-calibration.ts': + 'developer-invoked eval tooling: calibrates the eval suite\'s model judges by sending committed test fixtures (test/fixtures/judge-calibration) to Anthropic with the developer\'s own key; it imports test helpers and never runs from an installed skill, and no user state is sent', + 'scripts/preflight-agent-sdk.ts': + 'developer-invoked eval preflight: with --live it sends one fixed ~15-token prompt to Anthropic through the Agent SDK with the developer\'s own key to check the SDK event shape before paid evals; it imports test helpers and never runs from an installed skill, and no user state is sent', 'scripts/ubicloud': 'developer-invoked test infrastructure: Ubicloud API calls (VM create/show/destroy) with the developer\'s own token, the checkout streamed over SSH to that developer\'s own ephemeral VM, and toolchain downloads run on the VM; no installed-gstack user state is sent', // Skill prose templates: these render agent-executed instructions (the @@ -231,6 +242,20 @@ const CURL_OP = /(^|[|&;(`]|\s|\$\()curl\s/; // fetch() with an absolute http(s) URL (loopback filtered separately). const FETCH_ABS = /(^|[^A-Za-z])fetch(Fn|Impl)?\(\s*[`'"]https?:\/\//; +// Model-provider calls (#4617). An SDK request method is a send whatever +// the URL, and it can hide inside a shell script's inline `bun -e` string, +// so it counts in shell files too and needs a receipt in the 30 lines above. +const PROVIDER_SDK_CALL = + /\.(?:beta\.)?messages\.(?:create|stream|countTokens)\(|\.chat\.completions\.(?:create|stream)\(|\.responses\.(?:create|stream)\(|\.generateContent(?:Stream)?\(/; +// A file that loads a provider SDK, or names a provider API host and makes +// an HTTP call (the URL is usually built from a base constant, out of the +// per-line scanner's sight), must write a receipt somewhere in the file. +const PROVIDER_SDK_IMPORT = + /(?:from\s+|require\(\s*|import\(\s*)['"](?:@anthropic-ai\/sdk|@anthropic-ai\/claude-agent-sdk|openai|@google\/genai|@google\/generative-ai|@mistralai\/mistralai|groq-sdk)['"]/; +const PROVIDER_HOST = + /\b(?:api\.anthropic\.com|api\.openai\.com|generativelanguage\.googleapis\.com|openrouter\.ai|api\.x\.ai|api\.mistral\.ai|api\.groq\.com|api\.deepseek\.com)\b/; +const HTTP_CALL = /(^|[^A-Za-z.])fetch(Fn|Impl)?\(|(^|[|&;(`]|\s|\$\()curl\s/; + function isTextFile(full: string): boolean { try { const buf = fs.readFileSync(full); @@ -254,8 +279,7 @@ function* walk(dir: string): Generator { * loopback lines, `command -v` probes, message-emitting lines, and shell * heredoc bodies (echoed instructions are not executed ops). */ -function scanFile(rel: string): string[] { - const src = read(rel); +function scanFile(rel: string, src: string = read(rel)): string[] { const isTs = /\.(ts|js|mjs|tsx)$/.test(rel); const lines = src.split('\n'); const offenders: string[] = []; @@ -281,9 +305,9 @@ function scanFile(rel: string): string[] { const tsExecGit = GIT_SPAWN_OP.test(line) || (GIT_REMOTE_OP.test(line) && /\b(spawn|spawnSync|exec|execSync|execFileSync|runCommand)\b/.test(line)); - const isNetOp = isTs - ? FETCH_ABS.test(line) || tsExecGit - : CURL_OP.test(line) || GIT_REMOTE_OP.test(line); + const isNetOp = + PROVIDER_SDK_CALL.test(line) || + (isTs ? FETCH_ABS.test(line) || tsExecGit : CURL_OP.test(line) || GIT_REMOTE_OP.test(line)); if (!isNetOp) continue; if (guarded(lines, i)) continue; offenders.push(`${rel}:${i + 1}: ${line.trim().slice(0, 100)}`); @@ -291,6 +315,28 @@ function scanFile(rel: string): string[] { return offenders; } +/** + * File-level model-provider check (#4617): a file that loads a provider SDK, + * or names a provider API host and makes an HTTP call, must contain a receipt + * marker. Comment and message lines do not count as either. + */ +function scanProviderFile(rel: string, src: string = read(rel)): string[] { + let provider: string | null = null; + let http = false; + let receipt = false; + for (const line of src.split('\n')) { + if (RECEIPT_MARKER.test(line)) receipt = true; + const trimmed = line.trimStart(); + if (/^(#|\/\/|\*|\/\*)/.test(trimmed) || /^(echo|printf|emit|die|fail|log)\b/.test(trimmed)) continue; + if (HTTP_CALL.test(line)) http = true; + if (provider === null && PROVIDER_SDK_IMPORT.test(line)) provider = `loads a provider SDK: ${line.trim().slice(0, 80)}`; + if (provider === null && PROVIDER_HOST.test(line)) provider = `names a provider API host: ${line.trim().slice(0, 80)}`; + } + const sdk = provider?.startsWith('loads') ?? false; + if (provider === null || receipt || (!sdk && !http)) return []; + return [`${rel}: ${provider} (no egress receipt in the file)`]; +} + describe('egress receipt wiring tripwire', () => { test('every TS sink imports lib/egress-receipt and calls writeReceipt()', () => { for (const rel of MODULE_SINKS) { @@ -374,6 +420,7 @@ describe('egress receipt wiring tripwire', () => { 'brain-sync', 'browse-tunnel (ngrok)', 'design-detect-engine-download', + 'distill-free-text', 'gbrain-mcp-verify', 'gbrain-sync', 'memorable-recall', @@ -424,6 +471,45 @@ describe('egress receipt wiring tripwire', () => { const rf = read('design/src/receipted-fetch.ts'); expect(rf).toContain('fail-open'); expect(rf.indexOf('writeReceipt(')).toBeLessThan(rf.indexOf('fetchImpl(url, init)')); + // distill-free-text (closed): receipt before the SDK call, refusal exits. + const distill = read('bin/gstack-distill-free-text'); + expect(distill).toMatch(/sink:\s*"distill-free-text"/); + expect(distill).toContain('fail-closed'); + expect(distill.indexOf('writeReceipt(')).toBeGreaterThan(0); + expect(distill.indexOf('writeReceipt(')).toBeLessThan(distill.indexOf('client.messages.create(')); + }); + + test('model-provider scanner: an unreceipted SDK or HTTP call fails, a receipted one passes', () => { + const tsSdk = [ + "import Anthropic from '@anthropic-ai/sdk';", + 'const client = new Anthropic();', + "const resp = await client.messages.create({ model: 'm', max_tokens: 1, messages: [] });", + ].join('\n'); + const bashSdk = [ + '#!/usr/bin/env bash', + "RESULT=$(bun -e '", + ' const OpenAI = require("openai").default;', + ' const resp = await new OpenAI().chat.completions.create({ model: "m", messages: [] });', + "')", + ].join('\n'); + const tsHttp = [ + "const BASE = 'https://generativelanguage.googleapis.com/v1beta';", + 'export async function call(body: string) {', + ' return fetch(`${BASE}/models/x:generateContent`, { method: "POST", body });', + '}', + ].join('\n'); + for (const [rel, src] of [['lib/fake-sdk.ts', tsSdk], ['bin/gstack-fake-sdk', bashSdk], ['lib/fake-http.ts', tsHttp]]) { + expect([...scanFile(rel, src), ...scanProviderFile(rel, src)].length, `${rel} must be flagged`).toBeGreaterThan(0); + } + const wired = tsSdk.replace( + 'const resp', + "writeReceipt({ sink: 's', host: 'api.anthropic.com', payloadClass: 'c', consent: 'k' });\nconst resp", + ); + expect([...scanFile('lib/fake-sdk.ts', wired), ...scanProviderFile('lib/fake-sdk.ts', wired)]).toEqual([]); + // Negative control: the known-wired model senders in the tree still pass. + for (const rel of ['lib/outside-voice-api.ts', 'lib/context-bill.ts', 'design/src/provider.ts', 'bin/gstack-distill-free-text']) { + expect([...scanFile(rel), ...scanProviderFile(rel)], rel).toEqual([]); + } }); test('NEW-SINK SCANNER: every outbound network op in the tree is wired or reasoned-exempt', () => { @@ -436,7 +522,7 @@ describe('egress receipt wiring tripwire', () => { const rel = path.relative(ROOT, full).split(path.sep).join('/'); if (!/\.(ts|js|mjs|sh|tsx)$/.test(rel) && !isTextFile(full)) continue; if (isExempt(rel)) continue; - offenders.push(...scanFile(rel)); + offenders.push(...scanFile(rel), ...scanProviderFile(rel)); } } expect(