Skip to content

fix(shell): ensure PR exists after git push#378

Merged
skulidropek merged 3 commits into
mainfrom
issue-375
Jun 6, 2026
Merged

fix(shell): ensure PR exists after git push#378
skulidropek merged 3 commits into
mainfrom
issue-375

Conversation

@skulidropek

@skulidropek skulidropek commented Jun 6, 2026

Copy link
Copy Markdown
Member

Summary

  • ensure generated post-push hooks create or reuse an open GitHub PR after successful git push
  • support fork remotes by targeting upstream and owner-qualified head branches
  • extract the post-push PR helper fragment into canonical lib + app mirror modules
  • add CI-covered mirror parity coverage to prevent drift between package templates

Source TZ/Issues

Requirements Alignment

  • Successful non-dry-run git push runs the open-PR check before plan-to-git sync and session backup.
  • Existing open PRs are reused; missing PRs are created with gh pr create --fill.
  • Fork remotes target upstream with owner-qualified head branches.
  • packages/app keeps its standalone package boundary; rendered app/lib PR fragments are asserted equal in the lib template test.

Mathematical Guarantees

  • Invariant: renderAppPostPushPrEnsure() === renderLibPostPushPrEnsure().
  • Precondition: post-push PR creation/listing requires gh when a GitHub remote is present.
  • Postcondition: PR-bound post-push tools run only after the open-PR check succeeds or intentionally skips because no GitHub remote exists.

Verification

  • rtk bun run --filter @effect-template/lib test -- tests/core/git-post-push-wrapper.test.ts tests/core/templates.test.ts
  • rtk ./node_modules/.bin/vitest run tests/docker-git/core-templates.test.ts from packages/app
  • rtk bun run --filter @effect-template/lib typecheck
  • rtk bun run --filter @prover-coder-ai/docker-git typecheck
  • rtk bun run --filter @effect-template/lib lint
  • rtk bun run --filter @prover-coder-ai/docker-git lint
  • rtk git diff --check

Closes #375

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown

Wondering what really moved? Review this PR in Change Stack to inspect semantic changes, definitions, and references.

Review Change Stack

Warning

Review limit reached

@skulidropek, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 4 minutes and 9 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 0bc06393-f211-4e1a-8b46-8fcea945a873

📥 Commits

Reviewing files that changed from the base of the PR and between 8a62c12 and cc36eda.

📒 Files selected for processing (7)
  • packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
  • packages/app/src/lib/core/templates-entrypoint/post-push-pr.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/src/core/templates-entrypoint/post-push-pr.ts
  • packages/lib/tests/core/git-post-push-wrapper.test.ts
  • packages/lib/tests/core/templates.test.ts
📝 Walkthrough

Walkthrough

PR добавляет функцию автоматического создания GitHub PR при git push. Новые bash-функции извлекают владельца/репо из git remote, определяют default branch через gh repo view, проверяют наличие open PR и создают его при отсутствии. Логика интегрирована в post-push action шаблонов и протестирована через расширенную инфраструктуру тестирования GitHub CLI.

Changes

GitHub PR auto-creation on git push

Layer / File(s) Summary
Основные bash-функции для PR
packages/lib/src/core/templates-entrypoint/git-hooks.ts, packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
Три bash-функции: извлечение owner/repo из URL, получение repo из git remote, основная функция docker_git_ensure_open_pr с проверкой gh CLI, текущей ветки, detached HEAD, выбором base repo и созданием PR через gh pr create --fill при отсутствии.
Интеграция в post-push templates
packages/lib/src/core/templates-entrypoint/git-hooks.ts, packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
Вызов docker_git_ensure_open_pr в post-push action перед plan-to-git sync и session backup для гарантии наличия PR перед последующими инструментами.
Расширение тестовой инфраструктуры
packages/lib/tests/core/git-post-push-wrapper.test.ts
Добавлено логирование вызовов GitHub CLI через ghLogPath в WrapperHarness. Расширены fakeGitScript (rev-parse, remote get-url) и fakeGhScript (логирование, repo view, pr list, pr create) с управляемыми exit-code и environment-переменными.
Интеграционные тесты
packages/lib/tests/core/git-post-push-wrapper.test.ts
Существующие тесты дополнены проверками gh.log на создание PR. Новые тест-кейсы: повторное использование существующего PR, fork-PR с owner-qualified head, распространение ошибок pr create/pr list, отказ на detached HEAD.
Тесты генерации шаблонов
packages/app/tests/docker-git/core-templates.test.ts, packages/lib/tests/core/templates.test.ts
Проверки содержимого и порядка строк в сгенерированном entrypoint.sh: наличие docker_git_ensure_open_pr, gh pr list/create и правильная последовательность cd → PR logic → plan-to-git sync → session backup.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • ProverCoderAI/docker-git#371: Изменение post-push git-hooks.ts с добавлением docker_git_ensure_open_pr перед plan-to-git sync дополняет PR #371, расширяя workflow загрузки PR в Codex в одном шаблоне.
🚥 Pre-merge checks | ✅ 6 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive Описание PR хорошо структурировано с Summary, Requirements Alignment и Verification разделами, но не следует шаблону репозитория. Переструктурируйте описание согласно шаблону: добавьте секцию 'Source TZ / Issues' с явным указанием формата 'Fixes #375', явно перечислите 'Implemented' и 'Out of scope', а 'Verification' переформатируйте списком с тире.
✅ Passed checks (6 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: ensuring a GitHub PR exists after git push, which aligns with the primary objective of the changeset.
Linked Issues check ✅ Passed The PR implementation meets all coding requirements from issue #375: creates new PR if missing, reuses existing PR, and handles fork remotes with owner-qualified heads.
Out of Scope Changes check ✅ Passed All changes directly support the PR objective of ensuring GitHub PR exists after git push; no out-of-scope modifications were introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Requirements Alignment ✅ Passed Все требования из PR и issue #375 реализованы: PR создается/переиспользуется после push, покрыты все обещанные сценарии, документировано, нет недокументированного поведения.
Security Regression ✅ Passed Нет высокоуровневых регрессий безопасности: переменные экранированы, входные данные валидируются, ошибки обработаны, нет утечек credentials, безопасные bash паттерны.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-375

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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/app/src/lib/core/templates-entrypoint/git-hooks.ts`:
- Around line 148-274: Duplicate GitHub helper functions
(docker_git_github_repo_from_remote_url, docker_git_github_repo_from_remote,
docker_git_ensure_open_pr) exist in both packages causing drift; extract them to
a single shared location and make both packages source/use that canonical
fragment. Create a new shared script/module (e.g., lib/shared-git-hooks.sh or a
shared template string) that defines those functions, replace the duplicated
definitions in packages/app and packages/lib with a single source step (source
or include that shared script) and update packaging/CI to ensure the shared file
is present; also add a lightweight CI check that compares the two originals
against the shared canonical file to prevent regressions.
🪄 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: b014b42e-2e82-450e-b58f-b5380f9e87a2

📥 Commits

Reviewing files that changed from the base of the PR and between b4426a3 and 8a62c12.

📒 Files selected for processing (5)
  • packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.test.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). (9)
  • GitHub Check: E2E (OpenCode)
  • GitHub Check: E2E (Clone cache)
  • GitHub Check: E2E (Runtime volumes + SSH)
  • GitHub Check: E2E (Clone auto-open SSH)
  • GitHub Check: E2E (Login context)
  • GitHub Check: E2E (Browser command)
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Final build (windows-latest)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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-entrypoint/git-hooks.ts
  • packages/lib/tests/core/templates.test.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.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-entrypoint/git-hooks.ts
  • packages/lib/tests/core/templates.test.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.test.ts
**/*.{sh,bash,py,js,ts,jsx,tsx,go,java,rb,php}

📄 CodeRabbit inference engine (Custom checks)

Fail if changed files introduce command injection or unsafe shell/process execution with user-controlled input

Files:

  • packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/templates.test.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.test.ts
**/*.{py,js,ts,jsx,tsx,go,java,rb,php,sh,bash,c,cpp}

📄 CodeRabbit inference engine (Custom checks)

Fail if changed files introduce path traversal or writes outside intended project/container state directories

Files:

  • packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/templates.test.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.test.ts
**/*.{js,ts,jsx,tsx,py,java,go,rb,php,sh,bash,yml,yaml,json,env*,toml,cfg,config,dockerfile,dockerignore}

📄 CodeRabbit inference engine (Custom checks)

Fail if changed files expose credentials, tokens, private-keys, or PII in source, generated config, logs, or CI output

Files:

  • packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/templates.test.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.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-entrypoint/git-hooks.ts
  • packages/lib/tests/core/templates.test.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.test.ts
**

⚙️ CodeRabbit configuration file

**: РОЛЬ: Математик-программист, специализирующийся на формально верифицируемой функциональной архитектуре.

ЦЕЛЬ: Создавать математически доказуемые решения через функциональную парадигму с полным разделением чистых вычислений и контролируемых эффектов.

МОДЕЛЬ РАССУЖДЕНИЯ:

  • Не выдавать “личные мнения”. Формировать вывод как результат симуляции профессионального обсуждения релевантных ролей
    (архитектор Effect/FP, ревьюер типов, страж CORE↔SHELL, тест-инженер).
  • Если запрос сформулирован как “что думаешь”, отвечать в терминах аргументов ролей и выбирать решение
    по критериям инвариантов, типовой безопасности и тестируемости (если пользователь явно просит выбор — выбрать и обосновать).

ПРАВИЛО ПРОЦЕССА (НЕ ФОРМАТ ОТВЕТА):
В начале работы (внутренне) формулировать Deep Research вопрос:
"I am looking for code that does , is there existing code that can do this?"
Далее:

  • если доступен проект/код — сперва искать и переиспользовать существующие паттерны (минимальный корректный diff),
  • если проект недоступен — опираться на предоставленный контекст и явно фиксировать допущения,
  • код писать только после формального понимания задачи (типы/инварианты → архитектура → код → тесты),
  • источники указывать только если реально использован внешний материал; иначе SOURCE: n/a.

ИНСТРУМЕНТАЛЬНОЕ ПОВЕДЕНИЕ (ОБЯЗАТЕЛЬНО, НЕ ФОРМАТ ОТВЕТА):

  • Агент всегда использует доступные инструменты среды (терминал, поиск по проекту, запуск тестов/скриптов, анализ сборки, web-ресёрч при необходимости)
    для ресёрча, проверки гипотез и выполнения действий. Приоритет: проверяемость, воспроизводимость, минимальный риск.
  • Агент не предлагает “гайд” как замену действия. Если действие возможно выполнить инструментами — агент выполняет его сам,
    затем сообщает, что было сделано и как повторить.
  • Любые инструкции (команды/процедуры) агент даёт только после собственной проверки на доступной среде.
    Если проверить невозможно — явно фиксирует ограничение и перечисляе...

Files:

  • packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/templates.test.ts
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/src/core/templates-entrypoint/git-hooks.ts
  • packages/lib/tests/core/git-post-push-wrapper.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
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/tests/core/git-post-push-wrapper.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
  • packages/app/tests/docker-git/core-templates.test.ts
  • packages/lib/tests/core/git-post-push-wrapper.test.ts
🧠 Learnings (2)
📚 Learning: 2026-05-13T07:10:13.213Z
Learnt from: CR
Repo: ProverCoderAI/docker-git PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-05-13T07:10:13.213Z
Learning: Applies to **/*.{test,spec}.{ts,tsx} : Property-based tests (fast-check) must verify mathematical invariants; unit tests must use Effect test utilities without async/await.

Applied to files:

  • packages/lib/tests/core/git-post-push-wrapper.test.ts
📚 Learning: 2026-05-13T07:09:47.992Z
Learnt from: CR
Repo: ProverCoderAI/docker-git PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-05-13T07:09:47.992Z
Learning: Applies to **/*.test.{ts,tsx} : Mock external dependencies in unit tests using Effect's testing utilities. Run tests without Effect runtime for speed. Example: `Effect.provide(MockService), Effect.runPromise`.

Applied to files:

  • packages/lib/tests/core/git-post-push-wrapper.test.ts
🔇 Additional comments (4)
packages/lib/src/core/templates-entrypoint/git-hooks.ts (1)

148-274: LGTM!

packages/app/tests/docker-git/core-templates.test.ts (1)

113-137: LGTM!

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

483-525: LGTM!

packages/lib/tests/core/git-post-push-wrapper.test.ts (1)

1-619: LGTM!

Comment thread packages/app/src/lib/core/templates-entrypoint/git-hooks.ts Outdated
@skulidropek

skulidropek commented Jun 6, 2026

Copy link
Copy Markdown
Member Author

AI Session Backup

Commit: ed459e5
Status: success
Files: 3 (2.71 MB)
Links: README | Manifest

git status

On branch issue-375
Your branch is up to date with 'origin/issue-375'.

nothing to commit, working tree clean

@skulidropek

skulidropek commented Jun 6, 2026

Copy link
Copy Markdown
Member Author

AI Session Backup

Commit: ed459e5
Status: success
Files: 3 (3.08 MB)
Links: README | Manifest

git status

On branch issue-375
Your branch is up to date with 'origin/issue-375'.

nothing to commit, working tree clean

@skulidropek

Copy link
Copy Markdown
Member Author

Agent Plan Update

Branch: issue-375 at cc36eda.

1. Plan

Source: codex - Captured: 2026-06-06T09:25:15.467Z

Ensure PR Exists After Git Push

Summary

Implement issue #375 by updating generated project-container post-push hooks so every successful non-dry-run git push ensures an open GitHub PR for the current branch before running plan-to-git sync and session backup. If an open PR already exists, reuse it; if not, create one with gh pr create --fill.

Key Changes

  • Update both mirrored hook templates:
    • packages/lib/src/core/templates-entrypoint/git-hooks.ts
    • packages/app/src/lib/core/templates-entrypoint/git-hooks.ts
  • Add a docker_git_ensure_open_pr shell helper inside generated /opt/docker-git/hooks/post-push.
  • Hook behavior:
    • require gh before PR ensure;
    • resolve current branch via git rev-parse --abbrev-ref HEAD;
    • fail clearly on detached HEAD;
    • prefer upstream as base GitHub repo when present, otherwise use origin/gh repo view;
    • resolve default base branch via gh repo view --json defaultBranchRef;
    • check existing open PR with gh pr list --state open --head <head> --json url;
    • create missing PR with gh pr create -R <base-repo> --base <default-branch> --head <head> --fill;
    • run PR ensure before plan-to-git sync and before docker-git-session-sync backup --require-comment.
  • Do not change docker-git-session-sync: once PR exists, its current open-PR lookup/comment flow should work unchanged.

Tests

  • Extend packages/lib/tests/core/git-post-push-wrapper.test.ts fake gh/git harness to cover:
    • existing open PR skips gh pr create;
    • missing PR calls gh pr create before plan sync/session backup;
    • PR creation failure stops post-push before plan sync/session backup;
    • dry-run push and failed push do not run PR ensure;
    • DOCKER_GIT_SKIP_PLAN_TO_GIT=1 does not skip PR ensure.
  • Update template assertions:
    • packages/lib/tests/core/templates.test.ts
    • packages/app/tests/docker-git/core-templates.test.ts
  • Verification commands:
    • rtk bun install --frozen-lockfile if vitest is missing;
    • rtk bun run --filter @effect-template/lib test -- tests/core/git-post-push-wrapper.test.ts tests/core/templates.test.ts;
    • rtk bun run --filter @prover-coder-ai/docker-git test -- tests/docker-git/core-templates.test.ts;
    • rtk bun run --filter @effect-template/lib typecheck;
    • rtk bun run --filter @prover-coder-ai/docker-git typecheck.

Assumptions

  • Scope is GitHub PRs only; GitLab merge-request creation is out of scope for issue Сделать что бы при git push всегда был открыт PR #375.
  • PR title/body should use gh pr create --fill.
  • PR is keyed to the current checked-out branch after push; unusual explicit refspec workflows like git push origin local:remote are not expanded in this change.
  • PR creation failure should fail the post-push action, matching the current strict behavior of required PR comments.

2. Plan

Source: codex - Captured: 2026-06-06T10:20:49.040Z

Исправление review #4442380897 для PR #378

Summary

Убрать опасное дублирование bash-хелперов из двух git-hooks.ts, не вводя runtime-зависимость packages/app от @effect-template/lib. Каноническим источником будет packages/lib, а mirror в packages/app будет автоматически проверяться тестом на byte-for-byte совпадение.

Key Changes

  • Вынести GitHub PR helper fragment в отдельный local template module:
    • canonical: packages/lib/src/core/templates-entrypoint/post-push-pr.ts
    • mirror: packages/app/src/lib/core/templates-entrypoint/post-push-pr.ts
  • В обоих git-hooks.ts заменить inline-блок функций на импорт локального renderPostPushPrEnsure() и вставку результата перед plan-to-git sync.
  • Добавить CI-enforced drift check в существующие template tests: rendered fragment из packages/lib и packages/app должен совпадать полностью.
  • Сохранить текущее поведение hook:
    • после успешного non-dry-run git push определяется GitHub repo из origin или upstream;
    • если для текущей branch уже есть open PR, новый PR не создается;
    • если PR нет, вызывается gh pr create --fill --repo ... --head ...;
    • ошибки создания PR прерывают post-push sync/backup.
  • Обновить PR body, чтобы закрыть warning review-description check: добавить sections про Closes #375, alignment с требованиями и verified commands/CI.

Test Plan

  • Запустить targeted tests:
    • rtk bun run --filter @effect-template/lib test -- tests/core/git-post-push-wrapper.test.ts tests/core/templates.test.ts
    • из packages/app: rtk ./node_modules/.bin/vitest run tests/docker-git/core-templates.test.ts
  • Запустить type/lint checks:
    • rtk bun run --filter @effect-template/lib typecheck
    • rtk bun run --filter @prover-coder-ai/docker-git typecheck
    • rtk bun run --filter @effect-template/lib lint
    • rtk bun run --filter @prover-coder-ai/docker-git lint
  • Проверить diff:
    • rtk git diff --check
  • После выхода из Plan Mode: commit, push, затем проверить PR fix(shell): ensure PR exists after git push #378 через gh pr checks --watch.

Assumptions

  • Не добавлять прямой import @effect-template/lib в packages/app, потому что repo уже запрещает это lint-правилами и e2e packaging check.
  • packages/lib считается canonical source; packages/app хранит mirror только ради standalone app/package архитектуры.
  • Review исправляется через extraction + drift test, что соответствует требованию “single shared location or automatic verification of identity in CI” без изменения package topology.

@skulidropek

skulidropek commented Jun 6, 2026

Copy link
Copy Markdown
Member Author

AI Session Backup

Commit: cc36eda
Status: success
Files: 4 (4.93 MB)
Links: README | Manifest

git status

On branch issue-375
Your branch is up to date with 'origin/issue-375'.

nothing to commit, working tree clean

@skulidropek skulidropek merged commit f52a87f into main Jun 6, 2026
18 of 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.

Сделать что бы при git push всегда был открыт PR

1 participant