Skip to content

Commit 6448550

Browse files
authored
fix(codex): preserve project instructions in restricted turns (#126891)
* fix(codex): preserve restricted project instructions * fix(codex): preserve ring-zero context isolation * docs(codex): explain restricted turns and ring zero
1 parent 781ded8 commit 6448550

10 files changed

Lines changed: 254 additions & 42 deletions

‎docs/plugins/codex-harness-reference.md‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -808,14 +808,67 @@ the fallback catalog:
808808
}
809809
```
810810

811+
## Restricted turns
812+
813+
The Codex harness evaluates the effective tool policy for every turn. It marks
814+
the turn policy-restricted when any explicit policy would otherwise leave a
815+
Codex-native capability outside the OpenClaw policy boundary.
816+
817+
Restriction sources include global, provider, agent, group, sender, sandbox,
818+
subagent, inherited, scheduled/runtime, and per-run tool policies. A finite
819+
allowlist always restricts the native surface. A deny list restricts it when an
820+
expanded entry is unknown or absent from the audited safe-deny set; this includes
821+
wildcards and tool groups containing any unsafe entry. `disableTools` becomes an
822+
empty per-run allowlist and therefore also restricts the native surface. Default
823+
tool-profile narrowing is not an explicit restriction and does not activate this
824+
mode.
825+
826+
The current audited safe-deny names are:
827+
828+
```text
829+
automations, canvas, dashboard, gateway, heartbeat_respond, image_generate,
830+
memory_get, memory_search, message, music_generate, show_widget, skill_workshop,
831+
tts, video_generate, web_fetch, x_search
832+
```
833+
834+
A policy containing only those denies stays on the normal Codex native surface;
835+
the harness applies the named OpenClaw denial directly. Any other deny fails
836+
closed into the restricted surface. For example, `tools.deny: ["nodes"]`
837+
restricts the native surface because `nodes` is not in the audited set.
838+
839+
Policy-restricted turns have no Codex environment selection or native Code Mode.
840+
OpenClaw disables inherited and configured MCP servers, attests that they remain
841+
disabled, disables native hook relays, and applies the effective policy to its
842+
dynamic tools. A temporary restriction on an existing session uses a transient
843+
Codex thread and preserves the unrestricted binding for later resume.
844+
845+
Ring zero is not a configurable policy profile. It is the host-scoped system
846+
agent path used by OpenClaw setup and repair flows. The host must activate the
847+
system-agent authority and provide the exact single-tool allowlist
848+
`["openclaw"]`. Ring zero applies the restricted tool surface plus host-authored
849+
base instructions and zero project-document budget. It also suppresses
850+
OpenClaw's `AGENTS.md` developer-instruction carrier, so ambient workspace
851+
instructions cannot enter the setup/repair turn.
852+
853+
Message-only source replies also use the restricted tool surface. Lightweight
854+
bootstrap turns and tool-disabled internal turns additionally set the project-
855+
document budget to zero. These modes are separate inputs even when their final
856+
thread configuration overlaps.
857+
811858
## Workspace bootstrap files
812859

813-
Codex handles `AGENTS.md` itself through native project-doc discovery.
860+
Codex normally handles `AGENTS.md` itself through native project-doc discovery.
814861
OpenClaw does not write synthetic Codex project-doc files or depend on Codex
815862
fallback filenames for persona files, because Codex fallbacks only apply when
816-
`AGENTS.md` is missing.
817-
818-
For OpenClaw workspace parity, local tool notes live in the `## Tools` section of `AGENTS.md` and ride Codex's native project-doc discovery. The Codex harness forwards the other bootstrap files as developer instructions:
863+
`AGENTS.md` is missing. Ordinary policy-restricted turns have no native
864+
filesystem environment, so OpenClaw instead sends the bounded workspace
865+
`AGENTS.md` snapshot as thread-level developer instructions. Ring-zero,
866+
lightweight, message-only, and tool-disabled internal turns suppress that
867+
carrier.
868+
869+
For OpenClaw workspace parity, local tool notes live in the `## Tools` section
870+
of `AGENTS.md` and normally ride Codex's native project-doc discovery. The
871+
Codex harness forwards the other bootstrap files as developer instructions:
819872

820873
- `SOUL.md`, `IDENTITY.md`, and `USER.md` are forwarded as **turn-scoped**
821874
collaboration instructions. Native Codex subagents do not inherit them,

‎docs/plugins/codex-harness-runtime.md‎

Lines changed: 18 additions & 15 deletions
Large diffs are not rendered by default.

‎docs/plugins/codex-harness.md‎

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,13 +271,63 @@ Changing auth order does not make a custom, Completions, HTTP, or
271271
request-overridden route Codex-compatible. Valid model-scoped Fast-mode and
272272
cutoff controls are runtime controls, not request overrides.
273273

274+
### Restricted turns and ring zero
275+
276+
OpenClaw applies Codex restrictions per turn, not as a permanent session mode.
277+
An existing session can therefore run one restricted turn and return to its
278+
normal Codex thread on the next unrestricted turn. When a restriction is
279+
temporary, OpenClaw preserves the normal thread binding and uses a temporary
280+
restricted thread where necessary.
281+
282+
An ordinary **policy-restricted turn** occurs when an explicit OpenClaw tool
283+
policy cannot be mapped safely onto Codex's native tool surface. Common
284+
triggers include:
285+
286+
- a finite `tools.allow` list or an internal per-run allowlist
287+
- `disableTools` or a sender/group policy that denies all tools
288+
- a `tools.deny` entry with a wildcard, tool group, unknown name, or name that
289+
is not in the Codex harness's audited safe-deny set
290+
- an applicable agent, provider, group, sender, sandbox, subagent, inherited,
291+
scheduled, or runtime tool policy with one of those restrictions
292+
293+
Default tool-profile narrowing alone does not trigger this mode. A deny list
294+
containing only audited OpenClaw-owned tools can also stay on the normal native
295+
surface; the harness enforces those denies without disabling unrelated Codex
296+
capabilities. See [Native tool-policy enforcement](/plugins/sdk-agent-harness#native-tool-policy-enforcement)
297+
for the generic harness contract and [Codex harness reference](/plugins/codex-harness-reference#restricted-turns)
298+
for the current Codex rules.
299+
300+
For an ordinary policy-restricted turn, OpenClaw disables Codex native Code
301+
Mode, removes environment selections, disables and verifies inherited and
302+
configured MCP servers, disables native hook relays, and filters OpenClaw
303+
dynamic tools through the effective policy. The bounded workspace `AGENTS.md`
304+
snapshot still reaches the model as thread-level developer instructions because
305+
project instructions are context, not tool authority.
306+
307+
**Ring zero** is stronger and separate. It is the host-owned OpenClaw system
308+
agent used for setup and repair operations. The host activates it with the
309+
single `openclaw` tool; normal agent config cannot opt a chat into ring zero.
310+
Ring-zero turns keep only that host-scoped tool, replace ambient Codex
311+
instructions with host-authored setup instructions, disable native tools and
312+
MCP servers, and suppress workspace project documents, including the
313+
`AGENTS.md` developer-instruction carrier.
314+
315+
Other narrow internal modes also suppress project documents: lightweight
316+
bootstrap turns, message-only source replies, and tool-disabled internal turns.
317+
They share some isolation settings with policy-restricted turns but are not
318+
synonyms for ring zero.
319+
274320
### Project instructions
275321

276322
Codex loads `AGENTS.md` files through native project-document discovery. For
277323
normal app-server threads, OpenClaw raises Codex's aggregate root-to-working-
278324
directory budget from the upstream 32 KiB default to a bounded 128 KiB so later
279-
scoped instructions are not silently clipped. Lightweight and restricted turns
280-
set the native project-document budget to zero instead.
325+
scoped instructions are not silently clipped. Ordinary conversation tool-policy
326+
restrictions preserve that budget because project instructions are context, not
327+
tool authority. Their isolated native environment cannot read workspace files,
328+
so OpenClaw supplies the bounded workspace `AGENTS.md` snapshot as thread-level
329+
developer instructions. Lightweight, ring-zero, message-only, and tool-disabled
330+
internal turns set the native project-document budget to zero instead.
281331

282332
This byte budget is separate from the character-based workspace bootstrap
283333
limits configured through `agents.defaults.bootstrapMaxChars` and

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ describe("Codex app-server attempt context", () => {
141141
sessionKey: "agent:main:session-1",
142142
sessionAgentId: "main",
143143
memoryToolNames: ["memory_search", "memory_get"],
144+
ringZeroActive: false,
144145
});
145146

146147
expect(context.memoryReferenceFiles).toEqual([]);
@@ -181,6 +182,7 @@ describe("Codex app-server attempt context", () => {
181182
sessionKey: "agent:marketing-agent:session-1",
182183
sessionAgentId: "marketing-agent",
183184
memoryToolNames: ["memory_search", "memory_get"],
185+
ringZeroActive: false,
184186
sandboxed: true,
185187
});
186188

@@ -219,6 +221,7 @@ describe("Codex app-server attempt context", () => {
219221
sessionKey: "agent:main:session-1",
220222
sessionAgentId: "main",
221223
memoryToolNames: ["memory_search", "memory_get"],
224+
ringZeroActive: false,
222225
});
223226

224227
expect(context.threadDeveloperInstructions).toContain("Canonical agent instructions");
@@ -241,6 +244,37 @@ describe("Codex app-server attempt context", () => {
241244
}
242245
});
243246

247+
it("keeps ambient workspace instructions out of overlapping ring-zero restrictions", async () => {
248+
const workspaceDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-ring-zero-workspace-"));
249+
const executionDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-ring-zero-execution-"));
250+
await fs.writeFile(path.join(workspaceDir, "AGENTS.md"), "Ambient workspace instructions");
251+
252+
try {
253+
const context = await buildCodexWorkspaceBootstrapContext({
254+
params: {
255+
sessionId: "session-1",
256+
sessionKey: "agent:openclaw:session-1",
257+
toolsAllow: ["openclaw"],
258+
pluginHarnessToolPolicyRestricted: true,
259+
config: { agents: { defaults: { workspace: workspaceDir } } },
260+
} as EmbeddedRunAttemptParams,
261+
resolvedWorkspace: workspaceDir,
262+
executionWorkspace: executionDir,
263+
effectiveWorkspace: executionDir,
264+
sessionKey: "agent:openclaw:session-1",
265+
sessionAgentId: "openclaw",
266+
memoryToolNames: [],
267+
ringZeroActive: true,
268+
});
269+
270+
expect(context.threadDeveloperInstructions).toBeUndefined();
271+
expect(context.threadDeveloperInstructionFiles).toEqual([]);
272+
} finally {
273+
await fs.rm(workspaceDir, { recursive: true, force: true });
274+
await fs.rm(executionDir, { recursive: true, force: true });
275+
}
276+
});
277+
244278
it("reads and compares thread-bootstrap context-engine projections", () => {
245279
const projection = readContextEngineThreadBootstrapProjection({
246280
mode: "thread_bootstrap",

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import type {
2626
} from "openclaw/plugin-sdk/session-transcript-runtime";
2727
import { readNonBlankString as readNonEmptyString } from "openclaw/plugin-sdk/string-coerce-runtime";
2828
import type { EmbeddedRunAttemptResult } from "./attempt-terminal.js";
29+
import { isMessageOnlyCodexSourceReply } from "./dynamic-tool-profile.js";
2930
import type { CodexDynamicToolFunctionSpec, CodexDynamicToolSpec, JsonValue } from "./protocol.js";
3031
import { flattenCodexDynamicToolFunctions, isJsonObject } from "./protocol.js";
3132
import type { CodexAppServerThreadBinding } from "./session-binding.js";
@@ -176,6 +177,7 @@ export async function buildCodexWorkspaceBootstrapContext(params: {
176177
sessionKey: string;
177178
sessionAgentId: string;
178179
memoryToolNames: readonly string[];
180+
ringZeroActive: boolean;
179181
sandboxed?: boolean;
180182
}): Promise<CodexWorkspaceBootstrapContext> {
181183
try {
@@ -244,8 +246,15 @@ export async function buildCodexWorkspaceBootstrapContext(params: {
244246
memoryWorkspaceDir: params.effectiveWorkspace,
245247
});
246248
const injectOpenClawContext = shouldInjectCodexOpenClawPromptContext(params.params);
249+
const restrictedProjectDocNeedsOpenClawCarrier =
250+
params.params.pluginHarnessToolPolicyRestricted === true &&
251+
!params.params.disableTools &&
252+
!isMessageOnlyCodexSourceReply(params.params) &&
253+
params.params.bootstrapContextMode !== "lightweight";
247254
const threadDeveloperInstructionFiles =
248-
injectOpenClawContext && inheritsAgentWorkspace
255+
injectOpenClawContext &&
256+
!params.ringZeroActive &&
257+
(inheritsAgentWorkspace || restrictedProjectDocNeedsOpenClawCarrier)
249258
? selectCodexWorkspaceAgentProjectInstructionFiles(contextFiles, params.resolvedWorkspace)
250259
: [];
251260
const turnScopedDeveloperInstructionFiles = injectOpenClawContext

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
CODEX_APP_SERVER_CONTEXT_ENGINE_HOST,
55
embeddedAgentLog,
66
getAgentHarnessHookRunner,
7+
isHostScopedAgentToolActive,
78
resolveContextEngineOwnerPluginId,
89
runHarnessContextEngineMaintenance,
910
} from "openclaw/plugin-sdk/agent-harness-runtime";
@@ -21,6 +22,7 @@ import {
2122
resolveCodexContinuityProjectionMaxChars,
2223
type CodexProjectedContextRange,
2324
} from "./context-engine-projection.js";
25+
import { isSystemAgentOnlyCodexDynamicToolAllowlist } from "./dynamic-tool-profile.js";
2426
import type { CodexAttemptRuntime } from "./run-attempt-runtime.js";
2527
import { joinPresentSections } from "./run-attempt-state.js";
2628
import type { CodexAttemptTools } from "./run-attempt-tool-setup.js";
@@ -148,11 +150,14 @@ export async function prepareCodexAttemptContext(
148150
sessionKey: contextSessionKey,
149151
sessionAgentId,
150152
memoryToolNames,
153+
ringZeroActive:
154+
isHostScopedAgentToolActive("openclaw") &&
155+
isSystemAgentOnlyCodexDynamicToolAllowlist(runtimeParams.toolsAllow),
151156
sandboxed: sandbox?.enabled === true,
152157
});
153158
// A thread keeps the bounded agent-workspace snapshot captured at creation.
154159
// Workspace edits take effect only in the next session.
155-
const agentWorkspaceDeveloperInstructions = workspaceBootstrapContext.inheritsAgentWorkspace
160+
const agentWorkspaceDeveloperInstructions = workspaceBootstrapContext.threadDeveloperInstructions
156161
? (connection.mutable.startupBinding?.agentWorkspaceDeveloperInstructions ??
157162
workspaceBootstrapContext.threadDeveloperInstructions)
158163
: undefined;

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,7 @@ async function buildCodexTurnContextForTest(
429429
sessionKey: params.sessionKey ?? params.sessionId,
430430
sessionAgentId,
431431
memoryToolNames,
432+
ringZeroActive: false,
432433
});
433434
const threadDeveloperInstructions = testing.buildDeveloperInstructions(params, { dynamicTools });
434435
const openClawPromptContext = buildCodexOpenClawPromptContext({
@@ -2415,6 +2416,10 @@ describe("runCodexAppServerAttempt", () => {
24152416
deny: ["exec", "process", "write", "edit"],
24162417
};
24172418
params.pluginHarnessToolPolicyRestricted = true;
2419+
const agentsGuidance = "Restricted turns keep workspace AGENTS guidance.";
2420+
await fs.mkdir(params.workspaceDir, { recursive: true });
2421+
await fs.writeFile(path.join(params.workspaceDir, "AGENTS.md"), agentsGuidance);
2422+
setAgentWorkspaceForTest(params, params.workspaceDir);
24182423
const onAgentEvent = vi.fn();
24192424
params.onAgentEvent = onAgentEvent;
24202425
const harness = createStartedThreadHarness(async (method) => {
@@ -2437,6 +2442,7 @@ describe("runCodexAppServerAttempt", () => {
24372442
| {
24382443
dynamicTools?: CodexDynamicToolSpec[];
24392444
environments?: unknown[];
2445+
developerInstructions?: string;
24402446
config?: Record<string, unknown>;
24412447
}
24422448
| undefined;
@@ -2445,6 +2451,8 @@ describe("runCodexAppServerAttempt", () => {
24452451
);
24462452

24472453
expect(startParams?.environments).toEqual([]);
2454+
expect(startParams?.config?.project_doc_max_bytes).toBe(131_072);
2455+
expect(startParams?.developerInstructions?.split(agentsGuidance)).toHaveLength(2);
24482456
expect(startParams?.config?.["tools.update_plan.enabled"]).toBe(false);
24492457
expect(dynamicToolNames.toSorted()).toEqual(["apply_patch", "progress_card", "read"]);
24502458
const progressCardSpec = flattenSpecsWithNamespace(startParams?.dynamicTools ?? []).find(

‎extensions/codex/src/app-server/session-binding.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,8 +210,8 @@ const threadBindingSchema = z
210210
connectionScope: z.literal("supervision").optional(),
211211
supervisionSourceThreadId: z.string().trim().min(1).optional(),
212212
authProfileId: optionalStringSchema,
213-
// Freeze external-cwd AGENTS.md at thread creation; bootstrap refreshes must
214-
// not mutate the inherited policy of a resumed native session.
213+
// Freeze OpenClaw-carried AGENTS.md at thread creation; bootstrap refreshes
214+
// must not mutate the inherited policy of a resumed native session.
215215
agentWorkspaceDeveloperInstructions: optionalNonBlankStringSchema,
216216
model: optionalStringSchema,
217217
// Codex App Server owns selection for supervised and adopted threads. Keep

‎extensions/codex/src/app-server/thread-lifecycle.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,18 +355,22 @@ describe("Codex ring-zero thread config", () => {
355355
it("applies the restriction to both thread start and resume", () => {
356356
const params = createAttemptParams({ provider: "openai" });
357357
params.toolsAllow = ["openclaw"];
358+
params.pluginHarnessToolPolicyRestricted = true;
358359
const appServer = createAppServerOptions() as never;
360+
const developerInstructions = "Host-authored ring-zero instructions.";
359361
const start = buildThreadStartParams(params, {
360362
appServer,
361363
cwd: "/repo",
362364
dynamicTools: [],
365+
developerInstructions,
363366
hostSystemAgentActive: true,
364367
nativeCodeModeEnabled: false,
365368
config: { project_doc_max_bytes: 64_000 },
366369
});
367370
const resume = buildThreadResumeParams(params, {
368371
appServer,
369372
dynamicTools: [],
373+
developerInstructions,
370374
hostSystemAgentActive: true,
371375
nativeCodeModeEnabled: false,
372376
threadId: "thread-1",
@@ -375,6 +379,8 @@ describe("Codex ring-zero thread config", () => {
375379

376380
expect(start.environments).toEqual([]);
377381
expect(start.baseInstructions).toBe("");
382+
expect(start.developerInstructions).toBe(developerInstructions);
383+
expect(resume.developerInstructions).toBe(developerInstructions);
378384
for (const config of [start.config, resume.config]) {
379385
expect(config?.["agents.enabled"]).toBe(false);
380386
expect(config?.["tools.experimental_request_user_input.enabled"]).toBe(false);
@@ -402,6 +408,47 @@ describe("Codex ring-zero thread config", () => {
402408
expect(normal.baseInstructions).toBeUndefined();
403409
expect(normal.config?.["features.goals"]).toBe(false);
404410
});
411+
412+
it("preserves project documents for ordinary policy-restricted turns", () => {
413+
const params = createAttemptParams({ provider: "openai" });
414+
params.pluginHarnessToolPolicyRestricted = true;
415+
const appServer = createAppServerOptions() as never;
416+
const start = buildThreadStartParams(params, {
417+
appServer,
418+
cwd: "/repo",
419+
dynamicTools: [],
420+
hostSystemAgentActive: false,
421+
nativeCodeModeEnabled: false,
422+
});
423+
const resume = buildThreadResumeParams(params, {
424+
appServer,
425+
dynamicTools: [],
426+
hostSystemAgentActive: false,
427+
nativeCodeModeEnabled: false,
428+
threadId: "thread-1",
429+
config: { project_doc_max_bytes: 64_000 },
430+
});
431+
432+
expect(start.config?.project_doc_max_bytes).toBe(131_072);
433+
expect(resume.config?.project_doc_max_bytes).toBe(64_000);
434+
for (const threadConfig of [start.config, resume.config]) {
435+
expect(threadConfig?.["features.multi_agent"]).toBe(false);
436+
expect(threadConfig?.["orchestrator.mcp.enabled"]).toBe(false);
437+
}
438+
439+
const toolsDisabled = createAttemptParams({ provider: "openai" });
440+
toolsDisabled.disableTools = true;
441+
toolsDisabled.pluginHarnessToolPolicyRestricted = true;
442+
const disabled = buildThreadStartParams(toolsDisabled, {
443+
appServer,
444+
cwd: "/repo",
445+
dynamicTools: [],
446+
hostSystemAgentActive: false,
447+
nativeCodeModeEnabled: false,
448+
config: { project_doc_max_bytes: 64_000 },
449+
});
450+
expect(disabled.config?.project_doc_max_bytes).toBe(0);
451+
});
405452
});
406453

407454
describe("Codex delegation capability", () => {
@@ -3620,6 +3667,7 @@ describe("Codex app-server supervised branch lifecycle", () => {
36203667
| { config?: Record<string, unknown> }
36213668
| undefined;
36223669
expect(threadRequest?.config).toMatchObject({
3670+
project_doc_max_bytes: 0,
36233671
mcp_servers: {
36243672
inherited: { enabled: false },
36253673
"request-only": { enabled: false },

0 commit comments

Comments
 (0)