Skip to content

Commit 2a6ddf4

Browse files
committed
fix(docs): correct ARCH-005/ARCH-022/GEN-004 per review
Address CodeRabbit findings, verified against actual code before applying: - ARCH-005: globalThis.fetch mocking guidance wrongly implied mock.restore() undoes a direct assignment — it only restores spyOn()/mock()-created mocks. Fixed the Do's/Don'ts item, the Manual Enforcement item, and the Implementation Pattern example to match the save-and-reassign pattern already used in tests/commands/upgrade.test.ts and tests/helpers/auth.test.ts. - ARCH-005: fixed garbled NODE_ENV wording in the cross-file pollution risk bullet ("left unset to \"test\"" -> "left unset instead of set to \"test\""). - ARCH-022: clarified guardrail-ordering clause 3, which read as if all four guardrail steps run "before any subprocess" even though steps 3-4 (interpreter probe, guarded invocation) are themselves subprocess spawns. - GEN-004: added @argument, @prop, and @Satisfies to the Decision's structural-tag exemption list — both enforcement layers (.archgate/lint/concise-comments.ts and the companion .rules.ts) already treat these as structural; only the ADR's own prose list was out of sync. Signed-off-by: Rhuan Barreto <rhuan@barreto.work>
1 parent 6bd16db commit 2a6ddf4

3 files changed

Lines changed: 29 additions & 21 deletions

File tree

‎.archgate/adrs/ARCH-005-testing-standards.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,20 +43,20 @@ Use Bun's built-in test runner (`bun test`) for all tests. Test files live in `t
4343
- **DO** close external SDK instances with `await server.close()` in hooks, not test bodies.
4444
- **DO** set `git config user.email`/`user.name` locally after `git init`, before any commit.
4545
- **DO** assert with `expect()` — `bun-test/expect-expect` fails lint otherwise; use `test.skip`/`test.todo` for placeholders.
46-
- **DO** mock fetch via `globalThis.fetch`, restored via `mock.restore()`.
47-
- **DO** wrap inline `spyOn`/`mockImplementation` in `try/finally` so `mockRestore()` runs on a failed assertion, or manage spies in hooks.
48-
- **DO** make thresholds injectable, e.g. `resolveScopedFiles(root, globs, { fileWarnThreshold })` — inject `5`, never materialize 1000+ real files (Consequences: hangs).
46+
- **DO** save `globalThis.fetch` before assigning a mock, restore it in `afterEach` — `mock.restore()` doesn't undo a direct assignment.
47+
- **DO** wrap inline `spyOn`/`mockImplementation` in `try/finally` so `mockRestore()` runs on failure, or manage spies in hooks.
48+
- **DO** make thresholds injectable, e.g. `resolveScopedFiles(root, globs, { fileWarnThreshold })` — inject `5`, never materialize 1000+ files (Consequences).
4949
- **DO** mock first-party modules and `os.homedir()` via `import * as mod` + `spyOn(mod, "fn")`, restored by `mock.restore()`.
5050

5151
### Don't
5252

53-
- **DON'T** hit the network, import `node:test` (use `bun:test`), or `mock.module("node:fetch", ...)` — it silently no-ops.
54-
- **DON'T** `mock.module()` a first-party module (OK for third-party: `inquirer`, `node:readline`) — never dodge via an `-impl` file split.
53+
- **DON'T** hit the network, import `node:test` (use `bun:test`), or `mock.module("node:fetch")` — it silently no-ops.
54+
- **DON'T** `mock.module()` a first-party module (OK for `inquirer`, `node:readline`) — never dodge via an `-impl` file split.
5555
- **DON'T** restore an env var with bare `Bun.env.X = original` — `undefined` becomes the string `"undefined"`, not a clear.
5656
- **DON'T** leave temp files or SDK instances open post-test.
5757
- **DON'T** rely on global git identity in a temp repo — passes locally, fails only in CI (`ShellPromise` error).
58-
- **DON'T** touch real state — no real user-scope paths, no unset `NODE_ENV` before Sentry init; spy the writer or mock `os.homedir()`.
59-
- **DON'T** write assertion-less tests or skip silently (bare `return`, empty callback) — use `test.skipIf`/`test.skip`/`test.todo` with an issue.
58+
- **DON'T** touch real state — no real user-scope paths, no unset `NODE_ENV` before Sentry init; spy or mock `os.homedir()`.
59+
- **DON'T** write assertion-less tests or skip silently (bare `return`, empty callback) — use `test.skipIf`/`skip`/`todo` with an issue.
6060

6161
## Implementation Pattern
6262

@@ -115,9 +115,17 @@ it("processes data", () => {
115115
mock.module("node:fetch", () => ({
116116
default: () => Promise.reject(new Error("network error")),
117117
}));
118-
// GOOD: assign globalThis.fetch directly
119-
globalThis.fetch = (() =>
120-
Promise.reject(new Error("network error"))) as unknown as typeof fetch;
118+
// GOOD: assign globalThis.fetch directly, saved beforehand and restored in
119+
// afterEach — mock.restore() does not undo a direct assignment.
120+
let originalFetch: typeof fetch;
121+
beforeEach(() => {
122+
originalFetch = globalThis.fetch;
123+
globalThis.fetch = (() =>
124+
Promise.reject(new Error("network error"))) as unknown as typeof fetch;
125+
});
126+
afterEach(() => {
127+
globalThis.fetch = originalFetch;
128+
});
121129

122130
// BAD: mock.module on a first-party module is process-global and leaks into
123131
// every other test file, so auth.test.ts receives this mock instead of the
@@ -159,7 +167,7 @@ afterEach(() => {
159167
- **Mitigation:** the project pins a Bun version via `.prototools`; API changes surface during controlled upgrades with full suite validation.
160168
- **Coverage reporting gaps** — `bun test --coverage` may misreport code paths, especially dynamically imported modules.
161169
- **Mitigation:** the 90% threshold is enforced on total line coverage, not per-file, and critical modules (engine, formats) are tested thoroughly regardless of the aggregate.
162-
- **Cross-file pollution from shared process state** — leaked env vars, leaked spies, and writes to real user-scope paths (`~/.config/Code/User/settings.json`, `%APPDATA%`, `~/.cursor/`, `~/.config/opencode/`) produce order-dependent flakes that pass on a PR run and fail after merge with identical code. `Bun.env.NODE_ENV` left unset to `"test"` before Sentry initializes is the same class of leak — the SDK sets `enabled: Bun.env.NODE_ENV !== "test"`.
170+
- **Cross-file pollution from shared process state** — leaked env vars, leaked spies, and writes to real user-scope paths (`~/.config/Code/User/settings.json`, `%APPDATA%`, `~/.cursor/`, `~/.config/opencode/`) produce order-dependent flakes that pass on a PR run and fail after merge with identical code. `Bun.env.NODE_ENV` left unset instead of set to `"test"` before Sentry initializes is the same class of leak — the SDK sets `enabled: Bun.env.NODE_ENV !== "test"`.
163171
- **Mitigation:** `restoreEnv()` for every env capture, `try/finally` around inline spies, and an `os.homedir()` spy that keeps writes inside a `mkdtemp` directory; `test-isolation/no-bare-env-restore` blocks the env variant at lint time.
164172
- **Platform-specific hangs and timeouts** — an external SDK instance left open keeps Bun's event loop alive on Linux and hangs `bun test` after every test passes, while slow Windows CI filesystems let large fixtures blow the per-test timeout and kill the staging subprocess (`git add . failed (exit 143)`, where 143 = 128 + SIGTERM). Neither reproduces on macOS or locally.
165173
- **Mitigation:** close SDK instances in `afterEach`, inject small thresholds instead of generating large fixtures, and cap every CI job with `timeout-minutes` (10 minutes for `code-pull-request.yml`).
@@ -182,7 +190,7 @@ Code reviewers MUST verify:
182190
1. New source files have corresponding test files, and every test asserts with `expect()` — no smoke test that merely calls a function. "Does not throw" is spelled `expect(() => fn()).not.toThrow()` or `await expect(promise).resolves.toBeUndefined()`, never a bare invocation with no assertion.
183191
2. Filesystem work happens in temp directories (no hardcoded paths), and both temp directories and external SDK instances (servers, clients, transports) are cleaned up in `afterEach`/`afterAll`, with SDK lifecycles managed in hooks rather than test bodies.
184192
3. Temp repos that call `git commit` configure `user.email` and `user.name` locally first.
185-
4. HTTP mocking assigns `globalThis.fetch = mockFn as unknown as typeof fetch`; first-party mocking uses `import * as mod` + `spyOn`, with no production module split into an `-impl` file to dodge `mock.module` leakage.
193+
4. HTTP mocking saves `globalThis.fetch` and restores it directly in `afterEach` (`mock.restore()` does not undo a direct assignment); first-party mocking uses `import * as mod` + `spyOn`, restored via `mock.restore()`, with no production module split into an `-impl` file to dodge `mock.module` leakage.
186194
5. Inline `spyOn`/`mockImplementation` usage wraps the spy lifecycle in `try/finally` so `mockRestore()` runs even when assertions fail.
187195
6. Threshold tests inject a small value rather than generating fixtures large enough to trip the production default, and no per-test timeout override is shorter than the global `--timeout 60000`.
188196
7. Shared test helpers under `tests/**` that are not `*.test.ts` files (e.g. `tests/integration/cli-harness.ts`, `tests/test-utils.ts`) restore environment variables via `restoreEnv` for every capture (`NODE_ENV`, `GIT_CONFIG_GLOBAL`, `HOME`, and any other `Bun.env.X`/`process.env.X` read) — `test-isolation/no-bare-env-restore` is scoped to `tests/**/*.test.ts` and does not cover them, yet a leak from a shared helper reaches every test that imports it.

‎.archgate/adrs/ARCH-022-ast-aware-rule-context.md‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,18 +36,18 @@ ast(path: string, language: AstLanguage, opts?: AstOptions): Promise<AstNode>;
3636
// AstOptions = { rev?: "base"; comments?: boolean }
3737
```
3838

39-
Dispatch on `language` is internal and MUST be invisible to rule authors.
39+
Dispatch on `language` MUST be invisible to rule authors.
4040

4141
1. **TS/JS MUST reuse the in-process `meriyah` parser**, no subprocess. `rule-scanner.ts`'s duplicated `parseModule()` MUST factor into one helper (`parseTsOrJsSource`) shared by scanner and `ctx.ast()`.
42-
2. **Python/Ruby MUST invoke its own stdlib AST facility as a subprocess** via `Bun.spawn` ([ARCH-007](./ARCH-007-cross-platform-subprocess-execution.md); Key Definitions: commands). No third-party parser or binding.
43-
3. **Guardrail ordering.** Rule code MUST NEVER reach `Bun.spawn`, `child_process`, or any subprocess/filesystem primitive; `ctx.ast()` is the only door. All four MUST run inside `createRuleContext()`, before any subprocess, in the order Key Definitions lists.
44-
4. **Failure semantics.** `ctx.ast()` MUST throw — never `null` — on interpreter-unavailable, parse-failure, no-base-resolved, or absent-at-base (Key Definitions). `fileAtBase()` is the exception, returning `null` for base cases.
45-
5. **Base-revision access.** `ast(path, language, { rev: "base" })` and `fileAtBase(path)` MUST reach the base git revision (Key Definitions), closing the [ARCH-024](./ARCH-024-rule-file-sandbox-boundary.md) gap.
46-
6. **Comment access.** `{ comments: true }` MUST attach a `comments` array of `CommentToken` (Key Definitions). Opt-in, all languages, folded into `ast()`.
42+
2. **Python/Ruby MUST invoke its own stdlib AST facility as a subprocess** via `Bun.spawn` ([ARCH-007](./ARCH-007-cross-platform-subprocess-execution.md)). No third-party parser.
43+
3. **Guardrail ordering.** Rule code MUST NEVER reach `Bun.spawn`, `child_process`, or any subprocess/filesystem primitive; `ctx.ast()` is the only door. All four MUST run inside `createRuleContext()`, in Key Definitions' order: path/language checks first (no subprocess), then the guarded probe — the first sanctioned subprocess — then the guarded invocation. No unguarded subprocess may occur.
44+
4. **Failure semantics.** `ctx.ast()` MUST throw — never `null` — on interpreter-unavailable, parse-failure, no-base-resolved, or absent-at-base (Key Definitions). `fileAtBase()` is the exception.
45+
5. **Base-revision access.** `ast(path, language, { rev: "base" })`/`fileAtBase(path)` MUST reach the base git revision (Key Definitions), closing the [ARCH-024](./ARCH-024-rule-file-sandbox-boundary.md) gap.
46+
6. **Comment access.** `{ comments: true }` MUST attach a `comments` array of `CommentToken` (Key Definitions), opt-in, folded into `ast()`.
4747

48-
**Non-goal: cross-language shape unification.** `ctx.ast()` unifies the call site and failure contract, not the tree shape — ESTree for TS/JS, Python's `ast` schema, Ruby's s-expression. Authors MUST know the target vocabulary (Context: trade-off).
48+
**Non-goal: cross-language shape unification.** `ctx.ast()` unifies the call site and failure contract, not the tree shape — ESTree for TS/JS, Python's `ast` schema, Ruby's s-expression. Authors MUST know the vocabulary.
4949

50-
**Scope.** Covers `ast()`'s signature, dispatch, guardrail ordering, failure semantics — not rollout or authoring guidance.
50+
**Scope.** Covers `ast()`'s signature, dispatch, guardrails, failure semantics — not rollout or authoring guidance.
5151

5252
## Key Definitions
5353

‎.archgate/adrs/GEN-004-concise-forward-only-code-comments.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ Comments in all project-authored TypeScript MUST be concise and MUST describe cu
4646

4747
The bound measures **narrative**: a doc comment's untagged summary only. A structural tag opens an exempt section — the tag line and every line under it, up to the next tag.
4848

49-
- **Exempt:** `@param`, `@arg`, `@typeParam`, `@template`, `@returns`, `@throws`, `@example`, `@see`, `@link`, `@defaultValue`, `@deprecated`, `@internal`, `@public`, `@alpha`, `@beta`, `@experimental`, `@module`, `@packageDocumentation`, `@typedef`, `@callback`, `@property`, `@overload`, `@inheritDoc`, `@label`.
49+
- **Exempt:** `@param`, `@arg`, `@argument`, `@typeParam`, `@template`, `@returns`, `@throws`, `@example`, `@see`, `@link`, `@defaultValue`, `@deprecated`, `@internal`, `@public`, `@alpha`, `@beta`, `@experimental`, `@module`, `@packageDocumentation`, `@typedef`, `@callback`, `@property`, `@prop`, `@overload`, `@inheritDoc`, `@label`, `@satisfies`.
5050
- **NOT exempt:** `@remarks`, `@description`, `@summary`, `@notes`, `@todo`, `@fixme` — narrative in a tag's clothing, counted like untagged prose.
5151

5252
### Forward-only content

0 commit comments

Comments
 (0)