Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
# Add @suaveplan/slack-client
**Package**: `@suaveplan/slack-client`
**Status**: PROPOSED
**Type**: new-package
## Why
Genesis needs a typed, deterministic, OpenTelemetry-instrumented Slack client for transactional messaging (alerting, notifications, ops bots). The upstream `@suaveplan/slack-client@1.0.1` at `../suaveplan/packages/universal/slack-client/` works but does not meet genesis enterprise-quality bar — it monkey-patches `globalThis.fetch` in tests (`vi.stubGlobal`), has no Zod boundary validation, no OTel meters, no injectable `Clock`/`Rng`/`Logger`, leaks `as unknown` casts, and registers codes through the legacy `ErrorCodes.registerMany` runtime registry instead of `defineCodes`. This change ships a fresh build at enterprise quality with full functional parity.
## What changes
- ADDED: `@suaveplan/slack-client@0.1.0` under `packages/messaging/slack-client/`
- ADDED: `SlackApiClient` — Slack Web API: `sendMessage`, `updateMessage`, `deleteMessage`, `listChannels`, `getChannelInfo`, `listUsers`, `getStatus`
- ADDED: `SlackWebhook` — Slack incoming-webhook client: `send`, `sendText`
- ADDED: `SLACK_CODES` registry (`defineCodes("SLACK", [...])`) with 8 reasons: `API_ERROR`, `AUTH_ERROR`, `RATE_LIMITED`, `CHANNEL_NOT_FOUND`, `WORKSPACE_NOT_FOUND`, `CONFIG_MISSING`, `WEBHOOK_FAILED`, `TIMEOUT`
- ADDED: 8 typed error subclasses extending `SuaveplanError<SlackErrorCode>` (one per reason)
- ADDED: Zod schemas at every public boundary: `SlackApiClientOptionsSchema`, `SlackWebhookOptionsSchema`, `SlackMessageSchema`, `SlackBlockSchema`, `SlackBlockElementSchema`, `SlackTextObjectSchema`
- ADDED: OTel meter instruments — `slack.requests`, `slack.errors`, `slack.latency_ms`, `slack.webhook_sends` — emitted from every production hot path
- ADDED: Injectable transport bag — `Clock`, `Rng`, `FetchLike`, `LoggerLike` — all from `@suaveplan/types`
- ADDED: Deterministic `FakeFetch` test double under `src/fakes/` for parity tests (no `vi.mock` anywhere)
- ADDED: Retry-After parser supporting delay-seconds, HTTP-date, and `x-ratelimit-reset` epoch/ISO
- ADDED: Slack-error string classifier (`invalid_auth` / `channel_not_found` / `team_not_found` families)
## Out of scope
None. The package ships at full functional parity with the upstream package plus the enterprise upgrades demanded by `enterprise/slack-client.md` §3.
## Source mapping
This change derives from `../suaveplan/enterprise/slack-client.md` and the working implementation at `../suaveplan/packages/universal/slack-client/src/`.
| Requirement | Source lines | Notes |
|---|---|---|
| Generic Slack API client + webhook surface | enterprise/slack-client.md L10-L13 | verbatim |
| Zero browser/Node/React deps (universal tier) | enterprise/slack-client.md L37 | verbatim |
| Zod schemas at every boundary | enterprise/slack-client.md L38 | verbatim |
| Deterministic — no module-scope `Math.random` / `Date.now`, injectable clock/RNG | enterprise/slack-client.md L40 | verbatim |
| OpenTelemetry instrumentation via `@opentelemetry/api` | enterprise/slack-client.md L41 | verbatim |
| Structured errors extending `@suaveplan/error` with stable codes | enterprise/slack-client.md L42, L61 | verbatim |
| AbortSignal cancellation everywhere async | enterprise/slack-client.md L43 | verbatim |
| Idempotency + retry primitives wired | enterprise/slack-client.md L44 | applied to Retry-After / rate-limit; cooperative retry left to caller's `@suaveplan/retry` (no double-wrap) |
| i18n-ready (no hard-coded user-visible strings) | enterprise/slack-client.md L46 | every thrown error carries a stable code + structured context; messages are templated |
| Test coverage 100% statement/branch/function/line (istanbul) | enterprise/slack-client.md L50 + genesis CLAUDE.md "Quality" | genesis policy is 100%, stricter than the 95% in the source |
| File-size budget 250/300 soft/hard, 500 test | enterprise/slack-client.md L52 + CLAUDE.md | enforced by manual split |
| No mocks — injectable fakes only | enterprise/slack-client.md L53 + CLAUDE.md rule 2 | verbatim |
| `sideEffects: false` | enterprise/slack-client.md L55 | verbatim |
| Biome clean, zero suppressions | enterprise/slack-client.md L58 + CLAUDE.md rule 9 | verbatim |
| TypeScript strict, no `any` / `ts-ignore` | enterprise/slack-client.md L59 | verbatim |
| Error hierarchy with typed discriminants | enterprise/slack-client.md L61 | verbatim |
| `chat.postMessage`, `chat.update`, `chat.delete`, `conversations.list`, `conversations.info`, `users.list` | upstream packages/universal/slack-client/src/core/slack-api-client/slack-api-client.ts L52-L138 | parity |
| Webhook POST with text + blocks | upstream packages/universal/slack-client/src/core/slack-webhook/slack-webhook.ts L41-L105 | parity |
| HTTP 429 Retry-After / x-ratelimit-reset parsing | upstream slack-api-client.ts L259-L284 | parity |
| Slack-error → code classifier (`invalid_auth`, `channel_not_found`, `team_not_found`) | upstream slack-api-client.ts L286-L313 | parity |
### Requirements with no source line
| Requirement | Justification |
|---|---|
| 100% coverage threshold (vs. 95% in source) | Genesis-wide policy — `CLAUDE.md` Quality section |
| Test runner imports MUST go through `@suaveplan/testing/runner` | Genesis rule 11 — not applicable to upstream which predates the rule |
| `defineCodes("SLACK", […])` registry style | Genesis-wide error-codes convention — upstream used the legacy `ErrorCodes.registerMany` API |
| `FakeFetch` test double + setup polyfills wiring real `MeterProvider` | Genesis pre-archive checklist row 5 (OTel asserted with real `MeterProvider`, not `vi.mock`) |
## Verification approach
- `src/client/slack-api-client.test.ts` — pins every `SlackApiClient` method scenario with `FakeFetch`
- `src/webhook/slack-webhook.test.ts` — pins every `SlackWebhook` scenario with `FakeFetch`
- `src/errors/errors.test.ts` — pins error-code identity and message keys for all 8 codes
- `src/schemas/schemas.test.ts` — Zod boundary parse + safeParse assertions for every public schema
- `src/client/retry-after.test.ts` — pins every Retry-After header form (delay-seconds, HTTP-date, x-ratelimit-reset epoch + ISO, missing)
- `src/client/classify.test.ts` — pins HTTP-status and slack-error-string classifiers
- `src/otel/metrics.test.ts` — asserts the four OTel instruments emit on every production path, via real in-memory `MeterProvider`
- `src/fakes/fake-fetch.test.ts` — pins the deterministic test double itself
- `src/index.test.ts` — pins the public-surface barrel
## Migration impact
None — additive. No existing consumer of `@suaveplan/slack-client` exists in genesis.

View File

@@ -0,0 +1,308 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: slack-client (add-slack-client)
**Package**: `@suaveplan/slack-client`
**Status**: PROPOSED
> Every requirement below carries a `**Verified by:**` line at authoring time.
## ADDED Requirements
### Requirement: SlackApiClient sends messages via `chat.postMessage`
The package SHALL expose `SlackApiClient.sendMessage(message)` which POSTs to `${baseUrl}/chat.postMessage` with an `Authorization: Bearer <token>` header and a JSON body containing `channel`, `text`, and the optional `blocks`, `thread_ts`, `unfurl_links`, `unfurl_media`, `metadata` fields. On a successful Slack response carrying `ok: true` and `ts`, the client SHALL record a `SlackDeliveryReport { status: "delivered" }` retrievable via `getStatus(ts)`.
#### Scenario: successful send populates delivery report
- **WHEN** the caller invokes `sendMessage({ channel: "C1", text: "hi" })` and the fake fetch resolves `{ ok: true, channel: "C1", ts: "99.99" }`
- **THEN** the returned `SlackResponse.ok` is `true`, `getStatus("99.99")` returns a `delivered` report with channel `C1`, and the OTel `slack.requests` counter increments once with `{ method: "chat.postMessage", outcome: "ok" }`
#### Scenario: blocks + thread + metadata forwarded verbatim
- **WHEN** `sendMessage` is called with `blocks`, `threadTs`, `unfurlLinks`, `unfurlMedia`, `metadata`
- **THEN** the captured request body contains `thread_ts`, `unfurl_links`, `unfurl_media`, `blocks`, `metadata` matching the input
#### Scenario: default channel used when message channel is empty
- **WHEN** the client is constructed with `defaultChannel: "C999"` and `sendMessage({ channel: "", text: "hi" })` is invoked
- **THEN** the request body posts to channel `C999`
#### Scenario: no channel throws `SLACK.CHANNEL_NOT_FOUND`
- **WHEN** `sendMessage({ channel: "", text: "hi" })` is invoked with no `defaultChannel`
- **THEN** the call rejects with `SlackChannelNotFoundError` carrying code `SLACK.CHANNEL_NOT_FOUND`
**Verified by:** `src/client/slack-api-client.test.ts::"sendMessage posts to chat.postMessage and records a delivered report"` AND `src/client/slack-api-client.test.ts::"sendMessage forwards blocks thread metadata and unfurl flags"` AND `src/client/slack-api-client.test.ts::"sendMessage uses defaultChannel when message.channel is empty"` AND `src/client/slack-api-client.test.ts::"sendMessage throws SLACK.CHANNEL_NOT_FOUND when no channel is available"`
---
### Requirement: SlackApiClient updates and deletes messages
The package SHALL expose `updateMessage(channel, ts, text, blocks?)` and `deleteMessage(channel, ts)` which POST to `chat.update` and `chat.delete` respectively with the supplied identifiers.
#### Scenario: updateMessage forwards new text and optional blocks
- **WHEN** `updateMessage("C1", "1.1", "Updated", blocks)` is invoked
- **THEN** the request body contains `channel: "C1"`, `ts: "1.1"`, `text: "Updated"`, and the supplied `blocks`
#### Scenario: deleteMessage forwards channel and ts
- **WHEN** `deleteMessage("C1", "1.1")` is invoked
- **THEN** the request body contains exactly `{ channel: "C1", ts: "1.1" }`
**Verified by:** `src/client/slack-api-client.test.ts::"updateMessage posts to chat.update with new text and blocks"` AND `src/client/slack-api-client.test.ts::"deleteMessage posts to chat.delete with channel and ts"`
---
### Requirement: SlackApiClient lists channels and users with mapping
The package SHALL expose `listChannels(limit?)`, `getChannelInfo(channelId)`, and `listUsers(limit?)`. The client SHALL map snake_case Slack payload shapes (`is_private`, `topic.value`, `purpose.value`, `num_members`, `real_name`, `profile.email`, `is_bot`) onto camelCase domain types (`SlackChannel`, `SlackUser`). Missing arrays SHALL yield `[]`, not `undefined`.
#### Scenario: listChannels maps snake_case to domain
- **WHEN** the fake fetch returns `{ ok: true, channels: [{ id, name, is_private, topic, purpose, num_members }, ...] }`
- **THEN** the result is `SlackChannel[]` with camelCase fields populated
#### Scenario: listChannels returns empty array when key absent
- **WHEN** the fake fetch returns `{ ok: true }` with no `channels` key
- **THEN** the result is `[]`
#### Scenario: getChannelInfo maps single channel
- **WHEN** `getChannelInfo("C1")` is invoked and the fake fetch returns a channel object
- **THEN** the returned `SlackChannel` matches the mapped shape
#### Scenario: listUsers maps snake_case to domain
- **WHEN** the fake fetch returns `{ ok: true, members: [...] }`
- **THEN** the result is `SlackUser[]` with `realName`, `email`, `isBot` populated
#### Scenario: listUsers returns empty array when key absent
- **WHEN** the fake fetch returns `{ ok: true }` with no `members` key
- **THEN** the result is `[]`
**Verified by:** `src/client/slack-api-client.test.ts::"listChannels maps snake_case payload to SlackChannel"` AND `src/client/slack-api-client.test.ts::"listChannels returns empty array when channels key is absent"` AND `src/client/slack-api-client.test.ts::"getChannelInfo maps a single channel"` AND `src/client/slack-api-client.test.ts::"listUsers maps snake_case payload to SlackUser"` AND `src/client/slack-api-client.test.ts::"listUsers returns empty array when members key is absent"`
---
### Requirement: SlackApiClient classifies HTTP errors into typed Slack codes
The package SHALL convert HTTP 401/403 to `SLACK.AUTH_ERROR`, HTTP 404 to `SLACK.CHANNEL_NOT_FOUND`, HTTP 408/504 to `SLACK.TIMEOUT`, HTTP 429 to `SLACK.RATE_LIMITED` (with `retryAfterMs` populated from `Retry-After` or `x-ratelimit-reset`), and other non-2xx to `SLACK.API_ERROR`. A non-`ok: true` JSON body containing `error: "channel_not_found" | "is_archived" | "not_in_channel"` SHALL yield `SLACK.CHANNEL_NOT_FOUND`; `invalid_auth | not_authed | token_revoked | account_inactive` SHALL yield `SLACK.AUTH_ERROR`; `team_not_found | no_workspace` SHALL yield `SLACK.WORKSPACE_NOT_FOUND`; everything else SHALL yield `SLACK.API_ERROR`.
#### Scenario: HTTP 401 yields SLACK.AUTH_ERROR
- **WHEN** the fake fetch returns HTTP 401
- **THEN** the call rejects with `SlackAuthError` carrying code `SLACK.AUTH_ERROR`
#### Scenario: HTTP 404 yields SLACK.CHANNEL_NOT_FOUND
- **WHEN** the fake fetch returns HTTP 404
- **THEN** the call rejects with `SlackChannelNotFoundError`
#### Scenario: HTTP 429 yields SLACK.RATE_LIMITED with parsed retry-after
- **WHEN** the fake fetch returns HTTP 429 with `Retry-After: "30"`
- **THEN** the rejection is `SlackRateLimitedError` whose `context.retryAfterMs` is `30000`
#### Scenario: HTTP 500 yields SLACK.API_ERROR
- **WHEN** the fake fetch returns HTTP 500
- **THEN** the call rejects with `SlackApiError`
#### Scenario: Slack error string classifies to typed code
- **WHEN** the fake fetch returns `{ ok: false, error: "channel_not_found" }`
- **THEN** the call rejects with `SlackChannelNotFoundError`
#### Scenario: invalid_auth string yields SLACK.AUTH_ERROR
- **WHEN** the fake fetch returns `{ ok: false, error: "invalid_auth" }`
- **THEN** the call rejects with `SlackAuthError`
#### Scenario: team_not_found string yields SLACK.WORKSPACE_NOT_FOUND
- **WHEN** the fake fetch returns `{ ok: false, error: "team_not_found" }`
- **THEN** the call rejects with `SlackWorkspaceNotFoundError`
#### Scenario: unknown error string yields SLACK.API_ERROR
- **WHEN** the fake fetch returns `{ ok: false, error: "ratelimited_internal" }`
- **THEN** the call rejects with `SlackApiError`
**Verified by:** `src/client/classify.test.ts::"HTTP 401 classifies to SLACK.AUTH_ERROR"` AND `src/client/classify.test.ts::"HTTP 404 classifies to SLACK.CHANNEL_NOT_FOUND"` AND `src/client/classify.test.ts::"HTTP 500 classifies to SLACK.API_ERROR"` AND `src/client/classify.test.ts::"slack error string channel_not_found maps to SLACK.CHANNEL_NOT_FOUND"` AND `src/client/classify.test.ts::"slack error string invalid_auth maps to SLACK.AUTH_ERROR"` AND `src/client/classify.test.ts::"slack error string team_not_found maps to SLACK.WORKSPACE_NOT_FOUND"` AND `src/client/classify.test.ts::"unknown slack error string falls back to SLACK.API_ERROR"` AND `src/client/slack-api-client.test.ts::"HTTP 429 produces SlackRateLimitedError with parsed retryAfterMs"`
---
### Requirement: Retry-After header parsing supports three forms
The package SHALL parse the `Retry-After` HTTP header in delay-seconds (`"30"`) and HTTP-date (`"Wed, 21 Oct 2026 07:28:00 GMT"`) forms, and fall back to `x-ratelimit-reset` in epoch-seconds, epoch-milliseconds, or ISO-8601 form. The parser SHALL return `undefined` when no header is present or the value is unparseable, and SHALL clamp negative deltas to `0`.
#### Scenario: delay-seconds form
- **WHEN** the response carries `Retry-After: "45"`
- **THEN** `parseRetryAfterMs` returns `45000`
#### Scenario: HTTP-date form
- **WHEN** the response carries `Retry-After: <ISO date 60s in the future>` and the injected clock is at the present
- **THEN** the parser returns a value `>= 0` (≈60000)
#### Scenario: x-ratelimit-reset epoch seconds fallback
- **WHEN** no `Retry-After` is present but `x-ratelimit-reset` is epoch seconds in the future
- **THEN** the parser returns the difference in milliseconds
#### Scenario: x-ratelimit-reset ISO fallback
- **WHEN** no `Retry-After` is present but `x-ratelimit-reset` is an ISO timestamp in the future
- **THEN** the parser returns the difference in milliseconds
#### Scenario: missing headers yields undefined
- **WHEN** neither header is present
- **THEN** the parser returns `undefined`
#### Scenario: negative delta clamps to 0
- **WHEN** the header points at a past timestamp
- **THEN** the parser returns `0`
**Verified by:** `src/client/retry-after.test.ts::"parses delay-seconds form"` AND `src/client/retry-after.test.ts::"parses HTTP-date form"` AND `src/client/retry-after.test.ts::"falls back to x-ratelimit-reset epoch seconds"` AND `src/client/retry-after.test.ts::"falls back to x-ratelimit-reset ISO string"` AND `src/client/retry-after.test.ts::"returns undefined when no headers are present"` AND `src/client/retry-after.test.ts::"clamps negative deltas to 0"`
---
### Requirement: SlackApiClient enforces AbortSignal-driven timeout
The package SHALL abort an in-flight Slack request after `timeoutMs` (default `10000`) and surface the abort as `SlackTimeoutError` (code `SLACK.TIMEOUT`). Caller-supplied `AbortSignal` SHALL also terminate the request and propagate.
#### Scenario: internal timeout surfaces SlackTimeoutError
- **WHEN** the fake fetch never resolves and `timeoutMs: 1` is configured
- **THEN** the call rejects with `SlackTimeoutError`
#### Scenario: caller signal aborts the request
- **WHEN** the caller passes a pre-aborted `AbortSignal`
- **THEN** the call rejects with `SlackTimeoutError` whose `context.url` matches
**Verified by:** `src/client/slack-api-client.test.ts::"timeoutMs aborts an in-flight request with SlackTimeoutError"` AND `src/client/slack-api-client.test.ts::"caller-supplied AbortSignal cancels the request with SlackTimeoutError"`
---
### Requirement: SlackWebhook posts to an incoming webhook URL
The package SHALL expose `SlackWebhook.send(message)` and `SlackWebhook.sendText(text)`. Both SHALL POST a JSON body with `text` and optional `blocks` to the configured `webhookUrl` with `Content-Type: application/json; charset=utf-8`. On 2xx, the returned `SlackDeliveryReport.status` SHALL be `"delivered"`. On non-2xx, the call SHALL reject with `SlackAuthError` (401/403) or `SlackWebhookFailedError` (otherwise). On network failure or timeout, the call SHALL reject with `SlackTimeoutError`.
#### Scenario: send returns delivered report on 2xx
- **WHEN** the fake fetch returns HTTP 200
- **THEN** the report's status is `"delivered"`, channel `"webhook"`, and `messageId` is non-empty
#### Scenario: sendText forwards plain text
- **WHEN** `sendText("hi")` is invoked
- **THEN** the request body parses to `{ text: "hi" }` with no `blocks`
#### Scenario: 401 yields SlackAuthError
- **WHEN** the fake fetch returns HTTP 401
- **THEN** the call rejects with `SlackAuthError`
#### Scenario: 400 yields SlackWebhookFailedError
- **WHEN** the fake fetch returns HTTP 400 with body `"invalid_payload"`
- **THEN** the call rejects with `SlackWebhookFailedError` carrying the body in `context`
#### Scenario: message IDs are monotonic
- **WHEN** two successive sends complete
- **THEN** their `messageId`s differ
**Verified by:** `src/webhook/slack-webhook.test.ts::"send returns a delivered report on HTTP 200"` AND `src/webhook/slack-webhook.test.ts::"sendText posts only the text field"` AND `src/webhook/slack-webhook.test.ts::"HTTP 401 rejects with SlackAuthError"` AND `src/webhook/slack-webhook.test.ts::"HTTP 400 rejects with SlackWebhookFailedError"` AND `src/webhook/slack-webhook.test.ts::"sequential sends yield distinct messageIds"`
---
### Requirement: Constructors validate configuration via Zod
The package SHALL reject construction of `SlackApiClient` with an empty `token` and `SlackWebhook` with an empty `webhookUrl`, throwing `SlackConfigMissingError` (code `SLACK.CONFIG_MISSING`) at construct time. All public option bundles SHALL be validated through a Zod schema; safeParse SHALL surface a `ZodError` cause on the thrown `SlackConfigMissingError`.
#### Scenario: empty token rejected
- **WHEN** `new SlackApiClient({ token: "" })` is invoked
- **THEN** the constructor throws `SlackConfigMissingError`
#### Scenario: empty webhookUrl rejected
- **WHEN** `new SlackWebhook({ webhookUrl: "" })` is invoked
- **THEN** the constructor throws `SlackConfigMissingError`
#### Scenario: schemas are exposed for boundary parse
- **WHEN** `SlackMessageSchema.safeParse({ channel: 1, text: "x" })` is invoked
- **THEN** `success` is `false`
**Verified by:** `src/client/slack-api-client.test.ts::"empty token rejects with SlackConfigMissingError"` AND `src/webhook/slack-webhook.test.ts::"empty webhookUrl rejects with SlackConfigMissingError"` AND `src/schemas/schemas.test.ts::"SlackMessageSchema rejects non-string channel"`
---
### Requirement: OTel instruments emit on every Slack request
The package SHALL emit four OpenTelemetry instruments on every production path: a `slack.requests` counter, a `slack.errors` counter, a `slack.latency_ms` histogram, and a `slack.webhook_sends` counter. Counters SHALL carry attributes `{ method, outcome }` where `outcome ∈ { "ok", "error" }`.
#### Scenario: successful sendMessage emits slack.requests + slack.latency_ms
- **WHEN** `sendMessage` succeeds
- **THEN** the in-memory `MeterProvider` records one `slack.requests` increment with `outcome: "ok"` and one `slack.latency_ms` observation
#### Scenario: failed sendMessage emits slack.requests + slack.errors
- **WHEN** `sendMessage` rejects with `SlackApiError`
- **THEN** the in-memory `MeterProvider` records one `slack.requests` with `outcome: "error"` and one `slack.errors` increment
#### Scenario: webhook send emits slack.webhook_sends
- **WHEN** `SlackWebhook.send` succeeds
- **THEN** the in-memory `MeterProvider` records one `slack.webhook_sends` increment with `outcome: "ok"`
**Verified by:** `src/otel/metrics.test.ts::"successful sendMessage emits slack.requests with outcome ok"` AND `src/otel/metrics.test.ts::"failed sendMessage emits slack.requests outcome error and slack.errors"` AND `src/otel/metrics.test.ts::"webhook send emits slack.webhook_sends"`
---
### Requirement: Stable error code registry
The package SHALL export `SLACK_CODES` (built via `defineCodes("SLACK", [...])`) containing eight stable codes: `API_ERROR`, `AUTH_ERROR`, `RATE_LIMITED`, `CHANNEL_NOT_FOUND`, `WORKSPACE_NOT_FOUND`, `CONFIG_MISSING`, `WEBHOOK_FAILED`, `TIMEOUT`. Each code SHALL have a typed `SuaveplanError` subclass and SHALL be thrown by at least one production path. `src/index.ts` SHALL side-effect import `./error-codes.js` so subpath consumers register codes too.
#### Scenario: SLACK_CODES contains all eight reasons
- **WHEN** consumer imports `SLACK_CODES`
- **THEN** the record has exactly eight keys mapping reason → `SLACK.<REASON>`
#### Scenario: each error subclass carries its code
- **WHEN** an instance of `SlackApiError`, `SlackAuthError`, `SlackRateLimitedError`, `SlackChannelNotFoundError`, `SlackWorkspaceNotFoundError`, `SlackConfigMissingError`, `SlackWebhookFailedError`, or `SlackTimeoutError` is constructed
- **THEN** its `.code` equals the corresponding `SLACK.<REASON>` literal
**Verified by:** `src/errors/errors.test.ts::"SLACK_CODES exposes exactly the eight stable reasons"` AND `src/errors/errors.test.ts::"every error subclass carries its SLACK.<REASON> code"`
---
### Requirement: Deterministic FakeFetch test double
The package SHALL ship a `FakeFetch` under `src/fakes/fake-fetch.ts` which the test suite uses to drive every transport-level scenario without monkey-patching `globalThis.fetch` and without `vi.mock`. `FakeFetch` SHALL queue scripted responses, record every request, and surface a `FetchLike` instance for direct injection into client constructors.
#### Scenario: queued response is consumed in FIFO order
- **WHEN** two responses are queued and two requests are made
- **THEN** the first request receives the first queued response
#### Scenario: pending request abort propagates to AbortError
- **WHEN** a request is queued as `pending` and the caller aborts the signal
- **THEN** the returned promise rejects with `AbortError`
**Verified by:** `src/fakes/fake-fetch.test.ts::"queued responses are consumed in FIFO order"` AND `src/fakes/fake-fetch.test.ts::"pending request rejects with AbortError when signal aborts"`
<!-- markdownlint-enable MD024 -->

View File

@@ -0,0 +1,64 @@
# Tasks — add @suaveplan/slack-client
> Every checkbox MUST reflect work actually done in this change. No retroactive ticking.
## 1. Spec authoring
- [x] 1.1 Read `../suaveplan/enterprise/slack-client.md` end-to-end
- [x] 1.2 No prior `openspec/specs/slack-client/spec.md` (new capability)
- [x] 1.3 Read `openspec/AGENTS.md` workflow (CLAUDE.md ref) + skill `enterprise-package-migration`
- [x] 1.4 Draft `proposal.md` from `openspec/templates/proposal.md`
- [x] 1.5 Source-mapping table filled — every requirement cites a line range or appears under "no source line"
- [x] 1.6 Draft `specs/slack-client/spec.md` from `openspec/templates/spec-delta.md`
- [x] 1.7 Every requirement carries a `**Verified by:**` line
## 2. Implementation
- [x] 2.1 `package.json` + `tsconfig.lib.json` + `vite.config.ts` + `vitest.config.ts` at 0.1.0
- [x] 2.2 `src/error-codes.ts` — `defineCodes("SLACK", […])` registry + 8 typed error subclasses
- [x] 2.3 `src/types/slack-client.types.ts` — public shapes (`SlackMessage`, `SlackChannel`, `SlackUser`, `SlackResponse`, `SlackDeliveryReport`, options bags)
- [x] 2.4 `src/schemas/schemas.ts` — Zod schemas for every public boundary input
- [x] 2.5 `src/otel/metrics.ts` — meter + four instruments wired via `@opentelemetry/api`
- [x] 2.6 `src/client/retry-after.ts` — parser for delay-seconds, HTTP-date, x-ratelimit-reset
- [x] 2.7 `src/client/classify.ts` — HTTP-status and slack-error-string classifiers
- [x] 2.8 `src/client/slack-api-client.ts` — `SlackApiClient` with injectable `FetchLike`/`Clock`/`Rng`/`LoggerLike`
- [x] 2.9 `src/webhook/slack-webhook.ts` — `SlackWebhook` with injectable transport bag
- [x] 2.10 `src/fakes/fake-fetch.ts` — deterministic test double (no `vi.mock`)
- [x] 2.11 `src/index.ts` — explicit named re-exports, side-effect `import "./error-codes.js"`
## 3. Tests
- [x] 3.1 Unit tests at every `<feature>.test.ts` site, ≥1 test per scenario in the spec delta — 121 tests, 8 files
- [x] 3.2 OTel test asserts emission via real in-memory `MeterProvider`
- [x] 3.3 Every `it(...)` carries `{ timeout: 5000 }` (or 30000 for genuinely async)
- [x] 3.4 Test files import ONLY from `@suaveplan/testing/runner` — zero direct `vitest` / `bun:test` imports
## 4. Documentation
- [x] 4.1 Sibling `.md` for every implementation `.ts` (≥200 words, basic + advanced examples, full API reference)
- [x] 4.2 README at package root only
## 5. Pre-archive verification (5-gate triple)
- [x] 5.1 `bun run check` — slack-client clean (one pre-existing root-level failure in `packages/api/api-plugin-vault/src/plugin/plugin.ts:217` is out of scope; verified slack-client itself is biome-clean)
- [x] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/slack-client` — green (121 tests pass)
- [x] 5.3 `bunx turbo test:coverage --filter=@suaveplan/slack-client` — 100/100/100/100 istanbul
- [x] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/slack-client` — `PASS @suaveplan/slack-client (0 error, 5 warn, 0 info)`
- [x] 5.5 `bunx turbo build --filter=@suaveplan/slack-client` — green, 9 modules in dist
## 6. Pre-archive 9-row checklist
- [x] 6.1 Generics threaded; literal types preserved through public surface (`SlackErrorCode` literal union, `SLACK_CODES` frozen record)
- [x] 6.2 Zod schemas wired at every declared boundary (constructors call `.safeParse` and throw `SlackConfigMissingError` with the `ZodError` as cause)
- [x] 6.3 Every error code in `error-codes.ts` thrown by ≥1 production path (all 8 verified via conformance script)
- [x] 6.4 Strict-mode behaviors tested — constructor rejection on empty/invalid options AND Block-Kit `.strict()` rejection of unknown keys
- [x] 6.5 OTel instruments emitted from production paths and asserted with real in-memory `MeterProvider` (4 tests in `src/otel/metrics.test.ts`)
- [x] 6.6 Lifecycle dedup tested — delivery-report Map idempotency, webhook message-id monotonicity
- [x] 6.7 No retroactive tick — every box above reflects work done in this change
- [x] 6.8 No `export *` in any feature barrel (verified — every export is named)
- [x] 6.9 No direct `vitest` / `bun:test` imports in test files (every test imports from `@suaveplan/testing/runner`)
## 7. Archive
- [x] 7.1 Fold spec delta into `openspec/specs/slack-client/spec.md`
- [x] 7.2 Move `openspec/changes/add-slack-client/` → `openspec/archive/2026-05-18-add-slack-client/`