…p-research
Refines both builtin workflows across all three SDKs (claude/copilot/opencode)
using shared, SDK-agnostic helpers under `_context/`.
Ralph (per-iteration coding loop):
- R1 infra-discovery hoist with `shouldReRunInfraDiscovery` invalidation —
re-run only when infra files (lockfiles, manifests, configs, CI, agent
instructions) change, otherwise reuse the cached overview.
- R2 persistent scratchpad at `.atomic/ralph/<runId>/state.md` records
planner output, debugger reports, and modified files; planner reads the
latest prior RFC + session intent from it, enabling cheap re-plans.
- R4 SPEC_REMINDER positioned at planner + reviewer prompt heads so the
primacy slot reinforces the contract on every iteration.
- R5 reviewer + debugger prompts run their changeset through `maskChangeset`
— top-N by churn for diff-stat, top-N for staged uncommitted, ALL `??`
untracked entries preserved verbatim (correctness invariant).
- R6 debugger report capped at MAX_DEBUGGER_REPORT_CHARS via
`truncateMarkdownReport` (head + tail with elision marker).
Deep-research-codebase (scout → fan-out → aggregator):
- D2 history-analyzer output condensed via `deriveHistoryBrief` (≤150
words) and injected as `<PRIOR_RESEARCH_HINT>` into per-partition
locator + analyzer prompts.
- D3 aggregator pre-flight: when the sum of partition scratch sizes
exceeds SCRATCH_COMPACT_THRESHOLD, each oversized scratch is rewritten
with `compactScratchFile` (head/tail truncation that preserves every
`## ` / `### ` heading verbatim so the aggregator's reading contract
still holds).
- D5 prose-guard: every specialist call (history-locator/analyzer +
per-partition locator/pattern-finder/analyzer/online-researcher) wrapped
in `queryWithProseGuard` — retries once with a short reminder prompt
when the assistant ends on a tool call instead of emitting prose.
New shared module `_context/`:
- `budget.ts` — token approximator + thresholds.
- `masking.ts` — pure functions: maskChangeset, compactDiffStat,
compactUncommitted, isInfraPath, infraInvalidationPaths,
shouldReRunInfraDiscovery, truncateMarkdownReport, deriveHistoryBrief,
compactReminder, queryWithProseGuard, compactScratchFile.
- `scratchpad.ts` — single-writer Ralph state-file helpers
(initScratchpad, recordPlannerOutput, recordDebuggerReport,
recordFilesModified, latestPriorRFC, detectSpecPath).
- 29 unit tests covering the pure helpers.
Verification: bun typecheck ✓, bun lint 0 warnings, bun test 1191/1191 pass.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Summary
Extracts shared context-engineering utilities into a new
_contextmodule and applies them across the Ralph and deep-research-codebase builtin workflows (Claude, Copilot, and OpenCode SDKs). The changes reduce per-turn token consumption, improve cross-iteration continuity, and harden specialist stages against empty-text responses.Key Changes
New
_contextmodule (src/sdk/workflows/builtin/_context/)budget.ts— Centralized token-budget thresholds (COMPACT_TRIGGER_FRACTION,CHANGESET_MASK_THRESHOLD,DIFF_STAT_TOP_N, etc.) so a single edit propagates to all consumersmasking.ts— Pure, unit-tested utilities: changeset masking (maskChangeset,compactDiffStat,compactUncommitted), infra-discovery invalidation (isInfraPath,shouldReRunInfraDiscovery), markdown truncation (truncateMarkdownReport), history-brief derivation (deriveHistoryBrief), compact reminder formatting, prose-guard retry (queryWithProseGuard), and scratch-file compaction (compactScratchFile)scratchpad.ts— Per-run persistent markdown scratchpad for Ralph (.atomic/ralph/<session-id>/state.md) tracking prior RFCs, files modified, decisions, rejected approaches, and debugger reports across all iterations_context.test.ts— Comprehensive test suite covering all pure utility functionsRalph workflow (
ralph/)CAVEMAN_PREAMBLE— Token-reduction meta-prompt prepended to all stage prompts (planner, orchestrator, infra-discovery agents); exempts code blocks and structured outputspriorRfcfield added toPlannerContext; injected with explicit precedence note ("Debugger Report takes precedence")<SPEC_REMINDER>anchor — Compact session intent pinned at the bottom of planner/reviewer prompts to resist prompt driftshouldReRunInfraDiscoverydetects changes to build/CI/agent-instruction files; otherwise cached result reusedDeep-research-codebase workflow (
deep-research-codebase/)CAVEMAN_PREAMBLE— Applied to all stage prompts (scout, locator, analyzer, pattern-finder, online-researcher)deriveHistoryBriefdistills the history-analyzer output (≤150 words) and injects it as<PRIOR_RESEARCH_HINT>into per-partition locator and analyzer prompts across all three SDKsqueryWithProseGuardwraps history-locator and history-analyzer stages; auto-retries with a follow-up prompt when the first response returns empty textcompactScratchFilesForAggregatortrims oversized partition scratch files before the aggregator reads them, preventing token overruns on large codebases