Created
March 22, 2026 01:57
-
-
Save jkoelker/78d05a2bb1543beff864d11d334468bd to your computer and use it in GitHub Desktop.
apply-opencode bounded worker integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fn ticket_section_value(value: &str) -> String { | |
| value.trim().to_string() | |
| } | |
| fn trusted_opencode_target_family(path: &Path) -> bool { | |
| let file_name = path | |
| .file_name() | |
| .and_then(|value| value.to_str()) | |
| .unwrap_or(""); | |
| let first = path | |
| .components() | |
| .next() | |
| .and_then(|component| match component { | |
| Component::Normal(value) => value.to_str(), | |
| _ => None, | |
| }) | |
| .unwrap_or(""); | |
| match first { | |
| "skills" => file_name == "SKILL.md", | |
| "capabilities" => file_name == "README.md" || file_name == "SKILL.md", | |
| _ => false, | |
| } | |
| } | |
| fn opencode_command() -> anyhow::Result<(String, Vec<String>)> { | |
| if let Some(value) = env::var("OPENCODE_BIN") | |
| .ok() | |
| .filter(|value| !value.trim().is_empty()) | |
| { | |
| return Ok((value, Vec::new())); | |
| } | |
| let current_exe = std::env::current_exe() | |
| .context("failed to locate bounded-worker binary for opencode shim")?; | |
| let default_exe = | |
| if current_exe.file_name().and_then(|value| value.to_str()) != Some("bounded-worker") { | |
| current_exe | |
| .parent() | |
| .and_then(Path::parent) | |
| .map(|dir| dir.join("bounded-worker")) | |
| .filter(|path| path.exists()) | |
| .unwrap_or(current_exe) | |
| } else { | |
| current_exe | |
| }; | |
| Ok(( | |
| default_exe.display().to_string(), | |
| vec!["opencode-shim".to_string()], | |
| )) | |
| } | |
| fn opencode_allowed_env(relative_targets: &[String]) -> Vec<(String, String)> { | |
| let mut values = Vec::new(); | |
| for name in ["PATH", "HOME", "TMPDIR"] { | |
| if let Ok(value) = env::var(name) { | |
| if !value.trim().is_empty() { | |
| values.push((name.to_string(), value)); | |
| } | |
| } | |
| } | |
| if let Ok(value) = env::var("OPENCODE_LOG") { | |
| if !value.trim().is_empty() { | |
| values.push(("OPENCODE_LOG".to_string(), value)); | |
| } | |
| } | |
| values.push(( | |
| "FLEET_TARGET_PATHS".to_string(), | |
| relative_targets.join("\n"), | |
| )); | |
| if let Ok(value) = env::var("FLEET_TICKET_ID") { | |
| if !value.trim().is_empty() { | |
| values.push(("FLEET_TICKET_ID".to_string(), value)); | |
| } | |
| } | |
| values | |
| } | |
| fn ticket_managed_block_markers(ticket_id: &str) -> (String, String) { | |
| ( | |
| format!("<!-- fleet:{}:begin -->", ticket_id), | |
| format!("<!-- fleet:{}:end -->", ticket_id), | |
| ) | |
| } | |
| fn managed_block_segments<'a>( | |
| content: &'a str, | |
| ticket_id: &str, | |
| ) -> anyhow::Result<(&'a str, &'a str, &'a str)> { | |
| let (start_marker, end_marker) = ticket_managed_block_markers(ticket_id); | |
| let start = content | |
| .find(&start_marker) | |
| .with_context(|| format!("missing start marker {start_marker}"))?; | |
| let end_rel = content[start..] | |
| .find(&end_marker) | |
| .with_context(|| format!("missing end marker {end_marker}"))?; | |
| let end = start + end_rel + end_marker.len(); | |
| Ok((&content[..start], &content[start..end], &content[end..])) | |
| } | |
| fn managed_block_payload(content: &str, ticket_id: &str) -> anyhow::Result<String> { | |
| let (start_marker, end_marker) = ticket_managed_block_markers(ticket_id); | |
| let (_, block, _) = managed_block_segments(content, ticket_id)?; | |
| let without_start = block | |
| .strip_prefix(&start_marker) | |
| .with_context(|| format!("missing start marker {start_marker}"))?; | |
| let without_end = without_start | |
| .strip_suffix(&end_marker) | |
| .with_context(|| format!("missing end marker {end_marker}"))?; | |
| Ok(without_end.trim().to_string()) | |
| } | |
| fn prepare_trusted_opencode_targets( | |
| ticket_id: &str, | |
| target_paths: &[PathBuf], | |
| ) -> anyhow::Result<Vec<(PathBuf, String)>> { | |
| let mut baseline = Vec::new(); | |
| for target_path in target_paths { | |
| let (start_marker, end_marker) = ticket_managed_block_markers(ticket_id); | |
| if target_path.exists() { | |
| write_ticket_target(target_path, ticket_id, "")?; | |
| } else { | |
| fs::write(target_path, format!("{}\n{}", start_marker, end_marker)) | |
| .with_context(|| format!("failed to seed {}", target_path.display()))?; | |
| } | |
| let content = fs::read_to_string(target_path) | |
| .with_context(|| format!("failed to read {}", target_path.display()))?; | |
| baseline.push((target_path.clone(), content)); | |
| } | |
| Ok(baseline) | |
| } | |
| fn validate_trusted_opencode_targets( | |
| ticket_id: &str, | |
| baseline: &[(PathBuf, String)], | |
| ) -> anyhow::Result<()> { | |
| for (target_path, original) in baseline { | |
| let rewritten = fs::read_to_string(target_path) | |
| .with_context(|| format!("failed to read {}", target_path.display()))?; | |
| let (original_prefix, _, original_suffix) = managed_block_segments(original, ticket_id)?; | |
| let (rewritten_prefix, _, rewritten_suffix) = | |
| managed_block_segments(&rewritten, ticket_id).map_err(|_| { | |
| anyhow::anyhow!( | |
| "trusted opencode adapter modified content outside the managed ticket block for {}", | |
| target_path.display() | |
| ) | |
| })?; | |
| if original_prefix != rewritten_prefix || original_suffix != rewritten_suffix { | |
| anyhow::bail!( | |
| "trusted opencode adapter modified content outside the managed ticket block for {}", | |
| target_path.display() | |
| ); | |
| } | |
| let original_payload = managed_block_payload(original, ticket_id)?; | |
| let rewritten_payload = managed_block_payload(&rewritten, ticket_id)?; | |
| if rewritten_payload.is_empty() { | |
| anyhow::bail!( | |
| "trusted opencode adapter did not write content inside the managed ticket block for {}", | |
| target_path.display() | |
| ); | |
| } | |
| if rewritten_payload == original_payload { | |
| anyhow::bail!( | |
| "trusted opencode adapter did not change the managed ticket block for {}", | |
| target_path.display() | |
| ); | |
| } | |
| } | |
| Ok(()) | |
| } | |
| fn build_opencode_apply_prompt( | |
| ticket: &TicketDocument, | |
| repo_dir: &Path, | |
| target_paths: &[PathBuf], | |
| ) -> anyhow::Result<String> { | |
| let relative_targets = target_paths | |
| .iter() | |
| .map(|path| { | |
| path.strip_prefix(repo_dir) | |
| .map(|value| value.display().to_string()) | |
| .with_context(|| format!("{} did not live under repo root", path.display())) | |
| }) | |
| .collect::<anyhow::Result<Vec<_>>>()?; | |
| let target_capability = ticket | |
| .front_matter | |
| .improvement_target_capability | |
| .as_deref() | |
| .unwrap_or("unspecified"); | |
| let target_skill = ticket | |
| .front_matter | |
| .improvement_target_skill | |
| .as_deref() | |
| .unwrap_or("unspecified"); | |
| let change_kinds = if ticket.front_matter.improvement_change_kinds.is_empty() { | |
| "unspecified".to_string() | |
| } else { | |
| ticket.front_matter.improvement_change_kinds.join(", ") | |
| }; | |
| Ok(format!( | |
| "You are applying a bounded Fleet self-improvement ticket inside the checked out repository.\n\nTicket ID: {}\nTicket title: {}\nTarget capability: {}\nTarget skill: {}\nChange kinds: {}\nAllowed targets: {}\n\nProblem statement:\n{}\n\nProposed approach:\n{}\n\nTesting notes:\n{}\n\nOpen questions:\n{}\n\nInstructions:\n- Edit only the allowed target files listed above.\n- Edit only inside the existing Fleet-managed block markers for this ticket: {} / {}.\n- Preserve any content outside those markers exactly.\n- Keep changes deterministic and minimal.\n- Do not create or edit files outside the allowed target list.\n- Focus on improving SKILL.md or capability-pack guidance using the ticket context.\n- Do not use network access.\n- Stop after making the bounded file updates.\n", | |
| ticket.front_matter.id, | |
| ticket.front_matter.title, | |
| target_capability, | |
| target_skill, | |
| change_kinds, | |
| relative_targets.join(", "), | |
| ticket_section_value(&ticket.sections.problem_statement), | |
| ticket_section_value(&ticket.sections.proposed_approach), | |
| ticket_section_value(&ticket.sections.testing_notes), | |
| ticket_section_value(&ticket.sections.open_questions), | |
| ticket_managed_block_markers(&ticket.front_matter.id).0, | |
| ticket_managed_block_markers(&ticket.front_matter.id).1, | |
| )) | |
| } | |
| pub fn apply_ticket_with_opencode(ticket_path: &Path, repo_dir: &Path) -> anyhow::Result<PathBuf> { | |
| let task_context = load_task_context_bundle(false)?; | |
| let markdown = fs::read_to_string(ticket_path) | |
| .with_context(|| format!("failed to read {}", ticket_path.display()))?; | |
| let ticket = TicketDocument::from_markdown(&markdown)?; | |
| let target_paths = preferred_apply_target_paths(&ticket, repo_dir)?; | |
| if target_paths.is_empty() { | |
| anyhow::bail!( | |
| "improvement ticket {} is missing structured target paths for opencode execution", | |
| ticket.front_matter.id | |
| ); | |
| } | |
| if target_paths.iter().any(|path| { | |
| path.strip_prefix(repo_dir) | |
| .map(|relative| !trusted_opencode_target_family(relative)) | |
| .unwrap_or(true) | |
| }) { | |
| anyhow::bail!( | |
| "opencode adapter only supports trusted SKILL.md / capability-pack doc targets" | |
| ); | |
| } | |
| for target_path in &target_paths { | |
| if let Some(parent) = target_path.parent() { | |
| fs::create_dir_all(parent) | |
| .with_context(|| format!("failed to create {}", parent.display()))?; | |
| } | |
| } | |
| let baseline = prepare_trusted_opencode_targets(&ticket.front_matter.id, &target_paths)?; | |
| let prompt = build_opencode_apply_prompt(&ticket, repo_dir, &target_paths)?; | |
| let relative_targets = target_paths | |
| .iter() | |
| .map(|path| { | |
| path.strip_prefix(repo_dir) | |
| .map(|value| value.display().to_string()) | |
| .with_context(|| format!("{} did not live under repo root", path.display())) | |
| }) | |
| .collect::<anyhow::Result<Vec<_>>>()?; | |
| unsafe { | |
| env::set_var("FLEET_TICKET_ID", &ticket.front_matter.id); | |
| } | |
| let (opencode_bin, opencode_prefix_args) = opencode_command()?; | |
| let status = Command::new(opencode_bin) | |
| .current_dir(repo_dir) | |
| .env_clear() | |
| .envs(opencode_allowed_env(&relative_targets)) | |
| .args(opencode_prefix_args) | |
| .arg("run") | |
| .arg("--format") | |
| .arg("json") | |
| .arg(prompt) | |
| .status() | |
| .context("failed to launch opencode adapter")?; | |
| unsafe { | |
| env::remove_var("FLEET_TICKET_ID"); | |
| } | |
| if !status.success() { | |
| anyhow::bail!("opencode adapter exited with status {status}"); | |
| } | |
| validate_trusted_opencode_targets(&ticket.front_matter.id, &baseline)?; | |
| let summary_path = repo_dir.join("job-summary.txt"); | |
| let mut summary = format!( | |
| "ticket_id={}\nresult=updated_runtime_repo\nadapter=opencode\n", | |
| ticket.front_matter.id | |
| ); | |
| if let Ok(value) = target_paths[0].strip_prefix(repo_dir) { | |
| summary.push_str(&format!("target_path={}\n", value.display())); | |
| } | |
| summary.push_str(&format!("target_paths={}\n", relative_targets.join(","))); | |
| if !ticket.front_matter.improvement_change_kinds.is_empty() { | |
| summary.push_str(&format!( | |
| "change_kinds={}\n", | |
| ticket.front_matter.improvement_change_kinds.join(",") | |
| )); | |
| } | |
| if let Some(value) = ticket.front_matter.improvement_target_capability.as_deref() { | |
| summary.push_str(&format!("target_capability={}\n", value)); | |
| } | |
| if let Some(value) = ticket.front_matter.improvement_target_skill.as_deref() { | |
| summary.push_str(&format!("target_skill={}\n", value)); | |
| } | |
| append_context_summary(&mut summary, task_context.as_ref()); | |
| fs::write(&summary_path, summary) | |
| .with_context(|| format!("failed to write {}", summary_path.display()))?; | |
| Ok(target_paths[0].clone()) | |
| } | |
| pub fn run_opencode_shim(prompt: &str) -> anyhow::Result<()> { | |
| let ticket_id = env::var("FLEET_TICKET_ID").context("missing FLEET_TICKET_ID")?; | |
| let target_paths = env::var("FLEET_TARGET_PATHS") | |
| .context("missing FLEET_TARGET_PATHS")? | |
| .lines() | |
| .map(str::trim) | |
| .filter(|value| !value.is_empty()) | |
| .map(ToString::to_string) | |
| .collect::<Vec<_>>(); | |
| if target_paths.is_empty() { | |
| anyhow::bail!("opencode shim received no target paths"); | |
| } | |
| let prompt_summary = prompt | |
| .lines() | |
| .next() | |
| .unwrap_or("bounded opencode shim update") | |
| .trim(); | |
| for path in target_paths { | |
| let target = PathBuf::from(&path); | |
| let content = fs::read_to_string(&target) | |
| .with_context(|| format!("failed to read {}", target.display()))?; | |
| let (start_marker, end_marker) = ticket_managed_block_markers(&ticket_id); | |
| let replacement = format!( | |
| "{start_marker}\n# Fleet Managed Update\nsource_prompt: {}\ntarget_path: {}\n{end_marker}", | |
| prompt_summary, | |
| path | |
| ); | |
| let (before, _) = content.split_once(&start_marker).with_context(|| { | |
| format!( | |
| "missing start marker {start_marker} in {}", | |
| target.display() | |
| ) | |
| })?; | |
| let (_, after) = content | |
| .split_once(&end_marker) | |
| .with_context(|| format!("missing end marker {end_marker} in {}", target.display()))?; | |
| fs::write(&target, format!("{before}{replacement}{after}")) | |
| .with_context(|| format!("failed to write {}", target.display()))?; | |
| } | |
| Ok(()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment