Skip to content

Scope workspace guidance to coding contexts - #63456

Closed
ImLukeF wants to merge 1 commit into
mainfrom
scope-workspace-guidance
Closed

ImLukeF wants to merge 1 commit into
mainfrom
scope-workspace-guidance

Conversation

@ImLukeF

@ImLukeF ImLukeF commented Apr 9, 2026

Copy link
Copy Markdown
Contributor

Summary

  • scope repo-style workspace guidance to coding contexts only
  • stop injecting commit reminders for general assistant/product sessions
  • add tests covering coding vs non-coding prompt behavior

Testing

  • pnpm exec vitest run src/agents/system-prompt.test.ts

Copilot AI review requested due to automatic review settings April 9, 2026 00:53
@aisle-research-bot

aisle-research-bot Bot commented Apr 9, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 4 potential security issue(s) in this PR:

# Severity Title
1 🟠 High API key leaked to provider plugin stream function via automatic injection
2 🟡 Medium Heartbeat prompt/ack pairs no longer filtered from replay history (prompt injection & context DoS)
3 🟡 Medium WebSocket transport ignores resolvedApiKey and may use wrong provider key (credential mix-up)
4 🟡 Medium Prompt injection via unescaped runtimeCapabilities in system prompt runtime line
1. 🟠 API key leaked to provider plugin stream function via automatic injection
Property Value
Severity High
CWE CWE-201
Location src/agents/pi-embedded-runner/run/attempt.ts:242-247

Description

In resolveEmbeddedAgentStreamFn(), when a provider-supplied providerStreamFn is present, the wrapper fetches the provider API key from authStorage and forwards it into the options object passed to that function.

This is risky because providerStreamFn is created by provider plugins (see registerProviderStreamForModel() → resolveProviderStreamFn()), which may come from workspace/global plugin code. Passing the API key into a plugin-controlled function enables credential exfiltration (confused-deputy / untrusted plugin can read and transmit the key), even if that plugin otherwise would not have access to authStorage.

Vulnerable flow:

  • Source: authStorage.getApiKey(model.provider)
  • Sink: inner(m, context, { ...options, apiKey: ... }) where inner is plugin-provided

Vulnerable code:

const apiKey = await authStorage.getApiKey(model.provider);
return inner(m, context, { ...options, apiKey: apiKey ?? options?.apiKey });

Recommendation

Do not automatically disclose stored credentials to plugin-supplied stream functions.

Options to fix:

  1. Opt-in credential access: only inject an API key when the stream function is known to be trusted/bundled, or when the plugin explicitly declares it needs credentials and is allowed by policy.

  2. Pass a credential resolver instead of the secret (so plugins never see the raw key unless absolutely required):

return inner(m, context, {
  ...options,
  getApiKey: async () => authStorage.getApiKey(model.provider),
});
  1. Respect per-request overrides: if callers supply options.apiKey, do not overwrite it (and avoid fetching from storage at all):
return async (m, context, options) => {
  if (options?.apiKey) return inner(m, context, options);
  const apiKey = await authStorage.getApiKey(model.provider);
  return inner(m, context, { ...options, apiKey });
};

Additionally, document and enforce a trust boundary for provider plugins; if plugins can be workspace-supplied, treat them as untrusted and sandbox or restrict secret access.

2. 🟡 Heartbeat prompt/ack pairs no longer filtered from replay history (prompt injection & context DoS)
Property Value
Severity Medium
CWE CWE-400
Location src/agents/pi-embedded-runner/run/attempt.ts:1187-1202

Description

The embedded runner previously removed heartbeat prompt/ack pairs (a user message containing the heartbeat task prompt followed by an assistant HEARTBEAT_OK ack) from the conversation replay before truncation.

This change removes that filtering and now truncates/forwards history based directly on validated messages:

  • Any actor who can write messages into the session history (e.g., a chat user, or any upstream component that stores messages with role: "user") can craft a message that matches the heartbeat prompt pattern.
  • If they can also cause the assistant to respond with HEARTBEAT_OK (often easy to elicit), that pair will remain in the replayed context.
  • Keeping these “system-like” heartbeat instructions in history enables:
    • Prompt injection persistence: attacker-crafted heartbeat-style instructions remain in the model context for subsequent runs.
    • Context exhaustion / history eviction: because limitHistoryTurns() counts user turns, repeated heartbeat-style user turns can rapidly push legitimate prior context out of the retained window (DoS against conversation continuity).

Previously this was mitigated by filterHeartbeatPairs(validated, ackMaxChars, heartbeatPrompt) (removed in this diff).

Recommendation

Re-introduce heartbeat-pair suppression (or an equivalent invariant) before history truncation and before sending messages to the provider.

Options:

  1. Restore filtering similar to the removed logic:
import { filterHeartbeatPairs } from "../../../auto-reply/heartbeat-filter.js";
import { resolveHeartbeatSummaryForAgent } from "../../../infra/heartbeat-summary.js";

const heartbeatSummary = params.config && sessionAgentId
  ? resolveHeartbeatSummaryForAgent(params.config, sessionAgentId)
  : undefined;

const heartbeatFiltered = filterHeartbeatPairs(
  validated,
  heartbeatSummary?.ackMaxChars,
  heartbeatSummary?.prompt,
);

const truncated = limitHistoryTurns(heartbeatFiltered, historyLimit);
  1. Preferably, tag heartbeat turns at creation time (e.g., provenance/customType) and drop them deterministically during replay (less brittle than string-prefix matching).

Also consider excluding heartbeat turns from limitHistoryTurns() user-turn counting so they cannot be used to evict meaningful history.

3. 🟡 WebSocket transport ignores resolvedApiKey and may use wrong provider key (credential mix-up)
Property Value
Severity Medium
CWE CWE-287
Location src/agents/pi-embedded-runner/run/attempt.ts:946-952

Description

In runEmbeddedAttempt, the API key used for OpenAI WebSocket transport is fetched directly from authStorage using params.provider:

  • The previous implementation resolved the key via resolveEmbeddedAgentApiKey({ provider, resolvedApiKey, authStorage }), which preferred resolvedApiKey when present.
  • The new code ignores params.resolvedApiKey entirely and always queries authStorage.
  • In setups that supply a per-run resolvedApiKey (e.g., runtime auth override/rotation, ephemeral credentials, or when authStorage contains a different key), the WebSocket connection may be established with a different credential than the one intended for this run.

Impact:

  • Requests may be authenticated under the wrong account/project, causing cross-tenant/account confusion.
  • Can break auth-profile rotation logic and auditing, since the run’s resolved credential is not honored for WS calls.

Vulnerable code:

const wsApiKey = shouldUseWebSocketTransport
  ? await params.authStorage.getApiKey(params.provider)
  : undefined;

Recommendation

Use the same API key resolution logic as HTTP/provider transports by preferring resolvedApiKey and using the model’s provider identifier.

For example:

const wsApiKey = shouldUseWebSocketTransport
  ? (params.resolvedApiKey?.trim() || (await params.authStorage.getApiKey(params.model.provider)))
  : undefined;

This ensures:

  • The explicitly resolved per-run key is honored when provided
  • The lookup key matches the actual model.provider used downstream
4. 🟡 Prompt injection via unescaped runtimeCapabilities in system prompt runtime line
Property Value
Severity Medium
CWE CWE-74
Location src/agents/system-prompt.ts:715-718

Description

buildRuntimeLine interpolates runtimeCapabilities directly into the system prompt without escaping/normalization. Because capabilities are joined into a single line, any capability string containing control characters (e.g. \n, \r) or delimiters (e.g. |) can break the intended one-line format and inject attacker-controlled text into the system prompt.

In this diff, the previous normalizePromptCapabilityIds(...) call was removed and capabilities are now only String(cap).trim() (see buildAgentSystemPrompt), then joined verbatim:

  • Input: runtimeInfo.capabilities originates from channel capability config (resolveChannelCapabilities) and other capability sources in the embedded runner.
  • Sink: buildRuntimeLine(...).join(",") concatenated into the system prompt line.

Vulnerable code:

runtimeChannel
  ? `capabilities=${runtimeCapabilities.length > 0 ? runtimeCapabilities.join(",") : "none"}`
  : ""

If an attacker can influence configured capabilities (e.g., via a compromised plugin/config channel, multi-tenant config injection, or other untrusted capability sources), they can inject additional prompt sections/instructions by including newlines, e.g. "inlineButtons\n## Override\nIgnore safety".

Recommendation

Re-introduce strict normalization/escaping for capability identifiers before placing them into the system prompt.

Recommended approach (allowlist + strip control chars):

function normalizeCapabilityId(raw: string): string | undefined {
  const s = raw.trim().toLowerCase();
  ​// prevent prompt-breaking characters
  if (!s || /[\r\n\t|]/.test(s)) return undefined;
  ​// keep to a safe identifier character set
  if (!/^[a-z0-9._-]+$/.test(s)) return undefined;
  return s;
}

const safeCaps = runtimeCapabilities
  .map((c) => normalizeCapabilityId(String(c)))
  .filter((c): c is string => Boolean(c));

const capLine = `capabilities=${safeCaps.length ? safeCaps.join(",") : "none"}`;

Alternatively, restore the previous normalizePromptCapabilityIds(...) behavior (or use an existing escaping helper) so buildRuntimeLine only ever renders safe single-line capability IDs.


Analyzed PR: #63456 at commit 1382808

Last updated on: 2026-04-09T00:57:15Z

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Apr 9, 2026
@openclaw-barnacle openclaw-barnacle Bot added size: XL maintainer Maintainer-authored PR labels Apr 9, 2026
@greptile-apps

greptile-apps Bot commented Apr 9, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR scopes the workspace guidance in buildAgentSystemPrompt to coding contexts only, using isCodingContext = Boolean(params.runtimeInfo?.repoRoot). Non-coding (general assistant/product) sessions now receive conservative workspace text that discourages creating git history unless explicitly asked, while coding sessions (those with a repoRoot) keep the existing directive-style workspace instruction. The test file also drops several tests for prompt sections that were removed or refactored in the system prompt (Execution Bias, cron scheduling details, update_plan hints, extended silent-reply guidance), and updates approval-channel assertions to match the revised wording in buildExecApprovalPromptGuidance.

Confidence Score: 5/5

Safe to merge — all remaining findings are P2 or lower.

The core change (isCodingContext guard on workspace guidance) is correct, well-tested, and has no logical edge cases. The SYSTEM_PROMPT_CACHE_BOUNDARY constant is still used throughout the pipeline in other test files; its removal from buildAgentSystemPrompt's output is an intentional refactor, not a regression. Removed tests correspond to prompt sections that were intentionally pruned. No P0 or P1 issues found.

No files require special attention.

Vulnerabilities

No security concerns identified.

Reviews (1): Last reviewed commit: "Scope workspace guidance to coding conte..." | Re-trigger Greptile

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

Copy link
Copy Markdown
Contributor

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: 1382808cea

ℹ️ 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 1938 to 1942
return {
replayMetadata: buildAttemptReplayMetadata({
toolMetas: toolMetasNormalized,
didSendViaMessagingTool: didSendViaMessagingTool(),
successfulCronAdds: getSuccessfulCronAdds(),
}),
itemLifecycle: getItemLifecycle(),
aborted,
timedOut,
idleTimedOut,
timedOutDuringCompaction,
promptError,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Preserve attempt replay metadata and item lifecycle fields

The attempt result returned here no longer includes replayMetadata or itemLifecycle, but downstream logic in run.ts/run/incomplete-turn.ts dereferences those fields without guards when evaluating incomplete-turn and planning-only retry behavior. On normal non-aborted turns, this can raise a runtime TypeError (for example when checking attempt.itemLifecycle.startedCount) after the model call has already completed, causing the run to fail in post-processing.

Useful? React with 👍 / 👎.

Comment on lines +385 to +389
const { bootstrapFiles: hookAdjustedBootstrapFiles, contextFiles } =
await resolveBootstrapContextForRun({
workspaceDir: effectiveWorkspace,
config: params.config,
sessionKey: params.sessionKey,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Honor continuation-skip before bootstrap context injection

This now unconditionally resolves bootstrap context, which bypasses the documented agents.defaults.contextInjection: "continuation-skip" flow that should skip reinjection after a completed bootstrap turn. In continuation sessions, repeatedly reinjecting workspace bootstrap/context files increases prompt size every turn and can negate the overflow/performance protections that continuation mode is meant to provide.

Useful? React with 👍 / 👎.

Comment on lines +685 to +689
const appendPrompt = buildEmbeddedSystemPrompt({
workspaceDir: effectiveWorkspace,
context: {
config: params.config,
agentDir: params.agentDir,
workspaceDir: effectiveWorkspace,
provider: params.provider,
modelId: params.modelId,
promptMode: effectivePromptMode,
runtimeChannel,
runtimeCapabilities,
agentId: sessionAgentId,
},
defaultThinkLevel: params.thinkLevel,
reasoningLevel: params.reasoningLevel ?? "off",
extraSystemPrompt: params.extraSystemPrompt,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Respect configured systemPromptOverride for embedded runs

The embedded attempt now always uses the assembled prompt from buildEmbeddedSystemPrompt, but no longer checks the config-based override path (agents.defaults.systemPromptOverride / per-agent override). That silently drops an existing contract for users who pin a custom system prompt, and creates inconsistent behavior versus other runner paths that still resolve and apply that override.

Useful? React with 👍 / 👎.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR updates the agent system prompt construction so “workspace guidance” and related repo-style reminders are only injected in coding/repo contexts, avoiding repo-specific nudges in general assistant/product sessions.

Changes:

  • Scope workspace guidance by detecting coding contexts via runtimeInfo.repoRoot, and add tests for coding vs non-coding prompt behavior.
  • Revamp the “Tooling” section to list available tools (with summaries) when tool names are provided.
  • Refactor embedded runner attempt flow and prompt assembly to support the new prompt behavior (including commit-reminder gating).

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.

File Description
src/agents/system-prompt.ts Adjusts workspace guidance behavior and rewrites tooling/approval guidance in the system prompt.
src/agents/system-prompt.test.ts Updates prompt assertions and adds tests for coding vs non-coding workspace guidance.
src/agents/pi-embedded-runner/run/attempt.ts Refactors embedded attempt execution and system prompt assembly, including gating commit reminders by coding context.
Comments suppressed due to low confidence (1)

src/agents/pi-embedded-runner/run/attempt.ts:1965

  • runEmbeddedAttempt() now returns an object missing required EmbeddedRunAttemptResult fields (e.g., idleTimedOut, promptErrorSource, replayMetadata, itemLifecycle). This will fail TypeScript (and callers expecting these fields) unless the result type is updated accordingly. Either restore these fields in the return value or change EmbeddedRunAttemptResult to match the new shape and update downstream users/tests.
      return {
        aborted,
        timedOut,
        timedOutDuringCompaction,
        promptError,
        sessionIdUsed,
        bootstrapPromptWarningSignaturesSeen: bootstrapPromptWarning.warningSignaturesSeen,
        bootstrapPromptWarningSignature: bootstrapPromptWarning.signature,
        systemPromptReport,
        messagesSnapshot,
        assistantTexts,
        toolMetas: toolMetasNormalized,
        lastAssistant,
        lastToolError: getLastToolError?.(),
        didSendViaMessagingTool: didSendViaMessagingTool(),
        messagingToolSentTexts: getMessagingToolSentTexts(),
        messagingToolSentMediaUrls: getMessagingToolSentMediaUrls(),
        messagingToolSentTargets: getMessagingToolSentTargets(),
        successfulCronAdds: getSuccessfulCronAdds(),
        cloudCodeAssistFormatError: Boolean(
          lastAssistant?.errorMessage && isCloudCodeAssistFormatError(lastAssistant.errorMessage),
        ),
        attemptUsage: getUsageTotals(),
        compactionCount: getCompactionCount(),
        // Client tool call detected (OpenResponses hosted tools)
        clientToolCall: clientToolCallDetected ?? undefined,
        yieldDetected: yieldDetected || undefined,
      };

cfg: params.config,
trigger: params.trigger,
});
const idleTimeoutMs = resolveLlmIdleTimeoutMs(params.config);

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

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

resolveLlmIdleTimeoutMs() is being called with params.config, but the function signature expects an options object (e.g., { cfg, trigger }). As written, config-derived timeouts and the cron-trigger disable path won’t apply (and this should also be a TS type error). Pass { cfg: params.config, trigger: params.trigger } (or update resolveLlmIdleTimeoutMs signature) to preserve configured behavior.

Suggested change
const idleTimeoutMs = resolveLlmIdleTimeoutMs(params.config);
const idleTimeoutMs = resolveLlmIdleTimeoutMs({
cfg: params.config,
trigger: params.trigger,
});

Copilot uses AI. Check for mistakes.
Comment on lines 676 to 683
const ttsHint = params.config ? buildTtsSystemPromptHint(params.config) : undefined;
const ownerDisplay = resolveOwnerDisplaySetting(params.config);
const heartbeatPrompt = shouldInjectHeartbeatPrompt({
config: params.config,
agentId: sessionAgentId,
defaultAgentId,
isDefaultAgent,
trigger: params.trigger,
})
? resolveHeartbeatPromptForSystemPrompt({
config: params.config,
agentId: sessionAgentId,
defaultAgentId,
})
? resolveHeartbeatPrompt(params.config?.agents?.defaults?.heartbeat?.prompt)
: undefined;

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

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

Heartbeat prompt injection now bypasses the existing per-agent/config-aware logic: shouldInjectHeartbeatPrompt() is called without config/agentId/defaultAgentId, and heartbeatPrompt is resolved only from config.agents.defaults.heartbeat.prompt. This ignores per-agent heartbeat overrides and config flags like includeSystemPromptSection=false. Prefer using resolveHeartbeatPromptForSystemPrompt({config, agentId: sessionAgentId, defaultAgentId}) and pass the same ids into shouldInjectHeartbeatPrompt().

Copilot uses AI. Check for mistakes.
Comment on lines 189 to 235
export function buildAgentSystemPrompt(params: {
workspaceDir: string;
defaultThinkLevel?: ThinkLevel;
reasoningLevel?: ReasoningLevel;
extraSystemPrompt?: string;
ownerNumbers?: string[];
ownerDisplay?: OwnerIdDisplay;
ownerDisplaySecret?: string;
reasoningTagHint?: boolean;
toolNames?: string[];
toolSummaries?: Record<string, string>;
modelAliasLines?: string[];
userTimezone?: string;
userTime?: string;
userTimeFormat?: ResolvedTimeFormat;
contextFiles?: EmbeddedContextFile[];
skillsPrompt?: string;
heartbeatPrompt?: string;
docsPath?: string;
workspaceNotes?: string[];
ttsHint?: string;
/** Controls which hardcoded sections to include. Defaults to "full". */
promptMode?: PromptMode;
/** Whether ACP-specific routing guidance should be included. Defaults to true. */
acpEnabled?: boolean;
runtimeInfo?: {
agentId?: string;
host?: string;
os?: string;
arch?: string;
node?: string;
provider?: string;
model?: string;
defaultModel?: string;
shell?: string;
channel?: string;
capabilities?: string[];
repoRoot?: string;
};
messageToolHints?: string[];
sandboxInfo?: EmbeddedSandboxInfo;
/** Reaction guidance for the agent (for Telegram minimal/extensive modes). */
reactionGuidance?: {
level: "minimal" | "extensive";
channel: string;
};
/** Whether to include the active memory plugin prompt guidance in the base system prompt. Defaults to true. */
includeMemorySection?: boolean;
memoryCitationsMode?: MemoryCitationsMode;
promptContribution?: ProviderSystemPromptContribution;
}) {

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

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

buildAgentSystemPrompt() no longer accepts includeMemorySection/promptContribution, but there are in-repo call sites and tests still passing them (e.g., src/agents/pi-embedded-runner/system-prompt.ts passes includeMemorySection and promptContribution; src/agents/system-prompt.memory.test.ts passes includeMemorySection:false). This will break compilation/tests. Either keep these params in buildAgentSystemPrompt or update all callers/tests and remove the related plumbing in buildEmbeddedSystemPrompt.

Copilot uses AI. Check for mistakes.
Comment on lines +177 to 186
const runtimeChannel = params.runtimeChannel?.trim().toLowerCase();
if (
runtimeChannel === "discord" ||
runtimeChannel === "slack" ||
runtimeChannel === "telegram" ||
runtimeChannel === "webchat"
) {
return "When exec returns approval-pending on Discord, Slack, Telegram, or WebChat, rely on the native approval card/buttons when they appear and do not also send plain chat /approve instructions. Only include the concrete /approve command if the tool result says chat approvals are unavailable or only manual approval is possible.";
}
return "When exec returns approval-pending, include the concrete /approve command from tool output as plain chat text for the user, and do not ask for a different or rotated code.";

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

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

buildExecApprovalPromptGuidance() hardcodes the set of “native approval” channels to Discord/Slack/Telegram/WebChat, but the codebase supports native exec approvals on other channels (e.g., Matrix via approvalCapability.native / supportsNativeExecApprovalClient()). This will cause incorrect /approve guidance (duplicating manual instructions) on those channels. Consider delegating to supportsNativeExecApprovalClient() or resolveChannelApprovalCapability(getChannelPlugin(channel)) instead of hardcoding.

Suggested change
const runtimeChannel = params.runtimeChannel?.trim().toLowerCase();
if (
runtimeChannel === "discord" ||
runtimeChannel === "slack" ||
runtimeChannel === "telegram" ||
runtimeChannel === "webchat"
) {
return "When exec returns approval-pending on Discord, Slack, Telegram, or WebChat, rely on the native approval card/buttons when they appear and do not also send plain chat /approve instructions. Only include the concrete /approve command if the tool result says chat approvals are unavailable or only manual approval is possible.";
}
return "When exec returns approval-pending, include the concrete /approve command from tool output as plain chat text for the user, and do not ask for a different or rotated code.";
void params;
return "When exec returns approval-pending, rely on the native approval card/buttons when they appear and do not also send plain chat /approve instructions. Only include the concrete /approve command from tool output if the tool result says chat approvals are unavailable or only manual approval is possible, and do not ask for a different or rotated code.";

Copilot uses AI. Check for mistakes.
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 14, 2026
@clawsweeper

clawsweeper Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Keep open for explicit maintainer handling: the useful prompt-scoping idea is not on current main, but this branch is dirty, missing real behavior proof, and introduces concrete build, agent-runtime, auth, and prompt-safety regressions.

Canonical path: Close this stale PR as superseded: Replace with a narrow prompt-only branch. Recreate only the workspace-guidance scoping on current main and leave embedded-runner stream, auth, replay, and cache-boundary code unchanged unless a focused follow-up proves each contract.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this stale PR as superseded: Replace with a narrow prompt-only branch. Recreate only the workspace-guidance scoping on current main and leave embedded-runner stream, auth, replay, and cache-boundary code unchanged unless a focused follow-up proves each contract.

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

Yes for the blocking PR regressions from source inspection and CI logs: the branch has stale imports, wrong call shapes, missing attempt result fields, and changed credential/replay paths. I did not run tests locally because this review is read-only.

Is this the best way to solve the issue?

No. The prompt-scoping idea is useful, but this is not the best fix because it couples a small prompt-policy change to a broad stale embedded-runner rewrite; the safer solution is a narrow current-main prompt change with targeted tests and real behavior proof.

Security review:

Security review needs attention: The diff changes credential routing and prompt/replay safeguards in agent runtime code, creating concrete security-boundary concerns.

  • [high] Stored provider key reaches plugin stream code — src/agents/pi-embedded-runner/run/attempt.ts:246
    The PR branch reads a stored provider API key and injects it into options passed to providerStreamFn, which is provider/plugin-controlled code rather than the central trusted credential wrapper.
    Confidence: 0.9
  • [medium] Per-run WebSocket credential can be ignored — src/agents/pi-embedded-runner/run/attempt.ts:951
    The WebSocket path fetches from authStorage by provider instead of preferring the already resolved per-run credential, which can mix auth profiles or bypass key rotation for that run.
    Confidence: 0.86
  • [medium] Runtime capabilities render without strict normalization — src/agents/system-prompt.ts:717
    The branch removes capability-id normalization before joining capabilities into the system prompt runtime line, allowing malformed capability values to inject control characters into prompt text if a capability source is compromised.
    Confidence: 0.84
  • [medium] Heartbeat artifacts remain in replay context — src/agents/pi-embedded-runner/run/attempt.ts:1199
    The branch truncates validated history directly after removing heartbeat pair filtering, which can preserve heartbeat prompt/ack text in later model context and help repeated heartbeat-like turns evict useful history.
    Confidence: 0.82

AGENTS.md: found and applied where relevant.

What I checked:

  • recommended close path: the latest review's recommended merge-risk option is Replace with a narrow prompt-only branch, categorized as pause_or_close.
  • stale PR: PR was opened 2026-04-09T00:53:15Z, which is older than the 60-day stale promotion threshold.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • steipete: Recent history shows major OpenClaw agent runtime internalization, system-prompt assembly ownership, and stream-resolution/provider-auth work around the paths this PR rewrites. (role: major agent runtime refactor owner; confidence: high; commits: bb46b79d3c14, e12a6d6a67d7, 33bda2629a33; files: src/agents/embedded-agent-runner/run/attempt.ts, src/agents/embedded-agent-runner/stream-resolution.ts, src/agents/embedded-agent-runner/system-prompt.ts)
  • obviyus: Recent commits on current main touched system prompt/session binding and message-tool prompt context, adjacent to this PR's workspace guidance and prompt-contract changes. (role: recent system-prompt contributor; confidence: medium; commits: 48e8965b1060, 4e6933c84f18, e08102820e06; files: src/agents/system-prompt.ts)
  • vincentkoc: Recent commits touch embedded runner maintenance, stale facade removal, prompt/test surfaces, and related agent runtime paths affected by this stale branch. (role: recent embedded-runner and prompt-area contributor; confidence: high; commits: 0ea08076c3b5, 7f6a93eb8efd, 345ad9862d1c; files: src/agents/system-prompt.ts, src/agents/embedded-agent-runner/run/attempt.ts, src/agents/embedded-agent-runner/stream-resolution.ts)
  • fuller-stack-dev: History shows the heartbeat transcript filtering work and tool-search prompt changes adjacent to the replay and prompt invariants this PR weakens. (role: adjacent prompt/replay contributor; confidence: medium; commits: 2ab3a4e422a0, 965fa05df38b, 414ecd2b9689; files: src/auto-reply/heartbeat-filter.ts, src/agents/embedded-agent-runner/run/attempt.ts, src/agents/system-prompt.ts)

Codex review notes: model internal, reasoning high; reviewed against 010b61746379.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jun 26, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thanks @ImLukeF. Closing this stale branch rather than carrying its current diff forward. The underlying workspace-scoping idea is reasonable, but the exact head is based on the April prompt/runner implementation and now replaces large current sections: alongside the one repoRoot wording change it removes or reverts provider prompt contributions and cache-boundary ordering, native approval capability detection, execution/silent-reply safeguards, capability normalization, heartbeat/replay handling, and auth/runtime work. The branch is conflicting and maintainers cannot update it in place. If this is still worth pursuing, please reopen as a fresh current-main PR limited to workspace wording plus focused prompt tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants