Sweep API
The sweep engine runs a prompt multiple times with context chaining — each iteration receives the previous iteration's summary as additional context, enabling progressive refinement.
sweepPrompt()
Main entry point for multi-iteration sweeps.
import { sweepPrompt } from "prompts-gpt";
const result = await sweepPrompt({
promptFile: ".prompts-gpt/sweeps/security-audit.md",
iterations: 3,
provider: "codex",
model: "gpt-5.5",
cwd: process.cwd(),
timeoutSeconds: 5400,
maxRetries: 2,
summaryLines: 40,
onProgress: (event) => {
console.log(`Iteration ${event.iteration}/${event.total}: ${event.status}`);
},
});
console.log(result.ok); // boolean
console.log(result.iterationsCompleted); // number
console.log(result.totalDurationMs); // number
SweepInput
| Property | Type | Required | Default | Description |
|---|---|---|---|---|
promptFile | string | Yes | — | Path to sweep Markdown file |
iterations | number | Yes | — | Number of iterations to run |
provider | string | Yes | — | Provider name |
model | string | No | — | Model override |
cwd | string | No | process.cwd() | Working directory |
timeoutSeconds | number | No | 5400 | Per-iteration timeout |
maxRetries | number | No | 2 | Retries per iteration |
summaryLines | number | No | 40 | Lines of summary to extract |
artifactsDir | string | No | .scripts/runs | Artifacts directory |
runId | string | No | auto | Custom run ID |
maxRunDirs | number | No | 20 | Max artifact dirs to keep |
phase | string | No | — | Phase label for prompts |
sandbox | string | No | workspace-write | Codex sandbox mode |
permissionMode | string | No | acceptEdits | Claude permission mode |
background | boolean | No | false | Cursor background mode |
quiet | boolean | No | false | Suppress live output |
silent | boolean | No | false | Suppress all output |
dryRun | boolean | No | false | Preview only |
allowDestructiveGit | boolean | No | false | Allow git stash/reset |
parallel | number | No | — | Parallel iteration batches |
eval | SweepEvalConfig | No | — | Self-evaluation config |
onProgress | function | No | — | Progress callback |
SweepResult
| Property | Type | Description |
|---|---|---|
ok | boolean | Overall success |
iterations | SweepIterationResult[] | Per-iteration results |
totalDurationMs | number | Total duration |
provider | string | Provider used |
model | string | Model used |
iterationsCompleted | number | Completed iteration count |
iterationsRequested | number | Requested iterations |
evalScores | SweepEvalScore[] | Evaluation scores (if eval enabled) |
SweepIterationResult
| Property | Type | Description |
|---|---|---|
iteration | number | Iteration number (1-based) |
status | SweepIterationStatus | "completed", "failed", "timeout", "skipped" |
exitCode | number | Process exit code |
durationMs | number | Duration in ms |
summaryText | string | Extracted summary |
outputFile | string | Raw output log path |
tokenUsage | TokenUsage | Token consumption |
error | string | Error message (if failed) |
retryCount | number | Number of retries used |
Self-Evaluation
Configure self-evaluation via YAML frontmatter or the eval parameter:
const result = await sweepPrompt({
promptFile: ".prompts-gpt/sweeps/audit.md",
iterations: 3,
provider: "codex",
eval: {
criteria: ["correctness", "completeness", "code-quality"],
passThreshold: 0.7,
},
});
for (const score of result.evalScores ?? []) {
console.log(`Iteration ${score.iteration}: ${score.overallScore}`);
for (const criterion of score.criteria) {
console.log(` ${criterion.name}: ${criterion.score}`);
}
}
SweepEvalConfig
| Property | Type | Description |
|---|---|---|
criteria | string[] | Scoring dimensions |
passThreshold | number | Pass/fail threshold (0.0–1.0) |
SweepEvalScore
| Property | Type | Description |
|---|---|---|
iteration | number | Iteration number |
overallScore | number | Weighted average score |
criteria | Array<{ name: string; score: number }> | Per-criterion scores |
passed | boolean | Whether threshold was met |
Lock Management
Sweep uses lock files to prevent concurrent execution on the same prompt:
import { acquireSweepLock, releaseSweepLock, forceReleaseSweepLock } from "prompts-gpt";
const lock = await acquireSweepLock(promptFile, cwd);
try {
// ... sweep logic ...
} finally {
await releaseSweepLock(lock);
}
// Force-release a stale lock
await forceReleaseSweepLock(promptFile, cwd);
Helper Functions
buildIterationPrompt()
Build a prompt with context from previous iterations:
import { buildIterationPrompt } from "prompts-gpt";
const prompt = buildIterationPrompt({
originalPrompt: "Review security...",
iteration: 2,
totalIterations: 5,
previousSummary: "Fixed 3 SQL injection issues...",
phase: "hardening",
});
runPreFlight()
Execute pre-flight checks before a sweep:
import { runPreFlight } from "prompts-gpt";
const report = await runPreFlight({
promptFile: ".prompts-gpt/sweeps/audit.md",
provider: "codex",
cwd: process.cwd(),
});
if (!report.ok) {
console.error("Pre-flight failed:", report.errors);
}
Progress Events
sweepPrompt({
// ...
onProgress: (event: SweepProgressEvent) => {
switch (event.type) {
case "iteration-start":
console.log(`Starting iteration ${event.iteration}`);
break;
case "iteration-complete":
console.log(`Completed: ${event.status}`);
break;
case "sweep-complete":
console.log(`Sweep done: ${event.iterationsCompleted} iterations`);
break;
}
},
});
See Also
- Runtime API — Single-shot execution
- Orchestration API — Multi-agent modes
- Sweep vs Prompts Guide