Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ plan-to-git show
plan-to-git render
plan-to-git sync
plan-to-git sync --pr 7
plan-to-git --repo owner/repo sync --pr 7
plan-to-git import-codex --dry-run
plan-to-git import-codex
plan-to-git import-claude --dry-run
Expand Down Expand Up @@ -103,6 +104,8 @@ When `gh pr view` finds an open, non-draft PR for the current branch, `plan-to-g

Use `plan-to-git sync --pr 7` to post queued current-branch items to a specific pull request instead of relying on branch-based PR discovery. `sync` is source-agnostic: one run posts all unposted current-branch items in the state file, whether they came from Codex, Claude Code, or another supported agent.

Use `--repo owner/repo` or `PLAN_TO_GIT_REPO=owner/repo` when the local `origin` remote is not the pull request target repository, for example in fork-origin workflows. The explicit repository only selects the GitHub PR/comment target; local state and history matching remain tied to the current checkout.

The PR description is not edited. Closed, merged, or still-draft pull requests are not commented on; new items stay queued until the PR is valid (open and marked ready for review). After a comment is created, the local state file records the posted item hashes and GitHub comment id so repeated `sync`, `hook`, `import-codex`, or `import-claude` runs do not post the same plan again, including on a later PR.

## Safety
Expand Down
3 changes: 3 additions & 0 deletions changelog.d/20260617_explicit_repo_context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- Added `--repo` / `PLAN_TO_GIT_REPO` explicit GitHub repository context for hook, import, sync, show, render, and clear commands so fork-origin workflows can post plan comments to the upstream repository without mutating git remote configuration.
23 changes: 20 additions & 3 deletions src/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ struct ClaudeHookInput {
}

pub fn process_codex_hook(input: &str) -> AppResult<HookOutcome> {
process_codex_hook_with_repo(input, None)
}

pub fn process_codex_hook_with_repo(
input: &str,
target_repo: Option<&str>,
) -> AppResult<HookOutcome> {
let hook_input: CodexHookInput = serde_json::from_str(input)?;
process_agent_hook(&AgentHookInput {
source: AgentSource::Codex,
Expand All @@ -64,10 +71,18 @@ pub fn process_codex_hook(input: &str) -> AppResult<HookOutcome> {
prompt: hook_input.prompt,
last_assistant_message: hook_input.last_assistant_message,
transcript_path: None,
target_repo,
})
}

pub fn process_claude_hook(input: &str) -> AppResult<HookOutcome> {
process_claude_hook_with_repo(input, None)
}

pub fn process_claude_hook_with_repo(
input: &str,
target_repo: Option<&str>,
) -> AppResult<HookOutcome> {
let hook_input: ClaudeHookInput = serde_json::from_str(input)?;
process_agent_hook(&AgentHookInput {
source: AgentSource::Claude,
Expand All @@ -78,10 +93,11 @@ pub fn process_claude_hook(input: &str) -> AppResult<HookOutcome> {
prompt: hook_input.prompt,
last_assistant_message: hook_input.last_assistant_message,
transcript_path: hook_input.transcript_path,
target_repo,
})
}

struct AgentHookInput {
struct AgentHookInput<'a> {
source: AgentSource,
session_id: Option<String>,
cwd: Option<PathBuf>,
Expand All @@ -90,9 +106,10 @@ struct AgentHookInput {
prompt: Option<String>,
last_assistant_message: Option<String>,
transcript_path: Option<PathBuf>,
target_repo: Option<&'a str>,
}

fn process_agent_hook(hook_input: &AgentHookInput) -> AppResult<HookOutcome> {
fn process_agent_hook(hook_input: &AgentHookInput<'_>) -> AppResult<HookOutcome> {
let start_dir = hook_input.cwd.as_deref().unwrap_or_else(|| Path::new("."));
let context = git::discover(start_dir)?;
let state_path = state_path::state_path(&context);
Expand Down Expand Up @@ -200,7 +217,7 @@ fn process_agent_hook(hook_input: &AgentHookInput) -> AppResult<HookOutcome> {
save_state(&state_path, &state)?;
}

let sync_status = github::sync_state(&context, &mut state)?;
let sync_status = github::sync_state(&context, &mut state, hook_input.target_repo)?;
if changed || !state.items.is_empty() || !state.pending_questions.is_empty() {
save_state(&state_path, &state)?;
}
Expand Down
5 changes: 5 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ pub fn parse_github_slug(remote: &str) -> Option<String> {
None
}

#[must_use]
pub fn parse_github_slug_or_slug(value: &str) -> Option<String> {
parse_github_slug(value).or_else(|| normalize_slug(value.trim()))
}

fn normalize_slug(path: &str) -> Option<String> {
let mut parts = path.split('/');
let owner = parts.next()?;
Expand Down
55 changes: 37 additions & 18 deletions src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,35 +44,41 @@ struct IssueComment {
id: u64,
}

pub fn sync_state(context: &GitContext, state: &mut AgentPlanState) -> AppResult<SyncStatus> {
pub fn sync_state(
context: &GitContext,
state: &mut AgentPlanState,
target_repo: Option<&str>,
) -> AppResult<SyncStatus> {
if !state.has_current_branch_items() {
return Ok(SyncStatus::NoItems);
}

let Some(pull_request) = view_current_pr(&context.repo_root)? else {
let Some(pull_request) = view_current_pr(&context.repo_root, target_repo)? else {
return Ok(SyncStatus::NoPullRequest);
};

sync_to_pull_request(context, state, pull_request)
sync_to_pull_request(context, state, pull_request, target_repo)
}

pub fn sync_state_to_pr(
context: &GitContext,
state: &mut AgentPlanState,
number: u64,
target_repo: Option<&str>,
) -> AppResult<SyncStatus> {
if !state.has_current_branch_items() {
return Ok(SyncStatus::NoItems);
}

let pull_request = view_pr(&context.repo_root, number)?;
sync_to_pull_request(context, state, pull_request)
let pull_request = view_pr(&context.repo_root, number, target_repo)?;
sync_to_pull_request(context, state, pull_request, target_repo)
}

fn sync_to_pull_request(
context: &GitContext,
state: &mut AgentPlanState,
pull_request: PullRequest,
target_repo: Option<&str>,
) -> AppResult<SyncStatus> {
if !pull_request.state.eq_ignore_ascii_case("OPEN") {
return Ok(SyncStatus::ClosedPullRequest {
Expand All @@ -97,7 +103,8 @@ fn sync_to_pull_request(
(render_plan_comment(state, &items), item_ids, items.len())
};

let comment_id = create_issue_comment(context, pull_request.number, &comment_body)?;
let comment_id =
create_issue_comment(context, pull_request.number, &comment_body, target_repo)?;
state.mark_items_commented(pull_request.number, &item_ids, Some(comment_id));

Ok(SyncStatus::Commented {
Expand All @@ -107,11 +114,15 @@ fn sync_to_pull_request(
})
}

fn view_current_pr(repo_root: &Path) -> AppResult<Option<PullRequest>> {
let output = Command::new("gh")
fn view_current_pr(repo_root: &Path, target_repo: Option<&str>) -> AppResult<Option<PullRequest>> {
let mut command = Command::new("gh");
command
.current_dir(repo_root)
.args(["pr", "view", "--json", "number,state,url,isDraft"])
.output()?;
.args(["pr", "view", "--json", "number,state,url,isDraft"]);
if let Some(target_repo) = target_repo {
command.args(["--repo", target_repo]);
}
let output = command.output()?;

if output.status.success() {
return Ok(Some(serde_json::from_slice(&output.stdout)?));
Expand All @@ -125,13 +136,17 @@ fn view_current_pr(repo_root: &Path) -> AppResult<Option<PullRequest>> {
Err(AppError::new(format!("gh pr view failed: {stderr}")).into())
}

fn view_pr(repo_root: &Path, number: u64) -> AppResult<PullRequest> {
let output = Command::new("gh")
fn view_pr(repo_root: &Path, number: u64, target_repo: Option<&str>) -> AppResult<PullRequest> {
let mut command = Command::new("gh");
command
.current_dir(repo_root)
.args(["pr", "view"])
.arg(number.to_string())
.args(["--json", "number,state,url,isDraft"])
.output()?;
.args(["--json", "number,state,url,isDraft"]);
if let Some(target_repo) = target_repo {
command.args(["--repo", target_repo]);
}
let output = command.output()?;

if output.status.success() {
return Ok(serde_json::from_slice(&output.stdout)?);
Expand All @@ -141,10 +156,14 @@ fn view_pr(repo_root: &Path, number: u64) -> AppResult<PullRequest> {
Err(AppError::new(format!("gh pr view {number} failed: {stderr}")).into())
}

fn create_issue_comment(context: &GitContext, number: u64, body: &str) -> AppResult<u64> {
let repo_slug = context
.repo_slug
.as_deref()
fn create_issue_comment(
context: &GitContext,
number: u64,
body: &str,
target_repo: Option<&str>,
) -> AppResult<u64> {
let repo_slug = target_repo
.or(context.repo_slug.as_deref())
.ok_or_else(|| AppError::new("cannot sync PR comments without a GitHub origin remote"))?;
let request_file = temp_request_path();
let request = serde_json::json!({ "body": body });
Expand Down
38 changes: 27 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use plan_to_git::capture;
use plan_to_git::claude_history;
use plan_to_git::codex_history;
use plan_to_git::error::{AppError, AppResult};
use plan_to_git::git;
use plan_to_git::git::{self, parse_github_slug_or_slug};
use plan_to_git::github::{self, SyncStatus};
use plan_to_git::history::HistoryImportOutcome;
use plan_to_git::render::render_plan_comment;
Expand All @@ -20,6 +20,9 @@ use plan_to_git::store::{load_state, save_state, STATE_FILE_NAME};
about = "Capture agent plans and sync them to GitHub pull requests"
)]
struct Cli {
/// Target GitHub repository for state and PR comments. Accepts owner/repo or a GitHub URL.
#[arg(long, env = "PLAN_TO_GIT_REPO", global = true)]
repo: Option<String>,
#[command(subcommand)]
command: Commands,
}
Expand Down Expand Up @@ -85,20 +88,21 @@ fn main() {

match &cli.command {
Commands::Hook { source } => {
if let Err(error) = run_hook(*source) {
if let Err(error) = run_hook(*source, cli.repo.as_deref()) {
eprintln!("plan-to-git hook error: {error}");
}
}
command => {
if let Err(error) = run(command) {
if let Err(error) = run(command, cli.repo.as_deref()) {
eprintln!("plan-to-git error: {error}");
std::process::exit(1);
}
}
}
}

fn run(command: &Commands) -> AppResult<()> {
fn run(command: &Commands, repo_slug_override: Option<&str>) -> AppResult<()> {
let target_repo = target_repo(repo_slug_override)?;
match command {
Commands::Hook { .. } => Ok(()),
Commands::ImportCodex {
Expand Down Expand Up @@ -130,7 +134,7 @@ fn run(command: &Commands) -> AppResult<()> {
return Ok(());
}

let sync_status = github::sync_state(&context, &mut state)?;
let sync_status = github::sync_state(&context, &mut state, target_repo.as_deref())?;
save_state(&state_path, &state)?;
print_sync_status(&sync_status);
Ok(())
Expand Down Expand Up @@ -165,7 +169,7 @@ fn run(command: &Commands) -> AppResult<()> {
return Ok(());
}

let sync_status = github::sync_state(&context, &mut state)?;
let sync_status = github::sync_state(&context, &mut state, target_repo.as_deref())?;
save_state(&state_path, &state)?;
print_sync_status(&sync_status);
Ok(())
Expand All @@ -179,9 +183,9 @@ fn run(command: &Commands) -> AppResult<()> {
context.head_sha.clone(),
);
let sync_status = if let Some(pr_number) = pr {
github::sync_state_to_pr(&context, &mut state, *pr_number)?
github::sync_state_to_pr(&context, &mut state, *pr_number, target_repo.as_deref())?
} else {
github::sync_state(&context, &mut state)?
github::sync_state(&context, &mut state, target_repo.as_deref())?
};
save_state(&state_path, &state)?;
print_sync_status(&sync_status);
Expand Down Expand Up @@ -216,13 +220,14 @@ fn run(command: &Commands) -> AppResult<()> {
}
}

fn run_hook(source: HookSource) -> AppResult<()> {
fn run_hook(source: HookSource, repo_slug_override: Option<&str>) -> AppResult<()> {
let target_repo = target_repo(repo_slug_override)?;
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;

match source {
HookSource::Codex => {
let outcome = capture::process_codex_hook(&input)?;
let outcome = capture::process_codex_hook_with_repo(&input, target_repo.as_deref())?;
eprintln!(
"plan-to-git: captured {} plan(s), {} decision(s), {} pending question set(s), sync={:?}",
outcome.captured_plans,
Expand All @@ -232,7 +237,7 @@ fn run_hook(source: HookSource) -> AppResult<()> {
);
}
HookSource::Claude => {
let outcome = capture::process_claude_hook(&input)?;
let outcome = capture::process_claude_hook_with_repo(&input, target_repo.as_deref())?;
eprintln!(
"plan-to-git: captured {} plan(s), {} decision(s), {} pending question set(s), sync={:?}",
outcome.captured_plans,
Expand All @@ -253,6 +258,17 @@ fn state_context() -> AppResult<(git::GitContext, std::path::PathBuf)> {
Ok((context, state_path))
}

fn target_repo(repo_slug_override: Option<&str>) -> AppResult<Option<String>> {
repo_slug_override.map_or(Ok(None), |repo| {
let repo_slug = parse_github_slug_or_slug(repo).ok_or_else(|| {
AppError::new(format!(
"expected GitHub repository as owner/repo or GitHub URL, got {repo}"
))
})?;
Ok(Some(repo_slug))
})
}

fn print_sync_status(status: &SyncStatus) {
match status {
SyncStatus::NoItems => println!("no captured plan items to sync"),
Expand Down
11 changes: 3 additions & 8 deletions src/normalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,17 +223,12 @@ fn find_ascii_case_insensitive(haystack: &str, needle: &str, from: usize) -> Opt

let haystack = haystack.as_bytes();
let needle = needle.as_bytes();
for index in from..=haystack.len().saturating_sub(needle.len()) {
if haystack[index..index + needle.len()]
(from..=haystack.len().saturating_sub(needle.len())).find(|&index| {
haystack[index..index + needle.len()]
.iter()
.zip(needle.iter())
.all(|(candidate, expected)| candidate.eq_ignore_ascii_case(expected))
{
return Some(index);
}
}

None
})
}

fn closes_plan_block(message: &str, close_tag_end: usize) -> bool {
Expand Down
Loading
Loading