mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-06 00:44:07 +01:00
* docs: approved reliability follow-ups plan (Oct 2026)
* D1: score overlay wrong answers as comparison results (contract v4)
A completed answer that fails the fixture's output check is now a valid
measurement with taskCorrect false and answerError set, in either arm.
Only execution, scope and metric failures invalidate a trial. ON
correctness still gates the case, so an OFF wrong answer stays in the
comparison. OVERLAY_CONTRACT moves to v4; v3 verdicts are not
reinterpreted. Replays the 37198445662 sonnet trials (OFF-0 wrong).
* C4: score auq-matrix substance with a 3-sample judge panel
Each skill keeps one native capture in the same execution; the
recommendation-substance grader now runs as a JUDGE_PANEL_SAMPLES panel on
that capture and gates on the mean against the unchanged minimum of 4. A
failed sample fails the panel without resampling. Approved at the gate
2026-10-04 for censuses after this change.
* E1: one Bun version source; setup refuses below the 1.3.3 floor, updater checks before advancing
bin/gstack-bun-version.sh holds the security floor (1.3.3) and the tested
version (1.4.0, the CI pin and engines.bun). setup refuses Bun below the
floor before writing anything, warns between floor and tested, warns and
continues on an unparseable version, and prints a 1.4.0 install hint.
Prereleases sort below their release (semver).
gstack-session-update now fetches, reads the incoming release's floor and
checks the bun setup will run before fast-forwarding to that exact
revision; below it the update is held with reason bun-too-old and a
resume command, leaving the revision and installs untouched.
Fixture copies of setup (team-mode, claude-code migration) now include the
sourced file; the slow-git lock test sleeps on fetch, the updater's
network step.
* E3: record the owned Chromium's PID over CDP so the #2709 reap runs on Playwright 1.62
Playwright 1.62's Browser has no process(), so chromiumProcInfo was always
null and browse stop never reaped a surviving headless Chromium. The owned
headless launch now reads the browser PID from CDP SystemInfo.getProcessInfo
(bounded at 2s; a hung or failed call logs once and records nothing). The
reaper's start-time and cmdline identity checks are unchanged, so a recycled
PID or an externally owned browser is never signalled.
* A1: ship docs gate records post-child hashes with gstack-docs-candidate, saves each record once
Stored transcripts (37198445662 gate-census-2) show the parent's reads of
release files take ~1 s; the parent's own model time dominates (completion
268 s of 392 s, store ~270 s of 387 s), and 45-78 s of it is retyping hash
maps, child output and records into several artifacts after the child
returns. The child contract is unchanged.
* A2: /plan-ceo-review sends the mode handoff line before any other tool call
plan-ceo-mode-routing's HOLD SCOPE session spends its 240 s post-selection
window on model work: 37176837432 skipped the handoff helper and paraphrased
the mode, 37198445662 ran it, then wrote the plan, loaded sections and probed
Codex for 114 s before the posture chat. The handoff line is the posture.
* B3: accept wrapped unchanged rows in the cropped Edit preview
PR run 37176835584 timed out with the floor's owned Edit menu on screen:
unchanged diff rows soft-wrap under their gutter with a blank marker
column, and a trimmed empty unchanged row keeps only its number. The
parser accepted wrapped +/- rows only, so it never verified the owned
edit. Both forms are now parsed and still compared with the exact source
lines; the captured viewport is replayed with negative controls.
* A3: record per-phase headroom diagnosis for docsync, plan-mode-no-op, mode-routing and gate slice 11
* E4: /review Step 1 keeps going when the base fetch fails and reports stale base coverage
Under Codex's read-only .git, 'git fetch && merge-base && diff --stat'
stopped at the fetch, so the empty output read as 'Nothing to review'.
The fetch is now separate, prints BASE_REFRESH fresh or stale with the
local base revision, and the review states stale coverage.
* D2: reword the format-approach question prompt
Both plan-ceo-review-format-approach refusals in census 37195203538
(Fable 5.1 model_refusal_no_fallback, category reasoning_extraction:
"duplicating model outputs") were anchored on the session prompt, whose
capture instruction asked for the "verbatim" question and "the exact
prose you would have shown" in a "format-capture test". The approach
case now asks for the same question in the same file as the step's
output, without that wording. The other three plan-format cases keep
their unchanged prompt (no refusals in 72 trials).
* C2: /qa defines its outcome filename fields; QA report templates name the measured timing fields
Low judge samples in failing panels named both: qa workflow (37186854666)
'an undefined {user} in the outcome filename', and qa-only workflow
(37198445662) 'template asks for Duration / durationMs totals while
reporting.md mandates Probe budget and Guarded command time'. The qa
union stays under its 1.11 size ratio (93292 of 93294 bytes).
* 0.1: session ledger written by the claude -p, Agent SDK, PTY and Codex runners
Each armed model session appends one best-effort line to
$GSTACK_EVAL_DIR/session-ledger.jsonl: a stable session key, the timeout it
armed, monotonic elapsed time, its end reason (completed, session_timeout,
observer_timeout, api_error, refusal, aborted, error), one sanitized evidence
line and, for stream-JSON runners, a compact liveness summary (longest
in-request silence with nothing outstanding, last event kind, tool open at
end). Partial messages now stream for every claude -p session and for SDK
sessions without a custom query provider (runSharedInteractive opts in); their
rows feed only the summary, so transcripts keep their size unless
publicStreamDiagnostics is set. Structured refusal and API-error signals win
over phrases, and tool results are never read for them.
* 0.2: failure_cause beside failure_class, from runner facts and the session ledger
One pure failureCauseOf() beside failureClassOf() sets failure_cause
(contract > pre_turn_infra > api_error > refusal > provider_stall >
session_timeout > observer_timeout > assertion > unknown; no machine-set
'detector') with one bounded evidence line, and failureDetailOf() keeps a
Bun matcher's Expected/Received or a judge's failing dimensions in
failure_detail. Both record builders (classifyTrialShard, junitCensus) call
them and attach the trial's ledger sessions. failure_class, error and
TRIAL_ERROR_MAX are computed exactly as before; the new fields are optional,
bounded and validated only when present, and a frozen copy of the v1 reader
accepts every new record. A provider stall needs partial messages and
STALL_WINDOW_MS (120 s, eval-budgets.ts beside HEADROOM_WARN/FAIL) of
in-request silence with nothing outstanding; it stays a failure under
EVAL_POLICY v1.
* E4: fingerprint under a read-only .git via a private object dir owned by review-log
Codex's sandbox mounts .git read-only, so gstack-wtree's git add -A could not
write blobs and /review lost its start capture. gstack-review-log now creates
a private 0700 object directory under TMPDIR, passes it to gstack-wtree (which
writes new objects there with the common-dir object store, resolved before
exporting, as an alternate, so linked worktrees work), exposes it to the
bindReview/checkSharedLibsReuse consumers that read the tree and blobs, and
removes it on EXIT/INT/TERM after they finish. gstack-wtree prints one stderr
line and exits 1 on a failed write or unwritable TMPDIR instead of printing a
partial hash; review-log no longer swallows that line. Standalone gstack-wtree
keeps writing to the repository store so git diff between saved snapshots
(/ship) still works.
* 0.3: red lines name their values, evidence and an after-a-repair command; one published-text sanitizer
Each red line in the census report keeps its stored error and adds the
machine cause with its evidence, the failure_detail values (Expected/Received,
or each failing judge dimension with its mean, sample count and the sample
sentence naming it), the slice artifact and shard directory that hold the
transcript, a fetch command (eval:pass-rates --run <id> --case <id>), and
'after a repair:' with a command that selects only that case (E2E ids via
--case, judges via their selection and an exact test-name filter). A
session that completed and failed a check says so instead of 'assertion
(success)'. Report text that reaches a PR comment, issue or committed file
goes through scripts/lib/published-text.ts: control and bidi characters
stripped, credential-scan patterns redacted, mentions neutralized, HTML and
link brackets escaped inline, blocks in a fence longer than any backtick run,
length capped. Verdicts and collector verdict objects are unchanged.
* E2: one make-pdf resolver for readiness and every $P block on env-var hosts
make-pdf exported $P from its readiness block, which Codex and the other
env-var hosts lose between blocks. binaryAssignment gains 'make-pdf': the
MAKE-PDF SETUP readiness check and the runtime prelude both use it, so every
block that runs $P derives the same make-pdf/dist/pdf binary, with
MAKE_PDF_BIN (dev builds) winning when it is executable. Claude output keeps
its repo-local-first probe; only the false 'subsequent blocks' comment
changed. Root plus P=... fits the 400-byte prelude budget; the fixed
MAKE_PDF_OVERRIDE segment is the one exemption, named in runtime-root.ts and
the conformance test.
* 0.1: eval:pass-rates --headroom, --reds and --run report views; 85% headroom alarm in --gate
A new pure module, scripts/lib/eval-history.ts, reports per case the slowest
armed session against the timeout it armed (censored when it timed out,
insufficient below 3 samples, unknown without a session ledger, with the
case wall shown separately as an upper bound), the census critical path from
the slice jobs' timings, the verdict red ledger per census by failure class
and machine cause with shrunk per-case rates, and the all-green probability
(an approximation: the product of 1 - p_i, with an interval). --run <id>
lists one census's reds with their values and history and downloads only the
slice artifacts those reds name, reporting any over 64 MB instead of skipping
them. eval-flake-rank.ts only routes flags: --help works offline, an unknown
flag or case id exits 2 before any fetch, --case narrows the JSON and the
alarms, every view prints its run/branch scope, and --gate also alarms on a
session above HEADROOM_FAIL (85%) of its budget.
* E5: GSTACK_DESIGN_IMAGE_MODEL override; the live model check always tests the defaults
The image_generation tool model gains an env override validated against a
conservative gpt-image-<version> pattern; a bad value fails before any
request and the error names the variable. Pairing and rejection hints name
the tool model actually requested. design/scripts/live-model-check.ts now
ignores GSTACK_DESIGN_MODEL and GSTACK_DESIGN_IMAGE_MODEL (and says so), so
an override cannot mask a retirement of a default, and its exit 2 (no key)
says nothing was checked.
* C3: /deslop-shared-libs names a concrete risk for each recommendation, never 'none'
Both shared-libs-opportunity-judgment reds (37193478719 t3, 37195203538 t1)
failed adoption_and_risk because the top recommendation said 'Main risk:
none found inside the repo' / 'none in behavior'. The skill asked to 'name
the main risk or uncertainty' without saying what counts.
* B4: --case selects loop-registered cases; an unknown id exits before any process
caseSelection() resolves the one paid file that registers a case and how a
trial selects it: by its literal Bun test name, by the id a registration loop
names its test at runtime (coverage audits, TPA, journeys), or by running the
whole file when it registers no other case (plan-mode-no-op, whose test names
are not the id, so the old name pattern ran nothing). A whole-file case runs
one file shard per trial and is judged by shard status, as CI judges it.
--list prints the selection. Every E2E_TIERS id now resolves except
carve-section-loading, which fifteen files register (CI runs each as its own
shard) and which still fails with the owning files named.
* 0.3: after-a-repair runs the shard file when --case cannot resolve a case
A case that several files register (carve-section-loading) cannot be selected
by --case; its red line now prints the bun test command for the shard file
that went red, so every printed command selects exactly one case.
* C1: pre-register workflow-judge control bundles for qa, qa-only, review and setup-deploy
Positive (production bundle), negative (headings only) and one targeted
execution-blocking defect per judge, one 3-sample panel each, built with the
eval's own reader, prompt builder, options and floors.
* F: cost_known: a trial whose harness captured no billing says so; totals never hide it
cost_usd stays a finite number. Trial and eval records gain an optional
cost_known boolean (absent means known, so old records still parse; the
validator accepts only a boolean). Session-ledger rows record whether the
session's terminal result carried total_cost_usd; PTY and Codex sessions
never do, and SDK captures without a terminal result do not. A trial is
cost-known only when it has eval records and every record and session
captured billing, so JUnit-only PTY cases (125 of 298 trials in run
37198445662 recorded 0) now read cost unknown. The census headline prints the
known sum plus the unknown count, never a bare total over unknown costs, and
no total when every cost is unknown; the history import keeps the flag.
PTY transcripts are not priced: test/helpers/pricing.ts estimates exclude
cache writes, so they cannot give the billed cost.
* B1: replay corpora for the five repeat-offender cases
shared-libs-plan-callers, plan-ceo-section-loading, auto-decide-preserved,
plan-design-review-plan-mode and ship-docsync-late-result each get an
inventory of every wave census in scope (all artifacts still available)
and minimal, redacted detector or actor inputs replayed through the real
detector in the free suite: census passes, every distinct census red, and
derived negative controls labelled as derived. Fixed false reds stay as
expected passes with their history; the two genuine auto-decide product
failures (37176837432, 37179171083) stay refused. A contract test bounds
each entry at 64 KB, scans it for HIGH credentials, requires a pass and a
refusal per case, and reports entries whose series identity is stale.
Building the auto-decide corpus exposed a latent native detector misread:
a bold 'Mode application and rationale.' heading was parsed as a
withdrawn Mode field (37186854666). A field status now ends at its
sentence.
* B2: read approved stale-fill decisions from more valid ledger records
The structured ledger reader is authoritative before the prose fallback,
but it missed two valid approved records in passing censuses
(37186854666: a camelCase writeProfile subject; 37195203538: a
slash-joined 'D1 / STALE-FILL' row id), which then rested on the prose
detector that caused both historical reds. Both forms are accepted; an
unresolved row, an unrelated decision, the copied fixture plan and
non-write camelCase words stay refused.
* C1: record workflow-judge control results (negatives separated; qa and review miss a removed step)
* C2: record every low workflow-judge sample in the wave censuses with its disposition
* 0.3: published lines cannot break a fixed fence
evals.yml wraps collector-outcomes failures in a fixed three-backtick fence
for the PR comment, so those lines (and eval:pass-rates output meant for the
tracking issue) go through sanitizeFixedFenceLine: cleaned like every
published line, with backticks turned into quotes. Inline published text
also neutralizes backticks.
* A1: fit the post-child record wording under ship's 1.428 parity size cap
* E4: inline the Step 1 base refresh to fit review's 1.199 parity size cap
* B2: inventory of gate and periodic phrase-only detector checks
docs/evals/detector-inventory.md lists every pass/fail decision in gate
and periodic E2E cases that rests on phrases in model free text, with
its structured source (if any), whether the contract is user-visible,
and a disposition: already structured-first, convert candidate, phrase
witness required, or no structured source. Convert candidates are
ordered by census red history.
* 0.2: failureCauseOf takes the stall window instead of importing it; the PTY ledger never throws
eval-store.ts imported STALL_WINDOW_MS from eval-budgets.ts, which free tests
replace with mock.module stubs (review-finalization-budget, office-hours,
qa-fix-loop, qa-only), so loading eval-store failed there. failureCauseOf is
now dependency-free: the record builders pass STALL_WINDOW_MS. A PTY session
whose handle cannot show its text (test doubles) records no panel instead of
throwing from runPtySession's cleanup. The 37186854666 replay also runs
through classifyTrialShard.
* A2/auto-decide: the CEO handoff chat repeats the helper's printed line verbatim
Claude Code 2.1.284 collapses the helper's Bash output ('Ran 1 shell
command'), so the 'Auto-decided review mode → …' line reaches the user only
through chat. In lane D's auto-decide-preserved corpus every passing capture's
chat starts with that line, and the reds paraphrased it ('HOLD SCOPE was
auto-selected…', 'Mode decision done…', "I'm defaulting to HOLD SCOPE…").
The template now says verbatim and why.
* C2: record the judge panels rerun on the final ship and review wording
* integrate: touchfiles and module-size ratchet entries for the wave's new modules
GLOBAL_TOUCHFILES gains session-ledger.ts, published-text.ts and
auq-substance-panel.ts; bin/gstack-bun-version.sh joins every entry that
lists setup or the updater; auq-matrix stays a rule case with its C4
evidence beside E2E_KINDS; eval-history, published-text and session-ledger
are registered new modules.
* E1: BROWSE SETUP install hint pins the tested Bun (1.4.0)
* E2: quote "$P" in make-pdf commands so install paths with spaces work
* E1: /gstack-upgrade checks the incoming Bun floor before pulling
gstack_bun_incoming_hold (bin/gstack-bun-version.sh) is now the one
pre-advance check: the auto-updater calls it before its fast-forward and
/gstack-upgrade's git path calls it after fetching. Below the incoming
release's floor the upgrade stops with BUN_TOO_OLD and the checkout,
VERSION and installs stay untouched. Vendored installs were already safe:
setup refuses before writing and the swap restores the previous install.
* 0.3: only main posts or closes tracking issues; reports carry alarms, red ledger, headroom and all-green
A branch-dispatched periodic or marathon run writes its report to the step
summary and a report artifact; the upsert and close steps run only on
refs/heads/main. The periodic body now keeps every pass-rate alarm line (the
old grep kept only the header), adds the red ledger and session headroom read
with an explicit --branch, the all-green estimate and the triage guide link,
and routes report text through scripts/lib/published-text.ts. The marathon
lane gains the matching close-on-green step.
Migrated: evals-workflow-wiring pinned report-summary.md in the upsert step;
the body is now written by 'Write the census report'.
* C3: prosons neutral-posture detector ignores a negated "taste call"
Both plan-review-prosons-neutral-neg reds (37179171083 t3, 37193478719 t3)
recommended A and closed with "a coverage call, not a taste call"; the
old /taste call/i matched the negation. The detector moves to a helper so
the two census captures replay free as negatives, with positive controls.
* B2: credit the CEO mode handoff only when the chat shows its line
Claude Code 2.1.284 collapses the gstack-ceo-mode-handoff Bash result, so
the printed AUTO_DECIDE line is user-visible only when a later chat message
of the session begins with it. The native detector now requires that
witness; the helper's tool result locates it but no longer replaces it, and
a generic mode statement cannot stand in once a handoff ran. Census
37182865432 is relabelled a genuine miss (expected: refused): the chat said
"I'm defaulting to HOLD SCOPE…" and "Mode decided: HOLD SCOPE". Corpus
replay: 5 credited, 3 refused. ceo-mode-handoff tests migrated to the
witness rule (deliberate behavior change).
* test: baseline the wave's approved detector and harness replay tests
B1 corpora, B3, C3, C4 and D2 replay captures through paid-case detectors,
actors or fixtures (test code by design); each entry carries its reason.
* E6: live Codex multi-block periodic case in the host-run Codex job
test/codex-e2e-multiblock-live.test.ts runs ./setup --host codex once from the
job's checkout into a fresh HOME and CODEX_HOME (auth.json copied from the CI
login home), asserts codex debug prompt-input lists the gstack router as a
real file, seeds one learning, and runs /learn's Show recent block through
codex exec: that later block must root itself through its prelude, run the
installed gstack-learnings-search and print the seeded learning; no block may
report a missing install or an unresolved gstack helper path.
The file joins CODEX_CI_FILES so the planner gives it to the host-run Codex
job. paid-test-durations.json carries a 180 s packing estimate (refreshed by
--write-durations after the first census) so the plan keeps every slice
within max-parallel. Oracles live in test/helpers/codex-multiblock.ts with
free replays in test/codex-multiblock.test.ts. Registration (E2E_TOUCHFILES,
E2E_TIERS periodic, E2E_KINDS rule) is the integrator's.
* E5: design live-model check as a periodic case
test/skill-e2e-design-model-smoke.test.ts runs design/scripts/live-model-check.ts
(default models only) under a temp HOME. Without OPENAI_API_KEY the case is a
Bun skip that the census lists as SKIPPED with no coverage credit; with a key,
exit 0 passes and any other exit fails with the script output (exit 2 under a
present key fails as 'nothing was checked'). paid-test-durations.json carries
a 90 s packing estimate. Registration (E2E_TOUCHFILES, E2E_TIERS periodic,
E2E_KINDS rule) is the integrator's.
* A1: docsync parent points children at a saved interface file
The /ship docsync fixture saved its observation interface only in the
parent prompt and told the parent to copy it into every child prompt,
about 30-40 s of parent generation per session (lane S, 37198445662).
docsSessionOptions now writes it to <home>/fixture-interface.md (0600) and
the parent tells each child to Read that file first. Fault-actor prompts,
which prepare already writes to a file, are unchanged. Fixture-only.
* A3: a JUnit case's recorded wall is capped by its shard's wall
junitCensus summed a case's JUnit test times as duration_ms; for
plan-mode-no-op's concurrent PTY tests that is 346 s inside a 176 s shard
(the "432-613 s" history). The case wall headroom shows is now
min(sum, shard elapsed), a true upper bound. Session headroom already
used the ledger's per-session clocks.
* A3: refresh paid-test durations from census 37198445662
Recorded 2026-09-29 estimates under-packed gate slice 11 (17 files
estimated 1078 s ran 1353 s; plan-review-report 76 s -> 198 s,
plan-ceo-plan-mode 37 s -> 112 s, safety-codex-consult 83 s -> 150 s).
Refreshed both tiers with --report --write-durations from the latest
census's slice walls. Old plan re-costed with observed walls: worst slice
~677 s (slice 11); refreshed plan: every slice estimated <= 539 s.
* C2: Browser Quick gets a feasible budget; QA loop names its directory and stop path
Judge rationales on the qa-only panels (2 of the last 3) cited the 30 s
Browser Quick budget: homepage + 5 targets, each a checkpoint write and a
guarded command, left ~5 s per probe. Quick is now 180 s (method text: 3
minutes); the qa-only-no-fix paid check expects the same native deadline.
PROBE_DIR points at its source line, a stopped loop goes to the final
report steps (annotations, materialize, Markdown), and /review and /ship
say that after smoke expiry only plan checks rerun in revalidation.
* C2: name the flows judges found implicit in review resolvers
Structured outside review: MISSING COVERAGE asks no fix question and is
never reported clean (was "preserve the existing user decision flow").
/review's HIGH-impact plan gate: spawned or non-interactive runs report
REQUIREMENTS MISSING and continue, writing no TODOs. Value cards: the byte
clamp applies to card lines; JSON records you write keep full values.
* C1: a free test catches a removed workflow step, which the judges missed
C1 controls showed the qa workflow judge passing /qa without Phase 10 and
the review judge passing /review without Step 3. The new test pins every
step/phase heading of qa, qa-only, review, ship, plan-ceo-review,
plan-eng-review and setup-deploy (derived from the templates' step
headings) and names any that goes missing or out of order; new step
headings must be pinned. The judge rubric is unchanged (EVAL_POLICY).
* size: fit the wave's wording under ship, review and qa parity caps
Measured after all lane merges: ship -79, review -210, qa -68 bytes over.
Trimmed the added wording first (post-expiry rule, MISSING COVERAGE,
plan-gate default, value-card JSON, stop line) and folded /review's
redundant INFORMATIONAL sentence and findings bullet. ship 268,036 (room
8), review 130,118 (room 1). qa needed 11 more bytes: cap 1.11 -> 1.1102
with the measured 93,305 / 84,049 = 1.11013 and its reason beside it.
* docs: troubleshooting sections for the wave's new messages
Bun floor (setup, auto-update, /gstack-upgrade), /review stale base and
fingerprint temp-dir errors, the design image model override, the
unrecorded Chromium PID, and a contributor section for census report
lines (pass-rates flags, failure causes, headroom, cost unknown, overlay
v4, stale corpora, auq substance). A free test checks every
troubleshooting.md#anchor printed by setup or bin scripts exists.
* TODOS: reliability follow-ups deferrals; close the Bun floor, make-pdf $P and #2709 reap
* 0.4: 'A census went red' guide; docs for causes, session ledger, headroom and new messages
docs/evals/census-red.md walks one red line to a diagnosis: prerequisites, the
report fields, eval:pass-rates --run/--reds/--headroom with expected output,
what unknown/insufficient/unrecorded data means, free replay, and the single
'after a repair' paid run allowed by TESTING_INTERNALS. Linked from
CONTRIBUTING, TESTING_INTERNALS and both census reports.
TESTING_INTERNALS documents the failure_cause glossary (one row per
FAILURE_CAUSES value, diagnostic only under EVAL_POLICY v1), failure_detail,
sessions[], cost_known, the session ledger, the pass-rates views and the 85%
headroom alarm, main-only tracking issues, overlay contract v4, auq-matrix's
3-sample substance panel and the E5/E6 periodic cases. troubleshooting.md
gains #bun-too-old and an anchor per new user-facing message from lanes P, D
and F. README names GSTACK_DESIGN_IMAGE_MODEL. test/census-red-docs.test.ts
pins the glossary to FAILURE_CAUSES, parses every guide command and checks the
links.
* v1.91.20.0: CHANGELOG and version for the reliability follow-ups
* regen: SKILL.md and sections for all hosts, digest, context-budget fixture
bun run gen:skill-docs --host all; goldens and llms.txt re-rendered
unchanged; bun test/helpers/capture-context-budget.ts.
* integrate: register codex-multiblock-live and design-model-smoke (periodic, rule)
* 0.4: census report and eval:pass-rates views link the census-red guide
* test: cookie approval fixture reverses the Bun install-hint pin (E1)
The historical approved cookie-workflow prompt carried BUN_VERSION=1.3.10;
the regenerated install hint now pins 1.4.0, so the fixture's reversal
list gains that edit like the earlier waves' entries.
* test: release floor counts the two new periodic cases (E5, E6)
* fix: /freeze, /guard, /unfreeze and /investigate work on Codex and other env-var hosts
Templates quoted "$HOME/.claude/skills/gstack/...", which the env-var hosts'
rewrites turned into "$HOME/.agents/skills/gstack/..." on Codex (a path a
global install never has; same class on the other hosts), and setup's
runtime roots had no freeze/bin. Quoted runtime paths now use
{{RUNTIME_ROOT}}: $GSTACK_ROOT on env-var hosts (the fence gets the
runtime prelude), the unchanged $HOME path on Claude. _link_runtime_dists
links freeze/bin and the careful/bin helper it sources into every
env-var host's root. Also fixes the same guess in /benchmark-models,
/retro and /diagram. test/env-host-runtime-assets.test.ts fails on the
previous code: no fence guesses a $HOME/<dir>/skills/gstack path, every
$GSTACK_ROOT path a fence uses is in the host's runtime root, and the
installed Codex /freeze and /unfreeze fences run from a fresh shell.
Template-reading tests now read the Claude render or expect the
placeholder (deliberate change).
* CHANGELOG/TODOS: lane W's workflow, cases and guide; the env-var host freeze fix
* E6: a block that reads a SKILL.md is not a missing install
The first live codex-multiblock-live run passed its real check (the /learn
block found the install and printed the seeded learning) but the oracle
flagged a sed of the learn SKILL.md, whose prelude source quotes the
'gstack: no install found (tried $_r)' text. Only an emitted line that
starts with the message and names a real root counts now; free replay
negative added.
* test: qa-only fixture keeps its caller-set 30 s deadline
The qa-only-no-fix fixture tells the model to start the guard with 30 s
(a caller limit), so its deadline assertion's default stays 30 000 ms; the
product's Browser Quick default (180 s) does not apply to it. Reverts the
helper and its test to their base.
* C2: keep PROBE_DIR 'owned' (qa-functional-prompt pins it); qa measured 93,311
* test: paid file count and periodic floor include the two new periodic cases
* test: ship docs freshness pin checks meaning after A1's wording trim
The snapshot still hashes selected release paths (--select narrows them),
generated outputs and docs; the pin now checks that instead of the
pre-trim sentence.
* E3: reap the recorded Chromium only after the daemon has exited
With the PID now recorded (E3), browse stop reaped Chromium while the
daemon was still shutting down; the daemon read that as a crash, exited 1
and left its state file (chromium-profile-isolation's headless stop test
failed 3/3 locally, passes on base). The CLI waits up to 5 s for the daemon
to exit before reaping a survivor.
* regen: qa and qa-only exploratory sections (PROBE_DIR wording)
* B1: batching counter reads a target declared mid-line; replay corpus
GSTA-23's census 37228573062 failed plan-eng-multi-finding-batching with
reviewCount=0 after 975 s although D1-D10 were asked one per finding,
each with its saved decision-ledger record. The report wrote 'Report
destination requested by the user. Review target (fixed): `PLAN.md` ...'
and the counter read target fields only at a line start, so no brief
inherited the plan identity. A target field may now open any sentence of
its line; a mid-sentence mention or another file still gives no identity.
Floor (3), budget and kind unchanged. Corpus: 9 earlier passing censuses,
the red (now credited at D5), and a derived batching refusal; 975 s noted
in the headroom diagnosis.
* B1: shared-libs corpus labels its git path and covers the supported shape
Every census entry was recorded in CI's eval image (git 2.43), where
gstack-safe-git falls back because --no-lazy-fetch is rejected; each entry
now says so (git_path: fallback). Two synthetic supported-path entries
(HEAD and a history citation in the brief, as git >= 2.44 produces) keep
the 37193478719 pass and the 37195203538 refusal, and a test asserts both
shapes are covered and the actor reads no git-path-specific text.
* v1.91.21.0: move off v1.91.20.0 (claimed by #3031)
* test: settle nav-guard commands before asserting; make two new tests Windows-safe
navigation-guard: Bun's expect(promise).rejects slows each Playwright round-trip
to ~1s while it waits (50 page.evaluate: 43ms plain vs 46.6s inside the matcher),
so the click's 5s timeout expired before the guard saw the link-local request
(CI: 'click: Timeout 5000ms exceeded ... waiting for scheduled navigations').
Settle the command first, then assert on the refusal; a source check keeps it so.
env-host-runtime-assets: PROBE_FILES now matches either path separator.
detector-corpus ship-docsync-late-result: JSON-escape the <ROOT> substitution so a
Windows temp path's backslashes do not break JSON.parse.
* fix: CI run/job ids are not phone numbers; context-recovery fixture gets the full runtime bin
pii.phone.e164 redacted the run id in the published eval report's fetch command
(--run 37235771700), breaking the command it prints. Digit-only spans in a run/job
flag, gh run argument, actions/runs/ or /job/ URL segment, or run_id/job_id key are
now exempt; the same digits elsewhere still report.
context-recovery-artifacts: the fixture's ./bin/ lacked gstack-skill-start and
gstack-context-recovery (the preamble's runtime scripts since v1.71), so the agent
spent its 10 turns hunting for them and hit error_max_turns with no final message
(run 37235771700, 11 turns). Link the whole runtime bin; diagnostic rerun passed
in 6 turns.
* test: replay run 37237194905's late-result capture through the docs authority detector
The only failure was call 20's write to a mistyped shard root (3GanyY for 3GanyU),
which the model disclosed; the detector is correct and the A1 post-snapshot
--out under the fixture home stays permitted. Named red recorded in TODOS.
* test: keep docsync-authority in the Windows profile
The replay test's literal helper path tripped the Windows curator's shebang-spawn
pattern, dropping the whole file from the Windows profile (test-free-shards
invariant). The snapshot --out case is already covered by docsync-command-grammar,
so it is removed here, and the Linux-path replay skips on win32.
* fix: gstack-docs-candidate --help works; docs gate red lines name the denying tool failure
PR run 37239016858 ship-docsync-completion: the parent ran
'gstack-docs-candidate --help' (the helper's usage error points at --help, which
failed). That undeclared command made docsToolFailures non-empty, which denied
the atomic-replacement proof of the child's legitimate native Edit, so the red
line blamed the Edit's temp file. A replay of the capture proves the atomic
replace once --help is declared.
- the helper prints its usage for --help/-h and exits 0
- the fixture interface and command grammar admit the helper's bare --help
- the atomic-proof denial names its check and the tool failures behind it
(deny labels renumbered to their lines)
- replay with negative controls (undeclared command, temp left behind, renamed
elsewhere); diagnostic rerun of ship-docsync-completion passed
* test: retro-base-branch fixture uses main and a shallow report path
PR run 37241493377: the agent wrote retro-output.md one directory above the
requested <tmp>/retro-base/retro-output.md (it dropped the retro-base segment),
so the report check found nothing. The fixture also ran plain git init, which
makes master on CI's git while the prompt says the repo is on main; the agent
logged that mismatch as a learning. Init on main and use the temp dir itself as
the repo. Diagnostic rerun passed (18 turns, 203s).
* test: qa-quick sets a caller probe limit and drains past its session budget
C2 raised Browser Quick's native budget to 180 s. qa-quick is the only gate case
on the native budget, and its wall went 194 s (main periodic, pre-C2) -> 254 s and
274 s (this PR's runs) -> 300 s session timeout (run 37242691913): the agent now
probes every navigation target with a checkpoint, then needs ~80 s to report.
Like qa-only-no-fix, the eval now sets a caller probe limit (30 s), scopes the
fixture, and gives bun's outer timeout the session drain margin instead of racing
the 300 s session. The product's 180 s budget and the session budget are unchanged.
Diagnostic rerun passed in 195 s.
* review/ship: use main's post-expiry smoke sentence; v1.91.24.0
GSTA-23's measurement on the review workflow judge: main's 'Post-expiry smoke
rechecks are not-run.' passed 10/10; the C2 wording passed 6/10 and the
'..., even in 4c.' variant failed in PR run 37248650879. qa-probe-gates pins
main's sentence before step 4c.
* test: record the plan-design corpus test in the test-of-test baseline
#3031's ratchet now counts tests that slice a paid test file's source; the B1
plan-design-review-plan-mode replay corpus reads test/skill-e2e-design.test.ts
like its sibling corpora already listed.
* fix: --case no longer deadlocks importing the running CLI
runCaseDiagnosis loaded runPaidShards with a dynamic import of
scripts/test-paid-shards.ts; when that file is the entry it is still in its
top-level await, so the import never resolved and `--case` hung after its
first line (on main since #3031, found by the per-case measurement runs). The
CLI now passes its runner in; library callers keep the lazy import.
* test: name the in-flight file and the native error when bun dies before its summary (#3037)
* Bun 1.4.2 everywhere CI and setup pin the tested version
Bun 1.4.0 on Windows aborts about 3% of free-suite shards with native
bad-handle errors (main too; #3037); the same head on 1.4.2 had none in 180
shard runs. Every current 1.4.0 pin moves together, as bun-version-drift
requires: setup-bun in every workflow (CSO orchestration included), the eval
image (sha256 from bun-v1.4.2's SHASUMS256.txt, re-hashed locally), GitLab,
the Ubicloud free-suite setup, gstack-bun-version.sh's tested version,
engines.bun and @types/bun, the install hint in generated skills, the Dia and
cookie native-qualification pins, and docs and tests that state the current
pin. Recorded 1.4.0 observations, fixtures, CHANGELOG history and the CSO
images' oven/bun:1.3.10 base stay.
* fix: --case runs a single-case file whole
A session option naming the case (testName: 'office-hours-section-loading')
made caseSelection pick test-name mode, whose filter matched no Bun test, so
every trial would run hollow. A file that registers only this case now runs
whole before any name match is tried.
* fix(office-hours): reviewer returns a hash-bound receipt instead of echoing its verdict
The spec reviewer now Writes its verdict once, seals it with
gstack-office-hours-review seal (validates the saved JSON and prints
OFFICE_HOURS_VERDICT round=N sha256=<hash> path=<verdict>), and returns
only that line. check --receipt recomputes the hash and fails closed on a
missing, malformed, stale-round, wrong-path or mismatched receipt. The
saved file stays the sole findings inventory; validators bind the receipt
to the saved bytes and the judge reads those bytes.
* fix(office-hours): only blocking findings send a design back for another review round
Review findings carry severity blocking|minor (verdict schema v2). PASS when
no blocking findings remain; minor findings are recorded in Reviewer
Concerns and the Spec Review table, never a reason for another round.
CONVERGENCE needs a persisting blocking prior. A persisting or unverified
blocking prior cannot be relabeled minor. The 3-round cap is unchanged.
* fix(office-hours): rounds 2 and 3 are delta re-reviews of the captured design diff
prepare saves each reviewed design as round-N.design.md and gives later
reviewers the exact line diff since the previous round. A new later-round
blocking finding must cite (changed_text) an excerpt of a changed line;
seal, check and the validators verify it against the snapshots and fail
closed when a citation or snapshot is missing. Other new observations are
minor. Severity, anti-downgrade and CONVERGENCE rules are unchanged.
* test(office-hours): preservation judge accepts COMPLETED with recorded minor findings
* fix(office-hours): parent fixes only blocking findings; callers may set --max-rounds
Between rounds the parent edits for blocking findings only; minor findings
stay recorded. gstack-office-hours-review takes --max-rounds 1|2|3 (default
3) on every command; reaching it stops at MAX_ITERATIONS. The marathon
fixture sets 2 rounds so round 1 (full) and round 2 (delta) run live.
* docs(changelog): office-hours review loop changes in v1.91.28.0
* fix(cso): helper JSON keeps run URLs only in the validated workflow slot
The shared redactor now treats GitHub Actions run ids as CI metadata
(c245d1bc2), so main's #3041 invariant that the same run digits stay
redacted outside qualification.workflow held only through the phone
false positive. Make it explicit in the CSO sanitizer.
* test(plan-ceo): split-overflow progress detector accepts the skill's candidate wording
Collection never ended when the model wrote 'E1 Slack:' / 'E1-SLACK:' or
labels like 'Include in this quarter' / 'Defer with flip trigger', so the
session ran the whole review (930-1464 s) and failed on its extra findings
or the case deadline (6 of 21 runs). The candidate check now accepts a
platform-bound E-id and the action is the bucket's leading verb, as the
skill names them (Include/Defer/Cut/Hold). The semantic judge, call floor
and include/defer/cut validation are unchanged. Replays the captured CI
37374526437, t2, t9 and t15 menus with negative controls.
* test(plan-ceo): split-overflow candidate identity is the one E1-E5 token
The skill fixes no header or question wording, and shape-matching kept
missing new forms (header 'D1.1 Slack' with 'SCOPE-E1:', 'D1.1 E1 Slack',
'E1 Slack DM bot ...:', a misspelled 'Mattermst'). Identity is now exactly
one E1-E5 token across the header and the question's first line, with no
other candidate's platform named. Options rules, judge, call floor and
include/defer/cut validation are unchanged. Replays all 31 measured runs;
the quoted-row controls now quote a second ledger id.
* v1.91.30.0: move past #3044's claimed 1.91.29.0
* test: register the split-overflow wording replay as a free fixture
* fix(skills): resolve judge-cited ambiguities in /qa and /plan-eng-review
- tasks JSONL keeps the raw branch as GIT_BRANCH instead of overwriting
gstack-slug's sanitized BRANCH used for artifact names
- the Codex outside-voice block runs for ready or unverified, matching
its routing rule
- plan-eng startup names the preamble's own setup prompts; the
cross-project question waits for Step 0
- /qa 8c: a fix that applies but leaves the finding reproducing gets one
revised fix, else it is reverted; browser verification names its before
screenshot; the exploratory loop drops its duplicate 3-step summary
* fix(plan-eng): keep the startup steps in their pinned order
* fix(plan-eng): explicit spawned sessions follow the spawned rule at the scope gate; one announcement rule
A missing tool still sends the prose menu whatever the session type, but a
session the caller or host explicitly marks spawned selects the menu's
Recommendation without prose or BLOCKED. The pre-load announcement
sentence now states Step 0's single check.
* eval policy v3: judge panels gate on the per-dimension median of 3 samples
A judge dimension now passes when at least 2 of its 3 samples meet the
unchanged threshold (judgePanelMedian); any other sample count or a
non-numeric sample fails closed. Thresholds, sample count, judge model and
prompts are unchanged; panel logs show every sample and the mean, and name
the median as the gate. Applies to the skill-llm-eval panels, the
workflow-judge cache, the auq-matrix substance panel and the calibration
replicas. EVAL_POLICY 2 -> 3 and HARNESS_VERSION 1 -> 2 (verdicts change),
so every case starts a new pass-rate series. Replays the captured panels
from jobs 112032744416 and 112049856586 as replayed evidence.
1028 lines
42 KiB
TypeScript
1028 lines
42 KiB
TypeScript
/**
|
|
* redact-patterns — the canonical redaction taxonomy.
|
|
*
|
|
* Single source of truth shared by `lib/redact-engine.ts`, `bin/gstack-redact`,
|
|
* `bin/gstack-redact-prepush`, and (via `scripts/resolvers/redact-doc.ts`) the
|
|
* generated SKILL.md docs for /spec, /ship, /cso, /document-release, and
|
|
* /document-generate.
|
|
*
|
|
* Design notes (locked in /plan-eng-review + two Codex passes):
|
|
*
|
|
* - Three tiers. HIGH = genuinely-secret credentials (block). MEDIUM = PII,
|
|
* legal/damaging, internal-leak, plus credential-shaped patterns that have
|
|
* high false-positive rates (confirm via AskUserQuestion). LOW = surface only.
|
|
* - NO wholesale MEDIUM->HIGH promotion on public repos (TENSION-2-followup).
|
|
* Public repos get sterner per-finding confirmation, not auto-block. The
|
|
* engine never mutates a finding's tier based on visibility.
|
|
* - Tier-1 calibration: a gate that cries wolf gets ignored. Stripe
|
|
* publishable keys, Google AIza keys, JWTs, and env-style KV are MEDIUM, not
|
|
* HIGH (they are context-variable / high-FP). Only genuinely-secret
|
|
* credentials block.
|
|
* - ReDoS safety: every pattern here MUST be linear-time (no nested unbounded
|
|
* quantifiers). `test/redact-pattern-lint.test.ts` fails CI on a catastrophic
|
|
* form. The engine also enforces a hard input-size cap that fails CLOSED.
|
|
* - Placeholder suppression is per-matched-span, not per-line.
|
|
*
|
|
* Pattern matching contract: every `regex` is used with the global+multiline
|
|
* flags the engine applies (`g`, `m`). Capture group 1, when present, is the
|
|
* "secret span" the engine masks and (for proximity rules) anchors on; when
|
|
* absent, match[0] is the span.
|
|
*/
|
|
|
|
export type Tier = "HIGH" | "MEDIUM" | "LOW";
|
|
|
|
export type Category =
|
|
| "secret"
|
|
| "pii"
|
|
| "legal"
|
|
| "internal"
|
|
| "hygiene";
|
|
|
|
export interface RedactPattern {
|
|
/** Stable dotted id, e.g. "aws.access_key". Used in findings + tests. */
|
|
id: string;
|
|
tier: Tier;
|
|
category: Category;
|
|
/** Human-readable one-liner for the findings table + docs. */
|
|
description: string;
|
|
/**
|
|
* The detection regex. Linter-enforced linear-time. The engine adds the
|
|
* `gm` flags; do not bake `g`/`m` into the source here (keeps `.source`
|
|
* clean for the docs table and avoids double-global bugs).
|
|
*/
|
|
regex: RegExp;
|
|
/**
|
|
* Patterns whose redaction is unambiguous enough to offer one-keystroke
|
|
* auto-redact at MEDIUM tier (email / phone / ssn / cc). The engine wires
|
|
* the `<REDACTED-*>` replacement token from `redactToken`.
|
|
*/
|
|
autoRedactable?: boolean;
|
|
/** Replacement token for auto-redact, e.g. "<REDACTED-EMAIL>". */
|
|
redactToken?: string;
|
|
/**
|
|
* Extra validators run AFTER the regex matches, ALL must pass for the match
|
|
* to count. Used for Luhn (credit cards), entropy (env-KV), checksum
|
|
* (crypto wallets), RFC1918-exclusion (public IPs), etc. Receives the
|
|
* matched secret span (group 1 or match[0]) and the full match array.
|
|
*/
|
|
validate?: (span: string, match: RegExpExecArray) => boolean;
|
|
/**
|
|
* Proximity requirement: the pattern only counts if `nearRegex` also matches
|
|
* within `nearWindow` chars of the match. Used for AWS secret keys (need
|
|
* `aws_secret_access_key` nearby) and Twilio auth tokens (need an SID nearby).
|
|
*/
|
|
nearRegex?: RegExp;
|
|
nearWindow?: number;
|
|
}
|
|
|
|
// ── Validators ──────────────────────────────────────────────────────────────
|
|
|
|
/** Luhn checksum — credit-card validity. Strips spaces/dashes first. */
|
|
export function luhnValid(span: string): boolean {
|
|
const digits = span.replace(/[ \-]/g, "");
|
|
if (!/^\d{13,19}$/.test(digits)) return false;
|
|
let sum = 0;
|
|
let alt = false;
|
|
for (let i = digits.length - 1; i >= 0; i--) {
|
|
let d = digits.charCodeAt(i) - 48;
|
|
if (alt) {
|
|
d *= 2;
|
|
if (d > 9) d -= 9;
|
|
}
|
|
sum += d;
|
|
alt = !alt;
|
|
}
|
|
return sum % 10 === 0;
|
|
}
|
|
|
|
/** Shannon entropy in bits/char. Used to gate env-style KV (skip placeholders). */
|
|
export function shannonEntropy(s: string): number {
|
|
if (!s.length) return 0;
|
|
const freq: Record<string, number> = {};
|
|
for (const ch of s) freq[ch] = (freq[ch] || 0) + 1;
|
|
let h = 0;
|
|
for (const ch in freq) {
|
|
const p = freq[ch] / s.length;
|
|
h -= p * Math.log2(p);
|
|
}
|
|
return h;
|
|
}
|
|
|
|
// env.kv name-shape calibration: the regex's zero-or-more-prefix net matches
|
|
// ANY identifier ending in a credential suffix, so `cacheKey:`, `sortKey:`,
|
|
// `partitionKey:`, `hotkey:`, even `monkey:` with an 8+-char entropic value
|
|
// all hit a MEDIUM confirm prompt — a gate that cries wolf gets ignored.
|
|
// A matched name only counts when its shape is credential-semantic:
|
|
// (i) suffix separated from the prefix by _ / - / . (api_key, x-access-key,
|
|
// AUTH.TOKEN)
|
|
// (ii) the whole name IS the bare suffix (key:, token:)
|
|
// (iii) the name is ALL-CAPS env style (APIKEY=, MY_APIKEY=)
|
|
// (iv) a lowercase/camel compound whose prefix ends in a credential word
|
|
// (apiKey, authToken, clientSecret, stripeApiKey) — cacheKey/sortKey/
|
|
// monkey have no credential prefix and are rejected.
|
|
const ENV_KV_NAME =
|
|
/^[ \t]*(?:export[ \t]+)?["']?([A-Za-z0-9_.-]*?(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE))["']?[ \t]*[:=]/i;
|
|
const ENV_KV_SUFFIX =
|
|
/(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)$/i;
|
|
const ENV_KV_CRED_PREFIX =
|
|
/(api|auth|access|secret|private|app|client|server|master|admin|signing|encryption|session|csrf|jwt|oauth|bearer)$/i;
|
|
|
|
/** True when the full env.kv match starts with a credential-shaped name. */
|
|
export function isCredentialShapedEnvName(fullMatch: string): boolean {
|
|
const nameMatch = ENV_KV_NAME.exec(fullMatch);
|
|
if (!nameMatch) return false;
|
|
const name = nameMatch[1];
|
|
const suffixMatch = ENV_KV_SUFFIX.exec(name);
|
|
if (!suffixMatch) return false;
|
|
const prefix = name.slice(0, name.length - suffixMatch[1].length);
|
|
if (prefix === "") return true; // (ii) bare suffix
|
|
if (/[_.\-]$/.test(prefix)) return true; // (i) separator before suffix
|
|
if (!/[a-z]/.test(name)) return true; // (iii) ALL-CAPS env style
|
|
return ENV_KV_CRED_PREFIX.test(prefix); // (iv) credential-semantic compound
|
|
}
|
|
|
|
/** True when an IPv4 string is a public address (not RFC1918/loopback/etc). */
|
|
export function isPublicIPv4(ip: string): boolean {
|
|
const m = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
if (!m) return false;
|
|
const o = m.slice(1, 5).map(Number);
|
|
if (o.some((n) => n > 255)) return false;
|
|
const [a, b] = o;
|
|
if (a === 10) return false; // 10.0.0.0/8
|
|
if (a === 127) return false; // loopback
|
|
if (a === 0) return false; // this-network
|
|
if (a === 192 && b === 168) return false; // 192.168.0.0/16
|
|
if (a === 169 && b === 254) return false; // link-local
|
|
if (a === 172 && b >= 16 && b <= 31) return false; // 172.16.0.0/12
|
|
if (a === 100 && b >= 64 && b <= 127) return false; // CGNAT 100.64.0.0/10
|
|
if (a >= 224) return false; // multicast / reserved
|
|
return true;
|
|
}
|
|
|
|
// EIP-55 checksum is out of scope (heavy); we require a length+charset match and
|
|
// reject all-same-char vanity strings to cut the worst FPs.
|
|
function looksLikeWallet(span: string): boolean {
|
|
if (/^0x[a-fA-F0-9]{40}$/.test(span)) {
|
|
// reject 0x000...0 / 0xfff...f style
|
|
const body = span.slice(2).toLowerCase();
|
|
return !/^(.)\1{39}$/.test(body);
|
|
}
|
|
// bech32 / base58 — length sanity only
|
|
return span.length >= 26 && span.length <= 62;
|
|
}
|
|
|
|
// Compact log/backup stamps (`20260727202423` = YYYYMMDDHHMMSS) are bare digit
|
|
// runs that the phone regex happily eats. Only a SEPARATOR-FREE 14-digit span
|
|
// qualifies: E.164 tops out at 15 digits and real numbers carry a + or spacing,
|
|
// so rejecting this shape costs no phone coverage.
|
|
function looksLikeCompactTimestamp(span: string): boolean {
|
|
if (!/^\d{14}$/.test(span)) {
|
|
return false;
|
|
}
|
|
const n = (from: number, to: number) => Number(span.slice(from, to));
|
|
const [year, month, day, hour, minute, second] = [
|
|
n(0, 4),
|
|
n(4, 6),
|
|
n(6, 8),
|
|
n(8, 10),
|
|
n(10, 12),
|
|
n(12, 14),
|
|
];
|
|
return (
|
|
year >= 1900 &&
|
|
year <= 2999 &&
|
|
month >= 1 &&
|
|
month <= 12 &&
|
|
day >= 1 &&
|
|
day <= 31 &&
|
|
hour <= 23 &&
|
|
minute <= 59 &&
|
|
second <= 59
|
|
);
|
|
}
|
|
|
|
/** Context window for pairing a normalized parcel ID with its punctuated form. */
|
|
const PARCEL_CONTEXT_CHARS = 400;
|
|
|
|
/**
|
|
* County tax-map parcel ID (APN). Ohio's dominant form is NN-NNNNNNN.NNN, and
|
|
* some counties use a hyphen before the 3-4 digit suffix instead of a dot.
|
|
*/
|
|
const PARCEL_PUNCT_RE = /\b\d{2}-\d{4,8}[.\-]\d{3,4}\b/g;
|
|
|
|
/**
|
|
* A parcel ID reads as a national-format phone number to pii.phone.e164 — the
|
|
* same collision class as the digit-only UUID that `insideUuid` already guards.
|
|
* Land/title repos carry these by the hundred, so the false positives are not
|
|
* incidental: they arrive on every branch that touches title, and a guardrail
|
|
* that cries wolf on the domain's primary identifier trains people to wave the
|
|
* warning through, which is how a real HIGH finding eventually gets ignored.
|
|
*
|
|
* Deliberately narrow, in two tiers:
|
|
*
|
|
* 1. The DOTTED form is exempt on its own shape. No phone convention places a
|
|
* dot before a trailing 3-4 digit group after a 4-8 digit middle, so this
|
|
* cannot swallow a real number. The hyphen-only variants (22-0001-000) are
|
|
* NOT exempted by shape — those genuinely are phone-shaped.
|
|
*
|
|
* 2. A DIGITS-ONLY span is phone-shaped in isolation, so it earns the exemption
|
|
* only by evidence: it must be the exact digit-normalization of a punctuated
|
|
* parcel ID within the surrounding window. Fixtures and marts always carry
|
|
* the pair ({parcel_id: "12-3456789.000", norm: "123456789000"}), and a bare
|
|
* phone number has no such twin nearby — so this reads the document's own
|
|
* evidence rather than guessing from digits.
|
|
*/
|
|
export function looksLikeParcelId(span: string, match: RegExpExecArray): boolean {
|
|
if (/^\d{2}-\d{4,8}\.\d{3,4}$/.test(span)) return true;
|
|
if (!/^\d{10,14}$/.test(span)) return false;
|
|
|
|
const input = match.input ?? "";
|
|
const spanStartInMatch = match[1] !== undefined ? match[0].indexOf(match[1]) : 0;
|
|
const spanStart = match.index + Math.max(0, spanStartInMatch);
|
|
const spanEnd = spanStart + span.length;
|
|
const window = input.slice(
|
|
Math.max(0, spanStart - PARCEL_CONTEXT_CHARS),
|
|
spanEnd + PARCEL_CONTEXT_CHARS,
|
|
);
|
|
|
|
PARCEL_PUNCT_RE.lastIndex = 0;
|
|
let p: RegExpExecArray | null;
|
|
while ((p = PARCEL_PUNCT_RE.exec(window)) !== null) {
|
|
if (p[0].replace(/\D/g, "") === span) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Vector geometry reads as a phone number to pii.phone.e164 (#2885, #2827).
|
|
* The pattern accepts `.` as a group separator, so a single float
|
|
* (`viewBox="0 0 581.66796875 695.65625"`) parses as 581 · 6679 · 6875, and a
|
|
* run of path coordinates (`37.6188 101.694`, `100 64.5326 100`) as four
|
|
* spaced groups. One rendered /diagram SVG carried 18 of these; a Figma icon
|
|
* carries dozens per path.
|
|
*
|
|
* Phone conventions put a separator between EVERY group, so a token with
|
|
* digits, one dot and digits is a decimal number, never a dotted phone
|
|
* (415.555.0123 has two dots in one token and stays flagged). Exempt a span
|
|
* whose space-separated tokens include at least one decimal and none with two
|
|
* dots. A leading `+` is the E.164 marker, so a span starting with it is a
|
|
* phone context and never exempt.
|
|
*/
|
|
export function looksLikeDecimalCoordinates(span: string): boolean {
|
|
if (span.startsWith("+")) return false;
|
|
const tokens = span.split(" ");
|
|
if (tokens.some((t) => t.split(".").length > 2)) return false;
|
|
return tokens.some((t) => /^\d+\.\d+$/.test(t));
|
|
}
|
|
|
|
/** Span start/end in `match.input`, derived exactly as redact-engine.ts does. */
|
|
function spanBounds(match: RegExpExecArray): { start: number; end: number } {
|
|
const spanStartInMatch = match[1] !== undefined ? match[0].indexOf(match[1]) : 0;
|
|
const start = match.index + Math.max(0, spanStartInMatch);
|
|
return { start, end: start + (match[1] ?? match[0]).length };
|
|
}
|
|
|
|
/**
|
|
* True when a digit span is one side of a decimal number: `<digit>.` sits
|
|
* immediately before it or `.<digit>` immediately after. pii.cc's `\b` stops
|
|
* at the dot, so the 14-digit fraction of `492.34399999999994` in an
|
|
* .excalidraw scene is a Luhn candidate, and a random digit run passes Luhn
|
|
* about one time in ten (#2827). A card number in prose is never glued to a
|
|
* decimal point; a sentence-ending period has no digit after it and stays
|
|
* flagged.
|
|
*/
|
|
export function insideDecimalNumber(match: RegExpExecArray): boolean {
|
|
const input = match.input ?? "";
|
|
const { start, end } = spanBounds(match);
|
|
const digit = (i: number) => i >= 0 && i < input.length && input[i] >= "0" && input[i] <= "9";
|
|
return (input[start - 1] === "." && digit(start - 2)) || (input[end] === "." && digit(end + 1));
|
|
}
|
|
|
|
/**
|
|
* JSON keys whose unquoted integer value is a random seed, nonce or epoch
|
|
* timestamp. Excalidraw writes three per element (`"seed":1808177121`,
|
|
* `"versionNonce":1365644783`, `"updated":1791059590857`), and pii.phone.e164
|
|
* reads each as a bare 10-13 digit number: 92 per /diagram scene (#2827).
|
|
*/
|
|
const NUMERIC_METADATA_KEY =
|
|
/"[A-Za-z0-9_]*(?:seed|nonce|updated|created|timestamp)(?:at|_at|ms|_ms)?"[ \t]*:[ \t]*$/i;
|
|
|
|
/**
|
|
* True when a digit-only span is the unquoted JSON value of a seed, nonce or
|
|
* timestamp key. The evidence is the key, not the digits: the same number
|
|
* under `"phone":` still reports.
|
|
*/
|
|
export function isNumericMetadataValue(span: string, match: RegExpExecArray): boolean {
|
|
if (!/^\d+$/.test(span)) return false;
|
|
const input = match.input ?? "";
|
|
const { start } = spanBounds(match);
|
|
const lineStart = input.lastIndexOf("\n", start - 1) + 1;
|
|
return NUMERIC_METADATA_KEY.test(input.slice(Math.max(lineStart, start - 80), start));
|
|
}
|
|
|
|
/**
|
|
* GitHub Actions run and job ids are bare 10-12 digit integers, so
|
|
* pii.phone.e164 reads them as phone numbers. A published eval report prints
|
|
* the run id inside the command the reader copies
|
|
* (`bun run eval:pass-rates --run 37235771700`), and redacting it breaks that
|
|
* command. Only the position decides: a run/job flag (`--run 37235771700`,
|
|
* `--job=111534615007`), a `gh run view|watch|rerun|download|cancel`
|
|
* argument, an `actions/runs/<id>` or `/job/<id>` URL segment, or a
|
|
* `run_id` / `job_id` key. The same digits anywhere else still report.
|
|
*/
|
|
const CI_ID_POSITION_BEFORE =
|
|
/(?:--(?:run|job)(?:-id)?(?:[ \t]+|[ \t]*=[ \t]*)|\bgh[ \t]+run[ \t]+(?:view|watch|rerun|download|cancel)[ \t]+|\/actions\/runs\/|\/jobs?\/|(?:run|job)_id["']?[ \t]*[:=][ \t]*["']?)$/i;
|
|
export function isCiRunIdentifier(span: string, match: RegExpExecArray): boolean {
|
|
if (!/^\d+$/.test(span)) return false;
|
|
const input = match.input ?? "";
|
|
const { start } = spanBounds(match);
|
|
const lineStart = input.lastIndexOf("\n", start - 1) + 1;
|
|
return CI_ID_POSITION_BEFORE.test(input.slice(Math.max(lineStart, start - 80), start));
|
|
}
|
|
|
|
/**
|
|
* A four-part version (MAJOR.MINOR.PATCH.BUILD: .NET assembly versions,
|
|
* gstack's own VERSION) is byte-for-byte a dotted quad, and `1.128.1.0` is a
|
|
* public address, so `"version": "1.128.1.0"` raised pii.ip_public on every
|
|
* release (#2784). The value cannot decide it, so only the declaration
|
|
* immediately before it on the same line can: a `version` key or word
|
|
* (`"version": "`, `app_version = `, `<Version>`, `AssemblyVersion("`,
|
|
* `version `), or a Keep a Changelog heading `## [1.2.3.4]`. The same digits
|
|
* after `host:`, `server = ` or in prose that merely mentions a version still
|
|
* report, and the pre-push hook's VERSION-file rule (#2856) is unchanged.
|
|
*/
|
|
const VERSION_DECLARATION_BEFORE =
|
|
/(?:\b[Vv]ersion|\bVERSION|[a-z0-9_]Version|[_-][Vv]ersion|_VERSION)["'\]]?(?:[ \t]*[:=(>][ \t]*|[ \t]+)["']?$/;
|
|
const CHANGELOG_HEADING_BEFORE = /^#{1,6}[ \t]+\[$/;
|
|
export function isDeclaredVersion(match: RegExpExecArray): boolean {
|
|
const input = match.input ?? "";
|
|
const { start, end } = spanBounds(match);
|
|
const lineStart = input.lastIndexOf("\n", start - 1) + 1;
|
|
if (VERSION_DECLARATION_BEFORE.test(input.slice(Math.max(lineStart, start - 48), start))) return true;
|
|
return CHANGELOG_HEADING_BEFORE.test(input.slice(lineStart, start)) && input[end] === "]";
|
|
}
|
|
|
|
// ── Placeholder suppression (per-matched-span, NOT per-line) ─────────────────
|
|
|
|
/**
|
|
* A finding is suppressed only if the MATCHED SPAN itself is a placeholder
|
|
* form — not merely co-located on a line with the word EXAMPLE. This is the
|
|
* tightened rule from the Codex review (line-based suppression was dangerous).
|
|
*/
|
|
// Structural placeholder forms — apply to ANY span (including URLs).
|
|
const PLACEHOLDER_STRUCTURAL = [
|
|
/^your[_-]/i,
|
|
/^<[^>]*>$/, // <REDACTED-FOO>, <your-key>
|
|
/^\*+$/, // all-asterisks mask
|
|
/^x{6,}$/i, // xxxxxx mask
|
|
];
|
|
|
|
// Substring placeholder words (example/test/dummy/...). These are NOT applied to
|
|
// compound spans containing `://` or `@`, because a legit URL/host can contain
|
|
// "example" (e.g. db.example.com) without being a placeholder secret. AWS docs
|
|
// keys like AKIAIOSFODNN7EXAMPLE are bare tokens, so the guard still catches them.
|
|
const PLACEHOLDER_SUBSTRING = [
|
|
/example/i, // AKIAIOSFODNN7EXAMPLE etc — AWS docs convention
|
|
/^pass(word)?$/i, // literal PASSWORD/pass in URL-format doc comments
|
|
/^changeme$/i,
|
|
/^redacted/i,
|
|
/^placeholder/i,
|
|
/^dummy/i,
|
|
/^fake/i,
|
|
/test[_-]?(key|token|secret)/i,
|
|
];
|
|
|
|
export function isPlaceholderSpan(span: string): boolean {
|
|
if (PLACEHOLDER_STRUCTURAL.some((re) => re.test(span))) return true;
|
|
const isCompound = span.includes("://") || span.includes("@");
|
|
if (!isCompound && PLACEHOLDER_SUBSTRING.some((re) => re.test(span))) return true;
|
|
return false;
|
|
}
|
|
|
|
/** Canonical 8-4-4-4-12 hex UUID. Global: a line may hold several. */
|
|
const UUID_RE = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g;
|
|
|
|
/** How far either side of a span to look for an enclosing UUID. A UUID is 36
|
|
* chars, so 40 covers one that starts immediately before the span. Bounded so
|
|
* this stays cheap on a multi-megabyte buffer. */
|
|
const UUID_CONTEXT_CHARS = 40;
|
|
|
|
/**
|
|
* True when an `internal.hostname` span is really the tail of a dotenv
|
|
* FILENAME (`.env.local`, `.env.staging`, `.env.prod`) rather than a host.
|
|
*
|
|
* The hostname pattern ends in `.local|.prod|.staging|…`, so `.env.local`
|
|
* matches on `env.local` — a false positive on one of the most commonly
|
|
* committed filenames there is. It arrives via npm scripts
|
|
* (`--env-file=.env.local`), READMEs, `.gitignore` and setup docs, i.e. on
|
|
* ordinary branches that leak nothing, which is the noise that teaches people
|
|
* to skim past MEDIUM findings.
|
|
*
|
|
* Deliberately narrow, in the same spirit as `insideUuid`: it exempts ONLY a
|
|
* span beginning `env.` that is immediately preceded by a dot — the literal
|
|
* `.env.<suffix>` form. A real host still reports, `api.corp` and
|
|
* `build-7.internal` included, and so does `myenv.local`, which is not a
|
|
* dotenv file.
|
|
*/
|
|
export function isDotenvFilename(match: RegExpExecArray): boolean {
|
|
const input = match.input ?? "";
|
|
const span = match[1] ?? match[0];
|
|
if (!/^env\./i.test(span)) return false;
|
|
// Mirror the engine: capture group 1 when present, else the whole match.
|
|
const spanStartInMatch = match[1] !== undefined ? match[0].indexOf(match[1]) : 0;
|
|
const spanStart = match.index + Math.max(0, spanStartInMatch);
|
|
return spanStart > 0 && input[spanStart - 1] === ".";
|
|
}
|
|
|
|
/** Extensions that mark a `<name>.local.<ext>` span as a file. Closed on
|
|
* purpose: `.md` is also Moldova's TLD, but no internal suffix sits in front
|
|
* of a public one, so after `.local` it can only be an extension. */
|
|
const LOCAL_CONFIG_EXTENSIONS = /^\.(?:md|json|jsonc|ya?ml|toml|ini|conf|txt)\b/i;
|
|
|
|
/**
|
|
* True when an `internal.hostname` span is the stem of a per-machine config
|
|
* FILENAME (`CLAUDE.local.md`, `settings.local.json`, `values.staging.yaml`)
|
|
* rather than a host (#2962). The pattern's `\b` stops at the dot before the
|
|
* extension, so `CLAUDE.local.md` reported `CLAUDE.local`. Claude Code's own
|
|
* per-user files are named this way, so any decision or doc that mentions
|
|
* them failed closed in the non-interactive stores.
|
|
*
|
|
* Exempts ONLY a span immediately followed by `.<known extension>` and a word
|
|
* boundary. `printer.local.` at the end of a sentence still reports, and so
|
|
* do `printer.local`, `printer.local/md` and `printer.local.mdx`.
|
|
*/
|
|
export function isLocalConfigFilename(match: RegExpExecArray): boolean {
|
|
const { end } = spanBounds(match);
|
|
return LOCAL_CONFIG_EXTENSIONS.test((match.input ?? "").slice(end, end + 8));
|
|
}
|
|
|
|
/**
|
|
* True when the matched span sits ENTIRELY inside a UUID.
|
|
*
|
|
* Digit-only UUIDs — `00000000-0000-0000-0000-000000000000`,
|
|
* `11111111-1111-…` — are the standard fixture shape in test suites, and their
|
|
* digit runs collide with both the credit-card and phone patterns: a 16-digit
|
|
* slice of one is Luhn-valid often enough to matter, and the hyphen groups read
|
|
* as national phone formatting. Observed live: 14 of 21 MEDIUM findings on one
|
|
* ordinary branch were this, all from test files. That volume is what stops
|
|
* people reading MEDIUM output at all, so it costs real detection elsewhere.
|
|
*
|
|
* Containment must be TOTAL, deliberately. A span merely adjacent to or
|
|
* overlapping a UUID still reports — suppression is the exception, so it may
|
|
* only fire when the whole match is demonstrably UUID interior.
|
|
*
|
|
* Takes the match (not just the span) because the decision needs surrounding
|
|
* context; span offset is derived exactly as redact-engine.ts derives it, so
|
|
* the two cannot disagree about where the span begins.
|
|
*/
|
|
export function insideUuid(match: RegExpExecArray): boolean {
|
|
const input = match.input ?? "";
|
|
// Mirror the engine: capture group 1 when present, else the whole match.
|
|
const spanStartInMatch = match[1] !== undefined ? match[0].indexOf(match[1]) : 0;
|
|
const spanStart = match.index + Math.max(0, spanStartInMatch);
|
|
const spanEnd = spanStart + (match[1] ?? match[0]).length;
|
|
|
|
const from = Math.max(0, spanStart - UUID_CONTEXT_CHARS);
|
|
const window = input.slice(from, spanEnd + UUID_CONTEXT_CHARS);
|
|
|
|
UUID_RE.lastIndex = 0;
|
|
let u: RegExpExecArray | null;
|
|
while ((u = UUID_RE.exec(window)) !== null) {
|
|
const uuidStart = from + u.index;
|
|
const uuidEnd = uuidStart + u[0].length;
|
|
if (spanStart >= uuidStart && spanEnd <= uuidEnd) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ── The taxonomy ─────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* URL-embedded passwords that are interpolation forms, not credentials:
|
|
* `${identifier}` (bash or JS template, any case) or bare `$UPPER_SNAKE`
|
|
* (shell convention). Bare lowercase `$word` stays BLOCKED — a real password
|
|
* that merely starts with `$` (e.g. `$` + a dictionary word) must not slip
|
|
* through the HIGH gate just because it looks vaguely variable-shaped.
|
|
* Shared by db.url_with_password and creds.basic_auth_url so the two
|
|
* validators cannot drift.
|
|
*/
|
|
// Fully-braced `${...}` spanning the whole password segment is template code
|
|
// regardless of content — `${dbPass}` and `${encodeURIComponent(dbPass)}`
|
|
// alike (the identifier-only form flagged the DSN-encoding call site as a
|
|
// pushed secret). Bare `$word` stays uppercase-only: `$hunter2` must block.
|
|
const INTERPOLATED_PASSWORD_RE = /^(\$\{.+\}|\$[A-Z_][A-Z0-9_]*)$/;
|
|
// URL-password placeholders are matched by EXACT token, never by shape or
|
|
// substring. A shape rule (`/^[A-Z][A-Z0-9_]*$/`) waved through real all-caps
|
|
// secrets like `PROD2026SECRET`; a substring rule would let `PROD2026SECRET`
|
|
// slip because it contains `SECRET`. So this is an anchored, hand-curated set
|
|
// of the doc-comment conventions (postgres://USER:PASSWORD@host) only. Compared
|
|
// case-sensitively against the raw span: the convention is ALL CAPS, and a
|
|
// lowercase `password`/`pass` at this position is a real (terrible) credential
|
|
// that must still block.
|
|
export const URL_PASSWORD_PLACEHOLDER_WORDS = new Set([
|
|
"PASSWORD",
|
|
"PASS",
|
|
"PASSWD",
|
|
"YOUR_PASSWORD",
|
|
"DB_PASSWORD",
|
|
"MY_PASSWORD",
|
|
"CHANGEME",
|
|
"CHANGE_ME",
|
|
"PLACEHOLDER",
|
|
"REDACTED",
|
|
"EXAMPLE",
|
|
]);
|
|
function urlPasswordIsPlaceholder(span: string): boolean {
|
|
const m = span.match(/:\/\/[^:]+:([^@]+)@/);
|
|
const pw = m?.[1] ?? "";
|
|
if (pw === "") return true;
|
|
if (INTERPOLATED_PASSWORD_RE.test(pw)) return true;
|
|
if (URL_PASSWORD_PLACEHOLDER_WORDS.has(pw)) return true;
|
|
return PLACEHOLDER_STRUCTURAL.some((re) => re.test(pw));
|
|
}
|
|
|
|
/**
|
|
* #2913: `postgres:postgres` is the official postgres image's default pair,
|
|
* committed in compose files and CI DATABASE_URLs. It is exempt only on a
|
|
* loopback host (`localhost` or `127.0.0.1`, optional port), never on a
|
|
* single-label host such as `db`: a compose service name says nothing about
|
|
* where the same URL is also deployed, and a weak default on a reachable host
|
|
* is exactly the leak to report. Exact user and password, case-sensitive;
|
|
* the host must end at a port, path, query, quote or the span's end.
|
|
*/
|
|
const POSTGRES_LOOPBACK_DEFAULT =
|
|
/^postgres(?:ql)?:\/\/postgres:postgres@(?:localhost|127\.0\.0\.1)(?::\d{1,5})?(?![\w.:@%-])/;
|
|
|
|
/** A value span that is only an environment-variable read expression (#2912). */
|
|
const ENV_READ_SPAN =
|
|
/^(?:os\.environ\[|os\.environ\.get\(|os\.getenv\(|getenv\(|ENV\[|process\.env\.[A-Za-z_$][\w$]*[;,)]?)$/;
|
|
function isBareEnvRead(span: string, match: RegExpExecArray): boolean {
|
|
if (!ENV_READ_SPAN.test(span)) return false;
|
|
return !carriesSecretLiteral(match.input.slice(match.index + match[0].length).split("\n", 1)[0]);
|
|
}
|
|
|
|
/** True when `text` holds a quoted, non-placeholder, high-entropy literal. */
|
|
function carriesSecretLiteral(text: string): boolean {
|
|
for (const [, literal] of text.matchAll(/["']([^\s'"]{8,})["']/g))
|
|
if (!isPlaceholderSpan(literal) && shannonEntropy(literal) >= 3.0) return true;
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* #2899: the value capture is any non-space run, so it swallows code:
|
|
* `session = _FlakySession(responses=[...])`, `token = make_token(user,`,
|
|
* `password = getpass.getpass()`. A bare credential name plus mixed-case code
|
|
* clears the entropy gate. The span alone cannot tell `Abc123(xyz` (a real
|
|
* password) from a call, so the exemption needs the line's evidence: the
|
|
* value is unquoted, starts with an identifier or dotted path followed by
|
|
* `(`, and that call closes on the line or opens a multi-line argument list.
|
|
* A quoted value is a literal, and a call whose arguments carry a
|
|
* high-entropy literal (`decrypt("<secret>")`) still reports.
|
|
*/
|
|
const CALL_SHAPED_VALUE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\(/;
|
|
function isCallExpression(span: string, match: RegExpExecArray): boolean {
|
|
if (!CALL_SHAPED_VALUE.test(span)) return false;
|
|
const { start } = spanBounds(match);
|
|
if (match.input[start - 1] === '"' || match.input[start - 1] === "'") return false;
|
|
const call = match.input.slice(start + span.indexOf("(")).split("\n", 1)[0];
|
|
if (!call.includes(")") && call.trim() !== "(") return false;
|
|
return !carriesSecretLiteral(call);
|
|
}
|
|
|
|
export const PATTERNS: RedactPattern[] = [
|
|
// ===== HIGH — genuinely-secret credentials (block) =====
|
|
{
|
|
id: "aws.access_key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "AWS access key ID (AKIA…)",
|
|
regex: /\b(AKIA[0-9A-Z]{16})\b/,
|
|
},
|
|
{
|
|
id: "aws.secret_key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "AWS secret access key (with aws_secret_access_key nearby)",
|
|
regex: /\b([A-Za-z0-9/+=]{40})\b/,
|
|
nearRegex: /aws.{0,3}secret.{0,3}access.{0,3}key/i,
|
|
nearWindow: 100,
|
|
},
|
|
{
|
|
id: "github.pat",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "GitHub personal access token (classic)",
|
|
regex: /\b(ghp_[A-Za-z0-9]{36})\b/,
|
|
},
|
|
{
|
|
id: "github.oauth",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "GitHub OAuth token",
|
|
regex: /\b(gho_[A-Za-z0-9]{36})\b/,
|
|
},
|
|
{
|
|
id: "github.server",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "GitHub server-to-server token",
|
|
regex: /\b(ghs_[A-Za-z0-9]{36})\b/,
|
|
},
|
|
{
|
|
id: "github.fine_grained",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "GitHub fine-grained PAT",
|
|
regex: /\b(github_pat_[A-Za-z0-9_]{82})\b/,
|
|
},
|
|
{
|
|
id: "gitlab.token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "GitLab token (personal/pipeline-trigger/deploy)",
|
|
// glpat- personal access, glptt- pipeline trigger, gldt- deploy token.
|
|
// gstack drives glab first-class — these were a coverage gap (#1946).
|
|
regex: /\b(gl(?:pat|ptt|dt)-[A-Za-z0-9_-]{20,})\b/,
|
|
},
|
|
{
|
|
id: "groq.key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Groq API key",
|
|
regex: /\b(gsk_[A-Za-z0-9]{20,})\b/,
|
|
},
|
|
{
|
|
id: "tavily.key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Tavily API key (incl. tvly-dev-/tvly-prod-)",
|
|
// Explicit environment infixes rather than a globally-optional segment,
|
|
// which would also match separator-less tvly-devabc… (same reasoning as
|
|
// openai.key above).
|
|
regex: /\b(tvly-(?:dev-|prod-)?[A-Za-z0-9]{16,})\b/,
|
|
},
|
|
{
|
|
id: "notion.token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Notion integration token (ntn_ current, secret_ legacy)",
|
|
// Two explicit shapes. The legacy `secret_` form keeps a high {40,} floor
|
|
// because the prefix is an ordinary English word — the length is what makes
|
|
// it a credential rather than prose.
|
|
regex: /\b(ntn_[A-Za-z0-9]{40,}|secret_[A-Za-z0-9]{40,})\b/,
|
|
},
|
|
{
|
|
id: "huggingface.token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "HuggingFace access token",
|
|
regex: /\b(hf_[A-Za-z0-9]{30,})\b/,
|
|
},
|
|
{
|
|
id: "npm.token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "npm granular access token",
|
|
regex: /\b(npm_[A-Za-z0-9]{36})\b/,
|
|
},
|
|
{
|
|
id: "digitalocean.token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "DigitalOcean personal access token",
|
|
regex: /\b(dop_v1_[a-f0-9]{64})\b/,
|
|
},
|
|
{
|
|
id: "gcp.service_account",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "GCP service-account JSON private key",
|
|
// The JSON-escaped form ("private_key": "-----BEGIN PRIVATE KEY-----\n...)
|
|
// dodges pem.private_key's literal-block match when minified to one line.
|
|
// Proximity to "private_key_id" confirms the GCP service-account shape.
|
|
regex: /("private_key"\s*:\s*"-----BEGIN (?:RSA |EC )?PRIVATE KEY-----)/,
|
|
nearRegex: /"private_key_id"/,
|
|
nearWindow: 300,
|
|
},
|
|
{
|
|
id: "anthropic.key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Anthropic API key",
|
|
regex: /\b(sk-ant-[A-Za-z0-9_\-]{20,})\b/,
|
|
},
|
|
{
|
|
id: "openai.key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "OpenAI API key (incl. sk-proj-/sk-svcacct-/sk-admin-)",
|
|
// Two explicit shapes (NOT a globally-optional prefix, which would match
|
|
// malformed sk--... or separator-less sk-projabc...):
|
|
// prefixed: sk-{proj,svcacct,admin}- + base64url-ish body (allows -_)
|
|
// bare: sk- + contiguous alphanumeric run (legacy), keeps {32,} floor
|
|
regex:
|
|
/\b(sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{32,})\b/,
|
|
},
|
|
{
|
|
id: "sendgrid.key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "SendGrid API key",
|
|
regex: /\b(SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43})\b/,
|
|
},
|
|
{
|
|
id: "stripe.secret",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Stripe live SECRET key",
|
|
regex: /\b(sk_live_[A-Za-z0-9]{24,})\b/,
|
|
},
|
|
{
|
|
id: "slack.token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Slack token (bot/user/app)",
|
|
regex: /\b(xox[baprs]-[A-Za-z0-9-]{10,})\b/,
|
|
},
|
|
{
|
|
id: "slack.webhook",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Slack incoming webhook URL",
|
|
regex: /(https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{24})/,
|
|
},
|
|
{
|
|
id: "discord.webhook",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Discord webhook URL",
|
|
regex: /(https:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/[0-9]{17,20}\/[A-Za-z0-9_\-]{60,})/,
|
|
},
|
|
{
|
|
id: "twilio.auth_token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Twilio auth token (32 hex, with an Account SID nearby)",
|
|
regex: /\b([a-f0-9]{32})\b/,
|
|
nearRegex: /\bAC[a-f0-9]{32}\b/,
|
|
nearWindow: 200,
|
|
},
|
|
{
|
|
id: "google.oauth_client_secret",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
// Distinct from google.api_key (MEDIUM): an AIza key is often a public
|
|
// client key, but a GOCSPX- client secret is never publishable — leaking
|
|
// it lets anyone impersonate the OAuth app's token exchange.
|
|
description: "Google OAuth client secret (GOCSPX-…)",
|
|
regex: /\b(GOCSPX-[A-Za-z0-9_-]{20,40})(?![A-Za-z0-9_-])/,
|
|
validate: (span) => !isPlaceholderSpan(span),
|
|
},
|
|
{
|
|
id: "telegram.bot_token",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Telegram bot token (<bot-id>:AA…)",
|
|
regex: /\b([0-9]{6,16}:A[A-Za-z0-9_-]{34})(?![A-Za-z0-9_-])/,
|
|
validate: (span) => !isPlaceholderSpan(span),
|
|
},
|
|
{
|
|
id: "pem.private_key",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "PEM private key block",
|
|
regex: /(-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----)/,
|
|
},
|
|
{
|
|
id: "db.url_with_password",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "Database URL with embedded password",
|
|
regex: /\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^:\s/@]+:[^@\s/]+@[^\s/]+)/,
|
|
// Skip when the password segment is itself a placeholder/interpolation,
|
|
// or the URL is postgres's default pair on a loopback host.
|
|
validate: (span) => !urlPasswordIsPlaceholder(span) && !POSTGRES_LOOPBACK_DEFAULT.test(span),
|
|
},
|
|
{
|
|
id: "creds.basic_auth_url",
|
|
tier: "HIGH",
|
|
category: "secret",
|
|
description: "HTTP(S) URL with embedded basic-auth credentials",
|
|
regex: /(https?:\/\/[^:\s/@]+:[^@\s/]+@[^\s/]+)/,
|
|
// Skip when the password segment is itself a placeholder/interpolation.
|
|
validate: (span) => !urlPasswordIsPlaceholder(span),
|
|
},
|
|
|
|
// ===== MEDIUM — demoted credential-shaped (high-FP / context-variable) =====
|
|
{
|
|
id: "stripe.publishable",
|
|
tier: "MEDIUM",
|
|
category: "secret",
|
|
description: "Stripe live publishable key (often intentionally public)",
|
|
regex: /\b(pk_live_[A-Za-z0-9]{24,})\b/,
|
|
},
|
|
{
|
|
id: "google.api_key",
|
|
tier: "MEDIUM",
|
|
category: "secret",
|
|
description: "Google API key (AIza…; sometimes a public client key)",
|
|
regex: /\b(AIza[0-9A-Za-z\-_]{35})\b/,
|
|
},
|
|
{
|
|
id: "jwt",
|
|
tier: "MEDIUM",
|
|
category: "secret",
|
|
description: "JSON Web Token (3-segment base64url)",
|
|
regex: /\b(eyJ[A-Za-z0-9_\-]{8,}\.eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,})\b/,
|
|
},
|
|
{
|
|
id: "env.kv",
|
|
tier: "MEDIUM",
|
|
category: "secret",
|
|
description: "Secret-named assignment (env/YAML/JSON) with high-entropy value",
|
|
// #1946 gap 3: the original shape required an UPPERCASE name and an `=`
|
|
// assignment, so `api_key=…`, `apiKey: "…"`, and `password: …` (YAML/JSON
|
|
// colon form) produced NO finding at all — a detection fail-open on the
|
|
// most common config shapes. Now case-insensitive with `:` or `=`
|
|
// assignment and optional quotes around the key (JSON). Still MEDIUM and
|
|
// entropy-gated: this is the calibrated generic net, not a blocker.
|
|
// The name part is `[A-Za-z0-9_.-]*` + suffix (zero-or-more prefix, not
|
|
// one-or-more): a mandatory first char would swallow the suffix's own
|
|
// first letter and bare names like `password:` / `key:` would never match.
|
|
// The wide net is then calibrated by isCredentialShapedEnvName in
|
|
// validate — without it, any identifier that merely ENDS in a suffix
|
|
// (cacheKey:, sortKey:, monkey:) fires a MEDIUM confirm on entropic
|
|
// values. The value must stay capture group 1 (the engine masks group 1),
|
|
// so name-shape checking lives in validate, not in a second group.
|
|
regex: /^[ \t]*(?:export[ \t]+)?["']?[A-Za-z0-9_.-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)["']?[ \t]*[:=][ \t]*["']?([^\s'"]{8,})["']?/i,
|
|
// Only fire on credential-shaped names with high-entropy values — kills
|
|
// `FOO_KEY=changeme` and `cacheKey: <entropic-id>` FPs. #2912: a value
|
|
// that is exactly an environment read (`os.environ["X"]`,
|
|
// `os.getenv("X")`, `process.env.X`, `ENV["X"]`) names a secret without
|
|
// holding one, unless the rest of its line carries a high-entropy quoted
|
|
// 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).
|
|
validate: (span, match) =>
|
|
isCredentialShapedEnvName(match[0]) &&
|
|
!isPlaceholderSpan(span) &&
|
|
!/^\$\{?[A-Za-z_]/.test(span) &&
|
|
!isBareEnvRead(span, match) &&
|
|
!isCallExpression(span, match) &&
|
|
shannonEntropy(span) >= 3.0,
|
|
},
|
|
{
|
|
id: "auth.bearer",
|
|
tier: "MEDIUM",
|
|
category: "secret",
|
|
description: "Authorization Bearer token (high-entropy, header context)",
|
|
// FP-prone shape (docs and examples are full of "Bearer <token>"), so:
|
|
// MEDIUM tier, requires "authorization" nearby, and the same entropy
|
|
// recipe as env.kv to kill Bearer YOUR_TOKEN_HERE placeholders.
|
|
regex: /\bBearer[ \t]+([A-Za-z0-9._~+/=-]{20,})\b/,
|
|
nearRegex: /authorization/i,
|
|
nearWindow: 80,
|
|
validate: (span) =>
|
|
!isPlaceholderSpan(span) &&
|
|
!/^\$\{?[A-Za-z_]/.test(span) &&
|
|
shannonEntropy(span) >= 3.0,
|
|
},
|
|
|
|
// ===== MEDIUM — PII (auto-redactable subset) =====
|
|
{
|
|
id: "pii.email",
|
|
tier: "MEDIUM",
|
|
category: "pii",
|
|
description: "Email address",
|
|
regex: /\b([A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,})\b/,
|
|
autoRedactable: true,
|
|
redactToken: "<REDACTED-EMAIL>",
|
|
// Engine layers the email allowlist (example.com, noreply@, user's own,
|
|
// repo-public authors) on top of this — see redact-engine.ts.
|
|
},
|
|
{
|
|
id: "pii.phone.e164",
|
|
tier: "MEDIUM",
|
|
category: "pii",
|
|
description: "Phone number (E.164 / common national formats; US/EU-biased)",
|
|
regex: /(?<![\w.])(\+?[1-9]\d{0,2}[ \-.]?\(?\d{2,4}\)?[ \-.]?\d{3,4}[ \-.]?\d{3,4})(?![\w.])/,
|
|
autoRedactable: true,
|
|
redactToken: "<REDACTED-PHONE>",
|
|
// A digit-only UUID's hyphen groups read as national phone formatting, and
|
|
// so do a county tax-map parcel ID (see looksLikeParcelId), vector
|
|
// coordinates (looksLikeDecimalCoordinates) and seed/nonce/timestamp JSON
|
|
// values (isNumericMetadataValue), and GitHub Actions run and job ids in
|
|
// their id positions (isCiRunIdentifier).
|
|
validate: (span, match) =>
|
|
!insideUuid(match) &&
|
|
span.replace(/\D/g, "").length >= 10 &&
|
|
!looksLikeCompactTimestamp(span) &&
|
|
!looksLikeParcelId(span, match) &&
|
|
!looksLikeDecimalCoordinates(span) &&
|
|
!isNumericMetadataValue(span, match) &&
|
|
!isCiRunIdentifier(span, match),
|
|
},
|
|
{
|
|
id: "pii.ssn",
|
|
tier: "MEDIUM",
|
|
category: "pii",
|
|
description: "US Social Security Number",
|
|
regex: /\b(\d{3}-\d{2}-\d{4})\b/,
|
|
autoRedactable: true,
|
|
redactToken: "<REDACTED-SSN>",
|
|
// Reject the all-zero-octet placeholders SSNs never use.
|
|
validate: (span) => {
|
|
const [a, b, c] = span.split("-");
|
|
return a !== "000" && b !== "00" && c !== "0000" && a !== "666" && a[0] !== "9";
|
|
},
|
|
},
|
|
{
|
|
id: "pii.cc",
|
|
tier: "MEDIUM",
|
|
category: "pii",
|
|
description: "Credit-card number (Luhn-valid)",
|
|
regex: /\b((?:\d[ \-]?){13,19})\b/,
|
|
autoRedactable: true,
|
|
redactToken: "<REDACTED-CC>",
|
|
// A 13-19 digit slice of a digit-only UUID or of a decimal number passes
|
|
// Luhn often enough to matter; both context checks run before Luhn.
|
|
validate: (span, match) => !insideUuid(match) && !insideDecimalNumber(match) && luhnValid(span),
|
|
},
|
|
{
|
|
id: "pii.ip_public",
|
|
tier: "MEDIUM",
|
|
category: "pii",
|
|
description: "Public IPv4 address",
|
|
regex: /\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/,
|
|
validate: (span, match) => isPublicIPv4(span) && !isDeclaredVersion(match),
|
|
},
|
|
{
|
|
id: "pii.wallet",
|
|
tier: "MEDIUM",
|
|
category: "pii",
|
|
description: "Crypto wallet address (ETH/BTC)",
|
|
regex: /\b(0x[a-fA-F0-9]{40}|bc1[a-z0-9]{25,39}|[13][a-km-zA-HJ-NP-Z1-9]{25,34})\b/,
|
|
validate: (span) => looksLikeWallet(span),
|
|
},
|
|
|
|
// ===== MEDIUM — internal-leak =====
|
|
{
|
|
id: "internal.hostname",
|
|
tier: "MEDIUM",
|
|
category: "internal",
|
|
description: "Internal hostname (*.internal/.corp/.local/.prod/.staging)",
|
|
regex: /\b([a-z0-9][a-z0-9\-]*\.(?:internal|corp|local|lan|prod|staging))\b/i,
|
|
// `.env.local`, `CLAUDE.local.md` and friends are filenames, not hosts.
|
|
// See isDotenvFilename and isLocalConfigFilename.
|
|
validate: (_span, match) => !isDotenvFilename(match) && !isLocalConfigFilename(match),
|
|
},
|
|
{
|
|
id: "internal.url_private",
|
|
tier: "MEDIUM",
|
|
category: "internal",
|
|
description: "localhost URL with a non-trivial path",
|
|
regex: /(https?:\/\/(?:localhost|127\.0\.0\.1):\d{2,5}\/[^\s)]+)/,
|
|
},
|
|
|
|
// ===== MEDIUM — legal / damaging =====
|
|
{
|
|
id: "legal.nda_marker",
|
|
tier: "MEDIUM",
|
|
category: "legal",
|
|
description: "Confidentiality / NDA marker",
|
|
regex: /\b(CONFIDENTIAL|UNDER NDA|ATTORNEY[- ]CLIENT|PRIVILEGED|DO NOT DISTRIBUTE|EYES ONLY)\b/,
|
|
},
|
|
{
|
|
id: "legal.named_criticism",
|
|
tier: "MEDIUM",
|
|
category: "legal",
|
|
description: "Negative judgment near a capitalized full name (semantic pass is primary)",
|
|
regex: /\b(incompetent|negligent|fraudulent|fraud|fired|terminated|harassed|underperforming)\b/i,
|
|
// Require a Capitalized Two-Word name within the window.
|
|
nearRegex: /\b[A-Z][a-z]+ [A-Z][a-z]+\b/,
|
|
nearWindow: 80,
|
|
},
|
|
|
|
// ===== LOW — surface only =====
|
|
{
|
|
id: "internal.user_path",
|
|
tier: "LOW",
|
|
category: "internal",
|
|
description: "Absolute path under a user home dir",
|
|
regex: /(\/(?:Users|home)\/[a-z][a-z0-9_\-]+\/[^\s)]*)/,
|
|
},
|
|
{
|
|
id: "hygiene.todo",
|
|
tier: "LOW",
|
|
category: "hygiene",
|
|
description: "TODO(owner) marker carried into the artifact",
|
|
regex: /\b(TODO\([^)]+\))/,
|
|
},
|
|
];
|
|
|
|
/** Lookup by id. */
|
|
export const PATTERNS_BY_ID: Record<string, RedactPattern> = Object.fromEntries(
|
|
PATTERNS.map((p) => [p.id, p]),
|
|
);
|