Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/adr/adr-022-automation-responsibility-separation.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,36 @@ takt fix は `@` を amend する (jj auto-snapshot が file edit を `@` に sq

`pnpm create-pr -- --title ... --body ...` で渡された title/body は automated actor が書き換えない。CodeRabbit が「PR description をもっと詳しく書け」と指摘したとしても、takt は該当する書き換えを行わない (fix step の `edit: true` はあくまで**リポジトリ内ファイル**への edit を意味する)。

### 例外: 分離型 fix commit の自己記述 (2026-04-20 追記)

ADR task 4 (takt fix のレビュー修正コミット分離) の実装に伴い、以下を例外として許可する:

**対象**: 自動生成された修正を、既存 commit を改変せずに新規 child commit として分離する場合のみ

**許可される内容**:

- commit 種別を示すラベル (例: `fix(review): apply CodeRabbit fixes for #<PR>`)
- 何を問題と捉えて修正したかの文脈 (CodeRabbit finding の severity / file / summary など)
- 対応した指摘の列挙 (ファイル/行/issue 要約)

**依然として禁止される内容**:

- 既存 commit (= 人間が意図を込めた元 PR commit) の description 書き換え
- PR title / PR body の書き換え
- bookmark / tag への介入
Comment on lines +87 to +91

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

bookmark auto-advanceとの境界を明記してください。

ここで「bookmark / tag への介入」を全面禁止にすると、push_jj_bookmark::advance_jj_bookmarksによる既存bookmark前進もADR違反に見えます。禁止対象が「生成・rename・任意移動」なのか、既存bookmarkをpush対象commitへ同期する操作は別ADRで許可済みなのかを明文化してください。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/adr/adr-022-automation-responsibility-separation.md` around lines 87 -
91, 本文の「bookmark / tag への介入」を全面禁止とすると push_jj_bookmark::advance_jj_bookmarks
による既存bookmarkの前進が禁止に見えるため、ADRに境界を明記してください。具体的には ADR
ファイル(adr-022)内の該当箇所で「禁止される操作=bookmark/tag
の新規作成・名前変更(rename)・任意の移動や改変」であることを明記し、対照的に
push_jj_bookmark::advance_jj_bookmarks
のような「既存bookmarkをpush対象のコミットへ同期(自動前進)する操作」は別途許可される例外として明示してください。これにより「生成・rename・任意移動」と「既存bookmarkの同期(advance_jj_bookmarks)」を区別して記述してください。


**根拠**:

- 独立した child commit の description は「その commit 自身の自己記述」であり、原則 1 が守るべき「人間の意図表現」を侵食しない
- automated actor の修正判断を残すことは、後のレビュー・post-merge-feedback (ADR-014) 等へのフィードバックループの情報資源になる
- 「最初の commit の意味は保ったまま、追加 commit に自動化の痕跡を残す」という形で、人間の意思と自動化の記録を両立させる

**実装上の拘束**:

- description は automated actor が生成してよいが、**常に新規 commit に対してのみ**適用する (`jj new -m ...`)
- 既存 commit への `jj describe` は引き続き禁止 (原則 3 は不変)
- fix commit が空になる (takt no-op) 場合は abandon する — 空 description の commit を残さない

## 影響

### 採用される構成要素
Expand Down
7 changes: 4 additions & 3 deletions docs/todo.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,10 @@
- **元コミット description の維持**: `jj new` 単独では元の description が保持される想定だが、過去の PR で `jj describe` による上書き事故があった (PR #44、ADR-022 の契機)。挙動を実測で再確認する必要あり
- **複数回 fix される場合**: 1 PR で 2 回 3 回と CodeRabbit 指摘 → takt 修正が走った場合、毎回新しい fix コミットを作るか、同じ fix コミットに積むか要検討
- **考慮事項**:
- コミット分離は `decide_repush == HasChange` のみ。NoChange (takt が実質変更なし) の場合は既存 no-op
- `auto_push_severity = "none"` の場合は分離せずに手動 push を待つ (ユーザーが `jj describe` する余地を残す)
- ADR-022 (automated actor boundary) の境界をまたがないこと。コミット分離のロジックは Rust 側に閉じる
- コミット分離は `has_coderabbit_findings` のみで判定 (auto_push と独立)。takt 実行自体の前提と同じ条件
- NoChange (takt が実質変更なし) の場合は事前に作った空 child を `jj abandon` で片付ける。ただし fail-safe として `jj diff -r @` で空確認してから abandon
- `auto_push_severity = "none"` の場合も**child commit は分離する**。分離結果をユーザーが確認してから手動 push または `jj describe` で再構成できる (fix の痕跡を可視化したまま判断材料を残す方針)
- ADR-022 (automated actor boundary) の境界: 既存 commit の description 改変は禁止。新規 child commit への description 生成は例外として許可 (ADR-022 追記予定)
- **参照 ADR**:
- ADR-018 (post-pr-monitor takt 化): 既存フローの前提
- ADR-022 (責務分離): takt は commit 操作禁止、Rust 側が担当
Expand Down
199 changes: 199 additions & 0 deletions src/cli-pr-monitor/src/fix_commit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
//! 分離型 fix commit の pre-create と description 生成。
//!
//! ADR-022 例外条項 (2026-04-20): 自動生成された修正を独立した child commit として
//! 分離する場合に限り、その child commit への description 付与を許可する。
//! 元 commit (= 人間が意図を込めた初回 PR commit) の description は改変しない。
//!
//! pre-takt で `jj new -m "..."` により空 child を作成し、takt が `@` を amend する
//! ことで fix 内容が自動的に child commit へ入る仕組み。

use lib_report_formatter::Finding;

use crate::log::log_info;
use crate::runner::{capture_commit_id, diff_at_is_empty, run_cmd_direct, JJ_CMD_TIMEOUT_SECS};

/// 分離型 fix commit の状態。
///
/// pre-takt で作成を試み、成否を型で表現する。
/// post-takt の分岐 (re-push / abandon / 放置) で消費される。
#[derive(Debug, Clone)]
pub(crate) enum FixCommitState {
/// 分離を行わなかった (findings なし、takt 未構成、または作成失敗)
None,
/// fix commit を pre-create 済み
Created { commit_id: String },
}

impl FixCommitState {
pub(crate) fn is_created(&self) -> bool {
matches!(self, Self::Created { .. })
}
}

/// fix commit の description を生成する。
///
/// ADR-022 例外の「新規 child commit への自己記述」として、
/// - header ラベル: commit 種別を示す
/// - findings summary: 何を問題と捉え、どれを修正したかの文脈
///
/// の 2 段構成で返す。findings が空なら header のみ返す。
pub(crate) fn build_fix_commit_description(pr_number: Option<u64>, findings: &[Finding]) -> String {
let header = match pr_number {
Some(n) => format!("fix(review): apply CodeRabbit fixes for #{}", n),
None => "fix(review): apply CodeRabbit fixes".to_string(),
};

if findings.is_empty() {
return header;
}

let mut body = String::with_capacity(256);
body.push_str(&header);
body.push_str("\n\nResolved findings:\n");
for f in findings {
body.push_str(&format!(
"- [{}] {}:{} {}\n",
f.severity, f.file, f.line, f.issue
));
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
body.trim_end().to_string()
}

/// pre-takt で fix commit を新規作成する (`jj new -m "..."`)。
///
/// 成功時: `FixCommitState::Created { commit_id }` を返す。@ は空 child を指す状態。
/// 失敗時: `FixCommitState::None` を返す (fallback = 分離なしで元の flow へフォールバック)。
///
/// 失敗要因として想定:
/// - `jj` コマンドが見つからない / 失敗
/// - 直後の `capture_commit_id` 失敗 (この場合は jj new の結果を追跡できないため None 扱い)
pub(crate) fn create_fix_commit(pr_number: Option<u64>, findings: &[Finding]) -> FixCommitState {
let desc = build_fix_commit_description(pr_number, findings);
let (ok, output) = run_cmd_direct("jj", &["new", "-m", &desc], &[], JJ_CMD_TIMEOUT_SECS);
if !ok {
log_info(&format!(
"[action] fix commit 分離 skip: jj new 失敗: {}",
output
));
return FixCommitState::None;
}
match capture_commit_id() {
Some(cid) => {
log_info(&format!("[state] fix commit pre-created: {}", cid));
FixCommitState::Created { commit_id: cid }
}
None => {
log_info("[state] fix commit 作成後の commit id capture 失敗 (fallback)");
FixCommitState::None
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

/// 空 fix commit を安全に abandon する。
///
/// `commit_id` が `Some(expected)` のとき: 現在の `@` が `expected` と一致する場合のみ
/// abandon を実行する。不一致または capture 失敗時は `[warn]` を出してスキップする。
/// `commit_id` が `None` のとき: 従来通り diff チェックのみで判定する。
///
/// diff あり判定失敗時は abandon をスキップ (fail-safe: 誤 abandon 防止)。
pub(crate) fn try_abandon_empty_fix_commit(context: &str, commit_id: Option<&str>) {
if let Some(expected) = commit_id {
match capture_commit_id().as_deref() {
Some(current) if current == expected => {}
Some(current) => {
log_info(&format!(
"[warn] {} expected={}, current={} abandon を見送り",
context, expected, current
));
return;
}
None => {
log_info(&format!(
"[warn] {} expected={}, current=<capture失敗> abandon を見送り",
context, expected
));
return;
}
}
}

if diff_at_is_empty() {
let label = commit_id.map_or_else(String::new, |id| format!(" ({})", id));
log_info(&format!(
"[action] {} 空 fix commit を abandon{}",
context, label
));
let (ok, out) = run_cmd_direct("jj", &["abandon"], &[], JJ_CMD_TIMEOUT_SECS);
if !ok {
Comment on lines +109 to +137

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

abandon対象を記録済みfix commitに固定してください。

commit_idを受け取っていますが、現状はログ表示だけで、実際には現在の@をjj abandonします。taktや別処理で@が移動していると、空の別commitを削除し、作成済みfix commitを残す可能性があります。

修正案
 pub(crate) fn try_abandon_empty_fix_commit(context: &str, commit_id: Option<&str>) {
+    if let Some(expected) = commit_id {
+        match capture_commit_id() {
+            Some(current) if current == expected => {}
+            Some(current) => {
+                log_info(&format!(
+                    "[warn] {} abandon 対象不一致のためスキップ: expected={}, current={}",
+                    context, expected, current
+                ));
+                return;
+            }
+            None => {
+                log_info(&format!(
+                    "[warn] {} current commit id を確認できないため abandon をスキップ",
+                    context
+                ));
+                return;
+            }
+        }
+    }
+
     if diff_at_is_empty() {
         let label = commit_id.map_or_else(String::new, |id| format!(" ({})", id));
         log_info(&format!("[action] {} 空 fix commit を abandon{}", context, label));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cli-pr-monitor/src/fix_commit.rs` around lines 94 - 99, The function
try_abandon_empty_fix_commit currently logs commit_id but always abandons the
current '@' via run_cmd_direct("jj", &["abandon"], ...); change it to target the
recorded commit when commit_id is Some by passing that id as an argument to jj
(e.g., run_cmd_direct("jj", &["abandon", commit_id], ...)), keeping the original
behavior only when commit_id is None; locate this logic in
try_abandon_empty_fix_commit and update the run_cmd_direct call and any label
handling so the actual recorded fix commit (not whatever '@' currently points
to) is abandoned when appropriate, leaving diff_at_is_empty() check intact.

log_info(&format!(
"[action] jj abandon 失敗 (手動片付け推奨): {}",
out
));
}
} else {
log_info(&format!(
"[warn] {} fix commit に diff あり、abandon を見送り",
context
));
}
}

#[cfg(test)]
mod tests {
use super::*;

fn finding(severity: &str, file: &str, line: &str, issue: &str) -> Finding {
Finding {
severity: severity.to_string(),
file: file.to_string(),
line: line.to_string(),
issue: issue.to_string(),
suggestion: String::new(),
source: "CodeRabbit".to_string(),
}
}

#[test]
fn description_without_findings_is_header_only() {
let desc = build_fix_commit_description(Some(42), &[]);
assert_eq!(desc, "fix(review): apply CodeRabbit fixes for #42");
}

#[test]
fn description_without_pr_number_falls_back_to_generic_header() {
let desc = build_fix_commit_description(None, &[]);
assert_eq!(desc, "fix(review): apply CodeRabbit fixes");
}

#[test]
fn description_with_findings_includes_summary_block() {
let fs = vec![
finding("Major", "src/foo.rs", "12", "null pointer"),
finding("Minor", "src/bar.rs", "34", "unused variable"),
];
let desc = build_fix_commit_description(Some(42), &fs);
assert!(
desc.starts_with("fix(review): apply CodeRabbit fixes for #42\n\nResolved findings:\n")
);
assert!(desc.contains("- [Major] src/foo.rs:12 null pointer"));
assert!(desc.contains("- [Minor] src/bar.rs:34 unused variable"));
assert!(!desc.ends_with('\n'));
}

#[test]
fn description_with_findings_without_pr_number() {
let fs = vec![finding("Major", "a.rs", "1", "issue")];
let desc = build_fix_commit_description(None, &fs);
assert!(desc.starts_with("fix(review): apply CodeRabbit fixes\n\n"));
assert!(desc.contains("- [Major] a.rs:1 issue"));
}

#[test]
fn fix_commit_state_is_created_truth_table() {
assert!(!FixCommitState::None.is_created());
assert!(FixCommitState::Created {
commit_id: "abc".into()
}
.is_created());
}
}
1 change: 1 addition & 0 deletions src/cli-pr-monitor/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
//! 1 - gh pr create 失敗 (PR 作成モードのみ)

mod config;
mod fix_commit;
mod log;
mod runner;
mod stages;
Expand Down
40 changes: 39 additions & 1 deletion src/cli-pr-monitor/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::time::Duration;
// こちらは check-ci-coderabbit の JSON 出力全体をパースするため制限なし。

const POLL_INTERVAL_MS: u64 = 100;
pub(crate) const JJ_CMD_TIMEOUT_SECS: u64 = 30;

pub(crate) fn drain_pipe(
pipe: impl std::io::Read + Send + 'static,
Expand Down Expand Up @@ -170,7 +171,7 @@ pub(crate) fn diff_is_empty(from: &str, to: &str) -> bool {
"jj",
&["diff", "--from", from, "--to", to, "--stat"],
&[],
30,
JJ_CMD_TIMEOUT_SECS,
);
if !ok {
crate::log::log_info(&format!(
Expand All @@ -182,6 +183,43 @@ pub(crate) fn diff_is_empty(from: &str, to: &str) -> bool {
out.trim().is_empty()
}

/// 現在の `@` が empty commit (親との差分なし) か判定する。
///
/// `diff_is_empty` は re-push 判定 (fail-safe で「空扱い → push しない」方向) だが、
/// こちらは **abandon 判定**用であり方向が逆: 失敗時は `false` (= diff あり扱い)
/// を返して abandon を見送る。
///
/// 理由: jj コマンド失敗時にうっかり `jj abandon` を走らせると、takt が部分的に
/// amend した child commit ごと消えるリスクがある。「判定不能なら何もしない」方向
/// に倒す。
///
/// 実装: `jj diff --stat` は空 commit でも "0 files changed, ..." のような
/// サマリ行を出力するため空判定に使えない。代わりに jj の `empty` テンプレート
/// keyword を使い、"true"/"false" の明示出力で判定する。
pub(crate) fn diff_at_is_empty() -> bool {
let (ok, out) = run_cmd_direct(
"jj",
&[
"log",
"-r",
"@",
"--no-graph",
"-T",
"if(empty, \"true\", \"false\")",
],
&[],
JJ_CMD_TIMEOUT_SECS,
);
if !ok {
crate::log::log_info(&format!(
"[state] diff_at_is_empty 判定失敗 (diff あり扱いで abandon をスキップ): {}",
out.trim()
));
return false;
}
out.trim() == "true"
}

/// takt ワークフロー実行のデフォルトタイムアウト (10 分)
const TAKT_TIMEOUT_SECS: u64 = 600;

Expand Down
15 changes: 13 additions & 2 deletions src/cli-pr-monitor/src/stages/monitor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::config::load_config;
use crate::fix_commit::{create_fix_commit, FixCommitState};
use crate::log::{log_info, truncate_safe};
use crate::stages::collect::collect_findings;
use crate::stages::poll::run_poll_loop;
Expand Down Expand Up @@ -43,12 +44,18 @@ pub(crate) fn start_monitoring(pr_info: &PrInfo) -> i32 {
let mut takt_succeeded = false;
// takt 実行前の @ commit id (取れない/takt 未実行なら None)。
// 二段構え re-push 判定のため run_takt の前に捕捉する。
// fix commit を pre-create した場合は、この cid は空 child を指す。
let mut pre_takt_cid: Option<String> = None;
// ADR task 4 (2026-04-20): 分離型 fix commit の状態
let mut fix_state = FixCommitState::None;

if has_coderabbit_findings {
if !collect_findings(&poll_result) {
log_info("review-comments.json 書き出し失敗 (takt 分析をスキップ)");
} else if let Some(takt_config) = &config.takt {
// ADR task 4
fix_state = create_fix_commit(pr_info.pr_number, &poll_result.findings);

// Stage 3: takt analysis + fix loop
pre_takt_cid = crate::runner::capture_commit_id();
log_info(&format!("[state] pre_takt_commit_id: {:?}", pre_takt_cid));
Expand All @@ -62,11 +69,15 @@ pub(crate) fn start_monitoring(pr_info: &PrInfo) -> i32 {
}
}

// Stage 4: re-push (二段構え判定)
// Stage 4: re-push (fix_state ごとに分岐)
// 1) commit id 変化 + 実 diff 非空 = HasChange のみ push 対象
// 2) さらに auto_push_severity 設定で自動 push 可否を判定
// 3) fix_state::Created かつ NoChange の場合は空 child を abandon で片付ける
if takt_succeeded && has_coderabbit_findings {
execute_repush_flow(&config.fix, &pr_label, pre_takt_cid.as_deref());
execute_repush_flow(&config.fix, &pr_label, pre_takt_cid.as_deref(), &fix_state);
} else if let FixCommitState::Created { commit_id } = &fix_state {
// takt が実行されなかった / 失敗した場合: 事前に作った fix child を片付ける。
crate::fix_commit::try_abandon_empty_fix_commit("takt 未完了:", Some(commit_id));
}

// Stage 5: report to stdout
Expand Down
Loading