Skip to content

Commit 1bf4c1d

Browse files
clawsweepersteipeteobviyus
authored
fix(sessions): inherit agent bootstrap outside workspace (#125675)
* fix(sessions): inherit agent bootstrap outside workspace * fix(sessions): layer execution-dir project context over agent bootstrap --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent f99a0c6 commit 1bf4c1d

24 files changed

Lines changed: 315 additions & 54 deletions

‎docs/concepts/system-prompt.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ Regenerate with `pnpm prompt:snapshots:gen`; verify drift with `pnpm prompt:snap
9191

9292
## Workspace bootstrap injection
9393

94-
Bootstrap files are resolved from the active workspace and routed to the prompt surface matching their lifetime:
94+
Agent identity, instructions, and memory are resolved from the configured agent workspace and routed to the prompt surface matching their lifetime. When a session runs from another folder or managed worktree, that folder remains the execution workspace. Its `AGENTS.md` is appended after the configured workspace files as project context; OpenClaw does not load `SOUL.md`, `IDENTITY.md`, `USER.md`, `MEMORY.md`, or `BOOTSTRAP.md` from the execution folder.
9595

9696
- `AGENTS.md`
9797
- `SOUL.md`
@@ -100,7 +100,7 @@ Bootstrap files are resolved from the active workspace and routed to the prompt
100100
- `BOOTSTRAP.md` (only on brand-new workspaces)
101101
- `MEMORY.md` when present
102102

103-
On the native Codex harness, OpenClaw avoids repeating stable workspace files in every user turn. Codex loads `AGENTS.md`, including its `## Tools` section, through native project-doc discovery. `SOUL.md`, `IDENTITY.md`, and `USER.md` are forwarded as turn-scoped collaboration developer instructions so native Codex sub-agents do not inherit them. `MEMORY.md` content is not pasted into every native Codex turn either: when memory tools are available for the workspace, Codex turns get a small workspace-memory note directing the model to `memory_search` or `memory_get`. If tools are disabled, memory search is unavailable, or the active workspace differs from the agent memory workspace, `MEMORY.md` falls back to the normal bounded turn-context path. `BOOTSTRAP.md` keeps the normal turn-context role.
103+
On the native Codex harness, OpenClaw avoids repeating stable workspace files in every user turn. Codex loads the execution folder's `AGENTS.md`, including its `## Tools` section, through native project-doc discovery, so OpenClaw does not inject that file again. When execution uses another folder, OpenClaw forwards only the configured agent workspace's `AGENTS.md`, `SOUL.md`, `IDENTITY.md`, and `USER.md` as turn-scoped collaboration developer instructions so native Codex sub-agents do not inherit them. `MEMORY.md` content is not pasted into every native Codex turn either: when memory tools are available for the agent workspace, Codex turns get a small workspace-memory note directing the model to `memory_search` or `memory_get`. If tools are disabled or memory search is unavailable, `MEMORY.md` falls back to the normal bounded turn-context path. `BOOTSTRAP.md` keeps the normal turn-context role.
104104

105105
Heartbeat monitor scratch is not a bootstrap file. The heartbeat runner appends it only to heartbeat turns; normal turns do not receive it. The default agent's system prompt automatically includes heartbeat guidance while its cadence is enabled, with no independent heartbeat setting to hide that section.
106106

‎extensions/codex/src/app-server/attempt-context.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,48 @@ describe("Codex app-server attempt context", () => {
197197
}
198198
});
199199

200+
it("inherits agent workspace instructions when Codex executes in another folder", async () => {
201+
const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-agent-workspace-"));
202+
const executionDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-execution-workspace-"));
203+
await fs.writeFile(path.join(workspaceDir, "AGENTS.md"), "Canonical agent instructions");
204+
await fs.writeFile(path.join(workspaceDir, "SOUL.md"), "Canonical agent soul");
205+
await fs.writeFile(path.join(workspaceDir, "MEMORY.md"), "Canonical agent memory");
206+
await fs.writeFile(path.join(executionDir, "AGENTS.md"), "Execution project instructions");
207+
208+
try {
209+
const context = await buildCodexWorkspaceBootstrapContext({
210+
params: {
211+
sessionId: "session-1",
212+
sessionKey: "agent:main:session-1",
213+
config: { agents: { defaults: { workspace: workspaceDir } } },
214+
} as EmbeddedRunAttemptParams,
215+
resolvedWorkspace: workspaceDir,
216+
executionWorkspace: executionDir,
217+
effectiveWorkspace: executionDir,
218+
sessionKey: "agent:main:session-1",
219+
sessionAgentId: "main",
220+
memoryToolNames: ["memory_search", "memory_get"],
221+
});
222+
223+
expect(context.turnScopedDeveloperInstructions).toContain("Canonical agent instructions");
224+
expect(context.turnScopedDeveloperInstructions).toContain("Canonical agent soul");
225+
expect(context.turnScopedDeveloperInstructions).toContain(
226+
path.join(workspaceDir, "AGENTS.md"),
227+
);
228+
expect(context.turnScopedDeveloperInstructions).not.toContain(
229+
"Execution project instructions",
230+
);
231+
expect(context.turnScopedDeveloperInstructions).not.toContain(
232+
path.join(executionDir, "AGENTS.md"),
233+
);
234+
expect(context.memoryToolRouted).toBe(true);
235+
expect(context.promptContext).toBeUndefined();
236+
} finally {
237+
await fs.rm(workspaceDir, { recursive: true, force: true });
238+
await fs.rm(executionDir, { recursive: true, force: true });
239+
}
240+
});
241+
200242
it("reads and compares thread-bootstrap context-engine projections", () => {
201243
const projection = readContextEngineThreadBootstrapProjection({
202244
mode: "thread_bootstrap",

‎extensions/codex/src/app-server/attempt-context.ts‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -168,19 +168,25 @@ export function resolveContextEngineBootstrapProjectionDecision(params: {
168168
export async function buildCodexWorkspaceBootstrapContext(params: {
169169
params: EmbeddedRunAttemptParams;
170170
resolvedWorkspace: string;
171+
executionWorkspace?: string;
171172
effectiveWorkspace: string;
172173
sessionKey: string;
173174
sessionAgentId: string;
174175
memoryToolNames: readonly string[];
175176
sandboxed?: boolean;
176177
}): Promise<CodexWorkspaceBootstrapContext> {
177178
try {
179+
const executionWorkspace = params.executionWorkspace ?? params.resolvedWorkspace;
180+
const inheritsAgentWorkspace = executionWorkspace !== params.resolvedWorkspace;
181+
const promptWorkspace = inheritsAgentWorkspace
182+
? params.resolvedWorkspace
183+
: params.effectiveWorkspace;
178184
const memoryToolsAvailable =
179185
params.memoryToolNames.length > 0 &&
180186
canRouteCodexWorkspaceMemoryThroughTools({
181187
config: params.params.config,
182188
agentId: params.params.agentId ?? params.sessionAgentId,
183-
workspaceDir: params.effectiveWorkspace,
189+
workspaceDir: inheritsAgentWorkspace ? params.resolvedWorkspace : params.effectiveWorkspace,
184190
});
185191
// Native Codex turns should read workspace MEMORY.md through tools when
186192
// possible; pasting it into every prompt turns durable memory into policy.
@@ -205,7 +211,7 @@ export async function buildCodexWorkspaceBootstrapContext(params: {
205211
remapCodexContextFilePath({
206212
file: toCodexEmbeddedContextFile(file),
207213
sourceWorkspaceDir: params.resolvedWorkspace,
208-
targetWorkspaceDir: params.effectiveWorkspace,
214+
targetWorkspaceDir: promptWorkspace,
209215
}),
210216
);
211217
const contextFiles = buildBootstrapContextForFiles(
@@ -227,7 +233,7 @@ export async function buildCodexWorkspaceBootstrapContext(params: {
227233
remapCodexContextFilePath({
228234
file,
229235
sourceWorkspaceDir: params.resolvedWorkspace,
230-
targetWorkspaceDir: params.effectiveWorkspace,
236+
targetWorkspaceDir: promptWorkspace,
231237
}),
232238
);
233239
const promptContextFiles = selectCodexWorkspacePromptContextFiles(contextFiles, {
@@ -237,7 +243,10 @@ export async function buildCodexWorkspaceBootstrapContext(params: {
237243
const turnScopedDeveloperInstructionFiles = shouldInjectCodexOpenClawPromptContext(
238244
params.params,
239245
)
240-
? selectCodexWorkspaceTurnScopedDeveloperInstructionFiles(contextFiles)
246+
? selectCodexWorkspaceTurnScopedDeveloperInstructionFiles(contextFiles, {
247+
agentWorkspaceDir: params.resolvedWorkspace,
248+
includeAgentProjectDocs: inheritsAgentWorkspace,
249+
})
241250
: [];
242251
return {
243252
bootstrapFiles,
@@ -675,7 +684,7 @@ function renderCodexWorkspaceBootstrapPromptContext(
675684
return undefined;
676685
}
677686
const lines = [
678-
"OpenClaw loaded these user-editable workspace files for the current turn. Codex loads AGENTS.md natively. SOUL.md, IDENTITY.md, and USER.md are provided as turn-scoped collaboration instructions so native Codex subagents do not inherit them. Those files are not repeated here.",
687+
"OpenClaw loaded these user-editable workspace files for the current turn. Codex loads project-local AGENTS.md natively. When execution uses another folder, the agent workspace AGENTS.md is inherited with SOUL.md, IDENTITY.md, and USER.md as turn-scoped collaboration instructions. Those files are not repeated here.",
679688
"",
680689
"# Project Context",
681690
"",
@@ -713,10 +722,24 @@ function selectCodexWorkspacePromptContextFiles(
713722

714723
function selectCodexWorkspaceTurnScopedDeveloperInstructionFiles(
715724
contextFiles: EmbeddedContextFile[],
725+
options: { agentWorkspaceDir: string; includeAgentProjectDocs?: boolean },
716726
): EmbeddedContextFile[] {
717-
return selectCodexWorkspaceDeveloperInstructionFiles(
727+
const files = selectCodexWorkspaceDeveloperInstructionFiles(
718728
contextFiles,
719-
CODEX_TURN_SCOPED_WORKSPACE_DEVELOPER_CONTEXT_BASENAMES,
729+
options.includeAgentProjectDocs
730+
? new Set([
731+
...CODEX_TURN_SCOPED_WORKSPACE_DEVELOPER_CONTEXT_BASENAMES,
732+
...CODEX_NATIVE_PROJECT_DOC_BASENAMES,
733+
])
734+
: CODEX_TURN_SCOPED_WORKSPACE_DEVELOPER_CONTEXT_BASENAMES,
735+
);
736+
const agentProjectDocPath = path.join(path.resolve(options.agentWorkspaceDir), "AGENTS.md");
737+
// Native Codex discovery owns execution-directory project docs. OpenClaw only
738+
// inherits the configured agent workspace's AGENTS.md through this channel.
739+
return files.filter(
740+
(file) =>
741+
!CODEX_NATIVE_PROJECT_DOC_BASENAMES.has(getCodexContextFileBasename(file.path)) ||
742+
path.resolve(file.path) === agentProjectDocPath,
720743
);
721744
}
722745

‎extensions/codex/src/app-server/run-attempt-context.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@ export async function prepareCodexAttemptContext(
141141
const memoryToolNames = getCodexWorkspaceMemoryToolNames(toolBridge.availableSpecs);
142142
const workspaceBootstrapContext = await buildCodexWorkspaceBootstrapContext({
143143
params: runtimeParams,
144-
resolvedWorkspace,
144+
resolvedWorkspace: runtimeParams.bootstrapWorkspaceDir ?? resolvedWorkspace,
145+
executionWorkspace: resolvedWorkspace,
145146
effectiveWorkspace,
146147
sessionKey: contextSessionKey,
147148
sessionAgentId,

‎src/agents/cli-runner/prepare.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ async function resolveCliSkillsPrompt(params: {
299299
? { workspaceAccess: sandboxWorkspace.workspaceAccess }
300300
: {}),
301301
},
302-
effectiveWorkspace: sandboxWorkspace.workspaceDir,
302+
skillsAnchorWorkspace: sandboxWorkspace.workspaceDir,
303303
skillsSnapshot: params.skillsSnapshot,
304304
});
305305
const { shouldLoadSkillEntries, skillEntries } = resolveEmbeddedRunSkillEntries({

‎src/agents/embedded-agent-runner/compact.types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ export type CompactEmbeddedAgentSessionParams = {
7373
/** Optional caller-observed live prompt tokens used for compaction diagnostics. */
7474
currentTokenCount?: number;
7575
workspaceDir: string;
76+
/** Canonical agent workspace used for bootstrap files when execution runs elsewhere. */
77+
bootstrapWorkspaceDir?: string;
7678
/** Optional task working directory; workspaceDir remains the agent bootstrap workspace. */
7779
cwd?: string;
7880
agentDir?: string;

‎src/agents/embedded-agent-runner/prepared-compaction-runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ export async function buildPreparedCompactionRuntime(prepared: DirectCompactionP
142142
workspaceOnly: loadSkillsWorkspaceOnly,
143143
} = resolveSandboxSkillRuntimeInputs({
144144
sandbox,
145-
effectiveWorkspace,
145+
skillsAnchorWorkspace: params.bootstrapWorkspaceDir ?? effectiveWorkspace,
146146
skillsSnapshot: params.skillsSnapshot,
147147
});
148148
const { shouldLoadSkillEntries, skillEntries, loadSkillEntries } =

‎src/agents/embedded-agent-runner/run-orchestrator.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,7 @@ async function runEmbeddedAgentInternal(
421421
agentDir,
422422
workspaceResolution,
423423
workspaceDir: resolvedWorkspace,
424+
bootstrapWorkspaceDir: canonicalWorkspace,
424425
isCanonicalWorkspace,
425426
globalLane,
426427
hookRunner,
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { prepareEmbeddedAttemptBootstrap } from "./attempt-bootstrap-prepare.js";
6+
import type { EmbeddedRunAttemptParams } from "./types.js";
7+
8+
const tempDirs: string[] = [];
9+
10+
afterEach(async () => {
11+
await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
12+
});
13+
14+
describe("prepareEmbeddedAttemptBootstrap", () => {
15+
async function prepare(params: { agentWorkspace: string; sessionWorkspace: string }) {
16+
return await prepareEmbeddedAttemptBootstrap({
17+
attempt: {
18+
sessionId: "session-1",
19+
sessionKey: "agent:main:session-1",
20+
trigger: "user",
21+
isCanonicalWorkspace: params.agentWorkspace === params.sessionWorkspace,
22+
config: { agents: { defaults: { workspace: params.agentWorkspace } } },
23+
} as EmbeddedRunAttemptParams,
24+
bootstrapWorkspaceDir: params.agentWorkspace,
25+
effectiveWorkspace: params.sessionWorkspace,
26+
hasReadTool: true,
27+
isRawModelRun: false,
28+
markStage: () => undefined,
29+
resolvedWorkspace: params.sessionWorkspace,
30+
sessionAgentId: "main",
31+
sessionLabel: "agent:main:session-1",
32+
});
33+
}
34+
35+
it("layers execution project instructions after agent bootstrap files", async () => {
36+
const agentWorkspace = await fs.realpath(
37+
await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-agent-workspace-")),
38+
);
39+
const sessionWorkspace = await fs.realpath(
40+
await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-workspace-")),
41+
);
42+
tempDirs.push(agentWorkspace, sessionWorkspace);
43+
await fs.writeFile(path.join(agentWorkspace, "AGENTS.md"), "Canonical agent instructions");
44+
await fs.writeFile(path.join(agentWorkspace, "SOUL.md"), "Canonical agent soul");
45+
await fs.writeFile(path.join(sessionWorkspace, "AGENTS.md"), "Execution project context");
46+
await fs.writeFile(path.join(sessionWorkspace, "SOUL.md"), "Execution soul must stay private");
47+
48+
const result = await prepare({ agentWorkspace, sessionWorkspace });
49+
const executionAgentsIndex = result.contextFiles.findIndex(
50+
(file) => file.path === path.join(sessionWorkspace, "AGENTS.md"),
51+
);
52+
const lastAgentFileIndex = result.contextFiles.findLastIndex((file) =>
53+
file.path.startsWith(`${agentWorkspace}${path.sep}`),
54+
);
55+
56+
expect(executionAgentsIndex).toBeGreaterThan(lastAgentFileIndex);
57+
expect(result.contextFiles[executionAgentsIndex]).toEqual(
58+
expect.objectContaining({
59+
path: path.join(sessionWorkspace, "AGENTS.md"),
60+
content: "Execution project context",
61+
}),
62+
);
63+
expect(result.contextFiles).toContainEqual(
64+
expect.objectContaining({
65+
path: path.join(agentWorkspace, "SOUL.md"),
66+
content: "Canonical agent soul",
67+
}),
68+
);
69+
expect(result.contextFiles).not.toContainEqual(
70+
expect.objectContaining({ path: path.join(sessionWorkspace, "SOUL.md") }),
71+
);
72+
});
73+
74+
it("keeps same-workspace bootstrap output byte-identical", async () => {
75+
const workspace = await fs.realpath(
76+
await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-same-workspace-")),
77+
);
78+
tempDirs.push(workspace);
79+
await fs.writeFile(path.join(workspace, "AGENTS.md"), "Same workspace instructions");
80+
await fs.writeFile(path.join(workspace, "SOUL.md"), "Same workspace soul");
81+
82+
const explicit = await prepare({ agentWorkspace: workspace, sessionWorkspace: workspace });
83+
const omitted = await prepareEmbeddedAttemptBootstrap({
84+
attempt: {
85+
sessionId: "session-1",
86+
sessionKey: "agent:main:session-1",
87+
trigger: "user",
88+
isCanonicalWorkspace: true,
89+
config: { agents: { defaults: { workspace } } },
90+
} as EmbeddedRunAttemptParams,
91+
effectiveWorkspace: workspace,
92+
hasReadTool: true,
93+
isRawModelRun: false,
94+
markStage: () => undefined,
95+
resolvedWorkspace: workspace,
96+
sessionAgentId: "main",
97+
sessionLabel: "agent:main:session-1",
98+
});
99+
100+
expect(explicit).toEqual(omitted);
101+
});
102+
});

0 commit comments

Comments
 (0)