Skip to content

fix(agents): preserve workspace rules in safeguard compaction - #168446

Merged
steipete merged 2 commits into
mainfrom
fix/safeguard-compaction-workspace-rules
Oct 10, 2026
Merged

steipete merged 2 commits into
mainfrom
fix/safeguard-compaction-workspace-rules

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #168131

What Problem This Solves

Fixes missing workspace rules in safeguard compaction summaries when the Gateway starts outside the agent workspace.

User Impact

Configured AGENTS.md sections now survive automatic and explicit compaction using the effective agent workspace. Unreadable files and missing configured sections produce warnings. No configuration, protocol, schema, or migration changes are required.

Why This Change Was Made

Both session preparation paths already know the effective workspace, but omitted it when building safeguard extensions. The factory now requires that input, both callers supply it, and the reader no longer falls back to the Gateway's working directory. Bounded reads, alias checks, the legacy heading fallback, and available sections remain intact.

The workspace reader and its existing tests now have a small owner module, removing the old global test-only reader export. An existing safeguard test group moved to test support to keep grandfathered oversized files shrinking without dropping coverage.

Evidence

Both real caller regressions failed on main and passed after the repair. Reverting only the two production callers made both marker assertions fail again. The main baseline was also reproduced through a real isolated Gateway on a fresh AWS machine with the QA mock provider: compaction succeeded, but the persisted summary lacked both <workspace-critical-rules> and the workspace marker.

The fixed candidate passed the same real Gateway flow on a separate fresh AWS machine: the persisted summary contains <workspace-critical-rules>, the configured heading, and QA-SAFEGUARD-WORKSPACE-RULE-168131 despite a different process cwd. Both real compaction-summary HTTP requests succeeded, and the Gateway shut down cleanly.

Local core types, the owning test-type groups (agents-root, agents-other, agents-sessions), targeted oxlint, oxfmt, documentation configuration checks, and assertion/mock/timeout ratchets passed. Independent Codex autoreview was scoped-clean through P2. pnpm check:changed is blocked by an inherited main environment-variable budget failure: 456 names against 455. The same failure was reproduced using the unchanged main index with node --import ./scripts/tsx.mjs scripts/check-env-var-count.mts --staged --base HEAD before staging this patch.

Proof commands, source identity, cost, and scope

Base refreshed with git fetch origin main && git merge origin/main before final proof: 8b677154aef03278c14100a8dca7c629a8b1b4cb.
Candidate: c0e68ecb4710a7bf756dc7c80b4a9e6c6277071d; full Git tree: 21c4d7219f1f3e800dde79aec2ef0ce63278a79a.

Caller regressions:

node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run/attempt-session.test.ts \
  src/agents/embedded-agent-runner/compact.hooks.test.ts

The two complete caller files passed 109 tests (29.00 s Vitest, 56.48 s wrapper). New cases took 27 ms and 244 ms. The production-only negative control used the same command with -t 'keeps .*workspace rules in .*compaction': both tests failed for the absent marker (8.28 s Vitest, 60.21 s wrapper including worker recompilation). Fixed bytes were restored and verified.

After owner extraction, those two files plus compaction-safeguard.test.ts and compaction-workspace-context.test.ts passed 184 tests with --maxWorkers=1 in 62.50 s wrapper wall time. The other affected factory/redaction tests also passed. CI is attached to the exact PR head: https://github.com/openclaw/openclaw/actions/runs/38052908605. Test-job timing remains pending while that run is in_progress.

Remote baseline: AWS cbx_f142786e0d1d, r7a.xlarge, 32 GiB, exact main 45c7bc9e9ca9a838115d560ec13b67d287c3d2b4. The task launcher fetched the pinned source into a fresh checkout, installed frozen dependencies, built private QA, started the real Gateway in isolated state on an ephemeral port with cwd distinct from workspace, wrote a synthetic AGENTS.md section, and called sessions.compact without maxLines. The persisted summary had hasWorkspaceBlock=false, hasMarker=false; two compaction-summary provider requests succeeded. Compaction took 1,873 ms; complete remote command 207.9 s. Gateway confirmed stopped, lease released and absent from the final lease inventory.

Remote candidate: separate fresh AWS cbx_00de3dcc73bc, r7a.xlarge, same memory class. The unpublished candidate was reconstructed from the pinned base plus a SHA-256-verified patch; git write-tree matched the candidate tree above before execution. All 358 files / 4,530 tests passed across nine configurations. Complete module tests took 1,138 s; core types 72 s; owning test-type lane 288 s; private QA build 72 s; live Gateway proof 57 s. Aggregate remote command exit 0 (28m27.714s); live compaction itself took 1,927 ms. A shared AWS vCPU quota refusal cleared after one retry following a 4.5-minute wait.

Exact credential-free baseline and candidate launch commands:

env -u CRABBOX_AWS_INSTANCE_PROFILE -u CRABBOX_TAILSCALE -u CRABBOX_TAILSCALE_AUTH_KEY -u CRABBOX_TAILSCALE_AUTH_KEY_ENV -u CRABBOX_TAILSCALE_EXIT_NODE -u CRABBOX_TAILSCALE_EXIT_NODE_ALLOW_LAN_ACCESS -u CRABBOX_TAILSCALE_HOSTNAME_TEMPLATE -u CRABBOX_TAILSCALE_TAGS TMPDIR=/private/tmp/oc-r7-safeguard CRABBOX_ENV_ALLOW=CI node scripts/crabbox-wrapper.mjs run --provider aws --type r7a.xlarge --market on-demand --network public --tailscale=false --tailscale-exit-node= --tailscale-exit-node-allow-lan-access=false --no-hydrate --no-sync --label r7-safeguard-baseline --idle-timeout 90m --ttl 240m --stop-after always --timing-json --capture-stdout /private/tmp/oc-r7-safeguard/aws-baseline.stdout.log --capture-stderr /private/tmp/oc-r7-safeguard/aws-baseline.stderr.log --download /private/tmp/oc-r7-safeguard/live-baseline.json=/private/tmp/oc-r7-safeguard/live-baseline.json --script /private/tmp/oc-r7-safeguard/run-live-baseline.sh

env -u CRABBOX_AWS_INSTANCE_PROFILE -u CRABBOX_TAILSCALE -u CRABBOX_TAILSCALE_AUTH_KEY -u CRABBOX_TAILSCALE_AUTH_KEY_ENV -u CRABBOX_TAILSCALE_EXIT_NODE -u CRABBOX_TAILSCALE_EXIT_NODE_ALLOW_LAN_ACCESS -u CRABBOX_TAILSCALE_HOSTNAME_TEMPLATE -u CRABBOX_TAILSCALE_TAGS TMPDIR=/private/tmp/oc-r7-safeguard CRABBOX_ENV_ALLOW=CI node scripts/crabbox-wrapper.mjs run --provider aws --type r7a.xlarge --market on-demand --network public --tailscale=false --tailscale-exit-node= --tailscale-exit-node-allow-lan-access=false --no-hydrate --no-sync --label r7-safeguard-candidate --idle-timeout 90m --ttl 240m --stop-after always --timing-json --capture-stdout /private/tmp/oc-r7-safeguard/aws-candidate.stdout.log --capture-stderr /private/tmp/oc-r7-safeguard/aws-candidate.stderr.log --download /private/tmp/oc-r7-safeguard/live-candidate.json=/private/tmp/oc-r7-safeguard/live-candidate.json --download /private/tmp/oc-r7-safeguard/candidate-phases.tsv=/private/tmp/oc-r7-safeguard/candidate-phases.tsv --script /private/tmp/oc-r7-safeguard/run-live-candidate.sh

The standalone task launcher fetched the exact public base into its own checkout and verified the applied candidate, then ran these phases sequentially:

OPENCLAW_BUILD_PRIVATE_QA=1 pnpm openclaw --version
node --import ./scripts/tsx.mjs /private/tmp/oc-r7-safeguard/live-safeguard-proof.mjs "$PWD" present /private/tmp/oc-r7-safeguard/live-candidate.json
pnpm tsgo:core
pnpm tsgo:core:test --changed-paths-json '["src/agents/agent-hooks/compaction-safeguard.test.ts","src/agents/agent-hooks/compaction-workspace-context.test.ts","src/agents/embedded-agent-runner/extensions.test.ts","src/agents/embedded-agent-runner.extensions.test.ts","src/agents/embedded-agent-runner/run/attempt-session.test.ts","src/agents/embedded-agent-runner/compact.hooks.test.ts","src/agents/sessions/agent-session-tool-result-redaction.test.ts"]'

node scripts/run-vitest.mjs received the explicit 358-file list: every test under src/agents/agent-hooks and src/agents/embedded-agent-runner, plus src/agents/embedded-agent-runner.extensions.test.ts and the session agent-session-compaction-boundary, agent-session-compaction, and agent-session-tool-result-redaction test files. No extensions changed, so the extension type lane was not needed.

Both live fixtures used compaction.mode: "safeguard" and postCompactionSections: ["Safeguard proof critical rules"]. The synthetic QA fixture disabled the separate semantic quality audit, while exercising the real Gateway, summary request, workspace read, and persisted transcript. Fixed summary excerpt:

<workspace-critical-rules>
## Safeguard proof critical rules

Always preserve QA-SAFEGUARD-WORKSPACE-RULE-168131.
</workspace-critical-rules>

Both task Gateways confirmed stopped. Both AWS leases were explicitly released, and the final crabbox list --provider aws --json inventory contains neither owned lease ID.

Exact aggregate numstat versus the proof base: production +82/-77 (net +5), tests/support +585/-394, docs +1/-1. The production LOC exception is the small reader-module extraction required by the enforced oversized-file growth gate, alongside visible warnings; the initial inline fix was net zero. No checks, bounds, or assertions were weakened to meet the size target.

ClawSweeper's issue findings are addressed by both caller-to-summary regressions, the required workspace contract, removal of the cwd fallback, and live persisted-summary proof. No claim is made that mocks test an external model service; the live proof tests the real Gateway and storage flow against the deterministic QA provider.

Landing CI attribution

Reviewed landing head: 0e1996f50cb4a53054229daa7c03373a81ffdde7. It incorporates the main fix for prepared-model-runtime.scoped-refresh.test.ts without changing this PR's product patch.

Exact-head CI run 38053560800, attempt 1 completed with 48 successful jobs, 23 skipped jobs, and two failures: checks-node-changed-compact-large-8 plus its downstream openclaw/ci-gate. The sole root failure is server-worker-placement-session-evidence.test.ts / keeps ordinary directory discovery failures independent from incognito evidence: expected [ 'unknown', 'unknown', 'unknown' ] to deeply equal [ 'unknown', 'current', 'absent' ].

The latest scheduled main run independently reports the identical failure. This PR does not change that test or its placement/config-session/state/infra inputs. The inspected CI checkout is 9dbae401bfb66affc492dc0e9493f5421c279b8c, with baseline 240fa4ae59b3016f9507f49cdd21658e6f56e161 and the exact reviewed head as ordered parents. No CI jobs were cancelled; security-fast and the remaining selected checks passed. Landing uses the authorized native inherited-failure exception and retains the failed CI result.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 10, 2026
@steipete
steipete marked this pull request as ready for review October 10, 2026 12:41
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR makes safeguard compaction read configured AGENTS.md sections from the effective agent workspace and warn when rules cannot be included.

Example: The Gateway runs from / while the agent workspace contains a configured section with QA-SAFEGUARD-WORKSPACE-RULE-168131.

  • Before: Compaction succeeds but the stored summary lacks the workspace rules.
  • After: The stored summary includes the configured section inside <workspace-critical-rules>.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused root-cause repair with shipped-entry-point proof and useful caller regressions; the unclassified CI failure remains a landing gate.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied real Gateway sessions.compact output exercises the changed workspace reader with cwd distinct from workspace and shows the marker in the persisted candidate summary; caller regressions additionally cover automatic and explicit preparation with reported negative controls.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Agents can lose explicitly configured workspace rules after compaction when the Gateway starts outside their workspace.
Reason: Restores the established workspace contract for both callers without changing defaults, public APIs, or stored settings.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it repairs a confirmed workspace handoff bug in both compaction paths, with no actionable code defects found.

Priority: P2
Reviewed head: 0e1996f50cb4a53054229daa7c03373a81ffdde7

Before merge

None.

Findings

None.

Agent review details

How this fits together

Embedded session preparation supplies workspace and configuration facts to the safeguard extension, which appends bounded workspace rules to the summary before session persistence.

flowchart TD
A[Automatic session preparation] --> C[Extension factory]
B[Explicit compaction preparation] --> C
C --> D[Session scoped safeguard runtime]
D --> E[Bounded workspace reader]
E --> F[Summary finalization]
F --> G[Persisted compaction summary]
Loading

Technical review

Best possible solution:

Use the effective workspace throughout both compaction paths while retaining the existing opt-in, file boundaries, and summary limits.

Do we have a high-confidence way to reproduce the issue?

Current main shows both missing workspace arguments and the cwd fallback; the supplied baseline Gateway trace confirms the resulting missing persisted rules.

Is this the best way to solve the issue?

The patch repairs the missing facts at both producers, strengthens the internal contract, and preserves the existing reader safeguards without adding configuration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 240fa4ae59b3.

Provenance checked

  • Workspace rule append keeps the original intent (c4f8294: Keep critical workspace rules available after conversation compaction.)
  • Opt-in selection and workspace parameter keeps the original intent (ab910f8: Make reinjection explicitly configured and read from the run workspace.)
  • Workspace file safety keeps the original intent (07b16d5: Harden bootstrap reads against boundary and alias violations.)
  • Bounded bootstrap reads keeps the original intent (31f2c51: Prevent oversized workspace metadata from causing unbounded allocations during compaction.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 89c9847 adds src/agents/embedded-agent-runner/extensions.ts:22 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 89c984736562; files: src/agents/embedded-agent-runner/extensions.ts)

PR surface

Source +5, Tests +191, Docs 0. Total +196 across 15 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 5 82 77 +5
Tests 9 585 394 +191
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 668 472 +196

Review metrics

Metric Value Why it matters
Production versus test LOC Production +82/-77; tests/support +585/-394 Most churn moves the reader and retained tests; the small production increase adds diagnostics and completes the workspace contract.

Labels

Label changes:

  • add P2: Configured workspace rules can silently disappear during compaction when the Gateway cwd differs, affecting an opt-in session-context feature.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Configured workspace rules can silently disappear during compaction when the Gateway cwd differs, affecting an opt-in session-context feature.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 10, 2026, 8:59 AM ET / 12:59 UTC.

@steipete
steipete merged commit d7f014a into main Oct 10, 2026
137 of 140 checks passed
@steipete
steipete deleted the fix/safeguard-compaction-workspace-rules branch October 10, 2026 13:09
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
RomneyDa added a commit that referenced this pull request Oct 12, 2026
… (extracted hotfix)

Extracted from #168446 (d7f014a): took only the workspaceDir plumbing.
Manual compaction (compaction-session-execution.ts) and attempt session
preparation (attempt-session-prepare.ts) now pass the effective workspace to
buildEmbeddedExtensionFactories, and extensions.ts makes workspaceDir
required. Without it the compaction safeguard defaults to process.cwd(), so
service installs (Gateway cwd != workspace) lose AGENTS.md critical rules on
compaction. Carried the attempt-session regression case and the
required-field updates in existing tests (plus the branch-only
compaction-safeguard.test.ts caller). Left out the compaction-workspace-context
module extraction, the compact.hooks test-suite reshuffle, and docs: they are
refactors with no behavior change for this bug.

Extracted-from: d7f014a
Co-authored-by: Peter Steinberger <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 12, 2026
Release provenance: 89329f6 -> #168587
Release provenance: e6a9022 -> #168905
Release provenance: 15f3f12 -> #162266
Release provenance: 20805b8 -> #169430
Release provenance: 568fec8 -> #169102
Release provenance: 39dba6d -> #160440
Release provenance: 5df28c7 -> #168393
Release provenance: 10bcd8e -> #168164
Release provenance: dc5f1f5 -> #168446
Release provenance: 9f1e441 -> #168044
Release provenance: 5a235fc -> #168651
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

1 participant