1mod pr;
11mod push;
12
13use super::commit;
14use crate::github::token;
15use crate::sys::cmd::CommandErrorContext;
16use std::ffi::OsStr;
17use std::io;
18use std::path::Path;
19use std::process::Output;
20use std::time::Duration;
21
22pub use pr::create_pr_if_needed;
23pub(crate) use pr::{
24 is_invalid_base_error, is_transient_github_api_error, is_transient_github_error,
25};
26pub(crate) use push::{
27 clear_push_lease, force_push_leased, record_push_lease, sanitize_git_output,
28 sanitize_push_error,
29};
30pub use push::{
31 is_large_file_error, is_missing_remote_ref_error, is_transient_network_error, large_file_lines,
32 push_branch,
33};
34use tokio::process::Command;
35use tokio::time;
36
37pub(crate) fn format_task_ref(task_id: &str) -> String {
43 if task_id.starts_with("internal:") {
44 task_id.replace(':', "-")
45 } else {
46 format!("#{task_id}")
47 }
48}
49
50#[derive(Debug, thiserror::Error)]
52pub enum PrCreateError {
53 #[error("GitHub API error: {0}")]
54 ApiError(#[from] anyhow::Error),
55}
56
57pub type PrCreateResult<T> = Result<T, PrCreateError>;
59
60pub(crate) fn find_stash_ref_by_hash(stash_list: &str, stash_hash: &str) -> Option<String> {
61 stash_list.lines().find_map(|line| {
62 let mut parts = line.split_whitespace();
63 match (parts.next(), parts.next()) {
64 (Some(hash), Some(reference)) if hash == stash_hash => Some(reference.to_string()),
65 _ => None,
66 }
67 })
68}
69
70pub(crate) struct StashRebaseOpts {
72 pub abort_on_failure: bool,
76}
77
78impl Default for StashRebaseOpts {
79 fn default() -> Self {
80 Self {
81 abort_on_failure: true,
82 }
83 }
84}
85
86#[derive(Debug)]
88pub(crate) enum RebaseOutcome {
89 Succeeded,
91 Failed(String),
95 Skipped(String),
98}
99
100pub(crate) async fn stash_rebase_restore(
117 dir: &Path,
118 target_ref: &str,
119 opts: StashRebaseOpts,
120) -> anyhow::Result<RebaseOutcome> {
121 let stash_ref: Option<String> = if commit::has_changes(dir).await {
122 let stash_out = Command::new("git")
123 .args(["stash", "push", "--include-untracked", "-m", "orch-rebase"])
124 .current_dir(dir)
125 .output_with_context()
126 .await;
127
128 match stash_out {
129 Ok(o) if o.status.success() => {
130 let stdout_preview = String::from_utf8_lossy(&o.stdout)
131 .lines()
132 .next()
133 .unwrap_or("")
134 .to_string();
135 tracing::debug!(
136 dir = %dir.display(),
137 stdout = %stdout_preview,
138 "git stash push succeeded before rebase"
139 );
140
141 let ref_out = Command::new("git")
145 .args(["rev-parse", "refs/stash@{0}"])
146 .current_dir(dir)
147 .output_with_context()
148 .await;
149 let stash_hash = ref_out
150 .ok()
151 .filter(|o| o.status.success())
152 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
153 .filter(|s| !s.is_empty());
154
155 if stash_hash.is_none() {
156 tracing::warn!(
159 dir = %dir.display(),
160 "git stash succeeded but rev-parse failed — popping stash and skipping rebase"
161 );
162 let _ = Command::new("git")
163 .args(["stash", "pop"])
164 .current_dir(dir)
165 .output_with_context()
166 .await;
167 return Ok(RebaseOutcome::Skipped(
168 "stash OID capture failed".to_string(),
169 ));
170 }
171 stash_hash
172 }
173 Ok(o) => {
174 let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
175 tracing::warn!(
176 dir = %dir.display(),
177 code = ?o.status.code(),
178 stderr = %stderr,
179 "git stash push failed — skipping rebase to preserve dirty state"
180 );
181 return Ok(RebaseOutcome::Skipped(format!(
182 "stash push failed: {stderr}"
183 )));
184 }
185 Err(e) => {
186 tracing::warn!(
187 dir = %dir.display(),
188 error = %e,
189 "failed to run git stash push — skipping rebase to preserve dirty state"
190 );
191 return Ok(RebaseOutcome::Skipped(format!("stash push error: {e}")));
192 }
193 }
194 } else {
195 None
196 };
197
198 let output = git()
199 .await
200 .args(["rebase", target_ref])
201 .current_dir(dir)
202 .output_with_context()
203 .await;
204
205 match output {
206 Ok(o) if o.status.success() => {
207 tracing::debug!(dir = %dir.display(), target_ref, "rebase succeeded");
208 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
209 Ok(RebaseOutcome::Succeeded)
210 }
211 Ok(o) => {
212 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
213 tracing::warn!(dir = %dir.display(), target_ref, err = %stderr, "rebase failed");
214 if opts.abort_on_failure {
215 let abort = Command::new("git")
216 .args(["rebase", "--abort"])
217 .current_dir(dir)
218 .output_with_context()
219 .await;
220 match abort {
221 Err(e) => {
222 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
223 }
224 Ok(o) if !o.status.success() => {
225 let stderr = String::from_utf8_lossy(&o.stderr);
226 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
227 }
228 _ => {}
229 }
230 }
231 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
232 Ok(RebaseOutcome::Failed(stderr))
233 }
234 Err(e) => {
235 if opts.abort_on_failure {
236 let abort = Command::new("git")
237 .args(["rebase", "--abort"])
238 .current_dir(dir)
239 .output_with_context()
240 .await;
241 match abort {
242 Err(e) => {
243 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
244 }
245 Ok(o) if !o.status.success() => {
246 let stderr = String::from_utf8_lossy(&o.stderr);
247 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
248 }
249 _ => {}
250 }
251 }
252 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
253 Err(e)
254 }
255 }
256}
257
258async fn restore_stash_by_hash(dir: &Path, stash_hash: Option<&str>) {
262 let Some(stash_hash) = stash_hash else {
263 return;
264 };
265
266 let apply = Command::new("git")
267 .args(["stash", "apply", stash_hash])
268 .current_dir(dir)
269 .output_with_context()
270 .await;
271 if apply.is_ok_and(|o| o.status.success()) {
272 let list = Command::new("git")
273 .args(["stash", "list", "--format=%H %gd"])
274 .current_dir(dir)
275 .output_with_context()
276 .await;
277 if let Ok(list_out) = list
278 && list_out.status.success()
279 {
280 let list_str = String::from_utf8_lossy(&list_out.stdout);
281 if let Some(stash_ref) = find_stash_ref_by_hash(&list_str, stash_hash) {
282 match Command::new("git")
283 .args(["stash", "drop", &stash_ref])
284 .current_dir(dir)
285 .output_with_context()
286 .await
287 {
288 Ok(drop_out) if !drop_out.status.success() => {
289 let stderr = String::from_utf8_lossy(&drop_out.stderr);
290 tracing::warn!(
291 dir = %dir.display(),
292 stash_ref = %stash_ref,
293 err = %stderr,
294 "stash drop failed after apply — entry may remain on stack"
295 );
296 }
297 Err(e) => {
298 tracing::warn!(
299 dir = %dir.display(),
300 stash_ref = %stash_ref,
301 error = %e,
302 "stash drop command failed after apply — entry may remain on stack"
303 );
304 }
305 _ => {}
306 }
307 } else {
308 tracing::warn!(
309 dir = %dir.display(),
310 stash = %stash_hash,
311 "stash applied but could not find ref by hash — stash entry may be orphaned on stack"
312 );
313 }
314 }
315 } else {
316 tracing::warn!(
317 dir = %dir.display(),
318 stash = %stash_hash,
319 "stash apply failed after rebase — stash preserved for manual recovery"
320 );
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct AutoCommit {
327 pub committed: bool,
328 pub skipped_oversized: Vec<String>,
329}
330
331pub async fn auto_commit(
333 dir: &Path,
334 task_id: &str,
335 title: &str,
336 agent: &str,
337 attempt: u32,
338 when: commit::When,
339) -> anyhow::Result<AutoCommit> {
340 if !commit::has_changes(dir).await {
341 return Ok(AutoCommit {
342 committed: false,
343 skipped_oversized: Vec::new(),
344 });
345 }
346
347 tracing::info!(task_id, "auto-committing uncommitted changes");
348 let task_ref = format_task_ref(task_id);
349 let message = format!("{title}\n\nTask {task_ref}\nAgent: {agent}\nAttempt: {attempt}");
350 match commit::commit_all(dir, &message, agent, when).await? {
351 commit::Outcome::Committed { skipped_oversized } => {
352 tracing::info!(task_id, "auto-commit succeeded");
353 Ok(AutoCommit {
354 committed: true,
355 skipped_oversized,
356 })
357 }
358 commit::Outcome::Nothing { skipped_oversized } => Ok(AutoCommit {
359 committed: false,
360 skipped_oversized,
361 }),
362 commit::Outcome::Refused {
363 by: commit::Tool::Git,
364 reason,
365 } => {
366 tracing::warn!(task_id, err = %reason, "git commit failed");
367 Ok(AutoCommit {
368 committed: false,
369 skipped_oversized: Vec::new(),
370 })
371 }
372 commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
373 }
374}
375
376const MAX_REBASE_COMMITS: usize = 50;
384
385pub async fn rebase_on_branch(dir: &Path, branch: &str) -> anyhow::Result<bool> {
395 let origin_branch = format!("origin/{branch}");
396
397 let fetch = time::timeout(
400 Duration::from_secs(120),
401 git()
402 .await
403 .args(["fetch", "origin", branch])
404 .kill_on_drop(true)
405 .current_dir(dir)
406 .output(),
407 )
408 .await
409 .map_err(|_| anyhow::anyhow!("git fetch timed out after 120s"))
410 .and_then(|r| r.map_err(Into::into));
411
412 match fetch {
413 Ok(o) if o.status.success() => {}
414 Ok(o) => {
415 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
416 anyhow::bail!("failed to fetch origin/{branch}: {stderr}");
417 }
418 Err(e) => anyhow::bail!("failed to fetch origin/{branch}: {e}"),
419 }
420
421 let count_output = Command::new("git")
423 .args(["rev-list", "--count", &format!("{origin_branch}..HEAD")])
424 .current_dir(dir)
425 .output_with_context()
426 .await;
427
428 let commit_count: usize = match count_output {
429 Ok(o) if o.status.success() => {
430 let raw = String::from_utf8_lossy(&o.stdout);
431 raw.trim().parse().map_err(|e| {
432 anyhow::anyhow!(
433 "failed to parse commit count from git rev-list output {:?}: {e}",
434 raw.trim()
435 )
436 })?
437 }
438 Ok(o) => {
439 let stderr = String::from_utf8_lossy(&o.stderr);
440 anyhow::bail!("git rev-list --count failed: {stderr}");
441 }
442 Err(e) => anyhow::bail!("failed to run git rev-list --count: {e}"),
443 };
444
445 if commit_count == 0 {
446 return Ok(false);
448 }
449
450 if commit_count > MAX_REBASE_COMMITS {
451 anyhow::bail!(
452 "refusing to rebase {commit_count} commits on origin/{branch} (max {MAX_REBASE_COMMITS})"
453 );
454 }
455
456 tracing::info!(
457 branch = branch,
458 commit_count,
459 "rebasing local commits on origin/{branch}"
460 );
461
462 match stash_rebase_restore(dir, &origin_branch, StashRebaseOpts::default()).await? {
463 RebaseOutcome::Succeeded => Ok(true),
464 RebaseOutcome::Failed(e) => anyhow::bail!("rebase failed: {e}"),
465 RebaseOutcome::Skipped(reason) => anyhow::bail!("rebase skipped: {reason}"),
466 }
467}
468
469pub async fn rebase_on_default(dir: &Path, default_branch: &str) {
477 if rebase_in_progress(dir).await {
479 tracing::info!("rebase already in progress, skipping pre-dispatch rebase");
480 return;
481 }
482
483 let branch = get_current_branch(dir).await;
485 record_push_lease(dir, &branch, default_branch).await;
486
487 let _ = git()
490 .await
491 .args(["fetch", "origin"])
492 .current_dir(dir)
493 .output_with_context()
494 .await;
495
496 let commit_count = Command::new("git")
501 .args([
502 "rev-list",
503 "--count",
504 &format!("origin/{default_branch}..HEAD"),
505 ])
506 .current_dir(dir)
507 .output_with_context()
508 .await
509 .ok()
510 .and_then(|o| {
511 String::from_utf8_lossy(&o.stdout)
512 .trim()
513 .parse::<usize>()
514 .ok()
515 })
516 .unwrap_or(0);
517
518 if commit_count > MAX_REBASE_COMMITS {
519 tracing::warn!(
520 default_branch,
521 commit_count,
522 max = MAX_REBASE_COMMITS,
523 "skipping rebase: branch has too many commits to replay safely"
524 );
525 return;
526 }
527
528 match stash_rebase_restore(
529 dir,
530 &format!("origin/{default_branch}"),
531 StashRebaseOpts::default(),
532 )
533 .await
534 {
535 Ok(RebaseOutcome::Succeeded) => {
536 tracing::debug!(default_branch, "rebased worktree on default branch");
537 }
538 Ok(RebaseOutcome::Failed(e)) => {
539 tracing::warn!(default_branch, err = %e, "rebase failed, continuing with current state");
540 }
541 Ok(RebaseOutcome::Skipped(reason)) => {
542 tracing::warn!(default_branch, %reason, "stash failed before rebase, continuing with current state");
543 }
544 Err(e) => tracing::warn!(err = %e, "rebase error"),
545 }
546}
547
548pub(crate) async fn rebase_in_progress(dir: &Path) -> bool {
549 for name in ["rebase-merge", "rebase-apply"] {
550 let out = Command::new("git")
551 .args(["rev-parse", "--git-path", name])
552 .current_dir(dir)
553 .output_with_context()
554 .await;
555 if let Ok(o) = out {
556 let p = String::from_utf8_lossy(&o.stdout).trim().to_string();
557 if !p.is_empty() && dir.join(p).exists() {
558 return true;
559 }
560 }
561 }
562 false
563}
564
565pub(crate) struct GitCommand {
567 inner: Command,
568}
569
570impl GitCommand {
571 pub(crate) fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
572 self.inner.arg(arg);
573 self
574 }
575
576 pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Self
577 where
578 I: IntoIterator<Item = S>,
579 S: AsRef<OsStr>,
580 {
581 self.inner.args(args);
582 self
583 }
584
585 pub(crate) fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
586 self.inner.current_dir(dir);
587 self
588 }
589
590 pub(crate) fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
591 where
592 K: AsRef<OsStr>,
593 V: AsRef<OsStr>,
594 {
595 self.inner.env(key, val);
596 self
597 }
598
599 pub(crate) fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
600 self.inner.kill_on_drop(kill);
601 self
602 }
603
604 pub(crate) async fn output(&mut self) -> io::Result<Output> {
605 self.inner.output().await.map(sanitize_git_output)
606 }
607
608 pub(crate) async fn output_with_context(&mut self) -> anyhow::Result<Output> {
609 self.inner
610 .output_with_context()
611 .await
612 .map(sanitize_git_output)
613 }
614}
615
616pub(crate) async fn git() -> GitCommand {
619 let mut cmd = Command::new("git");
620 cmd.envs(build_git_auth_env().await).kill_on_drop(true);
621 GitCommand { inner: cmd }
622}
623
624pub(crate) async fn build_git_auth_env() -> Vec<(String, String)> {
645 let token = token::shared().get_token().await.ok().flatten();
646 build_git_auth_env_for_token(token)
647}
648
649fn build_git_auth_env_for_token(token: Option<String>) -> Vec<(String, String)> {
650 let mut config: Vec<(String, String)> = match token {
651 Some(t) if !t.is_empty() => {
652 let authed = format!("url.https://x-access-token:{t}@github.com/.insteadOf");
653 vec![
654 (authed.clone(), "https://github.com/".into()),
655 (authed, "git@github.com:".into()),
656 ]
657 }
658 _ => vec![(
659 "url.https://github.com/.insteadOf".into(),
660 "git@github.com:".into(),
661 )],
662 };
663 config.push(("commit.gpgsign".into(), "false".into()));
665 config.push(("tag.gpgsign".into(), "false".into()));
666
667 let mut env = vec![("GIT_CONFIG_COUNT".to_string(), config.len().to_string())];
668 for (n, (key, value)) in config.into_iter().enumerate() {
669 env.push((format!("GIT_CONFIG_KEY_{n}"), key));
670 env.push((format!("GIT_CONFIG_VALUE_{n}"), value));
671 }
672 env
673}
674
675pub(crate) fn is_workflow_scope_error(stderr: &str) -> bool {
682 stderr.contains("without `workflow` scope")
683 || stderr.contains("without 'workflow' scope")
684 || (stderr.contains("refusing to allow")
685 && stderr.contains("workflow")
686 && stderr.contains("scope"))
687}
688
689async fn strip_workflow_files(dir: &Path, default_branch: &str) -> anyhow::Result<bool> {
700 let output = Command::new("git")
702 .args([
703 "diff",
704 "--name-only",
705 &format!("origin/{default_branch}...HEAD"),
706 "--",
707 ".github/workflows/",
708 ])
709 .current_dir(dir)
710 .output_with_context()
711 .await?;
712
713 let workflow_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
714 .lines()
715 .filter(|l| !l.is_empty())
716 .map(ToString::to_string)
717 .collect();
718
719 if workflow_files.is_empty() {
720 return Ok(false);
721 }
722
723 tracing::info!(
724 files = ?workflow_files,
725 "stripping workflow files from commits to bypass missing workflow scope"
726 );
727
728 let count_output = Command::new("git")
733 .args([
734 "rev-list",
735 "--count",
736 &format!("origin/{default_branch}..HEAD"),
737 ])
738 .current_dir(dir)
739 .output_with_context()
740 .await?;
741
742 let commit_count: usize = String::from_utf8_lossy(&count_output.stdout)
743 .trim()
744 .parse()
745 .unwrap_or(0);
746
747 if commit_count == 0 {
748 return Ok(false);
749 }
750
751 let log_output = Command::new("git")
756 .args([
757 "log",
758 "--format=%x00%H%n%B",
759 &format!("origin/{default_branch}..HEAD"),
760 ])
761 .current_dir(dir)
762 .output_with_context()
763 .await?;
764 let log_text = String::from_utf8_lossy(&log_output.stdout).to_string();
765
766 let commits: Vec<(String, String)> = log_text
770 .split('\0')
771 .filter(|s| !s.trim().is_empty())
772 .map(|block| {
773 let block = block.trim();
774 let first_nl = block.find('\n').unwrap_or(block.len());
775 let hash = block[..first_nl].to_string();
776 let msg = block[first_nl..].trim().to_string();
777 (hash, msg)
778 })
779 .collect::<Vec<_>>()
780 .into_iter()
781 .rev()
782 .collect();
783
784 if commits.is_empty() {
785 return Ok(false);
786 }
787
788 let reset = Command::new("git")
790 .args(["reset", "--soft", &format!("origin/{default_branch}")])
791 .current_dir(dir)
792 .output_with_context()
793 .await?;
794
795 if !reset.status.success() {
796 let stderr = String::from_utf8_lossy(&reset.stderr);
797 anyhow::bail!("git reset --soft failed during workflow file stripping: {stderr}");
798 }
799
800 let mut rm_args = vec!["rm", "--cached", "--ignore-unmatch", "--"];
802 let file_refs: Vec<&str> = workflow_files.iter().map(String::as_str).collect();
803 rm_args.extend(file_refs);
804
805 let rm = Command::new("git")
806 .args(&rm_args)
807 .current_dir(dir)
808 .output_with_context()
809 .await?;
810
811 if !rm.status.success() {
812 let stderr = String::from_utf8_lossy(&rm.stderr);
813 tracing::warn!("git rm --cached for workflow files failed (non-fatal): {stderr}");
814 }
815
816 let has_staged = Command::new("git")
819 .args(["diff", "--cached", "--quiet"])
820 .current_dir(dir)
821 .status()
822 .await
823 .is_ok_and(|s| !s.success());
824
825 if !has_staged {
826 tracing::warn!(
827 "after removing workflow files, no staged changes remain — \
828 the only changes were workflow files"
829 );
830 if let Some((hash, _)) = commits.last() {
833 let _ = Command::new("git")
834 .args(["reset", "--soft", hash])
835 .current_dir(dir)
836 .output_with_context()
837 .await;
838 }
839 return Ok(false);
840 }
841
842 let commit_msg = if commits.len() == 1 {
844 commits[0].1.clone()
845 } else {
846 let mut combined = String::new();
848 for (i, (_, msg)) in commits.iter().enumerate() {
849 if i > 0 {
850 combined.push_str("\n\n");
851 }
852 combined.push_str(msg);
853 }
854 combined.push_str("\n\n[workflow files stripped: token lacks `workflow` scope]");
855 combined
856 };
857
858 let commit = commit::git_commit(dir, &commit_msg, "orchestrator").await?;
860
861 if !commit.status.success() {
862 let stderr = String::from_utf8_lossy(&commit.stderr);
863 if let Some((original_head, _)) = commits.last() {
865 let _ = Command::new("git")
866 .args(["reset", "--hard", original_head])
867 .current_dir(dir)
868 .output_with_context()
869 .await;
870 }
871 anyhow::bail!("git commit failed during workflow file stripping: {stderr}");
872 }
873
874 tracing::info!(
875 stripped_files = ?workflow_files,
876 original_commits = commit_count,
877 "successfully stripped workflow files from commits"
878 );
879
880 Ok(true)
881}
882
883pub(crate) async fn get_current_branch(dir: &Path) -> String {
885 let output = Command::new("git")
886 .args(["branch", "--show-current"])
887 .current_dir(dir)
888 .output_with_context()
889 .await;
890
891 match output {
892 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
893 _ => String::new(),
894 }
895}
896
897async fn check_push_needed(dir: &Path, branch: &str, default_branch: &str) -> (bool, bool) {
905 let remote_exists = Command::new("git")
907 .args(["rev-parse", &format!("origin/{branch}")])
908 .current_dir(dir)
909 .output_with_context()
910 .await
911 .is_ok_and(|o| o.status.success());
912
913 let compare_ref = if remote_exists {
914 format!("origin/{branch}..{branch}")
915 } else {
916 format!("origin/{default_branch}..{branch}")
918 };
919
920 tracing::debug!(
921 branch,
922 compare_ref,
923 remote_exists,
924 "checking unpushed commits"
925 );
926
927 let output = Command::new("git")
928 .args(["log", &compare_ref, "--oneline"])
929 .current_dir(dir)
930 .output_with_context()
931 .await;
932
933 let has_unpushed = match output {
934 Ok(o) if o.status.success() => {
935 let out = String::from_utf8_lossy(&o.stdout);
936 let has = !out.trim().is_empty();
937 tracing::debug!(branch, has_unpushed = has, "unpushed commits check result");
938 has
939 }
940 _ => {
941 tracing::debug!(branch, "git log failed for compare ref, assuming unpushed");
942 true
945 }
946 };
947
948 (remote_exists, has_unpushed)
949}
950
951#[cfg(test)]
952mod tests;