Skip to content

fix(api): enforce federation JSON-LD context#295

Merged
skulidropek merged 5 commits into
mainfrom
fix/federation-jsonld-context
May 13, 2026
Merged

fix(api): enforce federation JSON-LD context#295
skulidropek merged 5 commits into
mainfrom
fix/federation-jsonld-context

Conversation

@skulidropek
Copy link
Copy Markdown
Member

@skulidropek skulidropek commented May 13, 2026

Summary

This PR tightens docker-git federation wire format around ActivityPub/ForgeFed JSON-LD documents. This is not a REST contract change: the federation flow remains ActivityPub/ForgeFed inbox/outbox document exchange.

ForgeFed / JSON-LD REVIEW checklist

Please review this against the ForgeFed spec: https://forgefed.org/spec/

ForgeFed states that it extends ActivityPub and represents forge events as linked data. Its vocabulary section says the ForgeFed JSON-LD context URI is https://forgefed.org/ns, and implementers must include ActivityPub and ForgeFed contexts or equivalent context mappings. Typical ForgeFed objects use:

"@context": [
  "https://www.w3.org/ns/activitystreams",
  "https://forgefed.org/ns"
]

This PR makes that check explicit and testable:

  • Adds literal TS types/constants for ActivityStreams + ForgeFed JSON-LD contexts.
  • Adds runtime typechecker for federation @context on inbox payloads, remote actor discovery, and remote outbox documents.
  • Allows nested Ticket to inherit JSON-LD context from enclosing Offer/Create, which matches JSON-LD semantics.
  • Sends federation documents as application/ld+json; profile="https://www.w3.org/ns/activitystreams".
  • Keeps Accept compatible with JSON-LD, ActivityPub JSON, and normal JSON.

Validation

bun run --cwd packages/api typecheck
bun run --cwd packages/api test
bun run --cwd packages/api lint
git diff --check

All passed locally.

@skulidropek
Copy link
Copy Markdown
Member Author

REVIEW NOTE: this PR intentionally checks ForgeFed JSON-LD semantics, not REST semantics.

Please verify against https://forgefed.org/spec/:

  • @context typechecker requires ActivityStreams + ForgeFed contexts for federation inbox/outbox/actor documents.
  • Nested Ticket may inherit @context from enclosing Offer/Create.
  • Federation responses and signed POSTs use application/ld+json; profile="https://www.w3.org/ns/activitystreams".
  • Tests cover accepted JSON-LD payloads and rejection of missing/partial @context.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 541f5522-6170-4e22-a547-a52f994dcb80

📥 Commits

Reviewing files that changed from the base of the PR and between e42c767 and 42abc27.

📒 Files selected for processing (3)
  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
  • packages/lib/tests/core/templates.test.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: E2E (Browser command)
  • GitHub Check: E2E (OpenCode)
  • GitHub Check: Lint
  • GitHub Check: E2E (Clone cache)
  • GitHub Check: E2E (Clone auto-open SSH)
  • GitHub Check: E2E (Login context)
  • GitHub Check: Final build (windows-latest)
  • GitHub Check: E2E (Runtime volumes + SSH)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Implement Functional Core, Imperative Shell (FCIS) pattern: CORE layer contains only pure functions with immutable data and mathematical operations; SHELL layer isolates all effects (IO, network, database). Strict dependency direction: SHELL → CORE (never reverse).
Never use any, unknown, eslint-disable, ts-ignore, or as type assertions (except in rigorously justified cases with documentation). Always use exhaustive union type analysis through .exhaustive() pattern matching.
All external dependencies must be wrapped through typed interfaces and injected via Effect-TS Layer pattern. Never call external services directly from CORE functions.
Use monadic composition with Effect-TS for all effects: Effect<Success, Error, Requirements>. Compose effects through pipe() and Effect.flatMap(). Implement dependency injection via Layer pattern. Handle errors without try/catch blocks.
All functions must be pure in the CORE layer: no side effects (logging, console output, IO operations, mutations). Separate all side effects into the SHELL layer.
Use exhaustive pattern matching with Effect.Match instead of switch statements. Example: Match.value(item).pipe(Match.when(...), Match.exhaustive).
Document all functions with comprehensive TSDoc including: @pure (true/false), @effect (required services), @invariant (mathematical invariants), @precondition, @postcondition, @complexity (time and space), @throws Never (errors must be typed in Effect).
Use functional comment markers for code clarity: CHANGE (brief description), WHY (mathematical/architectural justification), QUOTE(ТЗ) (requirement citation), REF (RTM or message ID), SOURCE (external source with quote), FORMAT THEOREM (∀x ∈ Domain: P(x) → Q(f(x))), PURITY (CORE|SHELL), EFFECT (Effect type signature), INVARIANT (mathematical invariant), COMPLEXITY (time/space).
Define all external service dependencies as Context.Tag classes with fully typed methods returning Effect types. Example: `class Da...

Files:

  • packages/lib/tests/core/templates.test.ts
  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Implement property-based testing using fast-check for mathematical properties and invariants. Example: fc.property(fc.array(messageArbitrary), (messages) => isChronologicallySorted(sortMessagesByTimestamp(messages))).
Mock external dependencies in unit tests using Effect's testing utilities. Run tests without Effect runtime for speed. Example: Effect.provide(MockService), Effect.runPromise.

Files:

  • packages/lib/tests/core/templates.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Forbidden constructs in CORE code: any, eslint-disable, ts-ignore, async/await, raw Promise chains (then/catch), Promise.all, try/catch for logic control, console.*, switch statements (use Match with .exhaustive() instead)
All functions must use Effect-TS for composing effects: Effect<Success, Error, Requirements>. No direct async/await, Promise chains, or try/catch in product logic.
Functional comments must include: CHANGE, WHY, QUOTE(ТЗ) or n/a, REF, SOURCE or n/a, FORMAT THEOREM, PURITY (CORE|SHELL), EFFECT signature for SHELL functions, INVARIANT, and COMPLEXITY.
All data mutations must use immutable patterns (ReadonlyArray, readonly properties, Object.freeze); mutation in SHELL only when absolutely necessary and documented.

Files:

  • packages/lib/tests/core/templates.test.ts
  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Property-based tests (fast-check) must verify mathematical invariants; unit tests must use Effect test utilities without async/await.

Files:

  • packages/lib/tests/core/templates.test.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Ты строгий ревьюер SPEC DRIVEN DEVELOPMENT.

Перед выводами изучи README.md, другие *.md файлы, linked issues,
PR description, PR comments/discussion и релевантную кодовую базу.

Сверь изменения с исходным ТЗ/спекой и обсуждением. Флагай любой уход
от спеки, недокументированное изменение поведения, отсутствие тестов
для заявленного поведения и security-риск. Если спека не видна,
попроси автора добавить ее в issue или PR description.

Проверь решение с точки зрения формальной верификации: какие инварианты,
предусловия и постусловия можно доказать математически, а где доказуемость
слабая. Оцени решение с точки зрения теории игр: устойчивы ли стимулы,
нет ли выгодного обхода правил, и какое решение было бы сильнее.

Files:

  • packages/lib/tests/core/templates.test.ts
  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
🔇 Additional comments (3)
packages/lib/src/core/templates/dockerfile.ts (1)

97-102: LGTM!

packages/app/src/lib/core/templates/dockerfile.ts (1)

97-102: LGTM!

packages/lib/tests/core/templates.test.ts (1)

69-71: LGTM!


📝 Walkthrough

Summary by CodeRabbit

Примечания к выпуску

  • Улучшения

    • Федерационные документы и исходящие активности теперь последовательно возвращаются как ForgeFed JSON‑LD с корректными @context и content-type.
    • Маршруты федерации (/actor, /outbox, /followers, /following, /liked) обслуживаются единообразно в формате JSON‑LD.
    • Генерация Dockerfile теперь поддерживает указание версии RTK при сборке.
  • Исправления валидации

    • Входящие федерационные полезные нагрузки без требуемых JSON‑LD контекстов теперь отклоняются с понятной ошибкой.
  • Тесты

    • Обновлены тесты для проверки JSON‑LD контекстов, заголовков content-type и поведения федерационных маршрутов.

Walkthrough

Добавляет JSON‑LD контексты и типы; требует и нормализует ForgeFed+ActivityStreams контексты, протягивает inheritedJsonLdContext через обработку входящих федеративных payload'ов, переключает исходящие федеративные документы и HTTP‑ответы на JSON‑LD, обновляет тесты; параметризует RTK в Dockerfile шаблонах.

Изменения

Федеративная обработка JSON-LD контекста

Layer / File(s) Summary
JSON-LD контракты и типы
packages/api/src/api/contracts.ts
Добавлены экспортируемые константы JSON‑LD контекстов, комбинированные контексты, content-type константы и typeof‑производные типы; сужены поля @context в ActivityPub контрактах.
HTTP слой и JSON-LD ответы
packages/api/src/http.ts, packages/api/tests/http-config.test.ts
Добавлен jsonLdResponse для сериализации с federation JSON‑LD content-type; экспортированы federation document handlers; маршруты /federation/actor, /federation/outbox, /federation/followers, /federation/following, /federation/liked делегируют этим handlers; HTTP тесты проверяют ответы.
Утилиты валидации контекста и negotiation
packages/api/src/services/federation.ts
IngestOptions расширена inheritedJsonLdContext; добавлены извлечение/нормализация @context и Effect‑валидаторы; Accept negotiation обновлён для включения federation JSON‑LD content type.
Наследование контекста через обработку входящих данных
packages/api/src/services/federation.ts
ingestFederationInbox требует top‑level контекст, извлекает inheritedJsonLdContext из payload или опций и передаёт его в parseTicket, ingestOfferTicket, ingestCreateTicket, ingestDirectTicket; polling и exchange parsing передают collection["@context"].
Исходящие документы и подписанные запросы
packages/api/src/services/federation.ts
Обновлены исходящие федеративные документы и активности (actor document, ordered collections, Follow, Update и пр.) для использования ForgeFed JSON‑LD контекстов; исходящий content-type для подписанных запросов переключён на federation JSON‑LD; persisted state версия записывается как литерал 1; fetchOutbox нормализует коллекцию.
Тестовое покрытие валидации контекста
packages/api/tests/federation.test.ts, packages/api/tests/http-config.test.ts
Тесты импортируют контекст и content‑type константы, проверяют @context в генерируемых активностях, добавлен тест отклонения payload'ов без ForgeFed контекста; добавлены HTTP тесты federation document endpoints и проверка заголовка content-type при follow.
Dockerfile RTK версия
packages/app/src/lib/core/templates/dockerfile.ts, packages/lib/src/core/templates/dockerfile.ts, packages/lib/tests/core/templates.test.ts
В шаблоны Dockerfile добавлен ARG RTK_VERSION с дефолтным значением и передача RTK_VERSION в вызов инсталлятора; тест ожиданий обновлён.

Диаграмма последовательности

sequenceDiagram
  participant RemoteFederation
  participant ingestFederationInbox
  participant requireFederationJsonLdContext
  participant ingestOfferTicket
  participant parseTicket
  participant MakeFederationActorDocument
  participant jsonLdResponse
  participant HttpResponse

  RemoteFederation->>ingestFederationInbox: POST входящая активность с `@context`
  ingestFederationInbox->>requireFederationJsonLdContext: требовать ForgeFed контекст
  alt Контекст валиден
    requireFederationJsonLdContext-->>ingestFederationInbox: inheritedJsonLdContext
    ingestFederationInbox->>ingestOfferTicket: обработать Offer с контекстом
    ingestOfferTicket->>parseTicket: парсить Ticket с inherited контекстом
  else Контекст невалиден
    requireFederationJsonLdContext-->>ingestFederationInbox: ApiBadRequestError
  end

  RemoteFederation->>MakeFederationActorDocument: GET /federation/actor
  MakeFederationActorDocument->>MakeFederationActorDocument: использовать actorJsonLdContext
  MakeFederationActorDocument->>jsonLdResponse: сериализовать JSON-LD
  jsonLdResponse->>HttpResponse: отправить с federationJsonLdResponseContentType
Loading

Оценка сложности кода

🎯 3 (Средняя сложность) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 7
✅ Passed checks (7 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: enforcing federation JSON-LD context validation in the API layer.
Description check ✅ Passed The description provides comprehensive explanation of changes, ForgeFed spec alignment, validation details, and local test results, though it deviates from the template structure.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Requirements Alignment ✅ Passed PR objectives fully implemented. JSON-LD constants, context validation, nested inheritance, Content-Type headers, comprehensive test coverage all verified.
Security Regression ✅ Passed No security regressions detected. Hardcoded JSON-LD contexts, safe RTK version handling with proper quoting, federation validation added, no credentials or command injection vulnerabilities found.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/federation-jsonld-context

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/src/services/federation.ts`:
- Around line 1495-1503: Remove the unnecessary "as const" assertion used inside
the Effect.as call in fetchOutbox: instead of using `"OrderedCollection" as
const` inline, construct the object with an explicit type annotation of
ActivityPubOrderedCollection (or assign the object to a variable typed as
ActivityPubOrderedCollection) so TypeScript infers the literal
"OrderedCollection" type without using `as`; update the Effect.flatMap branch
that builds the ordered collection (the object with "@context", type, id,
totalItems, orderedItems) to be typed as ActivityPubOrderedCollection and remove
the `as const` assertion.

In `@packages/api/tests/http-config.test.ts`:
- Around line 183-194: Add tests mirroring the existing "serves federation actor
documents as JSON-LD" case for the other federation endpoints
(/federation/outbox, /federation/followers, /federation/following,
/federation/liked). For each endpoint, call
readFederationDocumentRoute("<path>"), parse the response with parseJsonObject,
and assert actor.status === 200, actor.contentType ===
federationJsonLdResponseContentType, and that readField(payload, "@context")
equals the expected JSON-LD context (use actorJsonLdContext or the appropriate
context constant). Reuse the same clearFederationState() setup and test
structure (it.effect + Effect.gen) as in the existing test to ensure
consistency.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 7bfde134-0052-4aca-ac36-e33c0bd97790

📥 Commits

Reviewing files that changed from the base of the PR and between de017e6 and 3ed2eb8.

📒 Files selected for processing (5)
  • packages/api/src/api/contracts.ts
  • packages/api/src/http.ts
  • packages/api/src/services/federation.ts
  • packages/api/tests/federation.test.ts
  • packages/api/tests/http-config.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: E2E (Login context)
  • GitHub Check: E2E (Runtime volumes + SSH)
  • GitHub Check: E2E (Clone auto-open SSH)
  • GitHub Check: E2E (Browser command)
  • GitHub Check: E2E (Clone cache)
  • GitHub Check: E2E (OpenCode)
  • GitHub Check: Test
  • GitHub Check: Lint
  • GitHub Check: Final build (windows-latest)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Implement Functional Core, Imperative Shell (FCIS) pattern: CORE layer contains only pure functions with immutable data and mathematical operations; SHELL layer isolates all effects (IO, network, database). Strict dependency direction: SHELL → CORE (never reverse).
Never use any, unknown, eslint-disable, ts-ignore, or as type assertions (except in rigorously justified cases with documentation). Always use exhaustive union type analysis through .exhaustive() pattern matching.
All external dependencies must be wrapped through typed interfaces and injected via Effect-TS Layer pattern. Never call external services directly from CORE functions.
Use monadic composition with Effect-TS for all effects: Effect<Success, Error, Requirements>. Compose effects through pipe() and Effect.flatMap(). Implement dependency injection via Layer pattern. Handle errors without try/catch blocks.
All functions must be pure in the CORE layer: no side effects (logging, console output, IO operations, mutations). Separate all side effects into the SHELL layer.
Use exhaustive pattern matching with Effect.Match instead of switch statements. Example: Match.value(item).pipe(Match.when(...), Match.exhaustive).
Document all functions with comprehensive TSDoc including: @pure (true/false), @effect (required services), @invariant (mathematical invariants), @precondition, @postcondition, @complexity (time and space), @throws Never (errors must be typed in Effect).
Use functional comment markers for code clarity: CHANGE (brief description), WHY (mathematical/architectural justification), QUOTE(ТЗ) (requirement citation), REF (RTM or message ID), SOURCE (external source with quote), FORMAT THEOREM (∀x ∈ Domain: P(x) → Q(f(x))), PURITY (CORE|SHELL), EFFECT (Effect type signature), INVARIANT (mathematical invariant), COMPLEXITY (time/space).
Define all external service dependencies as Context.Tag classes with fully typed methods returning Effect types. Example: `class Da...

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/src/api/contracts.ts
  • packages/api/src/http.ts
  • packages/api/tests/federation.test.ts
  • packages/api/src/services/federation.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Implement property-based testing using fast-check for mathematical properties and invariants. Example: fc.property(fc.array(messageArbitrary), (messages) => isChronologicallySorted(sortMessagesByTimestamp(messages))).
Mock external dependencies in unit tests using Effect's testing utilities. Run tests without Effect runtime for speed. Example: Effect.provide(MockService), Effect.runPromise.

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/tests/federation.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Forbidden constructs in CORE code: any, eslint-disable, ts-ignore, async/await, raw Promise chains (then/catch), Promise.all, try/catch for logic control, console.*, switch statements (use Match with .exhaustive() instead)
All functions must use Effect-TS for composing effects: Effect<Success, Error, Requirements>. No direct async/await, Promise chains, or try/catch in product logic.
Functional comments must include: CHANGE, WHY, QUOTE(ТЗ) or n/a, REF, SOURCE or n/a, FORMAT THEOREM, PURITY (CORE|SHELL), EFFECT signature for SHELL functions, INVARIANT, and COMPLEXITY.
All data mutations must use immutable patterns (ReadonlyArray, readonly properties, Object.freeze); mutation in SHELL only when absolutely necessary and documented.

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/src/api/contracts.ts
  • packages/api/src/http.ts
  • packages/api/tests/federation.test.ts
  • packages/api/src/services/federation.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Property-based tests (fast-check) must verify mathematical invariants; unit tests must use Effect test utilities without async/await.

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/tests/federation.test.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Ты строгий ревьюер SPEC DRIVEN DEVELOPMENT.

Перед выводами изучи README.md, другие *.md файлы, linked issues,
PR description, PR comments/discussion и релевантную кодовую базу.

Сверь изменения с исходным ТЗ/спекой и обсуждением. Флагай любой уход
от спеки, недокументированное изменение поведения, отсутствие тестов
для заявленного поведения и security-риск. Если спека не видна,
попроси автора добавить ее в issue или PR description.

Проверь решение с точки зрения формальной верификации: какие инварианты,
предусловия и постусловия можно доказать математически, а где доказуемость
слабая. Оцени решение с точки зрения теории игр: устойчивы ли стимулы,
нет ли выгодного обхода правил, и какое решение было бы сильнее.

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/src/api/contracts.ts
  • packages/api/src/http.ts
  • packages/api/tests/federation.test.ts
  • packages/api/src/services/federation.ts
🔇 Additional comments (5)
packages/api/src/api/contracts.ts (1)

493-511: LGTM!

Also applies to: 573-573, 589-589, 607-607

packages/api/tests/http-config.test.ts (1)

8-13: LGTM!

Also applies to: 51-110

packages/api/src/http.ts (1)

14-15: LGTM!

Also applies to: 278-280, 598-604, 869-900

packages/api/tests/federation.test.ts (1)

5-9: LGTM!

Also applies to: 84-84, 90-90, 146-146, 162-162, 237-274, 350-356, 364-364, 418-418

packages/api/src/services/federation.ts (1)

37-42: LGTM!

Also applies to: 84-85, 107-108, 129-171, 541-603, 629-635, 755-807, 817-818, 877-894, 948-949, 1035-1035, 1189-1270, 1306-1306, 1551-1553, 1703-1703

Comment thread packages/api/src/services/federation.ts Outdated
Comment thread packages/api/tests/http-config.test.ts Outdated
@skulidropek
Copy link
Copy Markdown
Member Author

skulidropek commented May 13, 2026

AI Session Backup

Commit: 5271560
Status: success
Files: 3 (15.29 MB)
Links: README | Manifest

git status

On branch fix/federation-jsonld-context
Your branch is up to date with 'origin/fix/federation-jsonld-context'.

nothing to commit, working tree clean

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/src/http.ts`:
- Around line 278-279: Add comprehensive TSDoc to the jsonLdResponse helper:
locate the const jsonLdResponse declaration and prepend a TSDoc block that
documents the parameters and return, and includes the required tags — `@pure`
(false), `@effect` (calls textResponse / uses no external services), `@invariant`
(response content-type equals federationJsonLdResponseContentType),
`@precondition` (data is JSON.stringify-serializable), `@postcondition` (body is
JSON string and content-type is federationJsonLdResponseContentType),
`@complexity` (O(n) time and O(n) space where n is JSON.stringify cost), and
`@throws` Never; also mention that it calls textResponse and references
federationJsonLdResponseContentType so reviewers can trace behavior.
- Around line 598-631: Add comprehensive TSDoc comments for the five exported
handlers (federationActorDocumentResponse, federationOutboxDocumentResponse,
federationFollowersDocumentResponse, federationFollowingDocumentResponse,
federationLikedDocumentResponse) using the federationExchangeStatusResponse
docblock as a template: include `@pure` true/false, `@effect` describing that the
handler reads HttpServerRequest and resolves federation context, `@invariant`
about stable request→document mapping, `@precondition` requiring a non-empty
public origin, `@postcondition` describing the returned ActivityPub document (use
"Person document" for federationActorDocumentResponse and "OrderedCollection"
for outbox/followers/following/liked), `@complexity` with O(1) time/space, and
`@throws` Never; ensure each handler’s description and postcondition are adapted
to its specific document type and place the comment immediately above the
respective exported const.

In `@packages/api/src/services/federation.ts`:
- Around line 128-170: Add comprehensive TSDoc comments for jsonLdContextValues,
hasFederationJsonLdContext, requireFederationJsonLdContext, and
requireNestedFederationJsonLdContext: for each function include a short
description, `@param` tags for each parameter, `@returns` matching the return type,
and the required meta tags `@pure`, `@effect` (describe any Effect error type or
required services), `@invariant` (state the mathematical invariant about the
result), `@precondition`, `@postcondition` (describe behavior for different input
shapes), `@complexity` (time and space complexity), and `@throws` Never (errors are
typed in the Effect return); ensure the Effect-returning functions
(requireFederationJsonLdContext, requireNestedFederationJsonLdContext)
explicitly mention the ApiBadRequestError in the `@effect` description and that
they never throw synchronously.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6fd10df5-ccfe-4e04-9883-f82c06272d0e

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed2eb8 and 5271560.

📒 Files selected for processing (3)
  • packages/api/src/http.ts
  • packages/api/src/services/federation.ts
  • packages/api/tests/http-config.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: E2E (Clone cache)
  • GitHub Check: E2E (Login context)
  • GitHub Check: E2E (Runtime volumes + SSH)
  • GitHub Check: E2E (Clone auto-open SSH)
  • GitHub Check: E2E (Browser command)
  • GitHub Check: E2E (OpenCode)
  • GitHub Check: Lint
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Implement Functional Core, Imperative Shell (FCIS) pattern: CORE layer contains only pure functions with immutable data and mathematical operations; SHELL layer isolates all effects (IO, network, database). Strict dependency direction: SHELL → CORE (never reverse).
Never use any, unknown, eslint-disable, ts-ignore, or as type assertions (except in rigorously justified cases with documentation). Always use exhaustive union type analysis through .exhaustive() pattern matching.
All external dependencies must be wrapped through typed interfaces and injected via Effect-TS Layer pattern. Never call external services directly from CORE functions.
Use monadic composition with Effect-TS for all effects: Effect<Success, Error, Requirements>. Compose effects through pipe() and Effect.flatMap(). Implement dependency injection via Layer pattern. Handle errors without try/catch blocks.
All functions must be pure in the CORE layer: no side effects (logging, console output, IO operations, mutations). Separate all side effects into the SHELL layer.
Use exhaustive pattern matching with Effect.Match instead of switch statements. Example: Match.value(item).pipe(Match.when(...), Match.exhaustive).
Document all functions with comprehensive TSDoc including: @pure (true/false), @effect (required services), @invariant (mathematical invariants), @precondition, @postcondition, @complexity (time and space), @throws Never (errors must be typed in Effect).
Use functional comment markers for code clarity: CHANGE (brief description), WHY (mathematical/architectural justification), QUOTE(ТЗ) (requirement citation), REF (RTM or message ID), SOURCE (external source with quote), FORMAT THEOREM (∀x ∈ Domain: P(x) → Q(f(x))), PURITY (CORE|SHELL), EFFECT (Effect type signature), INVARIANT (mathematical invariant), COMPLEXITY (time/space).
Define all external service dependencies as Context.Tag classes with fully typed methods returning Effect types. Example: `class Da...

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/src/http.ts
  • packages/api/src/services/federation.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Implement property-based testing using fast-check for mathematical properties and invariants. Example: fc.property(fc.array(messageArbitrary), (messages) => isChronologicallySorted(sortMessagesByTimestamp(messages))).
Mock external dependencies in unit tests using Effect's testing utilities. Run tests without Effect runtime for speed. Example: Effect.provide(MockService), Effect.runPromise.

Files:

  • packages/api/tests/http-config.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Forbidden constructs in CORE code: any, eslint-disable, ts-ignore, async/await, raw Promise chains (then/catch), Promise.all, try/catch for logic control, console.*, switch statements (use Match with .exhaustive() instead)
All functions must use Effect-TS for composing effects: Effect<Success, Error, Requirements>. No direct async/await, Promise chains, or try/catch in product logic.
Functional comments must include: CHANGE, WHY, QUOTE(ТЗ) or n/a, REF, SOURCE or n/a, FORMAT THEOREM, PURITY (CORE|SHELL), EFFECT signature for SHELL functions, INVARIANT, and COMPLEXITY.
All data mutations must use immutable patterns (ReadonlyArray, readonly properties, Object.freeze); mutation in SHELL only when absolutely necessary and documented.

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/src/http.ts
  • packages/api/src/services/federation.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Property-based tests (fast-check) must verify mathematical invariants; unit tests must use Effect test utilities without async/await.

Files:

  • packages/api/tests/http-config.test.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Ты строгий ревьюер SPEC DRIVEN DEVELOPMENT.

Перед выводами изучи README.md, другие *.md файлы, linked issues,
PR description, PR comments/discussion и релевантную кодовую базу.

Сверь изменения с исходным ТЗ/спекой и обсуждением. Флагай любой уход
от спеки, недокументированное изменение поведения, отсутствие тестов
для заявленного поведения и security-риск. Если спека не видна,
попроси автора добавить ее в issue или PR description.

Проверь решение с точки зрения формальной верификации: какие инварианты,
предусловия и постусловия можно доказать математически, а где доказуемость
слабая. Оцени решение с точки зрения теории игр: устойчивы ли стимулы,
нет ли выгодного обхода правил, и какое решение было бы сильнее.

Files:

  • packages/api/tests/http-config.test.ts
  • packages/api/src/http.ts
  • packages/api/src/services/federation.ts
🔇 Additional comments (7)
packages/api/src/services/federation.ts (5)

543-543: LGTM!

Also applies to: 565-565, 576-576, 591-591, 602-602


628-664: LGTM!

Also applies to: 754-796, 798-832, 860-921


1188-1219: LGTM!

Also applies to: 1239-1269


1490-1505: LGTM!


382-382: LGTM!

Also applies to: 947-947, 1034-1034, 1305-1305, 1551-1551, 1702-1702

packages/api/src/http.ts (1)

896-914: LGTM!

packages/api/tests/http-config.test.ts (1)

56-68: LGTM!

Also applies to: 95-118, 130-166, 230-244

Comment thread packages/api/src/http.ts
Comment thread packages/api/src/http.ts
Comment thread packages/api/src/services/federation.ts
@skulidropek
Copy link
Copy Markdown
Member Author

skulidropek commented May 13, 2026

AI Session Backup

Commit: be85356
Status: success
Files: 3 (16.22 MB)
Links: README | Manifest

git status

On branch fix/federation-jsonld-context
Your branch is up to date with 'origin/fix/federation-jsonld-context'.

nothing to commit, working tree clean

@skulidropek
Copy link
Copy Markdown
Member Author

skulidropek commented May 13, 2026

AI Session Backup

Commit: e42c767
Status: success
Files: 3 (17.35 MB)
Links: README | Manifest

git status

On branch fix/federation-jsonld-context
Your branch is up to date with 'origin/fix/federation-jsonld-context'.

nothing to commit, working tree clean

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/lib/src/core/templates/dockerfile.ts`:
- Around line 97-103: Проблема: скачивание install.sh по постоянному пути
refs/heads/master делает сборку недетерминированной даже при заданном
RTK_VERSION; исправьте RUN-блок в шаблоне (где используется ARG RTK_VERSION и sh
/tmp/rtk-install.sh) чтобы вместо master загружать конкретную версию/тег/коммит,
привязанный к RTK_VERSION (например подставлять RTK_VERSION в URL к
refs/tags/${RTK_VERSION} или к конкретному коммиту), гарантируя, что скачиваемый
install.sh детерминированно соответствует RTK_VERSION; обновите URL в этом же
месте и оставьте поведение удаления /tmp/rtk-install.sh без изменений.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 3b4ede5c-d0a5-4964-a498-3147ebd53402

📥 Commits

Reviewing files that changed from the base of the PR and between be85356 and e42c767.

📒 Files selected for processing (3)
  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
  • packages/lib/tests/core/templates.test.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: E2E (Clone auto-open SSH)
  • GitHub Check: E2E (OpenCode)
  • GitHub Check: E2E (Runtime volumes + SSH)
  • GitHub Check: E2E (Login context)
  • GitHub Check: E2E (Clone cache)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Implement Functional Core, Imperative Shell (FCIS) pattern: CORE layer contains only pure functions with immutable data and mathematical operations; SHELL layer isolates all effects (IO, network, database). Strict dependency direction: SHELL → CORE (never reverse).
Never use any, unknown, eslint-disable, ts-ignore, or as type assertions (except in rigorously justified cases with documentation). Always use exhaustive union type analysis through .exhaustive() pattern matching.
All external dependencies must be wrapped through typed interfaces and injected via Effect-TS Layer pattern. Never call external services directly from CORE functions.
Use monadic composition with Effect-TS for all effects: Effect<Success, Error, Requirements>. Compose effects through pipe() and Effect.flatMap(). Implement dependency injection via Layer pattern. Handle errors without try/catch blocks.
All functions must be pure in the CORE layer: no side effects (logging, console output, IO operations, mutations). Separate all side effects into the SHELL layer.
Use exhaustive pattern matching with Effect.Match instead of switch statements. Example: Match.value(item).pipe(Match.when(...), Match.exhaustive).
Document all functions with comprehensive TSDoc including: @pure (true/false), @effect (required services), @invariant (mathematical invariants), @precondition, @postcondition, @complexity (time and space), @throws Never (errors must be typed in Effect).
Use functional comment markers for code clarity: CHANGE (brief description), WHY (mathematical/architectural justification), QUOTE(ТЗ) (requirement citation), REF (RTM or message ID), SOURCE (external source with quote), FORMAT THEOREM (∀x ∈ Domain: P(x) → Q(f(x))), PURITY (CORE|SHELL), EFFECT (Effect type signature), INVARIANT (mathematical invariant), COMPLEXITY (time/space).
Define all external service dependencies as Context.Tag classes with fully typed methods returning Effect types. Example: `class Da...

Files:

  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
  • packages/lib/tests/core/templates.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Forbidden constructs in CORE code: any, eslint-disable, ts-ignore, async/await, raw Promise chains (then/catch), Promise.all, try/catch for logic control, console.*, switch statements (use Match with .exhaustive() instead)
All functions must use Effect-TS for composing effects: Effect<Success, Error, Requirements>. No direct async/await, Promise chains, or try/catch in product logic.
Functional comments must include: CHANGE, WHY, QUOTE(ТЗ) or n/a, REF, SOURCE or n/a, FORMAT THEOREM, PURITY (CORE|SHELL), EFFECT signature for SHELL functions, INVARIANT, and COMPLEXITY.
All data mutations must use immutable patterns (ReadonlyArray, readonly properties, Object.freeze); mutation in SHELL only when absolutely necessary and documented.

Files:

  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
  • packages/lib/tests/core/templates.test.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Ты строгий ревьюер SPEC DRIVEN DEVELOPMENT.

Перед выводами изучи README.md, другие *.md файлы, linked issues,
PR description, PR comments/discussion и релевантную кодовую базу.

Сверь изменения с исходным ТЗ/спекой и обсуждением. Флагай любой уход
от спеки, недокументированное изменение поведения, отсутствие тестов
для заявленного поведения и security-риск. Если спека не видна,
попроси автора добавить ее в issue или PR description.

Проверь решение с точки зрения формальной верификации: какие инварианты,
предусловия и постусловия можно доказать математически, а где доказуемость
слабая. Оцени решение с точки зрения теории игр: устойчивы ли стимулы,
нет ли выгодного обхода правил, и какое решение было бы сильнее.

Files:

  • packages/app/src/lib/core/templates/dockerfile.ts
  • packages/lib/src/core/templates/dockerfile.ts
  • packages/lib/tests/core/templates.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Implement property-based testing using fast-check for mathematical properties and invariants. Example: fc.property(fc.array(messageArbitrary), (messages) => isChronologicallySorted(sortMessagesByTimestamp(messages))).
Mock external dependencies in unit tests using Effect's testing utilities. Run tests without Effect runtime for speed. Example: Effect.provide(MockService), Effect.runPromise.

Files:

  • packages/lib/tests/core/templates.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Property-based tests (fast-check) must verify mathematical invariants; unit tests must use Effect test utilities without async/await.

Files:

  • packages/lib/tests/core/templates.test.ts
🔇 Additional comments (1)
packages/app/src/lib/core/templates/dockerfile.ts (1)

97-103: Дубликат уже поднятой проблемы с непинованным installer URL RTK.

Здесь повторяется тот же паттерн, что и в packages/lib/src/core/templates/dockerfile.ts: при наличии ARG RTK_VERSION на Line 100 используется refs/heads/master, что не фиксирует источник installer по версии.

Comment thread packages/lib/src/core/templates/dockerfile.ts
@skulidropek
Copy link
Copy Markdown
Member Author

skulidropek commented May 13, 2026

AI Session Backup

Commit: 42abc27
Status: success
Files: 3 (17.47 MB)
Links: README | Manifest

git status

On branch fix/federation-jsonld-context
Your branch is up to date with 'origin/fix/federation-jsonld-context'.

nothing to commit, working tree clean

@ProverCoderAI ProverCoderAI deleted a comment from coderabbitai Bot May 13, 2026
@skulidropek skulidropek merged commit b56c7da into main May 13, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants