Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions .agents/skills/testing-patterns/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
name: testing-patterns
description: "Write, review, or prune better-auth-telegram tests; choose justified expectations, fixtures, behavior boundaries, and verification effort. Use when deciding whether a test adds protection. Does not authorize a general code audit, suite cleanup, or runtime changes."
---

# Tests that earn their place

Protect a justified contract or deliberate compatibility baseline, distinguish a
meaningful failure, and weigh the additional protection against maintenance cost.
Stay within the task. A small edit does not require a full audit or testing plan.
Read [repository guidance](references/repository.md) when choosing a local runner,
fixture, dependency boundary, or required gate.

## Establish the claim

Read the relevant implementation, callers and existing protection. Identify the
contract and its provenance, a plausible failure class, the behavior owner, and
what the proposed test adds. Usually the test name or a short explanation is enough.
If existing tests and static checks adequately protect the task, add no new test.

Requirements, protocol examples, checked calculations, domain properties and
reviewed references can justify expected results. Current implementation is useful
but fallible evidence; do not use the calculation under test as its own oracle.
Shared setup and unrelated parsing helpers can be legitimate. A recorded legacy
output can protect compatibility during a refactor: label and review that baseline
without claiming it proves business correctness. If the contract is unknown, keep
the uncertainty visible rather than inventing an expectation.

## Make the case discriminate

Choose reachable inputs, relevant boundaries, roles, states or combinations that
separate the contract from the named mistake. Run the actual behavior owner.
Assert promised outputs and relevant effects: identities, durable state, external
requests, user-visible results, errors and prohibited actions. A denial must reach
the intended decision; invalid setup or an unawaited operation can make it vacuous.
Be precise about important fields without freezing unrelated output.

Use the narrowest boundary that preserves the failure mechanism. Real database
engines are needed for claims about their constraints, transactions or locking;
a substitute does not establish those semantics. A real dependency is not required
for every test that happens to call it. Client-store behavior needs the real store;
DOM emulation does not establish browser layout or Telegram's live behavior.
Complementary unit, integration, contract and acceptance tests may overlap usefully.

Mocks and fakes can control external responses, time, rare errors or expensive
collaborators. Interaction assertions can protect request contracts, forbidden
calls, duplication limits or ordering. Reviewed snapshots/goldens can protect
formats or visual baselines; source/architecture checks can enforce an explicit
structural policy. Type, presence and smoke checks can protect limited interface
or startup contracts. Judge their purpose, not their syntax; do not ban these
techniques or present them as stronger evidence than they supply.

## Check sensitivity proportionately

For a confirmed bug, prefer a focused failing regression before the fix when RED
is stable and economical. Inspect why it fails. For a doubtful assertion or an
important invariant, consider a targeted fault or mutation when it adds useful
confidence. Do not impose mutation on every test, a universal coverage target,
mandatory separate-model review, or a new testing dependency.

A killed mutant does not validate the oracle. A survivor may be equivalent,
irrelevant, unreachable or evidence of weak protection. A broken build/import or
unselected case is not behavioral detection; an intentional consumer-type failure
can be the correct signal for a declaration contract. Restore only your own probes
and verify the resulting tree. Use an isolated copy when work is shared.

Generated inputs need a useful domain and property, reviewed preconditions/filters,
and reproducible failures. Round trips can hide mutually cancelling faults;
differential agreement depends on a fallible reference. Retain independent examples
where they protect another dimension. No technique is mandatory for every function.

## Decide and finish

For an authorized test review, use:

- **KEEP:** useful contract, reviewed baseline or distinct boundary at acceptable cost.
- **REWRITE:** meaningful risk, but inadequate oracle, fixture, boundary or reliability.
- **DELETE:** obsolete/no useful role, or equivalent relevant protection remains;
inspect callers, incident coverage, fixtures, registrations and required gates first.
- **UNRESOLVED:** insufficient contract or evidence; retain the test pending investigation.

Equal coverage or mutation scores do not prove equivalent future protection. Do not
prune to a count target. "Confirmation testing" can legitimately mean verifying a
bug fix; describe weak cases as implementation-mirroring or weak-oracle tests.

Await work and eventual assertions. Coordinate races at the relevant boundary
where practical; do not rely only on simultaneous promise creation. Prefer bounded
observable waits to guessed sleeps, and investigate intermittent product failures
instead of hiding them with retries. Any quarantine needs a reason, owner and path
back to coverage. Restore clocks, listeners, mocks and owned state; release owned
files, connections, processes and containers on failure, cancellation and timeout.

Preserve the project's required gates, including surface acceptance when applicable.
Use the smallest relevant checks and reuse valid evidence until its assumptions
change. Coverage is a diagnostic, not a correctness certificate: do not lower gates,
exclude code or weaken assertions for a score. Report decisions, checks actually run,
unproved boundaries and cleanup; distinguish observation from prediction.
138 changes: 138 additions & 0 deletions .agents/skills/testing-patterns/references/repository.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Repository testing reference

Paths below are relative to this reference. Run commands from the repository root.
Verify the current scripts/configuration when they change; this reference does not
override task scope or authorize installing dependencies or starting services.

## Owners and fixtures

| Claim | Owner and existing evidence |
| --- | --- |
| Signed Widget/Mini App data, freshness and canonical fields | [verify.ts](../../../../src/verify.ts), [literal vectors](../../../../src/verify.test.ts), [boundary tests](../../../../src/verify-hardening.test.ts) |
| OIDC token identity and mapping | [oidc-token.ts](../../../../src/oidc-token.ts), [oidc.ts](../../../../src/oidc.ts), co-located OIDC suites |
| Account ownership, hooks, revocation and session cookies | [account orchestration](../../../../src/telegram-account.ts), [identity hooks](../../../../src/telegram-identity.ts), [real-adapter suite](../../../../src/adapters.adapter.test.ts) |
| Client session refresh | [client.ts](../../../../src/client.ts), [real client/server tests](../../../../src/client.integration.test.ts) |
| Widget callback/host lifecycle | [client-widget.ts](../../../../src/client-widget.ts), [DOM tests](../../../../src/client.test.ts) |
| Installed exports and consumer types | [package verifier](../../../../scripts/check-package.mjs), [test-d](../../../../test-d/consumer.ts), [CommonJS consumer](../../../../test-d/commonjs.cts) |

[testing/harness.ts](../../../../src/testing/harness.ts) exposes real Better Auth on
memory or SQLite, a cookie-aware HTTP client, signed inputs and a fake Telegram
issuer. Substitute the external provider, not Better Auth's authentication decisions.
The signing helpers are input factories; literal OpenSSL vectors independently
check the cryptographic format. The fake issuer rejects unexpected network calls.
SQLite fixtures register `onTestFinished` cleanup, including setup failure.

The client integration tests use the real Better Auth store and server. Control
scheduled refresh work before asserting absence of a request; an immediate assertion
may run too early. Browser layout, iframe cookies and live Telegram login require
the corresponding acceptance environment. [test/](../../../../test/README.md) is a
manual playground, not an automated test lane.

## Selection and gates

The source of truth is [package.json](../../../../package.json),
[Vitest config](../../../../vitest.config.ts),
[adapter config](../../../../vitest.adapters.config.ts) and
[CI](../../../../.github/workflows/ci.yml). Node 24+ is required. Existing installs
are sufficient for the commands below; do not install or upgrade tools gratuitously.

```sh
# Focused default-suite cases; inspect the selected/passed/skipped counts.
npm test -- src/verify-hardening.test.ts -t 'auth_date freshness'
npm test -- src/client.integration.test.ts -t 'disableSignal'

# Scope lint while editing; type-check the package for affected TypeScript.
./node_modules/.bin/ultracite check src/verify-hardening.test.ts
npm run type-check

# Default suite and its coverage gate.
npm test
npm run test:coverage

# Bun compatibility uses Vitest under Bun, not the unrelated `bun test` runner.
bun --bun run test

# Built public declarations and an isolated installed-package consumer.
npm run build
npm run test:types
npm run test:package
```

Default tests use happy-dom unless their file selects Node. `*.adapter.test.ts` is
excluded from `npm test`; a passing default suite is not adapter evidence. Coverage
floors remain 90% lines/statements/branches and 80% functions. Broad/release CI also
requires lint, type checks, runtime dependency audit, package validation, Node 24.0.0,
current Node 24/26, the complete minimum Better Auth 1.7.12 family, Bun 1.4.4 and real
adapters. Do not infer a release pass from one local lane or bypass required checks.

Documentation/skill-only changes normally need readback, link/frontmatter validation
when relevant, and `git diff --check`; do not run the runtime matrix just for prose.
A type-contract failure is assessed through declaration consumers, not only runtime
coverage. Tests at different levels can protect different failures of one feature.

## Real adapters and resource ownership

[testing/adapters.ts](../../../../src/testing/adapters.ts),
[adapter-resources.ts](../../../../src/testing/adapter-resources.ts) and
[adapter-prisma.ts](../../../../src/testing/adapter-prisma.ts) own fixture lifecycle.
The lane requires explicit URLs to disposable, test-owned services:

- `BAT_TEST_POSTGRES_URL`: PostgreSQL, also used by Drizzle and Prisma.
- `BAT_TEST_MYSQL_URL`: MySQL; the fixture needs permission to create databases.
- `BAT_TEST_MONGODB_URL`: MongoDB replica set with direct connection support.

Missing URLs skip the corresponding lanes. An all-skipped collection is not a pass.
The checked-in CI service setup uses PostgreSQL 18, MySQL 8.4 and MongoDB 8.2 with a
replica set. There is no repository-local general container launcher; use the
workflow as the setup reference for an authorized disposable run, not guessed host
ports, shared databases or another project's commands.

Once those owned URLs are exported:

```sh
npm run test:adapters
npm run test:adapters -- src/adapters.adapter.test.ts -t 'rejects account hooks'
```

The fixtures create named `bat_*` databases, close pools and drop owned databases.
Prisma has a suite-owned database; generated clients/schemas have per-run directories
under `node_modules/.cache/better-auth-telegram-adapters` and are removed after tests.
Caller-owned harnesses still need `close()` in teardown, including failed assertions.
For a process killed before hooks finish, the coordinator must remove its identified
containers/volumes and run-specific files. Verify cleanup without deleting shared
services, all `bat_*` databases on an unverified host, or another run's cache.

Inside Better Auth transactions, use the current transaction adapter for reads.
Memory/SQLite rollback does not establish Drizzle/Prisma's default nontransactional
behavior. Generated serial/UUID IDs and independent servers need their actual
adapter lane. Existing cross-server identity uniqueness limits remain limits, not
promises supplied by containers or a process-local lock.

## Useful local decisions

- **Freshness:** the documented age window includes its endpoint. Use explicit
boundary expectations, with literal vectors elsewhere protecting signing. A
helper that computes the same age rule cannot be the oracle for that rule.
- **Binding refusal:** a 409 response alone misses a bad account insert that remains
after rejection. Use valid conflicting owners and durable readback on the relevant
nontransactional adapter. The faster memory case can remain complementary.
- **Session refresh:** keep the real store and await its scheduler; a mock notification
call alone cannot establish that the mounted session changed.
- **Compatibility:** preserve a reviewed serialized baseline during an internal
refactor, even if the format is quirky. A type-only public declaration change may
need a consumer check; a documentation correction with adequate existing coverage
may need no new test. Neither implies a blanket snapshot or structural-check ban.

## Provenance

Adapted from the supplied research reviewed 2026-11-04:
`guidelines.md` and `audit.md` in `/home/vcode/docs/research/test-quality-2026/`.
SHA-256 digests respectively:

- `0b19c15a4d1fbccbbea6f61564788fa4d9e2a1c2a1992710465faea19da8d764`
- `7bd25662e3f4964c087a30d9dd07ce49078bec0fae445945838d9aa99e9321ce`

Those external paths identify the source material; the skill does not require them
at runtime. The qualifications are incorporated in the shared core. The research
bibliography is not copied into default-loaded instructions. Historical repository
audit reports record their own scope and are not additional testing policies.
95 changes: 95 additions & 0 deletions .agents/skills/testing-patterns/references/validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Skill validation, 2026-11-04

This is a record of bounded checks, not an additional testing policy or a claim
about the correctness of the repository's authentication implementation.

## Discovery and portability

Installed clients were `codex-cli 0.166.0` and Claude Code `2.1.318` on Linux.
The official [Codex skills documentation](https://learn.chatgpt.com/docs/build-skills)
and [Claude Code skills documentation](https://code.claude.com/docs/en/skills)
describe their respective discovery directories and support directory symlinks.
The shared core has only portable `name` and `description` frontmatter.

- The installed Codex `app-server` answered `skills/list` with `forceReload: true`
for the repository root and `src/`. Each returned exactly one enabled,
repository-scoped `testing-patterns` at `.agents/skills/testing-patterns/SKILL.md`,
with no discovery errors. The server process was then terminated.
- A Claude Code provider evaluation selected the skill through its native `Skill`
tool: input `{"skill":"testing-patterns"}`, successful command `testing-patterns`.
This exercised actual invocation through `.claude/skills/testing-patterns`.
- The relative directory link is `../../.agents/skills/testing-patterns`.
Both paths resolve to the same instruction body. A disposable Git index and
`git checkout-index` roundtrip preserved mode `120000` and a working relative
link. `AGENTS.md` and `CLAUDE.md` are distinct regular files.

Codex invocation is `$testing-patterns`; Claude Code invocation is
`/testing-patterns`. No plugin wrapper, MCP server, hooks or global installation
was added. The interactive slash-command menu was not separately exercised.
Checkout portability was checked on Linux, not Windows or macOS.

## Behavioral checks

Each client received the same four tasks in its own disposable fixture directory.
The prompts supplied the contract and allowed edits, but not the evaluator's
expected decisions or mutation checks. Agents were directed to use applicable
repository instructions; the four fixture tasks themselves did not name a skill.

The Codex native subagent read the shared skill and repository reference. The
Claude Code provider used the native skill tool; it did not load the optional
reference because the fixtures explicitly selected Node's built-in test runner.
These are behavioral smoke checks, not a benchmark or exhaustive trigger test.

| Task | Observable outcome in both clients |
| --- | --- |
| Inclusive freshness threshold, with a mirrored interior-only test | Replaced the computed oracle with literal contract examples, added the exact endpoint and an expired case, observed an assertion failure on the endpoint, then fixed the fixture. |
| Final-seat reservation with a fake SQL transaction | Identified that two mocked writes do not establish one successful reservation; required coordinated independent PostgreSQL transactions and durable readback. Did not provision a database or edit the scenario. |
| Reviewed double-space label golden before an internal refactor | Kept the baseline and test unchanged; distinguished compatibility from ideal formatting. |
| README spelling correction | Corrected the word and added no test. |

Both clients observed RED with two passing cases and one failed assertion, then
GREEN with three passing cases. The lead independently ran each resulting test,
reintroduced the original `<` instead of `<=` defect, and observed exit 1 with an
`AssertionError`. Restoring the fix and running the freshness and compatibility
tests together gave exit 0. Node was `v26.13.0`.

Fixture commands actually executed included:

```sh
node --test regression/freshness.test.mjs
node --test regression/freshness.test.mjs compat/format.test.mjs
```

Hash comparisons found only the four allowed fixture outputs changed: freshness
implementation, freshness test, README and result report. The boundary scenario,
golden and compatibility test stayed unchanged. Evaluators made no changes to the
real tracked repository files or the shared skill/reference.

## Structural checks and local command verification

- The installed skill-creator `scripts/quick_validate.py` accepted the canonical
directory. Relative Markdown links, code fences, skill name and symlink target
were checked. `git diff --check` passed.
- Commands in [repository guidance](repository.md) were checked against local
package scripts, Vitest configuration, fixtures and CI. This source verification
does not mean the full commands or runtime matrix were executed for this task.
- `vitest list src/verify-hardening.test.ts -t 'auth_date freshness' --json=...`
found two static test templates; parameterized cases were not expanded.
- `vitest list src/client.integration.test.ts -t 'disableSignal' --json=...`
found one static test.
- The adapter selector `rejects account hooks` exists in the source. Both static
and `--staticParse=false` collection with `vitest.adapters.config.ts` returned
zero cases while all three `BAT_TEST_*_URL` variables were explicitly unset.
That is not a passing adapter run or proof of the selected runtime case.

No repository runtime suite, real adapter, browser acceptance or release matrix was
run for this instruction-only change. Existing CI gates, production code, tests,
dependencies and package scripts were preserved.

## Cleanup

Evaluation-owned fixtures, logs and nested checkout/index probes under
`node_modules/.cache/testing-skill-eval-mmuar67i` were removed after recording these
results. No database, container or persistent server was created. Unrelated caches,
services and work were left intact. The evidence above is retained as a summary;
temporary model traces and fixtures are not part of the skill distribution.
1 change: 1 addition & 0 deletions .claude/skills/testing-patterns
Loading
Loading