Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
v1.92.8.0 fix(redact): env.kv reads Python, Dart and JSX source syntax as code (#3630) (#3742)
Garry Tan64fb6ecaf8f3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ec0f1f734..a4695114b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,25 @@# Changelog+## [1.92.8.0] - 2026-11-01++**The secrets check no longer flags Python and Dart type names and variable reads as credentials (#3630).** A Python parameter like `session: HttpSession,` failed `gstack-pregate` as MEDIUM env.kv. Secrets findings can't be downgraded, so /ship wrote no receipt, and the only workaround was a file-wide allowlist entry. Dart's `'password': request.password,` and a React key like `key={item.id ?? index}` failed the same way. Reported by @dgrant in #3630. Approaches came from #3605 (@adam-balazs) and #3418/#3419 (@hbarney).++### Fixed+- **`lib/redact-patterns.ts`:** env.kv's source-syntax exemption (#3048) now covers `.dart`, `.py` and `.pyi` files as well as TypeScript. These languages have no unquoted string literal, so a bare name after `:` is a name. A JSX brace may join names with `??`, `||` or `&&` as well as `+`. Each case still reports when it is not code:+ - a quoted value;+ - a value that is not an identifier chain;+ - an annotation with a literal default (`api_token: AuthToken = "<secret>"`, now caught in TypeScript too);+ - a `password:` line inside a Dart or Python `'''`/`"""` string, where escaped quotes don't close the string and a delimiter inside a comment or a one-line string opens nothing;+ - a `password: <value>` pair inside a one-line Python or Dart string;+ - a literal fallback after the name (`"password": settings.db_pass or "<secret>"`);+ - the same lines in `.env` or YAML files.++ Python's `=` forms (`password=request.password`) still report.+- **`lib/pregate/checks/secrets.ts`:** a changed Python or Dart file is scanned whole, and only findings on its added lines count. A line added inside an existing triple-quoted string is still read as a literal. Its row gives the file's line number. A file over 4 MiB, or one that can't be read, has its added lines scanned without the exemption.+- **`bin/gstack-redact-prepush`:** the pre-push hook sees only added lines, so it scans Python and Dart lines without the exemption; a `password:` line added inside an existing triple-quoted string still warns.+- **`lib/pregate/allowlist.ts`:** a pattern entry that names a finding by id and path but doesn't match prints a row saying so. Patterns are matched from where the flagged value starts, so the issue's `session: HttpSession` entry never matched. Before this change, that miss was silent.+- **`docs/pregate.md`:** explains where a pattern is matched and how Python and Dart source is read.+## [1.92.7.0] - 2026-11-01- `gstack-review-dispatch pass` no longer dies on a large diff. `gstack-review-plan` exited before its stdout pipe drained, so a plan JSON past about 128 KB (1.39 MB on a 4,000-file results PR) reached `pass` cut short and failed to parse. Both bins now set the exit code and let their output drain, and a 4,000-file test keeps it that way (GST-507).diff --git a/VERSION b/VERSIONindex c5c92e3e0..7e03eab69 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.92.7.0+1.92.8.0diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.mdindex 4895bd158..af43139b6 100644--- a/agents-digest/gstack-AGENTS.md+++ b/agents-digest/gstack-AGENTS.md@@ -1,4 +1,4 @@-# gstack digest v1.92.7.0 — regenerate/re-copy after upgrading gstack+# gstack digest v1.92.8.0 — regenerate/re-copy after upgrading gstackBehavioral rules from gstack (https://github.com/garrytan/gstack), compressedfor agent hosts without a full skill install. The full skills add workflows,diff --git a/bin/gstack-redact-prepush b/bin/gstack-redact-prepushindex 80ebddeed..cf306bba1 100755--- a/bin/gstack-redact-prepush+++ b/bin/gstack-redact-prepush@@ -686,13 +686,15 @@ function main() {// as public-strict (HIGH blocks regardless either way).// Sliced (see scanAddedLines) so a large-but-legitimate diff is actually// scanned rather than blocked unscanned on the engine's size cap.- // Scanned per file so a pattern can use the file's type (#3048).+ // Scanned per file so a pattern can use the file's type (#3048). A Dart or+ // Python file's added lines go without their path: their source-syntax+ // exemption needs the whole file to see a triple-quoted string (#3630).// An allowlisted span is found by scanning with and without the entries,// so the report names exactly what they suppressed.const allowed: string[] = [];const findingKey = (f: Finding) => `${f.id}:${f.line}:${f.col}`;for (const { part, allowlist } of parts) {- const opts = { repoVisibility: "private" as const, ...emails.options, ...(part.file ? { sourcePath: part.file } : {}) };+ const opts = { repoVisibility: "private" as const, ...emails.options, ...(part.file && !/\.(?:dart|pyi?)$/i.test(part.file) ? { sourcePath: part.file } : {}) };const findings = scanAddedLines(part.text, opts);const kept = allowlist.length? new Set(scanAddedLines(part.text, { ...opts, allowlist }).map(findingKey))diff --git a/docs/pregate.md b/docs/pregate.mdindex 98a1caa0b..1cc821b6d 100644--- a/docs/pregate.md+++ b/docs/pregate.md@@ -178,7 +178,11 @@ Two stages with separate clocks, both printed:simply not proven.- `secrets`: `gstack-redact` over the branch's added lines (merge-base to theworking tree, untracked files included). HIGH, or MEDIUM in the `secret`- category, fails; other MEDIUM findings warn. Cannot be downgraded.+ category, fails; other MEDIUM findings warn. Cannot be downgraded. A+ changed Python (`.py`, `.pyi`) or Dart file is scanned whole and only+ findings on its added lines count, so a line added inside an existing+ `"""` or `'''` string is still read as a literal; its rows give the file's+ line number (`app.py, line 10`).- `strays`: a new file at the repository root, a new top-level directory, or ascratch name (`zz-*`, `tmp*`, `scratch*`) anywhere.- `literals`: for every changed exported constant or named timeout/retry@@ -802,6 +806,20 @@ those, each with its scope and its reason:the entry is inert for that finding and the row says so (`allowlist[0]env.kv not tested on env.kv (<file>): the scanner gave no position for itspattern; the finding is kept`) rather than silently keeping it.+- The position is where the flagged value starts, not the name before it.+ For `session: HttpSession` in a YAML file the pattern is `HttpSession`;+ `session: HttpSession` never matches there. An entry that names a finding+ by id and path, and whose pattern matches the line but not at the value,+ prints `allowlist[0] env.kv pattern did not match env.kv (<file>, added+ line N, col C): …; the finding is kept`.+- In Python and Dart source, a parameter or field annotation+ (`session: HttpSession,`) and a dict entry or Dart named argument that reads+ a name (`"password": request.password`) are code, not credentials, as they+ are in TypeScript (#3630). Python's keyword form (`password=request.password`)+ still reports. The same line inside a `"""` docstring is text and still+ reports; allowlist it by its value. The pre-push hook sees only added lines,+ so it scans Python and Dart lines without this exemption and may still warn+ (MEDIUM, non-blocking) on them.The `secrets` row says `N allowlisted (<ids>)` and lists each allowlistedfinding with the entry (`allowlisted env.kv (evals/receipts/t1.json, added linediff --git a/lib/pregate/allowlist.ts b/lib/pregate/allowlist.tsindex 7355d36af..fe5a85574 100644--- a/lib/pregate/allowlist.ts+++ b/lib/pregate/allowlist.ts@@ -17,6 +17,8 @@ export interface AllowlistFinding {id: string; category: string; severity: string; file: string; line?: number; col?: number;/** The added line the finding sits on (for `pattern`); absent when the scanner gave no position. */lineText?: string;+ /** `line` numbers the whole file (a Dart or Python file scanned whole, #3630), not the added lines. */+ fileLine?: boolean;}export interface Allowlisted<F extends AllowlistFinding = AllowlistFinding> { finding: F; index: number; entry: AllowlistEntry }@@ -38,26 +40,34 @@ function patternHits(entry: AllowlistEntry, f: AllowlistFinding): boolean {return re.test(f.lineText!.slice(f.col! - 1));}+function matchesLine(pattern: string, line: string): boolean {+ try { return new RegExp(pattern).test(line); } catch { return false; }+}+/*** Split findings into the ones an entry covers (with the entry) and the ones* kept; env.value and engine.* are always kept. `untested` lists kept findings* that a pattern entry named by id and path but could not test because the- * scanner gave no position, so the table says why the entry was inert.+ * scanner gave no position, so the table says why the entry was inert;+ * `missed` lists kept findings that a pattern entry named by id and path+ * whose pattern matches the finding's line but not at its position (#3630:+ * the entry was written from the name, not the value).*/-export function applyAllowlist<F extends AllowlistFinding>(findings: readonly F[], entries: readonly AllowlistEntry[]): { kept: F[]; allowlisted: Allowlisted<F>[]; untested: Allowlisted<F>[] } {+export function applyAllowlist<F extends AllowlistFinding>(findings: readonly F[], entries: readonly AllowlistEntry[]): { kept: F[]; allowlisted: Allowlisted<F>[]; untested: Allowlisted<F>[]; missed: Allowlisted<F>[] } {const kept: F[] = [];const allowlisted: Allowlisted<F>[] = [];const untested: Allowlisted<F>[] = [];+ const missed: Allowlisted<F>[] = [];for (const f of findings) {const scoped = (e: AllowlistEntry) => names(e, f) && (!e.paths || matchesAny(e.paths, f.file));const index = nonAllowlistable(f.id) ? -1 : entries.findIndex(e => scoped(e) && patternHits(e, f));if (index >= 0) { allowlisted.push({ finding: f, index, entry: entries[index]! }); continue; }kept.push(f);- if (nonAllowlistable(f.id) || positioned(f)) continue;- const named = entries.findIndex(e => e.pattern !== undefined && scoped(e));- if (named >= 0) untested.push({ finding: f, index: named, entry: entries[named]! });+ if (nonAllowlistable(f.id)) continue;+ const named = entries.findIndex(e => e.pattern !== undefined && scoped(e) && (!positioned(f) || matchesLine(e.pattern, f.lineText!)));+ if (named >= 0) (positioned(f) ? missed : untested).push({ finding: f, index: named, entry: entries[named]! });}- return { kept, allowlisted, untested };+ return { kept, allowlisted, untested, missed };}/** sha256 of the entries, for the check's `inputs.allowlist`. */@@ -68,8 +78,13 @@ export function describeUntested(a: Allowlisted): string {return `allowlist[${a.index}] ${a.entry.finding} not tested on ${a.finding.id} (${a.finding.file}): the scanner gave no position for its pattern; the finding is kept`;}+/** One table line per finding a pattern entry named but did not match: the pattern is tested from where the flagged value starts, never the name before it. */+export function describeMissed(a: Allowlisted): string {+ return `allowlist[${a.index}] ${a.entry.finding} pattern did not match ${a.finding.id} (${a.finding.file}${a.finding.line ? `, ${a.finding.fileLine ? 'line' : 'added line'} ${a.finding.line}` : ''}, col ${a.finding.col}): a pattern is matched from where the flagged value starts, not from the name; the finding is kept`;+}+/** One table line per allowlisted finding: what, where, and which entry (with its reason) covered it. */export function describeAllowlisted(a: Allowlisted): string {- const where = a.finding.line ? ` (${a.finding.file}, added line ${a.finding.line})` : ` (${a.finding.file})`;+ const where = a.finding.line ? ` (${a.finding.file}, ${a.finding.fileLine ? 'line' : 'added line'} ${a.finding.line})` : ` (${a.finding.file})`;return `allowlisted ${a.finding.id}${where} by allowlist[${a.index}] ${a.entry.finding}: ${a.entry.reason}`;}diff --git a/lib/pregate/checks/secrets.ts b/lib/pregate/checks/secrets.tsindex 4f28b9c25..934def71c 100644--- a/lib/pregate/checks/secrets.ts+++ b/lib/pregate/checks/secrets.ts@@ -11,7 +11,7 @@ import { spawnSync } from 'node:child_process';import * as fs from 'node:fs';import * as path from 'node:path';import { runScriptSync } from '../../script-invocation';-import { allowlistDigest, applyAllowlist, describeAllowlisted, describeUntested, type AllowlistFinding } from '../allowlist';+import { allowlistDigest, applyAllowlist, describeAllowlisted, describeMissed, describeUntested, type AllowlistFinding } from '../allowlist';import { baseInputs, sha256 } from '../context';import { environmentResult, launchCause } from '../environment';import { checkScratch } from '../run-scratch';@@ -33,24 +33,69 @@ export function parseAddedLines(diff: string): Map<string, string[]> {return files;}+/** Each file's added line numbers in the working-tree file, from the hunk headers' `+start`. */+export function parseAddedLineNumbers(diff: string): Map<string, number[]> {+ const files = new Map<string, number[]>();+ let file = '';+ let next = 0;+ for (const line of diff.split('\n')) {+ if (line.startsWith('diff --')) { file = ''; next = 0; continue; }+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);+ if (hunk) { next = Number(hunk[1]); continue; }+ if (!next) { if (line.startsWith('+++ ')) file = line.startsWith('+++ b/') ? line.slice(6) : ''; continue; }+ if (line.startsWith('+')) { if (!files.has(file)) files.set(file, []); files.get(file)!.push(next++); }+ else if (line.startsWith(' ')) next++;+ }+ return files;+}++/** Files whose source-syntax exemption needs the whole file: a line added inside an existing `'''`/`"""` block is a literal (#3630). */+const LEXICAL_CONTEXT_SOURCE = /\.(?:dart|pyi?)$/i;+const WHOLE_FILE_MAX_BYTES = 4 * 1024 * 1024;+/*** Added lines from the merge-base to the working tree, plus every line of* untracked files, grouped by file so gstack-redact can use each file's type- * (#3211). External diff and textconv drivers are off: either can empty or- * rewrite the diff, and an empty diff reads as clean.+ * (#3211). A tracked Dart or Python file is passed whole with `keep`, its+ * added line numbers, so the scanner sees the strings an added line sits in+ * and only findings on those lines count (#3630); an untracked one keeps every+ * line. One too large, unreadable, not a regular file, or whose working copy+ * no longer holds the diff's added lines at their numbers+ * to read whole is scanned under a neutral name, without that exemption. External diff and textconv+ * drivers are off: either can empty or rewrite the diff, and an empty diff+ * reads as clean.*/-export function addedLines(ctx: PregateContext): Array<{ file: string; text: string }> {+export function addedLines(ctx: PregateContext): Array<{ file: string; text: string; keep?: number[] }> {const diff = spawnSync('git', ['diff', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/', '--unified=0', '--diff-filter=ACMR', ctx.mergeBase, '--'], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024, env: ctx.env });const files = parseAddedLines(diff.stdout ?? '');+ const numbers = parseAddedLineNumbers(diff.stdout ?? '');+ const whole = new Map<string, { text: string; keep: number[] }>();+ for (const [file, keep] of numbers) {+ if (!LEXICAL_CONTEXT_SOURCE.test(file)) continue;+ try {+ const st = fs.lstatSync(path.join(ctx.repoRoot, file));+ if (!st.isFile() || st.size > WHOLE_FILE_MAX_BYTES) continue;+ const text = fs.readFileSync(path.join(ctx.repoRoot, file), 'utf8');+ const lines = text.split('\n');+ const added = files.get(file) ?? [];+ if (keep.length === added.length && keep.every((n, k) => lines[n - 1] === added[k])) whole.set(file, { text, keep });+ } catch { /* unreadable: its added lines are scanned alone */ }+ }for (const t of ctx.touched) {if (!t.uncommitted || t.status === 'D') continue;const tracked = spawnSync('git', ['ls-files', '--error-unmatch', '--', t.path], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: 15_000 }).status === 0;if (tracked) continue;- try { const st = fs.statSync(path.join(ctx.repoRoot, t.path)); if (st.isFile() && st.size <= 4 * 1024 * 1024) files.set(t.path, [...(files.get(t.path) ?? []), ...fs.readFileSync(path.join(ctx.repoRoot, t.path), 'utf8').split('\n')]); } catch { /* unreadable: skipped */ }+ try {+ const st = fs.statSync(path.join(ctx.repoRoot, t.path));+ if (!st.isFile() || st.size > WHOLE_FILE_MAX_BYTES) continue;+ const lines = fs.readFileSync(path.join(ctx.repoRoot, t.path), 'utf8').split('\n');+ if (LEXICAL_CONTEXT_SOURCE.test(t.path) && !files.has(t.path)) whole.set(t.path, { text: lines.join('\n'), keep: lines.map((_, n) => n + 1) });+ files.set(t.path, [...(files.get(t.path) ?? []), ...lines]);+ } catch { /* unreadable: skipped */ }}- return [...files].map(([file, lines]) => ({ file, text: lines.join('\n') })).filter(p => p.text.trim());+ return [...files].map(([file, lines]) => whole.get(file) ? { file, ...whole.get(file)! } : { file, text: lines.join('\n') }).filter(p => p.text.trim());}-type Finding = { id?: string; description?: string; severity?: string; category?: string; line?: number; col?: number; file: string };+type Finding = { id?: string; description?: string; severity?: string; category?: string; line?: number; col?: number; file: string; fileLine?: boolean };type Scanned = Finding & AllowlistFinding;function run(ctx: PregateContext): CheckResult {@@ -67,7 +112,7 @@ function run(ctx: PregateContext): CheckResult {let medium = false;let parsedAll = true;for (const [i, part] of parts.entries()) {- const file = path.join(tmp, String(i), path.basename(part.file) || 'added.txt');+ const file = path.join(tmp, String(i), (!part.keep && LEXICAL_CONTEXT_SOURCE.test(part.file) ? '' : path.basename(part.file)) || 'added.txt');fs.mkdirSync(path.dirname(file), { mode: 0o700 });fs.writeFileSync(file, part.text, { mode: 0o600 });const r = runScriptSync(path.join(BIN_DIR, 'gstack-redact'), ['--from-file', file, '--json', '--max-bytes', String(64 * 1024 * 1024)], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: Math.min(ctx.timeoutMs, 300_000), maxBuffer: 64 * 1024 * 1024, env: ctx.env });@@ -76,21 +121,21 @@ function run(ctx: PregateContext): CheckResult {high ||= r.status === 3;medium ||= r.status === 2;const lines = part.text.split('\n');- try { findings.push(...(JSON.parse(r.stdout).findings ?? []).map((f: Omit<Finding, 'file'>) => ({ ...f, id: f.id ?? 'finding', category: f.category ?? '?', severity: f.severity ?? '?', file: part.file, lineText: f.line ? lines[f.line - 1] : undefined }))); } catch { parsedAll = false; }+ try { findings.push(...(JSON.parse(r.stdout).findings ?? []).filter((f: Omit<Finding, 'file'>) => !part.keep || f.id?.startsWith('engine.') || (f.line !== undefined && part.keep.includes(f.line))).map((f: Omit<Finding, 'file'>) => ({ ...f, id: f.id ?? 'finding', category: f.category ?? '?', severity: f.severity ?? '?', file: part.file, fileLine: !!part.keep, lineText: f.line ? lines[f.line - 1] : undefined }))); } catch { parsedAll = false; }}// The allowlist applies only to findings the scanner reported in full; an unparsed report keeps its exit-code verdict.- const applied = parsedAll && ctx.config.allowlist.length ? applyAllowlist(findings, ctx.config.allowlist) : { kept: findings, allowlisted: [], untested: [] };+ const applied = parsedAll && ctx.config.allowlist.length ? applyAllowlist(findings, ctx.config.allowlist) : { kept: findings, allowlisted: [], untested: [], missed: [] };const kept = applied.kept;if (parsedAll) { high = kept.some(f => f.severity === 'HIGH'); medium = kept.some(f => f.severity === 'MEDIUM'); }- const render = (f: Scanned) => `${f.severity} ${f.id} [${f.category}]: ${f.description ?? ''}${f.line ? ` (${f.file ? `${f.file}, ` : ''}added line ${f.line})` : ''}`;- const allowLines = [...applied.allowlisted.map(describeAllowlisted), ...applied.untested.map(describeUntested)];+ const render = (f: Scanned) => `${f.severity} ${f.id} [${f.category}]: ${f.description ?? ''}${f.line ? ` (${f.file ? `${f.file}, ` : ''}${f.fileLine ? 'line' : 'added line'} ${f.line})` : ''}`;+ const allowLines = [...applied.allowlisted.map(describeAllowlisted), ...applied.untested.map(describeUntested), ...applied.missed.map(describeMissed)];const allowNote = applied.allowlisted.length ? `; ${applied.allowlisted.length} allowlisted (${[...new Set(applied.allowlisted.map(a => a.finding.id))].join(', ')})` : '';// HIGH and any MEDIUM credential fail; a MEDIUM hygiene/internal/pii/legal// hit in code (a `.local` property reads as a hostname) is listed as warn:// there is no user to answer gstack-redact's per-finding question here.const blocking = kept.filter(f => f.severity === 'HIGH' || (f.severity === 'MEDIUM' && f.category === 'secret'));const advisory = kept.filter(f => f.severity === 'MEDIUM' && f.category !== 'secret');- const lineCount = parts.reduce((n, p) => n + p.text.split('\n').length, 0);+ const lineCount = parts.reduce((n, p) => n + (p.keep?.length ?? p.text.split('\n').length), 0);const fail = (lines: string[], detail: string): CheckResult => ({ ...base, status: 'fail', cause: 'diff', lines: [...lines, ...allowLines], code: 'PREGATE_SECRETS', detail: `${detail}${allowNote}`, fix: 'rotate and remove the credential from the added lines (history included); secrets cannot be downgraded (a benign finding is allowlisted by id, path and pattern in the policy, never env.value)' });if (!high && !medium) return { ...base, status: 'pass', ...(allowLines.length ? { lines: allowLines } : {}), detail: `${lineCount} added lines clean${kept.length ? ` (${kept.length} WARN)` : ''}${allowNote}` };if (blocking.length) return fail([...blocking, ...advisory].map(render), `${blocking.length} credential finding(s) in added lines (${blocking.map(f => f.id).join(', ')})`);diff --git a/lib/redact-engine.ts b/lib/redact-engine.tsindex db8eda2e8..9b64bb8d8 100644--- a/lib/redact-engine.ts+++ b/lib/redact-engine.ts@@ -26,6 +26,7 @@import {PATTERNS,PATTERNS_BY_ID,+ clearStringSpanCache,isPlaceholderSpan,type RedactPattern,type Tier,@@ -472,6 +473,7 @@ function scanInternal(input: string, opts: ScanOptions, spans?: Map<Finding, Ori}}}+ clearStringSpanCache();// Environment values, by exact value: a credential that is already in the// process environment needs no shape to be recognized.diff --git a/lib/redact-patterns.ts b/lib/redact-patterns.tsindex bdc76a8ff..66d837b71 100644--- a/lib/redact-patterns.ts+++ b/lib/redact-patterns.ts@@ -673,28 +673,127 @@ function isCallExpression(span: string, match: RegExpExecArray): boolean {/*** #3048: in a TypeScript/JSX file, an unquoted value after `:` is a type or an* expression, never a string literal (`session: SessionState,`), and a JSX- * brace holding only names and property reads (`key={turn.requestId + turn.role}`)- * is an expression. Decided by file context, not by how the value looks:+ * brace holding only names and property reads joined by + ?? || or &&+ * (`key={turn.requestId + turn.role}`, `key={item.id ?? index}`, #3605) is an+ * expression. Decided by file context, not by how the value looks:* `API_KEY=VelvetRiverOrbitSunset;` in a .env or YAML file is still a literal.- * Without a known TS/JSX path nothing is exempt.+ * #3630 (#3418, #3419): Dart and Python (.py, .pyi) qualify on the same grammar+ * fact, no unquoted string literal, so `'password': request.password` and+ * `session: HttpSession,` are names. Python's `=` forms+ * (`password=request.password`) still fire: the separator must be `:`.+ * Without a known source path nothing is exempt.*/-const TS_SOURCE = /\.(?:[cm]?tsx?|jsx)$/i;+const CODE_SOURCE = /\.(?:[cm]?tsx?|jsx|dart|pyi?)$/i;const CODE_NAME_CHAIN = /^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*(?:<[\w$.,\s<>[\]|]*>)?(?:\[\])*$/;+/**+ * #3418: a `password:` pair inside a string is text in an embedded config,+ * not a dict entry or annotation, so the name exemption must not reach it.+ * In Python and Dart (no regex literals, so every quote is a string's), one+ * linear pass per input (a scan validates many candidates against the same+ * text) records every string's content span: a `'''`/`"""` block, or a+ * `'`/`"` string that ends at its line unless a backslash continues it.+ * Comments are skipped (`#` in Python; `//` and nested `/* *\/` in Dart), so a+ * delimiter inside one opens nothing; a backslash escapes the next character, except in a Dart raw+ * string (`r'''…'''`). The exemption needs the+ * whole file to see a block's opener: pregate passes Dart and Python files+ * whole, and the pre-push hook, which scans added lines alone, passes them+ * without their path.+ */+const STRING_SPAN_SOURCE = /\.(?:dart|pyi?)$/i;+let stringSpansCache: { text: string; lang: string; spans: Array<[number, number]> } | null = null;++/** Drops the cached text once a scan ends, so a long-lived process holds no scanned input. */+export function clearStringSpanCache(): void {+ stringSpansCache = null;+}++function stringSpans(text: string, lang: "py" | "dart"): Array<[number, number]> {+ if (stringSpansCache?.text === text && stringSpansCache.lang === lang) return stringSpansCache.spans;+ const spans: Array<[number, number]> = [];+ const n = text.length;+ for (let i = 0; i < n; ) {+ const c = text[i]!;+ if (lang === "py" ? c === "#" : text.startsWith("//", i)) {+ const eol = text.indexOf("\n", i);+ i = eol < 0 ? n : eol;+ continue;+ }+ if (lang === "dart" && text.startsWith("/*", i)) {+ let depth = 1;+ for (i += 2; i < n && depth > 0; ) {+ if (text.startsWith("/*", i)) { depth += 1; i += 2; }+ else if (text.startsWith("*/", i)) { depth -= 1; i += 2; }+ else i += 1;+ }+ continue;+ }+ if (c !== '"' && c !== "'") { i += 1; continue; }+ const close = text.startsWith(c.repeat(3), i) ? c.repeat(3) : c;+ const multiline = close.length === 3;+ const raw = lang === "dart" && text[i - 1] === "r" && !/[\w$]/.test(text[i - 2] ?? "");+ let j = i + close.length;+ while (j < n && !text.startsWith(close, j) && (multiline || text[j] !== "\n")) j += !raw && text[j] === "\\" ? 2 : 1;+ spans.push([i + close.length, Math.min(j, n)]);+ i = j + close.length;+ }+ stringSpansCache = { text, lang, spans };+ return spans;+}++function insideString(text: string, offset: number, sourcePath: string): boolean {+ if (!STRING_SPAN_SOURCE.test(sourcePath)) return false;+ const spans = stringSpans(text, /\.dart$/i.test(sourcePath) ? "dart" : "py");+ let lo = 0;+ let hi = spans.length - 1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (offset < spans[mid]![0]) hi = mid - 1;+ else if (offset >= spans[mid]![1]) lo = mid + 1;+ else return true;+ }+ return false;+}++/** The rest of a name's expression on its line, up to the comma, semicolon, bracket or comment that ends it; null when it continues on the next line. */+function expressionTail(line: string, comment: string): string | null {+ let rest = line;+ let depth = 0;+ for (let i = 0; i < rest.length; i += 1) {+ const c = rest[i]!;+ if (rest.startsWith(comment, i)) { rest = rest.slice(0, i); break; }+ if (c === '"' || c === "'" || c === "`") {+ const close = rest.indexOf(c, i + 1);+ if (close < 0) return null;+ i = close;+ } else if ("([{".includes(c)) depth += 1;+ else if (")]}".includes(c)) { if (--depth < 0) return rest.slice(0, i); }+ else if ((c === "," || c === ";") && depth === 0) return rest.slice(0, i);+ }+ return depth > 0 || /(?:[=+\\]|\?\?|\|\||&&|\b(?:or|and))\s*$/.test(rest) ? null : rest;+}+function isSourceExpression(span: string, match: RegExpExecArray, sourcePath: string | undefined): boolean {- if (!sourcePath || !TS_SOURCE.test(sourcePath)) return false;- const { start } = spanBounds(match);+ if (!sourcePath || !CODE_SOURCE.test(sourcePath)) return false;+ const { start, end } = spanBounds(match);const before = match.input[start - 1];if (before === '"' || before === "'" || before === "`") return false;if (span.startsWith("{")) {const line = match.input.slice(start + 1).split("\n", 1)[0];const close = line.indexOf("}");if (close < 0 || /["'`]/.test(line.slice(0, close))) return false;- return line.slice(0, close).split("+").every(term => CODE_NAME_CHAIN.test(term.trim()));+ if (!line.slice(0, close).split(/\+|\?\?|\|\||&&/).every(term => CODE_NAME_CHAIN.test(term.trim()))) return false;+ } else {+ const head = match[0].slice(0, match[0].length - span.length).trimEnd();+ const separator = head.slice(-1);+ if (separator !== ":" || !CODE_NAME_CHAIN.test(span.replace(/[,;)=|]+$/, ""))) return false;+ const rest = (span.endsWith("=") ? "=" : "") + match.input.slice(end).split("\n", 1)[0];+ if (!/[,;]$/.test(span)) {+ const tail = expressionTail(rest, /\.pyi?$/i.test(sourcePath) ? "#" : "//");+ if (tail === null || carriesSecretLiteral(tail)) return false;+ }}- const separator = match[0].slice(0, match[0].length - span.length).trimEnd().slice(-1);- if (separator !== ":") return false;- return CODE_NAME_CHAIN.test(span.replace(/[,;)=|]+$/, ""));+ return !insideString(match.input, start, sourcePath);}export const PATTERNS: RedactPattern[] = [@@ -980,7 +1079,7 @@ export const PATTERNS: RedactPattern[] = [// literal (`os.getenv("X", "<secret>")`). A literal appended to the read// itself (`process.env.X||"…"`) is not an exact read and still fires.// #2899: a function call assigned to the name is code, not a value (see- // isCallExpression). #3048: so is a TS/JSX type or expression (isSourceExpression).+ // isCallExpression). #3048, #3630: so is a TS/JSX/Dart/Python type or expression (isSourceExpression).// #3208: so is a schema field identifier (isSchemaFieldIdentifier).validate: (span, match, opts) =>isCredentialShapedEnvName(match[0]) &&diff --git a/package.json b/package.jsonindex d0f50953e..22f8645d7 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "gstack",- "version": "1.92.7",+ "version": "1.92.8","description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.","license": "MIT","type": "module",diff --git a/test/pregate-allowlist.test.ts b/test/pregate-allowlist.test.tsindex 5cafdb346..11345fabc 100644--- a/test/pregate-allowlist.test.ts+++ b/test/pregate-allowlist.test.ts@@ -84,6 +84,30 @@ describe('allowlist: the secrets check', () => {expect(secrets(shape).status).toBe(EXIT.fail);});+ // Value: protects=a pattern entry scoped to the finding that misses it says so, naming the column the pattern is tested from+ // (#3630: `session: HttpSession` as a pattern never matched, and the row was silent); fails_when=the miss is silent again or+ // the finding is dropped; why_new=the row is new; seam=none; no_claim=none+ test('a pattern entry that names the finding but misses its value prints a row and keeps the finding', () => {+ const line = 'session: HttpSessionStore\n';+ const missed = fixture({ ...BASE_PREGATE, allowlist: [{ finding: 'env.kv', paths: ['config.yaml'], pattern: 'session: HttpSessionStore', reason: 'a type name' }] });+ commit(missed, { 'config.yaml': line });+ expect(secrets(missed).status).toBe(EXIT.fail);+ expect(row(missed).lines.join('\n')).toContain('allowlist[0] env.kv pattern did not match env.kv (config.yaml, added line 1, col 10): a pattern is matched from where the flagged value starts, not from the name; the finding is kept');+ const value = fixture({ ...BASE_PREGATE, allowlist: [{ finding: 'env.kv', paths: ['config.yaml'], pattern: 'HttpSessionStore', reason: 'a type name' }] });+ commit(value, { 'config.yaml': line });+ expect(secrets(value).status).toBe(EXIT.ok);+ expect(row(value).detail).toContain('1 allowlisted (env.kv)');+ const other = fixture({ ...BASE_PREGATE, allowlist: [{ finding: 'env.kv', paths: ['config.yaml'], pattern: 'dummy-[0-9]+', reason: 'another value' }] });+ commit(other, { 'config.yaml': line });+ expect(secrets(other).status).toBe(EXIT.fail);+ expect(row(other).lines.join('\n')).not.toContain('pattern did not match');+ const token = 'Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJx';+ const py = fixture({ ...BASE_PREGATE, allowlist: [{ finding: 'env.kv', paths: ['app.py'], pattern: token, reason: 'a fixture' }] });+ commit(py, { 'app.py': `x = 1\nCONFIG = """\npassword: ${token}\n"""\n` });+ expect(secrets(py).status).toBe(EXIT.ok);+ expect(row(py).lines.join('\n')).toContain('allowlisted env.kv (app.py, line 3) by allowlist[0] env.kv: a fixture');+ });+// Value: protects=a category entry covers an advisory pii hit (a run id after a generic word, which the engine's run-word exemption does not cover, read as a phone number) and the WARN count drops;// fails_when=category matching is id-only; why_new=new; seam=none; no_claim=nonetest('a category entry silences the advisory pii finding for a run id', () => {diff --git a/test/pregate-secrets-source-context.test.ts b/test/pregate-secrets-source-context.test.tsindex 21f65463e..a46e1d178 100644--- a/test/pregate-secrets-source-context.test.ts+++ b/test/pregate-secrets-source-context.test.ts@@ -8,7 +8,8 @@ import { spawnSync } from 'child_process';import * as fs from 'fs';import * as os from 'os';import * as path from 'path';-import { parseAddedLines } from '../lib/pregate/checks/secrets';+import { parseAddedLineNumbers, parseAddedLines } from '../lib/pregate/checks/secrets';+import { cleanup, commit, makeFixtureRepo, runBin, BASE_PREGATE, type FixtureRepo } from './helpers/pregate-fixture';const PREGATE = path.resolve(import.meta.dir, '..', 'bin', 'gstack-pregate');const AWS = 'AKIA' + 'ZQ3XN7P2LM4RT8WV';@@ -58,6 +59,79 @@ describe('pregate secrets: source context and diff integrity', () => {expect(f.secrets().status).toBe('pass');});+ test('a Python parameter annotation is code, not a secret; a quoted value on the same name still fails (#3630)', () => {+ expect(repo({ 'app.py': 'def fetch_days(\n *,\n session: HttpSession,\n start: int,\n) -> None:\n pass\n' }).secrets().status).toBe('pass');+ const r = repo({ 'app.py': 'SETTINGS = dict(\n session="8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ",\n)\nCONFIG = {\n "session": "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ",\n}\n' }).secrets();+ expect(r.status).toBe('fail');+ expect(r.lines.join('\n')).toContain('app.py, line 5)');+ });++ test('parseAddedLineNumbers numbers each added line from its hunk header', () => {+ const diff = ['diff --git a/a.py b/a.py', '--- a/a.py', '+++ b/a.py', '@@ -3,0 +4,2 @@', '+one', '+two', '@@ -9 +11 @@', '-old', '+new'].join('\n');+ expect([...parseAddedLineNumbers(diff)]).toEqual([['a.py', [4, 5, 11]]]);+ });++ test('a line added inside an existing triple-quoted block in a Python or Dart file still fails; a separate hunk keeps its own context (#3630)', () => {+ const token = 'Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJx';+ for (const [file, open, close] of [['app.py', 'CONFIG = """', '"""'], ['lib/config.dart', "const config = '''", "''';"]] as const) {+ const base = `def fetch(\n *,\n start: int,\n) -> None:\n pass\n\n${open}\nhost: db\n${close}\n`;+ const fx: FixtureRepo = makeFixtureRepo({ pregate: BASE_PREGATE, baseFiles: { [file]: base } });+ try {+ commit(fx, { [file]: base.replace(' start: int,\n', ' session: HttpSession,\n start: int,\n').replace('host: db\n', `host: db\npassword: ${token}\n`) });+ const r = runBin(fx, 'gstack-pregate', ['--base', 'main', '--only', 'secrets', '--json']);+ const check = JSON.parse(r.out).checks.find((c: { id: string }) => c.id === 'secrets');+ expect({ file, status: check.status }).toEqual({ file, status: 'fail' });+ expect((check.lines as string[]).filter((l) => l.includes('env.kv'))).toEqual([expect.stringContaining(`${file}, line 10)`)]);+ } finally { cleanup(fx); }+ }+ });++ test('an untracked Python file reads annotations as code and still fails a literal, naming its line (#3630)', () => {+ const token = 'Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJx';+ const fx: FixtureRepo = makeFixtureRepo({ pregate: BASE_PREGATE, baseFiles: { 'README.md': 'x\n' } });+ try {+ const secrets = () => JSON.parse(runBin(fx, 'gstack-pregate', ['--base', 'main', '--only', 'secrets', '--json']).out).checks.find((c: { id: string }) => c.id === 'secrets');+ fs.writeFileSync(path.join(fx.work, 'app.py'), 'def f(\n session: HttpSession,\n) -> None:\n pass\n');+ expect(secrets().status).toBe('pass');+ fs.writeFileSync(path.join(fx.work, 'app.py'), `def f(\n session: HttpSession,\n) -> None:\n pass\n\nCONFIG = """\npassword: ${token}\n"""\n`);+ const check = secrets();+ expect({ status: check.status, rows: (check.lines as string[]).filter((l) => l.includes('env.kv')) }).toEqual({ status: 'fail', rows: [expect.stringContaining('app.py, line 7)')] });+ } finally { cleanup(fx); }+ });++ test('a Python file whose working copy no longer holds the diff\'s added lines is scanned by its added lines (#3630)', () => {+ const token = 'Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJx';+ const fx: FixtureRepo = makeFixtureRepo({ pregate: BASE_PREGATE, baseFiles: { 'app.py': 'x = 1\n' } });+ try {+ commit(fx, { 'app.py': `x = 1\nAPI_TOKEN = "${token}"\n` });+ fx.git('update-index', '--assume-unchanged', 'app.py');+ fs.writeFileSync(path.join(fx.work, 'app.py'), 'x = 1\ny = 2\n');+ const check = JSON.parse(runBin(fx, 'gstack-pregate', ['--base', 'main', '--only', 'secrets', '--json']).out).checks.find((c: { id: string }) => c.id === 'secrets');+ expect({ status: check.status, kv: (check.lines as string[]).some((l) => l.includes('env.kv') && l.includes('app.py, added line 1')) }).toEqual({ status: 'fail', kv: true });+ } finally { cleanup(fx); }+ });++ test('a one-line change to a Python file counts one added line (#3630)', () => {+ const fx: FixtureRepo = makeFixtureRepo({ pregate: BASE_PREGATE, baseFiles: { 'app.py': 'x = 1\n'.repeat(50) } });+ try {+ commit(fx, { 'app.py': 'x = 1\n'.repeat(50) + 'y = 2\n' });+ const check = JSON.parse(runBin(fx, 'gstack-pregate', ['--base', 'main', '--only', 'secrets', '--json']).out).checks.find((c: { id: string }) => c.id === 'secrets');+ expect({ status: check.status, detail: check.detail }).toEqual({ status: 'pass', detail: expect.stringMatching(/^1 added lines clean/) });+ } finally { cleanup(fx); }+ });++ test('a Python file too large to read whole has its added lines scanned without the source exemption (#3630)', () => {+ const token = 'Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJx';+ const base = `CONFIG = """\nhost: db\n"""\n${'# pad\n'.repeat(800_000)}`;+ const fx: FixtureRepo = makeFixtureRepo({ pregate: BASE_PREGATE, baseFiles: { 'app.py': base } });+ try {+ commit(fx, { 'app.py': base.replace('host: db\n', `host: db\npassword: ${token}\n`) });+ const r = runBin(fx, 'gstack-pregate', ['--base', 'main', '--only', 'secrets', '--json']);+ const check = JSON.parse(r.out).checks.find((c: { id: string }) => c.id === 'secrets');+ expect({ status: check.status, kv: (check.lines as string[]).some((l) => l.includes('env.kv') && l.includes('app.py')) }).toEqual({ status: 'fail', kv: true });+ } finally { cleanup(fx); }+ });+test('the same assignment in a .env file still fails, naming the file', () => {const f = repo({ 'deploy.env': 'API_TOKEN=8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ\n' });const r = f.secrets();diff --git a/test/redact-engine.test.ts b/test/redact-engine.test.tsindex d3555cba9..b25ef1025 100644--- a/test/redact-engine.test.ts+++ b/test/redact-engine.test.ts@@ -275,6 +275,86 @@ describe("MEDIUM demoted credential-shaped patterns (TENSION-1)", () => {const jwt = ["eyJhbGciOiJIUzI1NiJ9", "eyJzdWIiOiIxMjM0NTY3ODkwIn0", "dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"].join(".");expect(scan(`token: ${jwt},`, { repoVisibility: "private", sourcePath: "src/auth.ts" }).findings.map((f) => f.id)).toContain("jwt");});+ // #3630 (#3605, #3418, #3419) — the #3048 rule, extended: Dart and Python have+ // no unquoted string literal either, so a bare name chain after `:` is a name;+ // a JSX brace may join names with ?? || && as well as +. Each widening keeps a+ // negative control that still fires.+ test("env.kv skips Dart/Python source names and JSX logical joins, never a literal (#3630)", () => {+ const kv = (text: string, sourcePath?: string) =>+ scan(text, { repoVisibility: "private", ...(sourcePath ? { sourcePath } : {}) }).findings.some((f) => f.id === "env.kv");+ const v = "8Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJ";+ const vIdent = "Fk2pQ9vXz4wL7mN3rT6yB1cD5eG0hJx";+ for (const [code, file] of [+ ["def fetch_days(\n *,\n session: HttpSession,\n start: int,\n) -> None:\n pass", "app.py"],+ [" password: pydantic.SecretStr", "app/models.py"],+ [" password: pydantic.SecretStr", "app/models.pyi"],+ [' "password": request.password,', "app/api/handlers.py"],+ [' "api_key": settings.api_key,', "app/api/handlers.py"],+ [" 'password': request.password,", "backend/lib/src/handlers/onboarding_handlers.dart"],+ [" password: request.password,", "backend/lib/src/handlers/pfs_handlers.dart"],+ ["const doc = '''usage''';\n password: request.password,", "backend/lib/src/config.dart"],+ ["key={workout.id ?? index}", "src/SessionList.jsx"],+ ["key={item.uuid || item.slug}", "src/List.tsx"],+ ["key={row.ready && row.id}", "src/Grid.tsx"],+ // A trailing comment is not part of the expression.+ [" password: req.body.password // don't log it (see docs", "src/a.ts"], [" password: pydantic.SecretStr # the user's password, or", "app/models.py"],+ [" 'password': request.password // don't log", "lib/a.dart"],+ // A quote inside a comment opens nothing.+ ["# it's a session\ndef f(\n session: HttpSession,\n): pass", "app.py"], ["/* it's a session */\n password: request.password,", "lib/a.dart"],+ // A literal in the next pair on the line belongs to that pair.+ [' "session": request.session, "mode": "readwrite-primary",', "app.py"],+ // Quotes that close before the name leave it code.+ [" login('it\\'s', password: request.password);", "lib/a.dart"], [' "user": "a", "password": request.password,', "app.py"],+ // The triple-quote guard is Dart/Python only: a stray ''' in a TS string leaves #3048 as it was.+ ["const s = \"'''\";\n session: SessionState,", "src/a.ts"],+ ] as const) expect({ code, file, kv: kv(code, file) }).toEqual({ code, file, kv: false });+ for (const [literal, file] of [+ [" session: HttpSession,", "deploy/values.yaml"],+ [" session: HttpSession,", undefined],+ [` session: "${v}",`, "app.py"],+ [` "password": "${v}",`, "app/api/handlers.py"],+ [` password = "${v}"`, "app/config.py"],+ [" password=request.password,", "app/api/handlers.py"],+ [" password = request.password", "app/api/handlers.py"],+ [`CONFIG = """\npassword: ${vIdent}\n"""`, "tests/conftest.py"],+ [` 'password': '${v}',`, "backend/lib/src/handlers/onboarding_handlers.dart"],+ [` password: "${v}",`, "backend/lib/src/config.dart"],+ [` password = "${v}";`, "backend/lib/src/config.dart"],+ [` password: ${v},`, "backend/lib/src/config.dart"],+ [`const fixture = '''\npassword: ${vIdent}\n''';`, "test/fixtures.dart"],+ [`key={settings.apiKey ?? "${v}"}`, "src/A.tsx"],+ [`key={${v} || index}`, "src/A.tsx"],+ ["key={workout.id ?? index}", ".env"],+ // An annotation with a literal default is still a literal.+ [` api_token: AuthToken = "${v}"`, "app.py"], [` api_token: AuthToken="${v}"`, "app.py"],+ [` apiToken: AuthToken = "${v}";`, "src/a.ts"], [` apiToken: AuthToken = '${v}',`, "lib/a.dart"],+ // An escaped delimiter does not close the block.+ [`CONFIG = """\n\\"""\npassword: ${vIdent}\n"""`, "tests/conftest.py"],+ // A delimiter in a comment or a one-line string opens nothing, so the block after it is still a block.+ [`# don't use """ here\nCONFIG = """\npassword: ${vIdent}\n"""`, "tests/conftest.py"],+ [`DELIM = '"""'\nCONFIG = """\npassword: ${vIdent}\n"""`, "tests/conftest.py"],+ [`// no ''' here\nconst fixture = '''\npassword: ${vIdent}\n''';`, "test/fixtures.dart"],+ [`/* ''' */\nconst fixture = '''\npassword: ${vIdent}\n''';`, "test/fixtures.dart"],+ [`/* outer /* ''' */ still a comment ''' */\nconst fixture = '''\npassword: ${vIdent}\n''';`, "test/fixtures.dart"],+ [`const dir = r'''C:\\dir\\''';\nconst fixture = '''\npassword: ${vIdent}\n''';`, "test/fixtures.dart"],+ // An expression that continues on the next line may carry a literal there.+ [` api_token: AuthToken = (\n "${v}"\n )`, "app.py"],+ // A literal fallback after a name is still a literal.+ [` "password": settings.db_pass or "${v}",`, "app.py"], [` 'password': request.password ?? '${v}',`, "lib/a.dart"],+ // A one-line string continued by a backslash spans lines.+ [`CFG = "db: \\\npassword: ${vIdent} \\\n"`, "app.py"],+ // A key and value inside one quoted string are text, not a dict entry.+ [` 'password: ${vIdent} more',`, "lib/a.dart"], [` "password: ${vIdent} more",`, "app.py"],+ ] as const) expect({ literal, file, kv: kv(literal, file) }).toEqual({ literal, file, kv: true });+ });+ test("env.kv's source-syntax check stays linear on a match-dense file (#3630)", () => {+ for (const file of ["app.py", "src/a.ts"]) {+ const text = "def f(\n" + " session: HttpSession,\n".repeat(12_000) + "): pass\n";+ const t0 = performance.now();+ const found = scan(text, { repoVisibility: "private", sourcePath: file }).findings.filter((f) => f.id === "env.kv").length;+ expect({ file, found, fast: performance.now() - t0 < 3_000 }).toEqual({ file, found: 0, fast: true });+ }+ });// #2912 — a line that READS a secret from the environment holds no secret;// it must not fire (and so must not be masked or withhold a /cso source file).test("env.kv skips exact environment reads (#2912)", () => {diff --git a/test/redact-prepush-hook.test.ts b/test/redact-prepush-hook.test.tsindex 84c07690b..0880322f6 100644--- a/test/redact-prepush-hook.test.ts+++ b/test/redact-prepush-hook.test.ts@@ -761,4 +761,16 @@ describe("#3048: the pushed diff is scanned per file, so TS/JSX source syntax isconst yamlHead = git(["rev-parse", "HEAD"]);expect(mediums(runHook(`refs/heads/main ${yamlHead} refs/heads/main ${tsHead}\n`).stderr)).toBe(1);});+ // #3630: the hook sees added lines alone, so a Python line added inside an existing """ block has no opener in view;+ // Dart and Python lines are scanned without their path and still warn.+ test("a line added inside an existing Python triple-quoted block still warns", () => {+ fs.writeFileSync(path.join(repo, "settings.py"), 'CONFIG = """\nhost: db\n"""\n');+ git(["add", "settings.py"]);+ git(["commit", "-q", "-m", "base"]);+ const base = git(["rev-parse", "HEAD"]);+ fs.writeFileSync(path.join(repo, "settings.py"), 'CONFIG = """\nhost: db\npassword: VelvetRiverOrbitSunset\n"""\n');+ git(["add", "settings.py"]);+ git(["commit", "-q", "-m", "secret"]);+ expect(mediums(runHook(`refs/heads/main ${git(["rev-parse", "HEAD"])} refs/heads/main ${base}\n`).stderr)).toBe(1);+ });});