Skip to content

refactor: decompose cadis-core/lib.rs by extracting helper modules#59

Open
DeryFerd wants to merge 14 commits into
Growth-Circle:mainfrom
DeryFerd:refactor/decompose-cadis-core-lib
Open

refactor: decompose cadis-core/lib.rs by extracting helper modules#59
DeryFerd wants to merge 14 commits into
Growth-Circle:mainfrom
DeryFerd:refactor/decompose-cadis-core-lib

Conversation

@DeryFerd
Copy link
Copy Markdown
Contributor

@DeryFerd DeryFerd commented May 9, 2026

Problem Statement

The cadis-core/src/lib.rs file has grown to over 14,500 lines, making it increasingly difficult to navigate and maintain. The file contains a mix of high-level orchestration logic alongside numerous helper functions for worker lifecycle management, approval workflows, and session handling. This monolithic structure creates several issues:

  • Cognitive load: Developers must scroll through thousands of lines to find relevant code
  • Compilation time: Large single files can slow down incremental compilation
  • Code review difficulty: PRs touching different concerns become harder to review
  • Maintenance risk: Accidental coupling between unrelated subsystems

Solution Architecture

This PR extracts three groups of helper functions into dedicated modules, each focused on a specific domain:

Module Structure

crates/cadis-core/src/
├── lib.rs                    (main orchestration, ~14,300 lines after extraction)
├── worker_helpers.rs         (worker lifecycle and command handling)
├── approval_helpers.rs       (approval workflow utilities)
└── session_helpers.rs        (agent session lifecycle helpers)

Domain Separation

worker_helpers.rs - Encapsulates worker-related concerns:

  • Worker state transitions and lifecycle event mapping
  • Worktree state management and cleanup policies
  • Worker command execution, failure handling, and artifact generation
  • Worker status string representations and terminal state detection

approval_helpers.rs - Encapsulates approval workflow concerns:

  • Approval expiration checking
  • Conversion between store records and protocol payloads

session_helpers.rs - Encapsulates agent session lifecycle concerns:

  • Agent session event lifecycle mapping
  • Session status labeling for display/logging
  • Terminal session state detection

Implementation Details

Extraction Strategy

The extraction was performed as a pure code move operation:

  • Functions were moved verbatim to their respective modules
  • All imports were preserved and adjusted for the new module locations
  • Helper functions were made pub to maintain accessibility from lib.rs
  • Module declarations and use statements were added to lib.rs

No Functional Changes

This is a zero-functional-change refactor:

  • All function signatures remain identical
  • All logic remains unchanged
  • All tests continue to pass without modification
  • The public API of cadis-core is unaffected

Line Count Impact

  • Before: lib.rs = 14,586 lines
  • After: lib.rs = 14,364 lines (reduced by 222 lines)
  • New modules: worker_helpers.rs (184 lines), approval_helpers.rs (40 lines), session_helpers.rs (60 lines)
  • Total: Same code, better organized

Benefits

  1. Improved Navigation: Developers can quickly jump to the relevant helper module instead of searching through a monolithic file
  2. Better Compilation: Smaller files enable better incremental compilation performance
  3. Clearer Separation of Concerns: Each module has a single, well-defined responsibility
  4. Easier Code Review: PRs touching worker helpers can be reviewed in isolation from session or approval logic
  5. Future Refactoring: Smaller modules are easier to further decompose or reorganize if needed

Migration Notes

No migration is required. This is an internal refactoring that does not affect:

  • Public APIs
  • External dependencies
  • Configuration files
  • Database schemas
  • Protocol definitions

All existing code continues to work without modification.

Next Steps

Future refactoring opportunities (not included in this PR):

  • Consider extracting the orchestrator logic into its own module
  • Evaluate whether workspace helpers could also be extracted
  • Assess if voice-related functions warrant a dedicated module
  • Consider splitting the remaining lib.rs into logical subsystems (e.g., runtime, state, handlers)

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eed4462039

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/cadis-core/src/worker_helpers.rs Outdated
Comment on lines +3 to +5
use cadis_protocol::{
WorkerCommandFailure, WorkerCommandReport, WorkerEventPayload, WorkerLifecycleEventKind,
WorkerState, WorkerWorktreeCleanupPolicy, WorkerWorktreeState,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep worker helper types in cadis-core

This refactor moves worker helpers into a child module but imports WorkerCommandFailure, WorkerCommandReport, and WorkerLifecycleEventKind from cadis_protocol; these were not protocol exports (the command structs are still private in lib.rs, and the lifecycle enum was removed from there). With worker_helpers now included by lib.rs, cadis-core cannot resolve these imports, so the crate fails to compile before any worker functionality can run.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a8254ba3c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 242 to 245
self.debug_events.push_back(DebugEvent {
timestamp: Instant::now(),
label,
detail: String::new(),
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Restore DebugEvent detail initialization

When the HUD compiles this event path, this struct literal is now missing the required detail field that is still defined on DebugEvent in crates/cadis-hud/src/types.rs. Since there is no Default update or struct change in this commit, building cadis-hud fails as soon as this literal is type-checked.

Useful? React with 👍 / 👎.

Comment thread crates/cadis-core/src/worker_helpers.rs Outdated
"stdout": report.stdout,
"stderr": report.stderr,
"timed_out": report.timed_out,
"duration_ms": report.duration_ms,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve worker command report metadata

The extracted JSON helper no longer matches the original report artifact schema: the previous implementation included status, stdout_truncated, stderr_truncated, and timeout_ms, but this replacement swaps in duration_ms and omits the fields that tell consumers whether validation passed, timed out, or had truncated output. For workers that run validation commands, the generated validation_command artifact will lose the status and truncation metadata needed to interpret the captured stdout/stderr.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c8b1dfebd6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/cadis-core/src/worker_helpers.rs Outdated
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct WorkerRecord {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reuse the existing worker record type

This helper module declares a new private WorkerRecord instead of using the WorkerRecord that lib.rs still stores and passes into helpers. In the current diff, calls such as worker_terminal_worktree_state(worker, status) and plan_worker_terminal_worktree(worker, ...) pass lib.rs's WorkerRecord, so the extracted helper signatures now expect a different nominal type and cadis-core cannot type-check until these helpers operate on the original record type (or stay in the same module).

Useful? React with 👍 / 👎.

Comment on lines +206 to +207
if !report.stdout.is_empty() {
logs.push(format!("STDOUT:\n{}", report.stdout));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve bounded worker command logs

When a validation command produces stdout/stderr, this replacement pushes the entire captured output with a new STDOUT:/STDERR: prefix instead of using the previous bounded command stdout:/command stderr: log format with truncation markers. For long validation output, worker log deltas can now exceed WORKER_COMMAND_LOG_LIMIT_BYTES and lose the truncation signal that the existing worker log path/tests in lib.rs expect.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 83cf4be8e0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +184 to +191
let mut summary = String::new();
summary.push_str(&format!("**Command**: `{}`\n\n", report.command));
summary.push_str(&format!(
"**Exit Code**: {}\n\n",
report.exit_code.map(|c| c.to_string()).unwrap_or_else(|| "None".to_string())
));
if report.timed_out {
summary.push_str("**Status**: Timed out\n\n");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve validation summary status

For workers that run a validation command, write_worker_artifacts appends this markdown into the summary artifact. This rewrite starts directly with the command/exit code and only emits a status for timeouts, so normal passed/failed validation summaries no longer contain the ## Daemon Validation section or an unconditional Status: passed/failed line that existing summary consumers/tests use to identify the validation result. Restore the old section header and status line for all command outcomes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9554fafa09

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if !report.stderr.is_empty() {
logs.push(format!("STDERR:\n{}", report.stderr));
}
logs
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore worker command completion logs

When the validation command produces no stdout or stderr, this now returns an empty log list, so execute_worker_command emits only the earlier “command started” delta and never the completion/status delta. This is the normal path for a clean default git status --short worker command, and the existing worker lifecycle test in crates/cadis-core/src/lib.rs expects command finished: status=passed exit_code=Some(0) to be present so clients can observe that daemon validation finished successfully.

Useful? React with 👍 / 👎.

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.

1 participant