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
115 changes: 115 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Copilot Instructions — petry-projects/.github

> **Note:** This file applies to the `petry-projects/.github` repository only. Copilot
> instruction files are repository-scoped — there is no automatic org-wide propagation. Every
> other repo in the org must have its own `.github/copilot-instructions.md`. Use this file as
> the canonical template; the weekly compliance audit enforces deployment to each repo.

## Repository Overview

This is the **org standards repository** for `petry-projects`. It contains org-wide AI agent
standards (`AGENTS.md`), canonical CI workflow templates (`standards/workflows/`), the
compliance audit script, and the canonical Copilot instruction files that every repo should
adopt.

Primary stack for work done in this repo: Bash · YAML · Markdown · Python (scripts).

## Standards Reference

Full AI agent development standards live in **[AGENTS.md](../AGENTS.md)**. This file is a
Copilot-focused summary; AGENTS.md is authoritative when they conflict. Read the relevant
standard in [`standards/`](../standards/) before touching CI, repo settings, or agent
configuration.

Language-specific rules are applied automatically via files in `.github/instructions/`:
`typescript`, `javascript`, `python`, `go`, `terraform`, and `shell` — see those files for
per-language guidance.

## Core Development Rules

**Test-driven development is mandatory.** Write tests before implementing features. Never
`.skip()` a failing test — fix it. Never add coverage-ignore comments (`istanbul ignore`,
`c8 ignore`, `v8 ignore`). PRs that reduce coverage below the repo-defined threshold are
rejected.

**SOLID + DDD.** Each module has one reason to change. High-level policy never imports
infrastructure directly — inject dependencies. Use domain terminology in code, tests, and docs.
Bounded contexts communicate through well-defined interfaces or domain events. Use typed value
objects for domain identifiers and quantities instead of raw primitives.

**CLEAN Code + KISS + YAGNI.** Names reveal intent. Functions do one thing at one level of
abstraction. Implement exactly what the current story requires — no speculative features. Wait
for three concrete cases before extracting an abstraction.

**Fail loud, never fake.** Never swallow exceptions silently. Never substitute placeholder data
when a real fetch or computation fails without an explicit, disclosed fallback (log it, flag it,
or surface a `degraded: true` field). Never report a step complete when it errored.

**No breaking changes without explicit human approval.** Before removing or renaming any public
symbol, endpoint, field, event schema, or database column: search all consumers, count them, and
propose a non-breaking alternative first. Treat the existing test suite as a contract — failing
tests signal breaking changes, not tests to update.

## Pre-Commit Quality Checks

Before every commit run in order: **format → lint → typecheck → test**. Hooks may not execute
in Copilot sessions — apply manually. Zero warnings and zero errors required for lint and
typecheck. Run the full test suite with coverage before pushing.

## Structured Logging

All services emit structured JSON logs in production. Every entry includes `timestamp`
(ISO 8601 UTC), `level`, `msg`, `service`, `version`. Variable data goes in fields, never in
the message string:

- **Wrong:** `logger.info("User 1234 placed order 5678")`
- **Right:** `logger.info({ user_id: "1234", order_id: "5678" }, "order placed")`

Use `pino` in TypeScript/Node.js and `log/slog` in Go. Never use `console.log` in application
code. Never log passwords, tokens, API keys, cookies, or PII.

## CI Quality Gates

All PRs must pass before merge: CodeQL (SAST), SonarCloud (quality), project linter at zero
errors, type-checker, full test suite at coverage threshold, CodeRabbit and Copilot review
comments resolved. Never bypass CI gates or weaken thresholds to make a PR pass.

## Git and PR Workflow

Always branch from `main`:

```bash
git checkout main && git pull origin main && git checkout -b <branch-name>
```

All changes go through pull requests — never commit directly to `main`. Squash merge only
(enforced by the `pr-quality` ruleset). Resolve every review thread before merging. Use
`in-progress` labels when multiple agents work from a shared issue queue.

## Security

Never commit secrets, `.env` files, API keys, or Terraform state. Use GitHub Actions secrets or
an external secret manager. Mark all sensitive Terraform variables `sensitive = true`. Gitleaks
secret scanning runs on every PR.

---

## Deploying These Instructions to Each Repository

Every repository MUST have its own `.github/copilot-instructions.md` — this file does not
propagate automatically. Copy this file as the starting point, then tailor it to the repo.
A repo-level file SHOULD cover:

1. **About** — one sentence describing what the repo does and its role in the org
2. **Tech stack** — frameworks, libraries, and major versions specific to this repo
3. **Project structure** — key directories, naming conventions, bounded context layout
4. **Local dev commands** — exact install, dev, test, lint, and typecheck commands
5. **Required environment variables** — names, purposes, and example values
6. **Testing framework** — runner (Vitest / Jest / pytest / go test), coverage tool, thresholds
7. **Repo-specific rule overrides** — any rule that differs from these org-level defaults;
reference the specific AGENTS.md section being overridden

The repo-level file inherits all org-level rules; only document what differs or adds detail.
Copy the template from
[`standards/copilot-instructions-standard.md`](../standards/copilot-instructions-standard.md)
to get started.
154 changes: 154 additions & 0 deletions .github/instructions/go.instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
---
description: Go development standards for the Petry Projects organization, based on Effective Go and Google's Go Style Guide
applyTo: "**/*.go"
---

# Go Development Standards

These rules extend the org-level `copilot-instructions.md`. They are based on
[Effective Go](https://go.dev/doc/effective_go),
[Go Code Review Comments](https://go.dev/wiki/CodeReviewComments), and
[Google's Go Style Guide](https://google.github.io/styleguide/go/). Go is used for
infrastructure tools, CLI utilities, and backend services in this org.

## General Principles

- Write simple, clear, and idiomatic Go. Favor clarity over cleverness.
- Keep the happy path left-aligned — return early to reduce nesting.
- Make the zero value useful. Design types so the zero value is a valid, safe starting state.
- Prefer the standard library over third-party packages when equivalent functionality exists.
- Use Go modules (`go.mod` / `go.sum`) for all dependency management.

## Naming Conventions

- Package names: lowercase, single-word, no underscores or hyphens. Singular, not plural.
Avoid generic names (`util`, `common`, `base`, `helper`).
- Variables and functions: `camelCase`. Exported symbols: `PascalCase`.
- Interfaces: `-er` suffix when describing a single behavior (`Reader`, `Writer`, `Formatter`).
Keep interfaces small (1–3 methods is ideal).
- **Each Go file must have exactly ONE `package` declaration.** When editing an existing file,
preserve the existing declaration. When creating a new file, check the package names of
sibling files first.

## Code Style

- Always format with `gofmt` (or `goimports`). This is non-negotiable.
- Use `goimports` to manage import blocks automatically.
- Write comments in English. Document all exported symbols — start with the symbol name.
Comment the *why*, not the *what*, unless the logic is complex.
- Avoid emoji in code and comments.

## Error Handling

- Check errors immediately after every function call. Never ignore with `_` without a comment.
- Wrap errors with context: `fmt.Errorf("operation description: %w", err)`.
- Place error returns as the last return value, named `err`.
- Use `errors.Is` / `errors.As` for error checking, not string comparison.
- Log errors at the point of handling — not at every intermediate propagation layer. Add context
by wrapping, then log once at the top-level handler.
- Error messages: lowercase, no trailing punctuation.

## Project Structure

Follow standard Go project layout:

```text
cmd/ # Application entry points (one directory per binary)
internal/ # Private packages (not importable by external projects)
pkg/ # Reusable packages safe for external import
```

Avoid circular dependencies. Use `internal/` for packages that should not be imported outside
the module. Group related functionality into focused packages.

## Structured Logging

Use **`log/slog`** (Go 1.21+) as the default structured logger:

```go
import (
"log/slog"
"os"
)

// Wire up once at program start (e.g., main.go).
// Production — structured JSON for log aggregation:
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Development — swap the handler for human-readable text:
// logger := slog.New(slog.NewTextHandler(os.Stderr, nil))

// Propagate the logger via context so OpenTelemetry can bridge trace/span IDs:
logger.InfoContext(ctx, "order placed", "order_id", orderID, "user_id", userID)
```

- **Never use the global `log` package** from the standard library.
- Propagate loggers via `context.Context`. Use `slog.InfoContext(ctx, ...)` so trace/span IDs
are automatically bridged.
- In tests, suppress output: `slog.New(slog.NewTextHandler(io.Discard, nil))`.
- Log at the point of handling, not at every layer. Wrap errors with `fmt.Errorf` and log once.
- Never log variables named `password`, `secret`, `token`, `api_key`, `private_key`,
`authorization`, or `cookie`.

## Concurrency

- Be cautious about creating goroutines in libraries; prefer letting the caller control
concurrency.
- Always know how a goroutine will exit. Use `sync.WaitGroup` or channels to wait for
goroutines. Avoid goroutine leaks.
- Use channels for communication between goroutines; use `sync.Mutex` for protecting shared
state.
- Close channels from the sender side only.
- WaitGroup pattern:
- Go ≥ 1.25: `sync.WaitGroup` gains a `Go(fn func())` method — use `wg.Go(fn)` directly.
- Go < 1.25: use the classic `wg.Add(1)` / `defer wg.Done()` pattern.
- For error propagation across goroutines, prefer `golang.org/x/sync/errgroup` (`eg.Go(fn)`) over bare `sync.WaitGroup`.

## HTTP Clients and I/O

- HTTP client structs hold configuration only (base URL, `*http.Client`, auth, default headers).
Never store per-request state on the client struct.
- Construct a fresh `*http.Request` per method call. Never cache or reuse a request object.
- Always close response bodies: `defer resp.Body.Close()`.
- `io.Reader` streams are consumable once. To read a body multiple times, use `io.ReadAll` once
and create fresh readers: `bytes.NewReader(buf)`.
- Set `req.GetBody` for retryable requests so the transport can recreate the body.

## HTTP Server (net/http)

- Go ≥ 1.22: use the enhanced `net/http` `ServeMux` with method + pattern routing.
- Go < 1.22: handle methods manually in handlers or use a justified third-party router.

## Type Safety

- Prefer explicit type conversions. Use `any` (Go 1.18+) instead of `interface{}`.
- Use generics over unconstrained types. Prefer specific type constraints when possible.
- Use type assertions carefully — always check the second return value:
`v, ok := x.(SomeType); if !ok { ... }`.

## Testing

- Use table-driven tests with `t.Run` subtests.
- Name tests: `Test_FunctionName_Scenario` or `TestFunctionName`.
- Mark helper functions with `t.Helper()`. Use `t.Cleanup()` for teardown.
- Place test files next to source (`service.go` → `service_test.go`).
- White-box tests use the same package; black-box tests use the `_test` package suffix.
- Use `testify/assert` when it adds clarity, but avoid over-complicating simple assertions.

## Security

- Validate all external input at system boundaries.
- Use `crypto/rand` for random number generation. Never use `math/rand` for security-sensitive
operations.
- Use standard library `crypto` packages — never implement cryptographic algorithms.
- Store passwords with bcrypt, scrypt, or argon2 (`golang.org/x/crypto`).
- Use TLS for all network communication.

## Tooling

- `go fmt` — format code (non-negotiable)
- `go vet` — find suspicious constructs
- `golangci-lint` — extended linting (replaces deprecated `golint`)
- `go test ./...` — run all tests
- `go mod tidy` — clean up unused dependencies

Run `golangci-lint run` before committing. Zero warnings, zero errors.
52 changes: 52 additions & 0 deletions .github/instructions/javascript.instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
description: JavaScript development standards for the Petry Projects organization
applyTo: "**/*.js,**/*.mjs,**/*.cjs"
---

# JavaScript Development Standards

These rules extend the org-level `copilot-instructions.md` and apply to JavaScript files.

> **Prefer TypeScript.** If a file can be migrated to TypeScript without significant disruption,
> prefer the migration. JavaScript is accepted for configuration files (`eslint.config.js`,
> `vite.config.mjs`, `jest.config.js`), build scripts, and legacy code during migration.

## Style and Formatting

- **Formatter:** Prettier. Run `prettier --write` before committing.
- **Linter:** ESLint. Zero warnings, zero errors.
- Never use `var`. Use `const` for all bindings that are not reassigned; use `let` only when
reassignment is required.
- Prefer `async`/`await` over raw `.then()`/`.catch()` chains. Handle rejections — never leave
a floating promise.
- Use ES modules (`import`/`export`) in all new code. CommonJS (`require`/`module.exports`) is
acceptable only in config files that require it.
- Use destructuring assignment to extract values from objects and arrays.

## Naming Conventions

- `camelCase` for variables and functions. `PascalCase` for constructors and classes.
`SCREAMING_SNAKE_CASE` for module-level constants.
- File names match the primary export or purpose (`orderService.js`, `eslint.config.mjs`).

## Type Safety Without TypeScript

- Use JSDoc annotations (`@param`, `@returns`, `@type`) in JavaScript files that cannot yet be
migrated, to enable IDE type inference and `checkJs` validation.
- Enable `// @ts-check` at the top of critical JavaScript files to surface type errors in the
IDE without requiring full TypeScript migration.

## Error Handling

- Always handle Promise rejections — either with `try`/`catch` in `async` functions or with an
explicit `.catch()` handler.
- Never use empty catch blocks (`catch (e) {}`). At minimum, log the error with structured
fields.
- Do not use `console.log` in application or library code. Use a structured logger (`pino`).
`console.*` is acceptable only in CLI scripts and build tooling.

## Testing

- Follow the same TDD rules as TypeScript: write tests before implementing, never `.skip()`.
- Use the same test runner as the rest of the project (Vitest or Jest).
- Name tests as functional requirement specifications.
Loading
Loading