Skip to content

fix(orchestrator): use codebase cwd for direct chat provider execution#1233

Open
Wirasm wants to merge 3 commits intodevfrom
archon/task-fix-issue-1179
Open

fix(orchestrator): use codebase cwd for direct chat provider execution#1233
Wirasm wants to merge 3 commits intodevfrom
archon/task-fix-issue-1179

Conversation

@Wirasm
Copy link
Copy Markdown
Collaborator

@Wirasm Wirasm commented Apr 15, 2026

Summary

  • Problem: In codebase-scoped direct chat, the cwd passed to the AI provider was always ~/.archon/workspaces (the Archon root), ignoring the attached project.
  • Why it matters: Provider tools (file reads, directory listings, shell commands) ran from the wrong directory, so relative paths and tool results didn't reflect the user's project.
  • What changed: orchestrator-agent.ts now resolves cwd from the attached codebase — using conversation.cwd (worktree path) when set, otherwise codebase.default_cwd, with a fallback to getArchonWorkspacesPath() for non-scoped conversations.
  • What did not change: Workflow execution (already resolved cwd correctly), non-scoped chat, isolation/worktree creation for direct chat, and env injection (tracked in feat: managed execution env as a first-class, execution-consistent feature #1161).

UX Journey

Before

User                   Archon                         AI Client
────                   ──────                         ─────────
sends message ──────▶  resolves session
(attached to           loads context
my-project)            cwd = ~/.archon/workspaces  ← always wrong
                       streams to AI ────────────────▶ runs tools in ~/.archon/workspaces
                                                        ls src/ → empty / wrong results
sees wrong reply ◀───  sends to platform

After

User                   Archon                         AI Client
────                   ──────                         ─────────
sends message ──────▶  resolves session
(attached to           loads context
my-project)            [cwd = conversation.cwd        ← worktree if active
                              ?? codebase.default_cwd ← repo root otherwise
                              ?? getArchonWorkspacesPath()]
                       streams to AI ────────────────▶ runs tools in /repos/my-project
                                                        ls src/ → correct results
sees correct reply ◀─  sends to platform

Architecture Diagram

Before

orchestrator-agent.ts
  handleMessage()
    └── cwd = getArchonWorkspacesPath()  ← hardcoded
    └── handleStreamMode(cwd) / handleBatchMode(cwd)
          └── aiClient.sendQuery(prompt, cwd, ...)
                └── ClaudeProvider / CodexProvider (subprocess cwd = ~/.archon/workspaces)

After

orchestrator-agent.ts
  handleMessage()
    └── [~] cwd resolution (codebase-aware)
          if conversation.codebase_id:
            attachedCodebase = codebases.find(...)
            cwd = conversation.cwd ?? attachedCodebase.default_cwd
          else:
            cwd = getArchonWorkspacesPath()
    └── handleStreamMode(cwd) / handleBatchMode(cwd)   (unchanged)
          └── aiClient.sendQuery(prompt, cwd, ...)      (unchanged)
                └── ClaudeProvider / CodexProvider (subprocess cwd = project path)

Connection inventory:

From To Status Notes
handleMessage getArchonWorkspacesPath modified Now used as fallback only
handleMessage conversation.cwd / codebase.default_cwd new Read when codebase-scoped
handleStreamMode / handleBatchMode aiClient.sendQuery unchanged cwd param now correct

Label Snapshot

  • Risk: risk: low
  • Size: size: XS
  • Scope: core
  • Module: core:orchestrator

Change Metadata

  • Change type: bug
  • Primary scope: core

Linked Issue

Validation Evidence (required)

bun run validate
  • bun run type-check: ✅ 10 packages, 0 errors
  • bun run lint: ✅ 0 errors, 0 warnings
  • bun run format:check: ✅ all files formatted
  • bun run test: ✅ all passed, 0 failed

Also fixed a stale mock in cleanup-service.test.ts uncovered during validation (stale mockExecFileAsync calls replaced with proper mockGetById/mockGetCodebase setups).

Security Impact (required)

  • New permissions/capabilities? No
  • New external network calls? No
  • Secrets/tokens handling changed? No
  • File system access scope changed? No — cwd narrows to the already-registered project path; no new paths opened

Compatibility / Migration

  • Backward compatible? Yes — non-scoped conversations are unchanged; scoped conversations now correctly use the project path
  • Config/env changes? No
  • Database migration needed? No

Human Verification (required)

  • Verified scenarios: Type check, lint, format, full test suite all pass
  • Edge cases checked: conversation.cwd = null (uses default_cwd), conversation.cwd set (uses worktree path), no codebase attached (uses Archon root fallback), codebase_id set but not in loaded list (falls back gracefully)
  • What was not verified: Live end-to-end test with a real Claude/Codex session against a registered project

Side Effects / Blast Radius (required)

  • Affected subsystems/workflows: Only the direct chat path in handleMessage — workflow execution path is untouched
  • Potential unintended effects: If codebase.default_cwd points to a path that no longer exists, provider tools will fail on filesystem ops — same risk exists for workflow execution today
  • Guardrails/monitoring: No new monitoring needed; existing provider error handling applies

Rollback Plan (required)

  • Fast rollback command/path: Revert the single let cwd block in orchestrator-agent.ts (3 lines)
  • Feature flags or config toggles: None
  • Observable failure symptoms: Provider tool results coming from wrong directory (same as before this fix)

Risks and Mitigations

  • Risk: conversation.cwd points to a deleted worktree
    • Mitigation: Out of scope for this fix; same risk exists in workflow execution. IsolationBlockedError handling in the isolation layer addresses this separately.

Summary by CodeRabbit

  • Bug Fixes

    • Workflow execution now correctly resolves working directories based on conversation and codebase scope, with fallback to the root workspace path when codebase context is unavailable.
  • Tests

    • Expanded test coverage for working directory resolution logic and environment cleanup batch processing across multiple configuration scenarios.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 15, 2026

📝 Walkthrough

Walkthrough

The pull request implements provider cwd (current working directory) resolution logic in the orchestrator agent's message handler. When a conversation is scoped to a codebase, the handler now derives the execution directory from conversation.cwd or the codebase's default_cwd, falling back to the workspaces root if the codebase cannot be found.

Changes

Cohort / File(s) Summary
Orchestrator Agent Implementation
packages/core/src/orchestrator/orchestrator-agent.ts
Added cwd resolution logic: initializes to workspaces path, then uses conversation.cwd or codebase.default_cwd when codebase_id is set, with workspaces-root fallback and warning log if codebase lookup fails.
Orchestrator Agent Tests
packages/core/src/orchestrator/orchestrator-agent.test.ts
Added new provider cwd resolution test suite with four tests validating cwd selection from conversation.cwd, codebase.default_cwd, and getArchonWorkspacesPath fallback paths, plus fixture reset for mockListCodebases.
Cleanup Service Tests
packages/core/src/services/cleanup-service.test.ts
Updated test scenario from single-environment error handling to batch environment processing with both environments reported as removed due to missing paths.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 Hop through the codebases deep,
Where conversations sleep,
Find the cwd just right—
Default paths shining bright!
When the codebase goes away,
Workspaces save the day! 🏡

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: fixing the orchestrator to use codebase cwd instead of always using the Archon workspaces root for direct chat provider execution.
Description check ✅ Passed The PR description is comprehensive and follows the template structure with all required sections completed: Summary (Problem, Why it matters, What changed, What did not change), UX Journey (Before/After), Architecture Diagram, Labels, Change Metadata, Linked Issues, Validation Evidence, Security Impact, Compatibility, Human Verification, Side Effects, Rollback Plan, and Risks/Mitigations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch archon/task-fix-issue-1179

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Wirasm
Copy link
Copy Markdown
Collaborator Author

Wirasm commented Apr 15, 2026

Comprehensive PR Review

PR: #1233
Reviewed by: 3 specialized agents (code-review, error-handling, test-coverage)
Date: 2026-04-15


Summary

Clean, minimal fix. The 9-line cwd resolution block in orchestrator-agent.ts is type-safe, reuses the already-fetched codebases list (no extra DB call), and the ?? fallback chain handles null/undefined correctly. All three agents recommend APPROVE.

Verdict: APPROVE

Severity Count
🔴 CRITICAL 0
🟠 HIGH 0
🟡 MEDIUM 0
🟢 LOW 4

🟢 Low Issues (All Optional)

1. Silent fallback with no log when codebase lookup fails (reported by all 3 agents)

📍 packages/core/src/orchestrator/orchestrator-agent.ts:748-752

When conversation.codebase_id is set but codebases.find() returns undefined (e.g., codebase was deleted), the code silently falls back to getArchonWorkspacesPath() with no log warning. The AI query proceeds with the wrong cwd and there's no operator signal. CLAUDE.md says: "Document fallback behavior with a comment when a fallback is intentional and safe; otherwise throw." The existing comment covers the happy paths but not this miss.

View suggested fix
if (attachedCodebase) {
  cwd = conversation.cwd ?? attachedCodebase.default_cwd;
} else {
  // Intentional fallback: codebase may have been deleted; run with workspaces root.
  getLog().warn(
    { codebaseId: conversation.codebase_id, conversationId },
    'orchestrator.codebase_not_found_cwd_fallback'
  );
}

Matches the existing codebase_env_vars_load_failed warn pattern directly below (lines 774-781).


2. Missing test for codebase_id set but codebase not found (reported by all 3 agents)

📍 packages/core/src/orchestrator/orchestrator-agent.test.ts — new provider cwd resolution describe block

Three tests cover the three branches of the new cwd logic. The attachedCodebase === undefined false-branch is untested — a future refactor could break the fallback silently.

View suggested test
test('falls back to getArchonWorkspacesPath when codebase_id is set but codebase not in list', async () => {
  const conversation = makeConversation({ codebase_id: 'codebase-1', cwd: null });
  mockGetOrCreateConversation.mockReturnValueOnce(Promise.resolve(conversation));
  mockListCodebases.mockReturnValueOnce(Promise.resolve([]));

  const platform = makePlatform();
  await handleMessage(platform, 'conv-1', 'Hello');

  expect(mockSendQuery).toHaveBeenCalled();
  const calledCwd = mockSendQuery.mock.calls[0][1] as string;
  expect(calledCwd).toBe('/home/test/.archon/workspaces');
});

Follows the exact pattern of the existing no-codebase fallback test at line 1071.


3. Misleading test name in cleanup-service (code-review + test-coverage)

📍 packages/core/src/services/cleanup-service.test.ts:681

The test "continues processing after error on one environment" was correctly fixed to remove stale mockExecFileAsync calls — but the replacement also injects no errors. Both environments now succeed cleanly. The test verifies batch processing, not error resilience. The name creates a false expectation.

Suggested rename: 'processes all environments in batch (both paths missing)'


4. mockListCodebases not reset in beforeEach (code-review)

📍 packages/core/src/orchestrator/orchestrator-agent.test.ts:887

The beforeEach resets all other mocks but not mockListCodebases. Default returns [] so no current bug, but an unconsumed mockReturnValueOnce from a future test could leak.

Suggested addition to beforeEach:

mockListCodebases.mockReset();
mockListCodebases.mockImplementation(() => Promise.resolve([]));

✅ What's Good

  • No extra DB call: codebases from listCodebases() is already in scope at line 705 — reused directly for cwd resolution.
  • Null safety: ?? operator correctly handles null without collapsing empty strings.
  • Comment quality: Lines 744-746 document all three branches (worktree path → codebase default → global fallback).
  • Mock setup correctness: Tests correctly distinguish mockGetCodebase (for discoverAllWorkflows) from mockListCodebases (for codebaseDb.listCodebases()). Requires internal knowledge — well done.
  • Cleanup-service fix is accurate: Stale mockExecFileAsync rejections were never consumed (worktreeExists was separately mocked). Removing them and replacing with the correct mock chain is the right fix.
  • All CLAUDE.md rules pass: KISS, YAGNI, type safety, intentional fallback documented.

Review artifacts: /Users/rasmus/.archon/workspaces/coleam00/Archon/artifacts/runs/7201bc9c2f0e826abb6c8915f3cd9617/review/

@Wirasm
Copy link
Copy Markdown
Collaborator Author

Wirasm commented Apr 15, 2026

⚡ Self-Fix Report (Aggressive)

Status: COMPLETE
Pushed: ✅ Changes pushed to archon/task-fix-issue-1179
Commit: bd4bb0b
Philosophy: Fix everything unless clearly a new concern


Fixes Applied (4 total)

Severity Count
🔴 CRITICAL 0
🟠 HIGH 0
🟡 MEDIUM 0
🟢 LOW 4
View all fixes
  • Silent fallback with no log when codebase lookup fails (orchestrator-agent.ts:750) — Added getLog().warn(...) in the else branch, matching the codebase_env_vars_load_failed warn pattern immediately below
  • mockListCodebases not reset in beforeEach (orchestrator-agent.test.ts:887) — Added mockListCodebases.mockReset() and default implementation to the beforeEach block
  • Misleading test name after mock fix (cleanup-service.test.ts:681) — Renamed to "processes all environments in batch (both paths missing)"

Tests Added

  • orchestrator-agent.test.ts: falls back to getArchonWorkspacesPath when codebase_id is set but codebase not in list — covers the previously untested attachedCodebase === undefined fallback branch

Skipped (0)

(none — all findings addressed)


Suggested Follow-up Issues

(none)


Validation

✅ Type check | ✅ Lint | ✅ Tests (all packages, 0 fail)


Self-fix by Archon · aggressive mode · fixes pushed to archon/task-fix-issue-1179

Wirasm added 3 commits April 22, 2026 10:33
#1179)

Direct chat with a codebase-scoped conversation was always passing
the Archon workspaces root as cwd to the provider, ignoring the
attached project. Now resolves cwd from conversation.cwd (worktree)
or codebase.default_cwd, matching workflow execution behavior.

Changes:
- Resolve cwd from attached codebase in orchestrator-agent.ts
- Add 3 tests covering codebase-scoped, worktree, and fallback paths

Fixes #1179
…n cwd resolution

- Add warn log when codebase lookup fails in the cwd fallback path, matching
  the pattern used for codebase_env_vars_load_failed one block below
- Add test covering the codebase_id-set-but-not-found fallback branch
- Reset mockListCodebases in beforeEach to prevent potential mock leaks
- Rename misleading cleanup-service test that no longer injects errors
@Wirasm Wirasm force-pushed the archon/task-fix-issue-1179 branch from 5251cfa to d2b3ba3 Compare April 22, 2026 07:36
@Wirasm Wirasm marked this pull request as ready for review April 22, 2026 07:36
@Wirasm
Copy link
Copy Markdown
Collaborator Author

Wirasm commented Apr 22, 2026

Rebased on current `dev` (the duplicate cleanup-service mock fix dropped out since #1232 landed that independently) and marked ready for review. Not merging yet — flagging a couple of design questions surfaced during review that are worth pinning somewhere before this lands as the accepted pattern.

Fix itself: confirmed correct and scoped. Three-tier resolution (`conversation.cwd` → `codebase.default_cwd` → `getArchonWorkspacesPath()`) is the right shape. `codebases.find()` is free (already loaded at line 734 for prompt construction, no extra DB call). Tests cover all four branches (worktree, default_cwd, no codebase, codebase deleted).

Design questions to discuss (not blocking this PR)

1. `conversation.cwd` doing double duty

`conversation.cwd` is set by workflow runs (as the worktree path) and now observably read by direct chat (as the provider cwd). That coupling is convenient — if a user runs `/workflow run implement --branch feature` and then follows up with direct chat "now add a test for this", the follow-up naturally continues in the same worktree. Coherent UX.

But the lifecycle is leaky: if the user `/workflow abandon`s the run, `conversation.cwd` doesn't reset, the worktree gets deleted, and direct chat is now stuck pointing at a non-existent directory. Pre-existed this PR — but this PR makes it user-visible for the first time (before, the hardcoded `~/.archon/workspaces` fallback masked it).

Options:

  • (a) Accept it. Add a "path doesn't exist" guard in the cwd resolver that falls back to `codebase.default_cwd` when `conversation.cwd` points at a missing dir. Simple, pragmatic.
  • (b) Fix it at the source. When an isolation env is destroyed, null-out `conversation.cwd` for conversations that referenced it. Clean but requires a small schema/service change.
  • (c) Split the field. `conversation.workflowCwd` (owned by workflow lifecycle) vs. `conversation.directChatCwd` (owned by user session). Cleanest contract, more ceremony.

Leaning (a) — a single `existsSync` guard in the resolver is the minimum viable fix and keeps the primitive simple. (b) and (c) are overkill until the leaky abstraction bites in production.

2. Direct-chat tool surface — right default?

This PR makes direct chat run provider tools (Read, Write, Edit, Bash, Grep, etc.) against the attached project's live directory. That's how Claude Code / Codex natively behave, and it matches user expectations coming from those CLIs.

But it's a departure from Archon's "workflows provide structure (validation, retry, event emission, audit), direct chat just routes" model. A user running direct chat on their live repo can have the AI write/edit files without isolation — no worktree, no atomic revert, no per-step event emission, no retry on failure.

Options:

  • (a) Status quo (this PR). Direct chat is "Claude Code with your project loaded." Users who want isolation go through workflows explicitly. Matches user expectations from other agent CLIs.
  • (b) Restrict direct chat to read-only tools (`Read`, `Glob`, `Grep`, `WebFetch`) by default. Any Write/Edit/Bash invocation gets intercepted and suggests `/workflow run implement ""` instead.
  • (c) Make it configurable per conversation or per codebase (`direct_chat_mode: readonly | unrestricted`). Most flexible, most config surface.

(a) is what ships today (and what this PR makes work correctly). (b) is more conservative and aligns with the "workflows provide the safety rails" principle. (c) adds config surface we may not need.

I'd hold on this one — let the direct-chat-on-live-repo pattern get some real usage after this fix lands and see if anyone actually wants the read-only mode. File an issue to track.

3. Follow-up I'll file regardless of (1) and (2)

  • Null-out `conversation.cwd` (or add the exists-guard in the resolver) when the associated isolation env is destroyed — cleanest resolution for the lifecycle smell above

None of these block this PR. The fix is the right incremental move and the primitives it inherits (`conversation.cwd` as direct-chat cwd hint) were already in place.

Ready for CI + final look.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
packages/core/src/orchestrator/orchestrator-agent.test.ts (2)

1049-1102: Nit: provider cwd resolution is nested inside discoverAllWorkflows — remote sync.

These tests exercise cwd derivation in handleMessage, not discoverAllWorkflows. Promoting the inner describe to a top-level suite (alongside the other handleMessage describes) would make the grouping match the behavior under test and avoid implicit coupling to the parent's beforeEach.

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

In `@packages/core/src/orchestrator/orchestrator-agent.test.ts` around lines 1049
- 1102, The "provider cwd resolution" describe block is nested under
"discoverAllWorkflows — remote sync" but tests target handleMessage's cwd logic;
move the entire describe('provider cwd resolution', ...) block out to top-level
(alongside other handleMessage suites) so it isn't implicitly coupled to the
parent's beforeEach; update placement only (retain tests and references to
handleMessage, getCwdPassedToProvider, mockGetOrCreateConversation,
mockListCodebases, mockGetCodebase) to ensure the suite runs with the correct
setup.

1093-1101: Consider asserting the warn log on the not-found fallback branch.

The new test verifies cwd falls back to the workspaces root when codebase_id is set but the codebase isn't in the list, but it doesn't assert that orchestrator.codebase_not_found_cwd_fallback was logged. Since the warn log is the primary observability signal for this (otherwise silent) fallback, an assertion here would prevent the log from silently regressing:

Proposed addition
     await handleMessage(makePlatform(), 'conv-1', 'Hello');

     expect(getCwdPassedToProvider()).toBe('/home/test/.archon/workspaces');
+    expect(mockLogger.warn).toHaveBeenCalledWith(
+      expect.objectContaining({ codebaseId: 'codebase-1', conversationId: 'conv-1' }),
+      'orchestrator.codebase_not_found_cwd_fallback'
+    );
   });

Note: you may need mockLogger.warn.mockClear() at the top of this describe block (or in its own beforeEach) since other tests in the parent suite also trigger warns.

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

In `@packages/core/src/orchestrator/orchestrator-agent.test.ts` around lines 1093
- 1101, The test "falls back to getArchonWorkspacesPath when codebase_id is set
but codebase not in list" exercises the fallback but doesn't assert the warn
observability; update the test to also assert that the warn log key
orchestrator.codebase_not_found_cwd_fallback was emitted by checking
mockLogger.warn was called with that key (or contains that message) after
calling handleMessage (keep existing setup using mockGetOrCreateConversation and
mockListCodebases and check getCwdPassedToProvider as before); also add a
mockLogger.warn.mockClear() in the surrounding describe/beforeEach if needed to
avoid cross-test pollution so the warn assertion is deterministic.
packages/core/src/orchestrator/orchestrator-agent.ts (1)

812-827: LGTM — cwd resolution is clear, null-safe, and the fallback is explicitly documented.

Precedence (conversation.cwdattachedCodebase.default_cwd → workspaces root) matches the PR intent, the comment documents the intentional fallback (satisfies the "document fallback behavior with a comment when intentional and safe" guideline), and the warn event orchestrator.codebase_not_found_cwd_fallback follows the {domain}.{action}_{state} convention.

One small nit: codebases.find(c => c.id === conversation.codebase_id) duplicates the same lookup already performed in buildFullPrompt (line 477). If you want to tighten this further, you could resolve scopedCodebase once before buildFullPrompt and reuse it for the cwd block — purely optional.

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

In `@packages/core/src/orchestrator/orchestrator-agent.ts` around lines 812 - 827,
The code performs the same lookup twice; extract the result of
codebases.find(...) into a single variable (e.g., scopedCodebase or
attachedCodebase) before calling buildFullPrompt and reuse that variable in the
cwd resolution block instead of calling codebases.find again; update references
in buildFullPrompt usage and the cwd fallback logic (the warn call and
conversation.cwd ?? attachedCodebase.default_cwd) to use the single resolved
variable to avoid duplicated lookups.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/core/src/orchestrator/orchestrator-agent.test.ts`:
- Around line 1049-1102: The "provider cwd resolution" describe block is nested
under "discoverAllWorkflows — remote sync" but tests target handleMessage's cwd
logic; move the entire describe('provider cwd resolution', ...) block out to
top-level (alongside other handleMessage suites) so it isn't implicitly coupled
to the parent's beforeEach; update placement only (retain tests and references
to handleMessage, getCwdPassedToProvider, mockGetOrCreateConversation,
mockListCodebases, mockGetCodebase) to ensure the suite runs with the correct
setup.
- Around line 1093-1101: The test "falls back to getArchonWorkspacesPath when
codebase_id is set but codebase not in list" exercises the fallback but doesn't
assert the warn observability; update the test to also assert that the warn log
key orchestrator.codebase_not_found_cwd_fallback was emitted by checking
mockLogger.warn was called with that key (or contains that message) after
calling handleMessage (keep existing setup using mockGetOrCreateConversation and
mockListCodebases and check getCwdPassedToProvider as before); also add a
mockLogger.warn.mockClear() in the surrounding describe/beforeEach if needed to
avoid cross-test pollution so the warn assertion is deterministic.

In `@packages/core/src/orchestrator/orchestrator-agent.ts`:
- Around line 812-827: The code performs the same lookup twice; extract the
result of codebases.find(...) into a single variable (e.g., scopedCodebase or
attachedCodebase) before calling buildFullPrompt and reuse that variable in the
cwd resolution block instead of calling codebases.find again; update references
in buildFullPrompt usage and the cwd fallback logic (the warn call and
conversation.cwd ?? attachedCodebase.default_cwd) to use the single resolved
variable to avoid duplicated lookups.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 26b1e926-1844-445a-8491-41945fe4fefb

📥 Commits

Reviewing files that changed from the base of the PR and between 817186d and d2b3ba3.

📒 Files selected for processing (3)
  • packages/core/src/orchestrator/orchestrator-agent.test.ts
  • packages/core/src/orchestrator/orchestrator-agent.ts
  • packages/core/src/services/cleanup-service.test.ts

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.

orchestrator: make codebase-scoped direct chat run in true project context

1 participant