repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(chef): Temper hardening — tests, typed context, schema migrations, cleanup

587f8dfb38fb6cfaf4bca61b4ff19f3c499b2ac0

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Address 7 concerns in the Chef orchestrator plugin:

1. Test suite (HIGH PRIORITY)
   - test/builder.test.ts: 30 tests for pipeline DSL
   - test/store.test.ts: 21 tests for SQLite state management
   - test/executor.test.ts: 26 tests for execution engine
   - Total: 77 tests, 168 assertions

2. Typed context (Concern 2)
   - Add TContext generic to PipelineBuilder, step(), fragment(), pipeline()
   - Propagate through StepDefinition, WhenDefinition, ParallelDefinition
   - Default to Record<string, any> for backward compatibility

3. Remove dead code (Concern 3)
   - Delete SchemaValidationError class (never thrown)

4. SQL column whitelist (Concern 4)
   - Add ALLOWED_COLUMNS constant per table
   - Filter update keys against whitelist in updateRecord()

5. Remove unused step_state (Concern 5)
   - Delete StepState interface, StepStatus type
   - Delete CREATE TABLE, CREATE INDEX, and all CRUD methods

6. Improved session cleanup (Concern 6)
   - Track leaked sessions in Set<string>
   - Log via client.app.log() with structured data
   - Report summary in execute() finally block

7. Schema migration system (Concern 7)
   - Add schema_version table
   - Version-aware initSchema() with MIGRATIONS array
   - v1: initial schema, v2: drop step_state

Changed files (10)

opencode/plugins/chef/PLAN.md

Modified
94 94 | **Database** | SQLite with `bun:sqlite` (built into Bun) |
95 95 | **Location** | `.opencode/chef/chef.db` |
96 96 | **Concurrency** | WAL mode for concurrent reads, single writer |
97 -| **Schema migrations** | Manual (simple schema, can evolve later) |
97 +| **Schema migrations** | Versioned (schema_version table, sequential) |
99 99 ### State Schema (Draft)
121 121 started_at: number | null;
122 122 completed_at: number | null;
125 -interface StepState {
126 - id: string;
127 - phase_id: string;
128 - name: string;
129 - agent: string;
130 - status: StepStatus;
131 - output: unknown;
132 - error: string | null;
133 - attempts: number;
137 126 ### Pipeline DSL
202 191 | ------------------------- | ------------ | ------------------------------------ |
203 192 | Agent timeout | Yes | Retry or fail phase |
204 193 | Agent error | Maybe | Retry with feedback |
205 -| Schema validation failure | Yes | SDK auto-retries (retryCount: 2) |
206 194 | Gate failure | Yes | Loop back to appropriate phase |
207 195 | Max iterations reached | No | Fail pipeline, escalate |
208 196 | SDK error | No | Fail immediately (plugin bug) |
272 260 ### Phase 4: Polish
274 -- [ ] Test suite
275 -- [ ] DSL ergonomics improvements (typed context)
262 +- [x] Test suite
263 +- [x] DSL ergonomics improvements (typed context)
276 264 - [ ] Documentation improvements
303 291 - [x] Reusable step/fragment syntax: fragment() function + use() method
304 292 - [x] Loop target syntax: by step name
305 293 - [x] Pipeline validation on startup: validate() + startup check
294 +- [x] Parallel result access syntax (by step name? by array?) — resolved: nested
295 + context by step name
296 +- [x] Exact Zod schema for pipeline definition — resolved: Zod schemas in step
297 + definitions
442 -_Last updated: 2026-03-31_
434 +_Last updated: 2026-04-01_

opencode/plugins/chef/README.md

Modified
4 4 # Chef Orchestrator Plugin
6 6 Declarative pipeline orchestration for OpenCode multi-agent workflows.
8 8 ## Overview
10 -Chef provides a TypeScript DSL for defining structured workflows that coordinate multiple agents. It leverages OpenCode's SDK capabilities for:
10 +Chef provides a TypeScript DSL for defining structured workflows that coordinate
11 +multiple agents. It leverages OpenCode's SDK capabilities for:
12 13 - **Message Injection**: Pass context between agents via `noReply: true`
13 14 - **Structured Output**: Automatic JSON schema validation with retries
117 118 ## Retry Policies
119 -Steps support configurable retry behavior. When a step fails, Chef automatically retries with exponential backoff before marking the step as failed.
120 +Steps support configurable retry behavior. When a step fails, Chef automatically
121 +retries with exponential backoff before marking the step as failed.
121 123 ### Configuration
138 140 **Fields:**
140 -| Field | Type | Default | Description |
141 -|---|---|---|---|
142 -| `maxAttempts` | `number` | `1` | Maximum number of attempts (including the first run) |
143 -| `backoffMs` | `number` | `1000` | Base delay in milliseconds before the first retry |
144 -| `retryOn` | `string[] \| undefined` | `undefined` | Error types that trigger a retry |
142 +| Field | Type | Default | Description |
143 +| ------------- | ----------------------- | ----------- | ---------------------------------------------------- |
144 +| `maxAttempts` | `number` | `1` | Maximum number of attempts (including the first run) |
145 +| `backoffMs` | `number` | `1000` | Base delay in milliseconds before the first retry |
146 +| `retryOn` | `string[] \| undefined` | `undefined` | Error types that trigger a retry |
146 148 ### Backoff Behavior
148 -Delays use exponential backoff: `backoffMs * 2^attempt`. For `backoffMs: 2000` with 3 attempts:
150 +Delays use exponential backoff: `backoffMs * 2^attempt`. For `backoffMs: 2000`
151 +with 3 attempts:
150 153 - Attempt 1: immediate
151 154 - Attempt 2: waits 2000ms
164 167 ### Retry Feedback
166 -On retry, Chef injects the previous error message into the agent's context so it can correct its behavior:
169 +On retry, Chef injects the previous error message into the agent's context so it
170 +can correct its behavior:
169 173 Previous attempt failed with: Step "implement" timed out after 30000ms.
173 177 ## Timeout Handling
175 -Steps support a `timeout` option (in milliseconds) that limits how long an agent can run. If the agent exceeds the deadline, the step fails with an `AgentTimeoutError`.
179 +Steps support a `timeout` option (in milliseconds) that limits how long an agent
180 +can run. If the agent exceeds the deadline, the step fails with an
181 +`AgentTimeoutError`.
177 183 ### Usage
214 220 ## Reusable Fragments
216 -Fragments let you define reusable sequences of steps that can be included in multiple pipelines. This avoids duplicating common step definitions.
222 +Fragments let you define reusable sequences of steps that can be included in
223 +multiple pipelines. This avoids duplicating common step definitions.
218 225 ### Defining a Fragment
248 255 ### Including a Fragment
250 -Use the `.use()` method on a pipeline builder to include all steps from a fragment:
257 +Use the `.use()` method on a pipeline builder to include all steps from a
258 +fragment:
252 260 ```typescript
253 261 export default pipeline("feature")
257 265 .build();
260 -The `.use()` method adds each step from the fragment as an individual phase in the pipeline, preserving their order.
268 +The `.use()` method adds each step from the fragment as an individual phase in
269 +the pipeline, preserving their order.
262 271 ## Pipeline Validation
264 -Chef validates pipeline definitions at startup when pipelines are loaded from disk. This catches configuration errors early, before any execution begins.
273 +Chef validates pipeline definitions at startup when pipelines are loaded from
274 +disk. This catches configuration errors early, before any execution begins.
266 276 ### How It Works
268 -When the plugin loads pipeline files, it calls the builder's `validate()` method automatically. Validation warnings appear in the console:
278 +When the plugin loads pipeline files, it calls the builder's `validate()` method
279 +automatically. Validation warnings appear in the console:
271 282 Chef: Pipeline "feature" has validation errors:
294 305 ### What Gets Validated
296 -| Check | Description |
297 -|---|---|
298 -| Output schema | Each step must have a valid Zod schema (`parse` is a function) |
299 -| Agent name | Each step must have a non-empty string agent |
300 -| Gate expect schema | Each gate must have a valid Zod schema for `expect` |
301 -| Gate `onFail` target | If set, must reference a step that exists earlier in the pipeline |
302 -| `when` loop target | If set, must reference a step that exists in the pipeline |
303 -| `when` condition | Must be a function |
304 -| Parallel step schemas | Each parallel sub-step must have valid output and agent |
307 +| Check | Description |
308 +| --------------------- | ----------------------------------------------------------------- |
309 +| Output schema | Each step must have a valid Zod schema (`parse` is a function) |
310 +| Agent name | Each step must have a non-empty string agent |
311 +| Gate expect schema | Each gate must have a valid Zod schema for `expect` |
312 +| Gate `onFail` target | If set, must reference a step that exists earlier in the pipeline |
313 +| `when` loop target | If set, must reference a step that exists in the pipeline |
314 +| `when` condition | Must be a function |
315 +| Parallel step schemas | Each parallel sub-step must have valid output and agent |
306 317 ### Agent Name Checks
308 -In addition to structural validation, Chef checks that referenced agent names exist at startup. Unknown agents produce warnings:
319 +In addition to structural validation, Chef checks that referenced agent names
320 +exist at startup. Unknown agents produce warnings:
311 323 Chef: Pipeline "feature" step "research" references unknown agent "unknown_agent"
314 326 ## Error Handling
316 -Chef classifies errors into a taxonomy so that retry policies and debugging can target specific failure modes.
328 +Chef classifies errors into a taxonomy so that retry policies and debugging can
329 +target specific failure modes.
318 331 ### Error Types
320 -| Error Class | Type String | Cause |
321 -|---|---|---|
322 -| `AgentTimeoutError` | `agent_timeout` | Step exceeded its `timeout` deadline |
323 -| `AgentError` | `agent_error` | Agent returned an error during execution |
324 -| `GateFailureError` | `gate_failure` | Gate validation or agent evaluation failed |
325 -| `SchemaValidationError` | `schema_validation` | Agent output did not match the Zod schema |
333 +| Error Class | Type String | Cause |
334 +| -------------------- | ---------------- | --------------------------------------------------------- |
335 +| `AgentTimeoutError` | `agent_timeout` | Step exceeded its `timeout` deadline |
336 +| `AgentError` | `agent_error` | Agent returned an error during execution |
337 +| `GateFailureError` | `gate_failure` | Gate validation or agent evaluation failed |
326 338 | `MaxIterationsError` | `max_iterations` | A loop exceeded the maximum iteration count (default: 10) |
328 -All errors extend `ChefError`, which carries a `type` string for programmatic handling.
340 +All errors extend `ChefError`, which carries a `type` string for programmatic
341 +handling.
330 343 ### Error Flow
332 345 1. A step, gate, or parallel phase throws an error during execution
333 346 2. The executor catches the error and records it in the phase state
334 -3. If the step has a retry policy and the error type matches `retryOn`, the step is retried
347 +3. If the step has a retry policy and the error type matches `retryOn`, the step
348 + is retried
335 349 4. If all retries are exhausted, the step is marked as `failed`
336 350 5. The pipeline status is updated to `failed`
338 352 ### Loop Iteration Guard
340 -Loops (via `.when()` / `.loop()` or gate `onFail`) are bounded by a maximum iteration count (default: 10). If a loop exceeds this limit, the pipeline fails with a `MaxIterationsError` to prevent infinite cycles.
354 +Loops (via `.when()` / `.loop()` or gate `onFail`) are bounded by a maximum
355 +iteration count (default: 10). If a loop exceeds this limit, the pipeline fails
356 +with a `MaxIterationsError` to prevent infinite cycles.
342 358 ## Gate onFail
344 -Gates support an `onFail` option that creates a loop-back when the gate fails. Instead of failing the entire pipeline, execution jumps back to the specified step.
360 +Gates support an `onFail` option that creates a loop-back when the gate fails.
361 +Instead of failing the entire pipeline, execution jumps back to the specified
362 +step.
346 364 ### Usage
366 384 ### Combining with `.when()` / `.loop()`
368 -The `onFail` option and `.when()` / `.loop()` can be used together or independently:
386 +The `onFail` option and `.when()` / `.loop()` can be used together or
387 +independently:
370 389 ```typescript
371 390 // Gate onFail: automatic loop-back on gate failure
380 399 .loop("plan")
383 -The `onFail` handles gate evaluation failures (e.g., the agent returns `{ approved: false }`). The `.when()` / `.loop()` handles the conditional branch after a successful gate evaluation that returns a negative result.
402 +The `onFail` handles gate evaluation failures (e.g., the agent returns
403 +`{ approved: false }`). The `.when()` / `.loop()` handles the conditional branch
404 +after a successful gate evaluation that returns a negative result.
385 406 ### Validation
387 -The `onFail` target is validated at startup. If the target step does not exist in the pipeline, a validation error is reported.
408 +The `onFail` target is validated at startup. If the target step does not exist
409 +in the pipeline, a validation error is reported.
389 411 ## Tools
393 415 Start a new pipeline execution.
395 417 **Arguments:**
396 419 - `name` (string): Pipeline name
397 420 - `input` (any, optional): Input data
399 422 **Returns:**
400 424 ```json
402 426 "pipeline_id": "uuid",
410 434 Check pipeline status.
412 436 **Arguments:**
413 438 - `id` (string, optional): Pipeline ID (defaults to all running)
415 440 ### pipeline.continue
417 442 Continue after `needs_input` status.
419 444 **Arguments:**
420 446 - `id` (string): Pipeline ID
421 447 - `input` (any): Input data for next phase
425 451 Cancel a running pipeline.
427 453 **Arguments:**
428 455 - `id` (string): Pipeline ID
430 457 ### pipeline.list
451 478 Retry/Timeout → exponential backoff + Promise.race
453 480 State Persistence → SQLite (store.ts)
481 + ↳ schema_version (version tracking)
482 + ↳ pipeline_instance
483 + ↳ phase_state
486 +## Schema Migrations
488 +Chef uses a versioned migration system to manage database schema changes. The
489 +`schema_version` table tracks which migrations have been applied.
491 +- Migrations run automatically on startup
492 +- Each migration has a version number, description, and array of SQL statements
493 +- Only migrations newer than the current version are applied
494 +- Applied migrations are logged:
495 + `Chef: Applied schema migration v2: Remove unused step_state table`
497 +Current schema version: **2** (removed unused `step_state` table from initial
498 +schema).
456 500 ## Example Pipeline
458 502 See `pipelines/feature.ts` for a complete example with:
459 504 - Research phase
460 505 - Planning phase
461 506 - Approval gate with `onFail` loop-back to "plan"
462 507 - Conditional loop via `.when()` / `.loop()`
463 -- Implementation phase with retry policy (3 attempts, filtered to `agent_error` and `agent_timeout`)
508 +- Implementation phase with retry policy (3 attempts, filtered to `agent_error`
509 + and `agent_timeout`)
464 510 - Reusable review fragment via `fragment()` and `.use()`
465 511 - Per-step timeouts on review steps
491 537 ## Development
493 539 ```bash
494 -# Run tests (when available)
540 +# Run tests
495 541 bun test
497 543 # Type checking

opencode/plugins/chef/executor.ts

Modified
53 -export class SchemaValidationError extends ChefError {
54 - constructor(stepName: string, message: string) {
55 - super(
56 - `Schema validation failed for "${stepName}": ${message}`,
57 - "schema_validation",
58 - );
59 - this.name = "SchemaValidationError";
60 - }
53 +/** Internal context type for the executor. Uses `any` because context is a
54 + * JSON-serialized accumulator that flows into user-defined callbacks
55 + * (prompt functions, when conditions) typed as `(ctx: TContext) => ...`
56 + * where TContext defaults to Record<string, any>. */
57 +type PipelineContext = Record<string, any>;
63 59 const DEFAULT_MAX_LOOP_ITERATIONS = 10;
64 60 const DEFAULT_RETRY: RetryPolicy = {
70 66 export class Executor {
71 67 private maxLoopIterations: number;
68 + private leakedSessions = new Set<string>();
73 70 constructor(
74 71 private store: Store,
83 80 private async cleanupSession(sessionId: string): Promise<void> {
84 - await this.client.session.delete({ path: { id: sessionId } }).catch(
85 - (e) => {
86 - console.warn(
87 - `Chef: session cleanup failed for ${sessionId}:`,
88 - e?.message ?? e,
89 - );
90 - },
91 - );
81 + try {
82 + await this.client.session.delete({ path: { id: sessionId } });
83 + } catch (e) {
84 + this.leakedSessions.add(sessionId);
85 + const msg = e instanceof Error ? e.message : String(e);
86 + console.warn(`Chef: session cleanup failed for ${sessionId}: ${msg}`);
87 + try {
88 + await this.client.app.log({
89 + body: {
90 + service: "chef",
91 + level: "warn",
92 + message: `Session cleanup failed`,
93 + extra: { sessionId, error: msg },
94 + },
95 + });
96 + } catch {
97 + // truly best-effort — logging itself failed
98 + }
99 + }
94 - async execute(pipelineId: string, input: any): Promise<any> {
102 + async execute(pipelineId: string, input: PipelineContext): Promise<any> {
95 103 const instance = this.store.getPipeline(pipelineId);
96 104 if (!instance) {
97 105 throw new Error(`Pipeline ${pipelineId} not found`);
100 - let context: any = JSON.parse(instance.context ?? "{}");
108 + let context: PipelineContext = JSON.parse(instance.context ?? "{}");
109 + // Merge input into context so it's available to prompts and gate validation
110 + context = { ...context, ...input };
101 111 const phases = this.definition.phases;
102 112 let loopIterations = 0;
104 - for (let i = instance.current_phase; i < phases.length; i++) {
105 - // Check if pipeline was aborted
106 - const current = this.store.getPipeline(pipelineId);
107 - if (current && current.status === "aborted") {
108 - return { status: "aborted", context };
109 - }
111 - const phase = phases[i];
113 - // Update current phase
114 - this.store.updatePipeline(pipelineId, {
115 - current_phase: i,
116 - status: "running",
117 - });
119 - try {
120 - const result = await this.executePhase(phase, context, pipelineId);
122 - if (result.status === "needs_input") {
123 - this.store.updatePipeline(pipelineId, {
124 - status: "needs_input",
125 - context: JSON.stringify(context),
126 - });
127 - return { status: "needs_input", context };
114 + try {
115 + for (let i = instance.current_phase; i < phases.length; i++) {
116 + // Check if pipeline was aborted
117 + const current = this.store.getPipeline(pipelineId);
118 + if (current && current.status === "aborted") {
119 + return { status: "aborted", context };
130 - if (result.status === "loop") {
131 - loopIterations++;
132 - if (loopIterations > this.maxLoopIterations) {
122 + const phase = phases[i];
124 + // Update current phase
125 + this.store.updatePipeline(pipelineId, {
126 + current_phase: i,
127 + status: "running",
128 + });
130 + try {
131 + const result = await this.executePhase(phase, context, pipelineId);
133 + if (result.status === "needs_input") {
134 + this.store.updatePipeline(pipelineId, {
135 + status: "needs_input",
136 + context: JSON.stringify(context),
137 + });
138 + return { status: "needs_input", context };
141 + if (result.status === "loop") {
142 + loopIterations++;
143 + if (loopIterations > this.maxLoopIterations) {
144 + this.store.updatePipeline(pipelineId, {
145 + status: "failed",
146 + context: JSON.stringify(context),
147 + });
148 + return {
149 + status: "failed",
150 + error: new MaxIterationsError(this.maxLoopIterations).message,
151 + };
153 + const targetIndex = phases.findIndex((p) =>
154 + p.name === result.target
155 + );
156 + if (targetIndex >= 0) {
157 + i = targetIndex - 1; // -1 because loop will increment
158 + continue;
162 + if (result.status === "failed") {
133 163 this.store.updatePipeline(pipelineId, {
134 164 status: "failed",
135 165 context: JSON.stringify(context),
137 - return {
138 - status: "failed",
139 - error: new MaxIterationsError(this.maxLoopIterations).message,
140 - };
167 + return { status: "failed", error: result.error };
142 - const targetIndex = phases.findIndex((p) => p.name === result.target);
143 - if (targetIndex >= 0) {
144 - i = targetIndex - 1; // -1 because loop will increment
145 - continue;
146 - }
147 - }
149 - if (result.status === "failed") {
170 + // Merge output into context
171 + if (result.output) {
172 + context[phase.name] = result.output;
173 + this.store.updatePipeline(pipelineId, {
174 + context: JSON.stringify(context),
175 + });
177 + } catch (error: any) {
150 178 this.store.updatePipeline(pipelineId, {
151 179 status: "failed",
152 - context: JSON.stringify(context),
154 - return { status: "failed", error: result.error };
181 + throw error;
157 - // Merge output into context
158 - if (result.output) {
159 - context[phase.name] = result.output;
160 - this.store.updatePipeline(pipelineId, {
161 - context: JSON.stringify(context),
185 + // Pipeline completed
186 + this.store.updatePipeline(pipelineId, {
187 + status: "completed",
188 + current_phase: phases.length,
189 + });
191 + return { status: "completed", context };
192 + } finally {
193 + if (this.leakedSessions.size > 0) {
194 + const ids = Array.from(this.leakedSessions);
195 + console.warn(
196 + `Chef: pipeline ${pipelineId} completed with ${ids.length} leaked session(s): ${
197 + ids.join(", ")
198 + }`,
199 + );
200 + try {
201 + await this.client.app.log({
202 + body: {
203 + service: "chef",
204 + level: "warn",
205 + message: `Pipeline completed with leaked sessions`,
206 + extra: { pipelineId, leakedSessionIds: ids },
207 + },
209 + } catch {
210 + // best-effort
164 - } catch (error: any) {
165 - this.store.updatePipeline(pipelineId, {
166 - status: "failed",
167 - });
168 - throw error;
212 + this.leakedSessions.clear();
172 - // Pipeline completed
173 - this.store.updatePipeline(pipelineId, {
174 - status: "completed",
175 - current_phase: phases.length,
176 - });
178 - return { status: "completed", context };
181 217 private async executePhase(
182 218 phase: PhaseDefinition,
183 - context: any,
219 + context: PipelineContext,
184 220 pipelineId: string,
185 221 ): Promise<
186 222 { status: string; output?: any; error?: string; target?: string }
206 242 private async executeStep(
207 243 step: StepDefinition,
208 - context: any,
244 + context: PipelineContext,
209 245 pipelineId: string,
210 246 parentPhaseId?: string,
211 247 ): Promise<{ status: string; output?: any; error?: string }> {
357 393 private async executeGate(
358 394 gate: GateDefinition,
359 - context: any,
395 + context: PipelineContext,
360 396 pipelineId: string,
361 397 ): Promise<
362 398 { status: string; output?: any; error?: string; target?: string }
454 490 private async executeParallel(
455 491 parallel: ParallelDefinition,
456 - context: any,
492 + context: PipelineContext,
457 493 pipelineId: string,
458 494 ): Promise<{ status: string; output?: any; error?: string }> {
459 495 const phase = this.store.createPhase(pipelineId, parallel.name);
475 511 return failed;
478 - const outputs = results.reduce((acc, r, i) => {
479 - acc[parallel.steps[i].name] = r.output;
480 - return acc;
481 - }, {} as any);
514 + const outputs = Object.fromEntries(
515 + results.map((r, i) => [parallel.steps[i].name, r.output]),
516 + ) as PipelineContext;
483 518 this.store.updatePhase(phase.id, {
484 519 status: "completed",
500 535 private executeWhen(
501 536 when: WhenDefinition,
502 - context: any,
537 + context: PipelineContext,
503 538 ): { status: string; target?: string } {
504 539 const conditionMet = when.condition(context);

opencode/plugins/chef/package-lock.json

Added
new file mode 100644
1 +{
2 + "name": "@opencode-ai/chef",
3 + "version": "0.1.0",
4 + "lockfileVersion": 3,
5 + "requires": true,
6 + "packages": {
7 + "": {
8 + "name": "@opencode-ai/chef",
9 + "version": "0.1.0",
10 + "dependencies": {
11 + "glob": "^10.0.0",
12 + "zod": "^3.22.0",
13 + "zod-to-json-schema": "^3.22.0"
14 + },
15 + "devDependencies": {
16 + "@types/bun": "latest",
17 + "bun": "^1.3.11"
18 + }
19 + },
20 + "node_modules/@isaacs/cliui": {
21 + "version": "8.0.2",
22 + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
23 + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
24 + "license": "ISC",
25 + "dependencies": {
26 + "string-width": "^5.1.2",
27 + "string-width-cjs": "npm:string-width@^4.2.0",
28 + "strip-ansi": "^7.0.1",
29 + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
30 + "wrap-ansi": "^8.1.0",
31 + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
32 + },
33 + "engines": {
34 + "node": ">=12"
35 + }
36 + },
37 + "node_modules/@oven/bun-darwin-aarch64": {
38 + "version": "1.3.11",
39 + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-aarch64/-/bun-darwin-aarch64-1.3.11.tgz",
40 + "integrity": "sha512-/8IzqSu4/OWGRs7Fs2ROzGVwJMFTBQkgAp6sAthkBYoN7OiM4rY/CpPVs2X9w9N1W61CHSkEdNKi8HrLZKfK3g==",
41 + "cpu": [
42 + "arm64"
43 + ],
44 + "dev": true,
45 + "license": "MIT",
46 + "optional": true,
47 + "os": [
48 + "darwin"
49 + ]
50 + },
51 + "node_modules/@oven/bun-darwin-x64": {
52 + "version": "1.3.11",
53 + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64/-/bun-darwin-x64-1.3.11.tgz",
54 + "integrity": "sha512-TT7eUihnAzxM2tlZesusuC75PAOYKvUBgVU/Nm/lakZ/DpyuqhNkzUfcxSgmmK9IjVWzMmezLIGZl16XGCGJng==",
55 + "cpu": [
56 + "x64"
57 + ],
58 + "dev": true,
59 + "license": "MIT",
60 + "optional": true,
61 + "os": [
62 + "darwin"
63 + ]
64 + },
65 + "node_modules/@oven/bun-darwin-x64-baseline": {
66 + "version": "1.3.11",
67 + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64-baseline/-/bun-darwin-x64-baseline-1.3.11.tgz",
68 + "integrity": "sha512-CYjIHWaQG7T4phfjErHr6BiXRs0K/9DqMeiohJmuYSBF+H2m56vFslOenLCguGYQL9jeiiCZBeoVCpwjxZrMgQ==",
69 + "cpu": [
70 + "x64"
71 + ],
72 + "dev": true,
73 + "license": "MIT",
74 + "optional": true,
75 + "os": [
76 + "darwin"
77 + ]
78 + },
79 + "node_modules/@oven/bun-linux-aarch64": {
80 + "version": "1.3.11",
81 + "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64/-/bun-linux-aarch64-1.3.11.tgz",
82 + "integrity": "sha512-8XMLyRNxHF4jfLajkWt+F8UDxsWbzysyxQVMZKUXwoeGvaxB0rVd07r3YbgDtG8U6khhRFM3oaGp+CQ0whwmdA==",
83 + "cpu": [
84 + "arm64"
85 + ],
86 + "dev": true,
87 + "license": "MIT",
88 + "optional": true,
89 + "os": [
90 + "linux"
91 + ]
92 + },
93 + "node_modules/@oven/bun-linux-aarch64-musl": {
94 + "version": "1.3.11",
95 + "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64-musl/-/bun-linux-aarch64-musl-1.3.11.tgz",
96 + "integrity": "sha512-jBwYCLG5Eb+PqtFrc3Wp2WMYlw1Id75gUcsdP+ApCOpf5oQhHxkFWCjZmcDoioDmEhMWAiM3wtwSrTlPg+sI6Q==",
97 + "cpu": [
98 + "arm64"
99 + ],
100 + "dev": true,
101 + "license": "MIT",
102 + "optional": true,
103 + "os": [
104 + "linux"
106 + },
107 + "node_modules/@oven/bun-linux-x64": {
108 + "version": "1.3.11",
109 + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64/-/bun-linux-x64-1.3.11.tgz",
110 + "integrity": "sha512-z3GFCk1UBzDOOiEBHL32lVP7Edi26BhOjKb6bIc0nRyabbRiyON4++GR0zmd/H5zM5S0+UcXFgCGnD+b8avTLw==",
111 + "cpu": [
112 + "x64"
113 + ],
114 + "dev": true,
115 + "license": "MIT",
116 + "optional": true,
117 + "os": [
118 + "linux"
120 + },
121 + "node_modules/@oven/bun-linux-x64-baseline": {
122 + "version": "1.3.11",
123 + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-baseline/-/bun-linux-x64-baseline-1.3.11.tgz",
124 + "integrity": "sha512-KZlf1jKtf4jai8xiQv/0XRjxVVhHnw/HtUKtLdOeQpTOQ1fQFhLoz2FGGtVRd0LVa/yiRbSz9HlWIzWlmJClng==",
125 + "cpu": [
126 + "x64"
127 + ],
128 + "dev": true,
129 + "license": "MIT",
130 + "optional": true,
131 + "os": [
132 + "linux"
134 + },
135 + "node_modules/@oven/bun-linux-x64-musl": {
136 + "version": "1.3.11",
137 + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl/-/bun-linux-x64-musl-1.3.11.tgz",
138 + "integrity": "sha512-ADImD4yCHNpqZu718E2chWcCaAHvua90yhmpzzV6fF4zOhwkGGbPCgUWmKyJ83uz+DXaPdYxX0ttDvtolrzx3Q==",
139 + "cpu": [
140 + "x64"
141 + ],
142 + "dev": true,
143 + "license": "MIT",
144 + "optional": true,
145 + "os": [
146 + "linux"
148 + },
149 + "node_modules/@oven/bun-linux-x64-musl-baseline": {
150 + "version": "1.3.11",
151 + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl-baseline/-/bun-linux-x64-musl-baseline-1.3.11.tgz",
152 + "integrity": "sha512-J+qz4Al05PrNIOdj7xsWVTyx0c/gjUauG5nKV3Rrx0Q+5JO+1pPVlnfNmWbOF9pKG4f3IGad8KXJUfGMORld+Q==",
153 + "cpu": [
154 + "x64"
155 + ],
156 + "dev": true,
157 + "license": "MIT",
158 + "optional": true,
159 + "os": [
160 + "linux"
162 + },
163 + "node_modules/@oven/bun-windows-aarch64": {
164 + "version": "1.3.11",
165 + "resolved": "https://registry.npmjs.org/@oven/bun-windows-aarch64/-/bun-windows-aarch64-1.3.11.tgz",
166 + "integrity": "sha512-UOdkwScHRkGPz+n9ZJU7sTkTvqV7rD1SLCLaru1xH8WRsV7tDorPqNCzEN1msOIiPRK825nvAtEm9UsomO1GsA==",
167 + "cpu": [
168 + "arm64"
169 + ],
170 + "dev": true,
171 + "license": "MIT",
172 + "optional": true,
173 + "os": [
174 + "win32"
176 + },
177 + "node_modules/@oven/bun-windows-x64": {
178 + "version": "1.3.11",
179 + "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64/-/bun-windows-x64-1.3.11.tgz",
180 + "integrity": "sha512-E51tyWDP1l0CbjZYhiUxhDGPaY8Hf5YBREx0PHBff1LM1/q3qsJ6ZvRUa8YbbOO0Ax9QP6GHjD9vf3n6bXZ7QA==",
181 + "cpu": [
182 + "x64"
183 + ],
184 + "dev": true,
185 + "license": "MIT",
186 + "optional": true,
187 + "os": [
188 + "win32"
190 + },
191 + "node_modules/@oven/bun-windows-x64-baseline": {
192 + "version": "1.3.11",
193 + "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64-baseline/-/bun-windows-x64-baseline-1.3.11.tgz",
194 + "integrity": "sha512-cCsXK9AQ9Zf18QlVnbrFu2IKfr4sf2sfbErkF2jfCzyCO9Bnhl0KRx63zlN+Ni1xU7gcBLAssgcui5R400N2eA==",
195 + "cpu": [
196 + "x64"
197 + ],
198 + "dev": true,
199 + "license": "MIT",
200 + "optional": true,
201 + "os": [
202 + "win32"
204 + },
205 + "node_modules/@pkgjs/parseargs": {
206 + "version": "0.11.0",
207 + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
208 + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
209 + "license": "MIT",
210 + "optional": true,
211 + "engines": {
212 + "node": ">=14"
214 + },
215 + "node_modules/@types/bun": {
216 + "version": "1.3.11",
217 + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.3.11.tgz",
218 + "integrity": "sha512-5vPne5QvtpjGpsGYXiFyycfpDF2ECyPcTSsFBMa0fraoxiQyMJ3SmuQIGhzPg2WJuWxVBoxWJ2kClYTcw/4fAg==",
219 + "dev": true,
220 + "license": "MIT",
221 + "dependencies": {
222 + "bun-types": "1.3.11"
224 + },
225 + "node_modules/@types/node": {
226 + "version": "25.5.0",
227 + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz",
228 + "integrity": "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==",
229 + "dev": true,
230 + "license": "MIT",
231 + "dependencies": {
232 + "undici-types": "~7.18.0"
234 + },
235 + "node_modules/ansi-regex": {
236 + "version": "6.2.2",
237 + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
238 + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
239 + "license": "MIT",
240 + "engines": {
241 + "node": ">=12"
242 + },
243 + "funding": {
244 + "url": "https://github.com/chalk/ansi-regex?sponsor=1"
246 + },
247 + "node_modules/ansi-styles": {
248 + "version": "6.2.3",
249 + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
250 + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
251 + "license": "MIT",
252 + "engines": {
253 + "node": ">=12"
254 + },
255 + "funding": {
256 + "url": "https://github.com/chalk/ansi-styles?sponsor=1"
258 + },
259 + "node_modules/balanced-match": {
260 + "version": "1.0.2",
261 + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
262 + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
263 + "license": "MIT"
264 + },
265 + "node_modules/brace-expansion": {
266 + "version": "2.0.3",
267 + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
268 + "integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
269 + "license": "MIT",
270 + "dependencies": {
271 + "balanced-match": "^1.0.0"
273 + },
274 + "node_modules/bun": {
275 + "version": "1.3.11",
276 + "resolved": "https://registry.npmjs.org/bun/-/bun-1.3.11.tgz",
277 + "integrity": "sha512-AvXWYFO6j/ZQ7bhGm4X6eilq2JHsDVC90ZM32k2B7/srhC2gs3Sdki1QTbwrdRCo8o7eT+167vcB1yzOvPdbjA==",
278 + "cpu": [
279 + "arm64",
280 + "x64"
281 + ],
282 + "dev": true,
283 + "hasInstallScript": true,
284 + "license": "MIT",
285 + "os": [
286 + "darwin",
287 + "linux",
288 + "win32"
289 + ],
290 + "bin": {
291 + "bun": "bin/bun.exe",
292 + "bunx": "bin/bunx.exe"
293 + },
294 + "optionalDependencies": {
295 + "@oven/bun-darwin-aarch64": "1.3.11",
296 + "@oven/bun-darwin-x64": "1.3.11",
297 + "@oven/bun-darwin-x64-baseline": "1.3.11",
298 + "@oven/bun-linux-aarch64": "1.3.11",
299 + "@oven/bun-linux-aarch64-musl": "1.3.11",
300 + "@oven/bun-linux-x64": "1.3.11",
301 + "@oven/bun-linux-x64-baseline": "1.3.11",
302 + "@oven/bun-linux-x64-musl": "1.3.11",
303 + "@oven/bun-linux-x64-musl-baseline": "1.3.11",
304 + "@oven/bun-windows-aarch64": "1.3.11",
305 + "@oven/bun-windows-x64": "1.3.11",
306 + "@oven/bun-windows-x64-baseline": "1.3.11"
308 + },
309 + "node_modules/bun-types": {
310 + "version": "1.3.11",
311 + "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.3.11.tgz",
312 + "integrity": "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg==",
313 + "dev": true,
314 + "license": "MIT",
315 + "dependencies": {
316 + "@types/node": "*"
318 + },
319 + "node_modules/color-convert": {
320 + "version": "2.0.1",
321 + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
322 + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
323 + "license": "MIT",
324 + "dependencies": {
325 + "color-name": "~1.1.4"
326 + },
327 + "engines": {
328 + "node": ">=7.0.0"
330 + },
331 + "node_modules/color-name": {
332 + "version": "1.1.4",
333 + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
334 + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
335 + "license": "MIT"
336 + },
337 + "node_modules/cross-spawn": {
338 + "version": "7.0.6",
339 + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
340 + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
341 + "license": "MIT",
342 + "dependencies": {
343 + "path-key": "^3.1.0",
344 + "shebang-command": "^2.0.0",
345 + "which": "^2.0.1"
346 + },
347 + "engines": {
348 + "node": ">= 8"
350 + },
351 + "node_modules/eastasianwidth": {
352 + "version": "0.2.0",
353 + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
354 + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
355 + "license": "MIT"
356 + },
357 + "node_modules/emoji-regex": {
358 + "version": "9.2.2",
359 + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
360 + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
361 + "license": "MIT"
362 + },
363 + "node_modules/foreground-child": {
364 + "version": "3.3.1",
365 + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
366 + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
367 + "license": "ISC",
368 + "dependencies": {
369 + "cross-spawn": "^7.0.6",
370 + "signal-exit": "^4.0.1"
371 + },
372 + "engines": {
373 + "node": ">=14"
374 + },
375 + "funding": {
376 + "url": "https://github.com/sponsors/isaacs"
378 + },
379 + "node_modules/glob": {
380 + "version": "10.5.0",
381 + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
382 + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
383 + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
384 + "license": "ISC",
385 + "dependencies": {
386 + "foreground-child": "^3.1.0",
387 + "jackspeak": "^3.1.2",
388 + "minimatch": "^9.0.4",
389 + "minipass": "^7.1.2",
390 + "package-json-from-dist": "^1.0.0",
391 + "path-scurry": "^1.11.1"
392 + },
393 + "bin": {
394 + "glob": "dist/esm/bin.mjs"
395 + },
396 + "funding": {
397 + "url": "https://github.com/sponsors/isaacs"
399 + },
400 + "node_modules/is-fullwidth-code-point": {
401 + "version": "3.0.0",
402 + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
403 + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
404 + "license": "MIT",
405 + "engines": {
406 + "node": ">=8"
408 + },
409 + "node_modules/isexe": {
410 + "version": "2.0.0",
411 + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
412 + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
413 + "license": "ISC"
414 + },
415 + "node_modules/jackspeak": {
416 + "version": "3.4.3",
417 + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
418 + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
419 + "license": "BlueOak-1.0.0",
420 + "dependencies": {
421 + "@isaacs/cliui": "^8.0.2"
422 + },
423 + "funding": {
424 + "url": "https://github.com/sponsors/isaacs"
425 + },
426 + "optionalDependencies": {
427 + "@pkgjs/parseargs": "^0.11.0"
429 + },
430 + "node_modules/lru-cache": {
431 + "version": "10.4.3",
432 + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
433 + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
434 + "license": "ISC"
435 + },
436 + "node_modules/minimatch": {
437 + "version": "9.0.9",
438 + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
439 + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
440 + "license": "ISC",
441 + "dependencies": {
442 + "brace-expansion": "^2.0.2"
443 + },
444 + "engines": {
445 + "node": ">=16 || 14 >=14.17"
446 + },
447 + "funding": {
448 + "url": "https://github.com/sponsors/isaacs"
450 + },
451 + "node_modules/minipass": {
452 + "version": "7.1.3",
453 + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
454 + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
455 + "license": "BlueOak-1.0.0",
456 + "engines": {
457 + "node": ">=16 || 14 >=14.17"
459 + },
460 + "node_modules/package-json-from-dist": {
461 + "version": "1.0.1",
462 + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
463 + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
464 + "license": "BlueOak-1.0.0"
465 + },
466 + "node_modules/path-key": {
467 + "version": "3.1.1",
468 + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
469 + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
470 + "license": "MIT",
471 + "engines": {
472 + "node": ">=8"
474 + },
475 + "node_modules/path-scurry": {
476 + "version": "1.11.1",
477 + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
478 + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
479 + "license": "BlueOak-1.0.0",
480 + "dependencies": {
481 + "lru-cache": "^10.2.0",
482 + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
483 + },
484 + "engines": {
485 + "node": ">=16 || 14 >=14.18"
486 + },
487 + "funding": {
488 + "url": "https://github.com/sponsors/isaacs"
490 + },
491 + "node_modules/shebang-command": {
492 + "version": "2.0.0",
493 + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
494 + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
495 + "license": "MIT",
496 + "dependencies": {
497 + "shebang-regex": "^3.0.0"
498 + },
499 + "engines": {
500 + "node": ">=8"
502 + },
503 + "node_modules/shebang-regex": {
504 + "version": "3.0.0",
505 + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
506 + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
507 + "license": "MIT",
508 + "engines": {
509 + "node": ">=8"
511 + },
512 + "node_modules/signal-exit": {
513 + "version": "4.1.0",
514 + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
515 + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
516 + "license": "ISC",
517 + "engines": {
518 + "node": ">=14"
519 + },
520 + "funding": {
521 + "url": "https://github.com/sponsors/isaacs"
523 + },
524 + "node_modules/string-width": {
525 + "version": "5.1.2",
526 + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
527 + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
528 + "license": "MIT",
529 + "dependencies": {
530 + "eastasianwidth": "^0.2.0",
531 + "emoji-regex": "^9.2.2",
532 + "strip-ansi": "^7.0.1"
533 + },
534 + "engines": {
535 + "node": ">=12"
536 + },
537 + "funding": {
538 + "url": "https://github.com/sponsors/sindresorhus"
540 + },
541 + "node_modules/string-width-cjs": {
542 + "name": "string-width",
543 + "version": "4.2.3",
544 + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
545 + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
546 + "license": "MIT",
547 + "dependencies": {
548 + "emoji-regex": "^8.0.0",
549 + "is-fullwidth-code-point": "^3.0.0",
550 + "strip-ansi": "^6.0.1"
551 + },
552 + "engines": {
553 + "node": ">=8"
555 + },
556 + "node_modules/string-width-cjs/node_modules/ansi-regex": {
557 + "version": "5.0.1",
558 + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
559 + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
560 + "license": "MIT",
561 + "engines": {
562 + "node": ">=8"
564 + },
565 + "node_modules/string-width-cjs/node_modules/emoji-regex": {
566 + "version": "8.0.0",
567 + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
568 + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
569 + "license": "MIT"
570 + },
571 + "node_modules/string-width-cjs/node_modules/strip-ansi": {
572 + "version": "6.0.1",
573 + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
574 + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
575 + "license": "MIT",
576 + "dependencies": {
577 + "ansi-regex": "^5.0.1"
578 + },
579 + "engines": {
580 + "node": ">=8"
582 + },
583 + "node_modules/strip-ansi": {
584 + "version": "7.2.0",
585 + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
586 + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
587 + "license": "MIT",
588 + "dependencies": {
589 + "ansi-regex": "^6.2.2"
590 + },
591 + "engines": {
592 + "node": ">=12"
593 + },
594 + "funding": {
595 + "url": "https://github.com/chalk/strip-ansi?sponsor=1"
597 + },
598 + "node_modules/strip-ansi-cjs": {
599 + "name": "strip-ansi",
600 + "version": "6.0.1",
601 + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
602 + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
603 + "license": "MIT",
604 + "dependencies": {
605 + "ansi-regex": "^5.0.1"
606 + },
607 + "engines": {
608 + "node": ">=8"
610 + },
611 + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": {
612 + "version": "5.0.1",
613 + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
614 + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
615 + "license": "MIT",
616 + "engines": {
617 + "node": ">=8"
619 + },
620 + "node_modules/undici-types": {
621 + "version": "7.18.2",
622 + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
623 + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
624 + "dev": true,
625 + "license": "MIT"
626 + },
627 + "node_modules/which": {
628 + "version": "2.0.2",
629 + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
630 + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
631 + "license": "ISC",
632 + "dependencies": {
633 + "isexe": "^2.0.0"
634 + },
635 + "bin": {
636 + "node-which": "bin/node-which"
637 + },
638 + "engines": {
639 + "node": ">= 8"
641 + },
642 + "node_modules/wrap-ansi": {
643 + "version": "8.1.0",
644 + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
645 + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
646 + "license": "MIT",
647 + "dependencies": {
648 + "ansi-styles": "^6.1.0",
649 + "string-width": "^5.0.1",
650 + "strip-ansi": "^7.0.1"
651 + },
652 + "engines": {
653 + "node": ">=12"
654 + },
655 + "funding": {
656 + "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
658 + },
659 + "node_modules/wrap-ansi-cjs": {
660 + "name": "wrap-ansi",
661 + "version": "7.0.0",
662 + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
663 + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
664 + "license": "MIT",
665 + "dependencies": {
666 + "ansi-styles": "^4.0.0",
667 + "string-width": "^4.1.0",
668 + "strip-ansi": "^6.0.0"
669 + },
670 + "engines": {
671 + "node": ">=10"
672 + },
673 + "funding": {
674 + "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
676 + },
677 + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": {
678 + "version": "5.0.1",
679 + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
680 + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
681 + "license": "MIT",
682 + "engines": {
683 + "node": ">=8"
685 + },
686 + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": {
687 + "version": "4.3.0",
688 + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
689 + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
690 + "license": "MIT",
691 + "dependencies": {
692 + "color-convert": "^2.0.1"
693 + },
694 + "engines": {
695 + "node": ">=8"
696 + },
697 + "funding": {
698 + "url": "https://github.com/chalk/ansi-styles?sponsor=1"
700 + },
701 + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": {
702 + "version": "8.0.0",
703 + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
704 + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
705 + "license": "MIT"
706 + },
707 + "node_modules/wrap-ansi-cjs/node_modules/string-width": {
708 + "version": "4.2.3",
709 + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
710 + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
711 + "license": "MIT",
712 + "dependencies": {
713 + "emoji-regex": "^8.0.0",
714 + "is-fullwidth-code-point": "^3.0.0",
715 + "strip-ansi": "^6.0.1"
716 + },
717 + "engines": {
718 + "node": ">=8"
720 + },
721 + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": {
722 + "version": "6.0.1",
723 + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
724 + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
725 + "license": "MIT",
726 + "dependencies": {
727 + "ansi-regex": "^5.0.1"
728 + },
729 + "engines": {
730 + "node": ">=8"
732 + },
733 + "node_modules/zod": {
734 + "version": "3.25.76",
735 + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
736 + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
737 + "license": "MIT",
738 + "funding": {
739 + "url": "https://github.com/sponsors/colinhacks"
741 + },
742 + "node_modules/zod-to-json-schema": {
743 + "version": "3.25.2",
744 + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
745 + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
746 + "license": "ISC",
747 + "peerDependencies": {
748 + "zod": "^3.25.28 || ^4"

opencode/plugins/chef/package.json

Modified
5 5 "name": "@opencode-ai/chef",
6 6 "version": "0.1.0",
7 7 "description": "Orchestrator plugin for coordinating multiple agents in structured workflows",
8 8 "type": "module",
9 9 "dependencies": {
10 + "glob": "^10.0.0",
10 11 "zod": "^3.22.0",
11 - "zod-to-json-schema": "^3.22.0",
12 - "glob": "^10.0.0"
12 + "zod-to-json-schema": "^3.22.0"
14 14 "devDependencies": {
15 - "@types/bun": "latest"
15 + "@types/bun": "latest",
16 + "bun": "^1.3.11"

opencode/plugins/chef/pipeline/builder.ts

Modified
6 6 retryOn: string[] | undefined;
9 -export interface StepDefinition {
9 +export interface StepDefinition<
10 + TContext extends Record<string, any> = Record<string, any>,
11 +> {
10 12 name: string;
11 13 type: "step";
12 14 agent: string;
13 - prompt: string | ((ctx: any) => string);
15 + prompt: string | ((ctx: TContext) => string);
14 16 output: z.ZodType<any>;
15 17 timeout?: number;
16 18 retry?: RetryPolicy;
24 26 onFail?: string;
27 -export interface ParallelDefinition {
29 +export interface ParallelDefinition<
30 + TContext extends Record<string, any> = Record<string, any>,
31 +> {
28 32 name: string;
29 33 type: "parallel";
30 - steps: StepDefinition[];
34 + steps: StepDefinition<TContext>[];
33 -export interface WhenDefinition {
37 +export interface WhenDefinition<
38 + TContext extends Record<string, any> = Record<string, any>,
39 +> {
34 40 name: string;
35 41 type: "when";
36 - condition: (ctx: any) => boolean;
42 + condition: (ctx: TContext) => boolean;
37 43 loopTarget?: string;
40 -export type PhaseDefinition =
41 - | StepDefinition
46 +export type PhaseDefinition<
47 + TContext extends Record<string, any> = Record<string, any>,
48 +> =
49 + | StepDefinition<TContext>
42 50 | GateDefinition
43 - | ParallelDefinition
44 - | WhenDefinition;
51 + | ParallelDefinition<TContext>
52 + | WhenDefinition<TContext>;
46 54 export interface PipelineDefinition {
47 55 name: string;
48 56 phases: PhaseDefinition[];
51 -export interface FragmentDefinition {
59 +export interface FragmentDefinition<
60 + TContext extends Record<string, any> = Record<string, any>,
61 +> {
52 62 name: string;
53 - steps: Omit<StepDefinition, "type">[];
63 + steps: Omit<StepDefinition<TContext>, "type">[];
56 -export class PipelineBuilder {
57 - private phases: PhaseDefinition[] = [];
66 +export class PipelineBuilder<
67 + TContext extends Record<string, any> = Record<string, any>,
68 +> {
69 + private phases: PhaseDefinition<TContext>[] = [];
59 71 constructor(private name: string) {}
61 73 step(name: string, config: {
62 74 agent: string;
63 - prompt: string | ((ctx: any) => string);
75 + prompt: string | ((ctx: TContext) => string);
64 76 output: z.ZodType<any>;
65 77 timeout?: number;
66 78 retry?: RetryPolicy;
86 98 return this;
89 - parallel(steps: Omit<StepDefinition, "type">[]): this {
101 + parallel(steps: Omit<StepDefinition<TContext>, "type">[]): this {
90 102 this.phases.push({
91 103 name: `parallel_${this.phases.length}`,
92 104 type: "parallel",
95 107 return this;
98 - when(condition: (ctx: any) => boolean): this {
110 + when(condition: (ctx: TContext) => boolean): this {
99 111 this.phases.push({
100 112 name: `when_${this.phases.length}`,
101 113 type: "when",
112 124 return this;
115 - use(fragment: FragmentDefinition): this {
116 - for (const s of fragment.steps) {
117 - this.phases.push({
118 - ...s,
119 - type: "step" as const,
120 - });
121 - }
127 + use(fragment: FragmentDefinition<TContext>): this {
128 + this.phases.push(
129 + ...fragment.steps.map((s) => ({ ...s, type: "step" as const })),
130 + );
122 131 return this;
193 202 build(): PipelineDefinition {
194 203 return {
195 204 name: this.name,
196 - phases: this.phases,
205 + phases: this.phases as PhaseDefinition[],
201 -export function pipeline(name: string): PipelineBuilder {
202 - return new PipelineBuilder(name);
210 +export function pipeline<
211 + TContext extends Record<string, any> = Record<string, any>,
213 + name: string,
214 +): PipelineBuilder<TContext> {
215 + return new PipelineBuilder<TContext>(name);
205 -export function step(
218 +export function step<
219 + TContext extends Record<string, any> = Record<string, any>,
206 221 name: string,
207 - config: Omit<StepDefinition, "name" | "type">,
208 -): Omit<StepDefinition, "type"> {
222 + config: Omit<StepDefinition<TContext>, "name" | "type">,
223 +): Omit<StepDefinition<TContext>, "type"> {
209 224 return { name, ...config };
212 -export function fragment(
227 +export function fragment<
228 + TContext extends Record<string, any> = Record<string, any>,
213 230 name: string,
214 - steps: Omit<StepDefinition, "type">[],
215 -): FragmentDefinition {
231 + steps: Omit<StepDefinition<TContext>, "type">[],
232 +): FragmentDefinition<TContext> {
216 233 return { name, steps };

opencode/plugins/chef/store.ts

Modified
14 14 | "completed"
15 15 | "failed"
16 16 | "skipped";
17 -export type StepStatus = "pending" | "running" | "completed" | "failed";
19 18 export interface PipelineInstance {
20 19 id: string;
39 38 completed_at: number | null;
42 -export interface StepState {
43 - id: string;
44 - phase_id: string;
45 - name: string;
46 - agent: string;
47 - status: StepStatus;
48 - output: string;
49 - error: string | null;
50 - attempts: number;
41 +const ALLOWED_COLUMNS: Record<string, ReadonlySet<string>> = {
42 + pipeline_instance: new Set([
43 + "id",
44 + "definition",
45 + "status",
46 + "input",
47 + "context",
48 + "current_phase",
49 + "created_at",
50 + "updated_at",
51 + ]),
52 + phase_state: new Set([
53 + "id",
54 + "pipeline_id",
55 + "name",
56 + "status",
57 + "output",
58 + "error",
59 + "attempts",
60 + "started_at",
61 + "completed_at",
62 + ]),
63 +};
53 65 export class Store {
54 66 private db: Database;
68 + private static SCHEMA_VERSION = 2;
70 + private static MIGRATIONS: Array<{
71 + version: number;
72 + description: string;
73 + sql: string[];
74 + }> = [
75 + {
76 + version: 1,
77 + description: "Initial schema",
78 + sql: [
79 + `CREATE TABLE IF NOT EXISTS pipeline_instance (
80 + id TEXT PRIMARY KEY,
81 + definition TEXT NOT NULL,
82 + status TEXT NOT NULL,
83 + input TEXT,
84 + context TEXT,
85 + current_phase INTEGER DEFAULT 0,
86 + created_at INTEGER,
87 + updated_at INTEGER
88 + )`,
89 + `CREATE TABLE IF NOT EXISTS phase_state (
90 + id TEXT PRIMARY KEY,
91 + pipeline_id TEXT NOT NULL,
92 + name TEXT NOT NULL,
93 + status TEXT NOT NULL,
94 + output TEXT,
95 + error TEXT,
96 + attempts INTEGER DEFAULT 0,
97 + started_at INTEGER,
98 + completed_at INTEGER,
99 + FOREIGN KEY (pipeline_id) REFERENCES pipeline_instance(id)
100 + )`,
101 + `CREATE INDEX IF NOT EXISTS idx_phase_pipeline ON phase_state(pipeline_id)`,
102 + ],
103 + },
105 + version: 2,
106 + description: "Remove unused step_state table",
107 + sql: [
108 + `DROP TABLE IF EXISTS step_state`,
109 + `DROP INDEX IF EXISTS idx_step_phase`,
110 + ],
111 + },
112 + ];
56 114 constructor(directory: string) {
57 115 const dbPath = join(directory, ".opencode/chef/chef.db");
58 116 this.db = new Database(dbPath);
63 121 private initSchema() {
64 122 this.db.run(`
65 - CREATE TABLE IF NOT EXISTS pipeline_instance (
66 - id TEXT PRIMARY KEY,
67 - definition TEXT NOT NULL,
68 - status TEXT NOT NULL,
69 - input TEXT,
70 - context TEXT,
71 - current_phase INTEGER DEFAULT 0,
72 - created_at INTEGER,
73 - updated_at INTEGER
123 + CREATE TABLE IF NOT EXISTS schema_version (
124 + version INTEGER PRIMARY KEY,
125 + applied_at INTEGER
77 - this.db.run(`
78 - CREATE TABLE IF NOT EXISTS phase_state (
79 - id TEXT PRIMARY KEY,
80 - pipeline_id TEXT NOT NULL,
81 - name TEXT NOT NULL,
82 - status TEXT NOT NULL,
83 - output TEXT,
84 - error TEXT,
85 - attempts INTEGER DEFAULT 0,
86 - started_at INTEGER,
87 - completed_at INTEGER,
88 - FOREIGN KEY (pipeline_id) REFERENCES pipeline_instance(id)
129 + const row = this.db
130 + .query<{ version: number | null }, []>(
131 + "SELECT MAX(version) as version FROM schema_version",
90 - `);
133 + .get();
134 + const currentVersion = row?.version ?? 0;
92 - this.db.run(`
93 - CREATE TABLE IF NOT EXISTS step_state (
94 - id TEXT PRIMARY KEY,
95 - phase_id TEXT NOT NULL,
96 - name TEXT NOT NULL,
97 - agent TEXT NOT NULL,
98 - status TEXT NOT NULL,
99 - output TEXT,
100 - error TEXT,
101 - attempts INTEGER DEFAULT 0,
102 - FOREIGN KEY (phase_id) REFERENCES phase_state(id)
103 - )
104 - `);
106 - // Add indexes for foreign key lookups
107 - this.db.run(
108 - "CREATE INDEX IF NOT EXISTS idx_phase_pipeline ON phase_state(pipeline_id)",
109 - );
110 - this.db.run(
111 - "CREATE INDEX IF NOT EXISTS idx_step_phase ON step_state(phase_id)",
112 - );
136 + for (const migration of Store.MIGRATIONS) {
137 + if (migration.version > currentVersion) {
138 + for (const sql of migration.sql) {
139 + this.db.run(sql);
141 + this.db.run(
142 + "INSERT INTO schema_version (version, applied_at) VALUES (?, ?)",
143 + [migration.version, Date.now()],
144 + );
145 + console.log(
146 + `Chef: Applied schema migration v${migration.version}: ${migration.description}`,
147 + );
115 152 // Pipeline operations
140 177 updates: Record<string, any>,
141 178 withTimestamp = false,
142 179 ): void {
180 + const allowed = ALLOWED_COLUMNS[table];
143 181 const filtered = Object.fromEntries(
144 - Object.entries(updates).filter(([k]) => k !== "id"),
182 + Object.entries(updates).filter(
183 + ([k]) => k !== "id" && (allowed ? allowed.has(k) : false),
184 + ),
146 186 if (Object.keys(filtered).length === 0) {
147 187 if (withTimestamp) {
210 250 ).all(pipelineId);
213 - // Step operations
214 - createStep(phaseId: string, name: string, agent: string): StepState {
215 - const id = randomUUID();
217 - this.db.run(
218 - `INSERT INTO step_state (id, phase_id, name, agent, status, output, error, attempts)
219 - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
220 - [id, phaseId, name, agent, "pending", "{}", null, 0],
221 - );
223 - return this.getStep(id)!;
224 - }
226 - getStep(id: string): StepState | null {
227 - const result = this.db.query<StepState, [string]>(
228 - "SELECT * FROM step_state WHERE id = ?",
229 - ).get(id);
231 - return result || null;
232 - }
234 - updateStep(id: string, updates: Partial<StepState>): void {
235 - this.updateRecord("step_state", id, updates);
236 - }
238 - getStepsByPhase(phaseId: string): StepState[] {
239 - return this.db.query<StepState, [string]>(
240 - "SELECT * FROM step_state WHERE phase_id = ?",
241 - ).all(phaseId);
242 - }
244 253 close() {
245 254 this.db.close();

opencode/plugins/chef/test/builder.test.ts

Added
new file mode 100644
1 +import { describe, expect, test } from "bun:test";
2 +import { z } from "zod";
3 +import { fragment, pipeline, PipelineBuilder, step } from "../pipeline/builder";
5 +describe("pipeline()", () => {
6 + test("creates a PipelineBuilder instance", () => {
7 + const builder = pipeline("test");
8 + expect(builder).toBeInstanceOf(PipelineBuilder);
9 + });
11 + test("creates a builder with generic context type", () => {
12 + const builder = pipeline<{ foo: string }>("test");
13 + expect(builder).toBeInstanceOf(PipelineBuilder);
14 + // The type system ensures the context type is preserved
15 + });
16 +});
18 +describe("PipelineBuilder.step()", () => {
19 + test("adds a step phase to the pipeline", () => {
20 + const mockOutput = z.object({ result: z.string() });
21 + const builder = pipeline("test").step("s", {
22 + agent: "test-agent",
23 + prompt: "Hello",
24 + output: mockOutput,
25 + });
26 + const result = builder.build();
27 + expect(result.phases[0]).toMatchObject({
28 + name: "s",
29 + type: "step",
30 + agent: "test-agent",
31 + prompt: "Hello",
32 + output: mockOutput,
33 + });
34 + });
36 + test("accepts function prompt", () => {
37 + const mockOutput = z.object({ result: z.string() });
38 + const builder = pipeline("test").step("s", {
39 + agent: "test-agent",
40 + prompt: (ctx: Record<string, any>) => `Hello ${ctx.foo}`,
41 + output: mockOutput,
42 + });
43 + const result = builder.build();
44 + expect(result.phases[0]).toMatchObject({
45 + name: "s",
46 + type: "step",
47 + });
48 + // Verify prompt is stored as a function
49 + const stepPhase = result.phases[0] as { prompt?: unknown };
50 + expect(typeof stepPhase.prompt).toBe("function");
51 + });
53 + test("chains multiple steps", () => {
54 + const mockOutput = z.object({ result: z.string() });
55 + const builder = pipeline("test")
56 + .step("step1", { agent: "a1", prompt: "p1", output: mockOutput })
57 + .step("step2", { agent: "a2", prompt: "p2", output: mockOutput });
58 + const result = builder.build();
59 + expect(result.phases).toHaveLength(2);
60 + expect(result.phases[0]!.name).toBe("step1");
61 + expect(result.phases[1]!.name).toBe("step2");
62 + });
63 +});
65 +describe("PipelineBuilder.gate()", () => {
66 + test("adds a gate phase to the pipeline", () => {
67 + const mockExpect = z.object({ status: z.string() });
68 + const builder = pipeline("test").gate("g", {
69 + agent: "gate-agent",
70 + expect: mockExpect,
71 + });
72 + const result = builder.build();
73 + expect(result.phases[0]).toMatchObject({
74 + name: "g",
75 + type: "gate",
76 + agent: "gate-agent",
77 + expect: mockExpect,
78 + });
79 + });
81 + test("accepts optional agent", () => {
82 + const mockExpect = z.object({ status: z.string() });
83 + const builder = pipeline("test").gate("g", { expect: mockExpect });
84 + const result = builder.build();
85 + expect(result.phases[0]).toMatchObject({
86 + name: "g",
87 + type: "gate",
88 + expect: mockExpect,
89 + });
90 + // Agent is optional, so it should not be present when not provided
91 + const gatePhase = result.phases[0] as { agent?: string };
92 + expect(gatePhase.agent).toBeUndefined();
93 + });
95 + test("accepts onFail target", () => {
96 + const mockExpect = z.object({ status: z.string() });
97 + const mockOutput = z.object({ result: z.string() });
98 + const builder = pipeline("test")
99 + .step("s", { agent: "a", prompt: "p", output: mockOutput })
100 + .gate("g", { expect: mockExpect, onFail: "s" });
101 + const result = builder.build();
102 + expect(result.phases[1]).toMatchObject({
103 + name: "g",
104 + type: "gate",
105 + onFail: "s",
106 + });
107 + });
108 +});
110 +describe("PipelineBuilder.parallel()", () => {
111 + test("adds a parallel phase", () => {
112 + const mockOutput = z.object({ result: z.string() });
113 + const builder = pipeline("test").parallel([
114 + { name: "p1", agent: "a1", prompt: "p1", output: mockOutput },
115 + { name: "p2", agent: "a2", prompt: "p2", output: mockOutput },
116 + ]);
117 + const result = builder.build();
118 + const parallelPhase = result.phases[0] as {
119 + name: string;
120 + type: string;
121 + steps: any[];
122 + };
123 + expect(parallelPhase).toMatchObject({
124 + name: "parallel_0",
125 + type: "parallel",
126 + });
127 + expect(parallelPhase.steps).toHaveLength(2);
128 + expect(parallelPhase.steps[0]).toMatchObject({
129 + name: "p1",
130 + type: "step",
131 + agent: "a1",
132 + });
133 + expect(parallelPhase.steps[1]).toMatchObject({
134 + name: "p2",
135 + type: "step",
136 + agent: "a2",
137 + });
138 + });
140 + test("names parallel phase with index", () => {
141 + const mockOutput = z.object({ result: z.string() });
142 + const builder = pipeline("test")
143 + .parallel([{ name: "p1", agent: "a", prompt: "p", output: mockOutput }])
144 + .parallel([{ name: "p2", agent: "a", prompt: "p", output: mockOutput }]);
145 + const result = builder.build();
146 + expect(result.phases[0]!.name).toBe("parallel_0");
147 + expect(result.phases[1]!.name).toBe("parallel_1");
148 + });
149 +});
151 +describe("PipelineBuilder.when()", () => {
152 + test("adds a when phase", () => {
153 + const builder = pipeline("test").when((ctx) => ctx.condition === true);
154 + const result = builder.build();
155 + const whenPhase = result.phases[0] as {
156 + name: string;
157 + type: string;
158 + condition: Function;
159 + };
160 + expect(whenPhase).toMatchObject({
161 + name: "when_0",
162 + type: "when",
163 + });
164 + expect(typeof whenPhase.condition).toBe("function");
165 + });
167 + test("names when phase with index", () => {
168 + const builder = pipeline("test")
169 + .when((ctx) => ctx.a)
170 + .when((ctx) => ctx.b);
171 + const result = builder.build();
172 + expect(result.phases[0]!.name).toBe("when_0");
173 + expect(result.phases[1]!.name).toBe("when_1");
174 + });
175 +});
177 +describe("PipelineBuilder.loop()", () => {
178 + test("sets loopTarget on preceding when phase", () => {
179 + const mockOutput = z.object({ result: z.string() });
180 + const builder = pipeline("test")
181 + .step("target", { agent: "a", prompt: "p", output: mockOutput })
182 + .when((ctx) => ctx.continue)
183 + .loop("target");
184 + const result = builder.build();
185 + const whenPhase = result.phases[1]!;
186 + expect(whenPhase.type).toBe("when");
187 + if (whenPhase.type === "when") {
188 + expect(whenPhase.loopTarget).toBe("target");
190 + });
192 + test("does nothing when last phase is not when", () => {
193 + const mockOutput = z.object({ result: z.string() });
194 + const builder = pipeline("test")
195 + .step("s", { agent: "a", prompt: "p", output: mockOutput })
196 + .loop("target");
197 + const result = builder.build();
198 + expect(result.phases).toHaveLength(1);
199 + expect(result.phases[0]!.type).toBe("step");
200 + });
201 +});
203 +describe("PipelineBuilder.use()", () => {
204 + test("adds fragment steps as phases", () => {
205 + const mockOutput = z.object({ result: z.string() });
206 + const myFragment = fragment("my-fragment", [
207 + { name: "f1", agent: "a1", prompt: "p1", output: mockOutput },
208 + { name: "f2", agent: "a2", prompt: "p2", output: mockOutput },
209 + ]);
210 + const builder = pipeline("test").use(myFragment);
211 + const result = builder.build();
212 + expect(result.phases).toHaveLength(2);
213 + expect(result.phases[0]!.name).toBe("f1");
214 + expect(result.phases[0]!.type).toBe("step");
215 + expect(result.phases[1]!.name).toBe("f2");
216 + expect(result.phases[1]!.type).toBe("step");
217 + });
219 + test("preserves step order from fragment", () => {
220 + const mockOutput = z.object({ result: z.string() });
221 + const myFragment = fragment("my-fragment", [
222 + { name: "first", agent: "a", prompt: "p", output: mockOutput },
223 + { name: "second", agent: "a", prompt: "p", output: mockOutput },
224 + { name: "third", agent: "a", prompt: "p", output: mockOutput },
225 + ]);
226 + const builder = pipeline("test").use(myFragment);
227 + const result = builder.build();
228 + expect(result.phases[0]!.name).toBe("first");
229 + expect(result.phases[1]!.name).toBe("second");
230 + expect(result.phases[2]!.name).toBe("third");
231 + });
232 +});
234 +describe("PipelineBuilder.validate()", () => {
235 + test("returns valid for a correct pipeline", () => {
236 + const mockOutput = z.object({ result: z.string() });
237 + const mockExpect = z.object({ status: z.string() });
238 + const builder = pipeline("test")
239 + .step("s", { agent: "a", prompt: "p", output: mockOutput })
240 + .gate("g", { agent: "gate-agent", expect: mockExpect });
241 + const result = builder.validate();
242 + expect(result.valid).toBe(true);
243 + expect(result.errors).toHaveLength(0);
244 + });
246 + test("catches invalid output schema", () => {
247 + const builder = pipeline("test").step("s", {
248 + agent: "a",
249 + prompt: "p",
250 + output: {} as any,
251 + });
252 + const result = builder.validate();
253 + expect(result.valid).toBe(false);
254 + expect(result.errors).toContain(
255 + 'Step "s" has invalid output schema (expected Zod type)',
256 + );
257 + });
259 + test("catches empty agent", () => {
260 + const mockOutput = z.object({ result: z.string() });
261 + const builder = pipeline("test").step("s", {
262 + agent: "",
263 + prompt: "p",
264 + output: mockOutput,
265 + });
266 + const result = builder.validate();
267 + expect(result.valid).toBe(false);
268 + expect(result.errors).toContain(
269 + 'Step "s" has invalid agent (expected string)',
270 + );
271 + });
273 + test("catches invalid gate expect", () => {
274 + const builder = pipeline("test").gate("g", { expect: {} as any });
275 + const result = builder.validate();
276 + expect(result.valid).toBe(false);
277 + expect(result.errors).toContain(
278 + 'Gate "g" has invalid expect schema (expected Zod type)',
279 + );
280 + });
282 + test("catches missing onFail target", () => {
283 + const mockExpect = z.object({ status: z.string() });
284 + const builder = pipeline("test").gate("g", {
285 + expect: mockExpect,
286 + onFail: "nonexistent",
287 + });
288 + const result = builder.validate();
289 + expect(result.valid).toBe(false);
290 + expect(result.errors).toContain(
291 + 'Gate "g" onFail target "nonexistent" not found in pipeline',
292 + );
293 + });
295 + test("catches missing loop target", () => {
296 + const builder = pipeline("test").when((ctx) => ctx.continue).loop(
297 + "nonexistent",
298 + );
299 + const result = builder.validate();
300 + expect(result.valid).toBe(false);
301 + expect(result.errors).toContain(
302 + 'Loop target "nonexistent" not found in pipeline',
303 + );
304 + });
306 + test("validates when loop target exists in later phase", () => {
307 + const mockOutput = z.object({ result: z.string() });
308 + // When is added first, then step - the step doesn't exist yet when validating
309 + // So this should fail
310 + const builder = pipeline("test")
311 + .when((ctx) => ctx.continue)
312 + .loop("target")
313 + .step("target", { agent: "a", prompt: "p", output: mockOutput });
314 + const result = builder.validate();
315 + // The loop target "target" is not yet seen when we validate the when phase
316 + expect(result.valid).toBe(false);
317 + expect(result.errors).toContain(
318 + 'Loop target "target" not found in pipeline',
319 + );
320 + });
322 + test("catches invalid parallel step schema", () => {
323 + const builder = pipeline("test").parallel([
324 + { name: "p1", agent: "a", prompt: "p", output: {} as any },
325 + ]);
326 + const result = builder.validate();
327 + expect(result.valid).toBe(false);
328 + expect(result.errors).toContain(
329 + 'Parallel step "p1" has invalid output schema',
330 + );
331 + });
333 + test("catches invalid parallel step agent", () => {
334 + const mockOutput = z.object({ result: z.string() });
335 + const builder = pipeline("test").parallel([
336 + { name: "p1", agent: "", prompt: "p", output: mockOutput },
337 + ]);
338 + const result = builder.validate();
339 + expect(result.valid).toBe(false);
340 + expect(result.errors).toContain('Parallel step "p1" has invalid agent');
341 + });
342 +});
344 +describe("PipelineBuilder.build()", () => {
345 + test("returns PipelineDefinition with correct name", () => {
346 + const builder = pipeline("my-pipeline");
347 + const result = builder.build();
348 + expect(result.name).toBe("my-pipeline");
349 + });
351 + test("returns all phases", () => {
352 + const mockOutput = z.object({ result: z.string() });
353 + const mockExpect = z.object({ status: z.string() });
354 + const builder = pipeline("test")
355 + .step("s1", { agent: "a1", prompt: "p1", output: mockOutput })
356 + .gate("g", { expect: mockExpect })
357 + .when((ctx) => ctx.continue);
358 + const result = builder.build();
359 + expect(result.phases).toHaveLength(3);
360 + expect(result.phases[0]!.name).toBe("s1");
361 + expect(result.phases[1]!.name).toBe("g");
362 + // when is named using phases.length, so after 2 phases it's "when_2"
363 + expect(result.phases[2]!.name).toBe("when_2");
364 + });
365 +});
367 +describe("step() helper", () => {
368 + test("creates step config with name", () => {
369 + const mockOutput = z.object({ result: z.string() });
370 + const result = step("my-step", {
371 + agent: "test-agent",
372 + prompt: "test prompt",
373 + output: mockOutput,
374 + });
375 + expect(result).toMatchObject({
376 + name: "my-step",
377 + agent: "test-agent",
378 + prompt: "test prompt",
379 + output: mockOutput,
380 + });
381 + // Should NOT have type field
382 + expect(result).not.toHaveProperty("type");
383 + });
384 +});
386 +describe("fragment() helper", () => {
387 + test("creates fragment definition", () => {
388 + const mockOutput = z.object({ result: z.string() });
389 + const step1 = step("f1", { agent: "a1", prompt: "p1", output: mockOutput });
390 + const step2 = step("f2", { agent: "a2", prompt: "p2", output: mockOutput });
391 + const result = fragment("my-fragment", [step1, step2]);
392 + expect(result).toMatchObject({
393 + name: "my-fragment",
394 + steps: [step1, step2],
395 + });
396 + expect(result.steps).toHaveLength(2);
397 + });
398 +});
400 +describe("chaining", () => {
401 + test("each method returns this for chaining", () => {
402 + const mockOutput = z.object({ result: z.string() });
403 + const mockExpect = z.object({ status: z.string() });
404 + const myFragment = fragment("frag", [
405 + { name: "frag1", agent: "a", prompt: "p", output: mockOutput },
406 + ]);
408 + // Test step()
409 + const builder1 = pipeline("test");
410 + const result1 = builder1.step("s", {
411 + agent: "a",
412 + prompt: "p",
413 + output: mockOutput,
414 + });
415 + expect(result1).toBe(builder1);
417 + // Test gate()
418 + const builder2 = pipeline("test");
419 + const result2 = builder2.gate("g", { expect: mockExpect });
420 + expect(result2).toBe(builder2);
422 + // Test parallel()
423 + const builder3 = pipeline("test");
424 + const result3 = builder3.parallel([
425 + { name: "p", agent: "a", prompt: "p", output: mockOutput },
426 + ]);
427 + expect(result3).toBe(builder3);
429 + // Test when()
430 + const builder4 = pipeline("test");
431 + const result4 = builder4.when((ctx) => ctx.cond);
432 + expect(result4).toBe(builder4);
434 + // Test loop()
435 + const builder5 = pipeline("test");
436 + builder5.step("s", { agent: "a", prompt: "p", output: mockOutput });
437 + builder5.when((ctx) => ctx.cond);
438 + const result5 = builder5.loop("s");
439 + expect(result5).toBe(builder5);
441 + // Test use()
442 + const builder6 = pipeline("test");
443 + const result6 = builder6.use(myFragment);
444 + expect(result6).toBe(builder6);
445 + });
446 +});

opencode/plugins/chef/test/executor.test.ts

Added
new file mode 100644
1 +import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
2 +import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
3 +import { join } from "node:path";
4 +import { tmpdir } from "node:os";
6 +import {
7 + AgentError,
8 + AgentTimeoutError,
9 + ChefError,
10 + Executor,
11 + GateFailureError,
12 + MaxIterationsError,
13 +} from "../executor";
14 +import { Store } from "../store";
15 +import { z } from "zod";
17 +let store: Store;
18 +let tempDir: string;
19 +let mockClient: any;
21 +beforeEach(() => {
22 + tempDir = mkdtempSync(join(tmpdir(), "chef-exec-test-"));
23 + mkdirSync(join(tempDir, ".opencode/chef"), { recursive: true });
24 + store = new Store(tempDir);
26 + mockClient = {
27 + session: {
28 + create: mock(() => Promise.resolve({ id: "session-1" })),
29 + prompt: mock(() =>
30 + Promise.resolve({
31 + data: { info: { structured_output: { result: "ok" } } },
32 + })
33 + ),
34 + delete: mock(() => Promise.resolve()),
35 + },
36 + app: {
37 + log: mock(() => Promise.resolve()),
38 + agents: mock(() => Promise.resolve([])),
39 + },
40 + };
41 +});
43 +afterEach(() => {
44 + store.close();
45 + rmSync(tempDir, { recursive: true, force: true });
46 +});
48 +// Helper to create a basic pipeline definition
49 +function createDefinition(phases: any[]) {
50 + return { name: "test-pipeline", phases };
53 +function createExecutor(
54 + definition: any,
55 + options?: { maxLoopIterations?: number },
56 +) {
57 + return new Executor(
58 + store,
59 + mockClient as any,
60 + definition,
61 + options,
62 + );
65 +describe("Executor - Basic step execution", () => {
66 + test("executes a single step pipeline", async () => {
67 + const definition = createDefinition([
68 + {
69 + name: "step1",
70 + type: "step",
71 + agent: "test-agent",
72 + prompt: "do thing",
73 + output: z.object({ result: z.string() }),
74 + },
75 + ]);
77 + const instance = store.createPipeline("test-pipe", {});
78 + const executor = createExecutor(definition);
79 + const result = await executor.execute(instance.id, {});
81 + expect(result.status).toBe("completed");
82 + expect(result.context.step1).toEqual({ result: "ok" });
83 + });
85 + test("creates session with correct agent", async () => {
86 + const definition = createDefinition([
87 + {
88 + name: "step1",
89 + type: "step",
90 + agent: "my-special-agent",
91 + prompt: "do thing",
92 + output: z.object({ result: z.string() }),
93 + },
94 + ]);
96 + const instance = store.createPipeline("test-pipe", {});
97 + const executor = createExecutor(definition);
98 + await executor.execute(instance.id, {});
100 + expect(mockClient.session.create).toHaveBeenCalled();
101 + const createCall = (mockClient.session.create as any).mock.calls[0][0];
102 + expect(createCall.body.agent).toBe("my-special-agent");
103 + });
105 + test("injects context before prompting", async () => {
106 + const definition = createDefinition([
108 + name: "step1",
109 + type: "step",
110 + agent: "test-agent",
111 + prompt: "do thing",
112 + output: z.object({ result: z.string() }),
113 + },
114 + ]);
116 + const instance = store.createPipeline("test-pipe", { existing: "data" });
117 + const executor = createExecutor(definition);
118 + await executor.execute(instance.id, {});
120 + // Two prompt calls: context injection (noReply: true) and execution
121 + expect(mockClient.session.prompt).toHaveBeenCalledTimes(2);
123 + // First call is context injection
124 + const contextCall = (mockClient.session.prompt as any).mock.calls[0][0];
125 + expect(contextCall.body.noReply).toBe(true);
127 + // Second call is execution
128 + const execCall = (mockClient.session.prompt as any).mock.calls[1][0];
129 + expect(execCall.body.noReply).toBeUndefined();
130 + expect(execCall.body.format).toBeDefined();
131 + });
133 + test("uses string prompt directly", async () => {
134 + const definition = createDefinition([
136 + name: "step1",
137 + type: "step",
138 + agent: "test-agent",
139 + prompt: "do the thing now",
140 + output: z.object({ result: z.string() }),
141 + },
142 + ]);
144 + const instance = store.createPipeline("test-pipe", {});
145 + const executor = createExecutor(definition);
146 + await executor.execute(instance.id, {});
148 + const execCall = (mockClient.session.prompt as any).mock.calls[1][0];
149 + expect(execCall.body.parts[0].text).toBe("do the thing now");
150 + });
152 + test("evaluates function prompt with context", async () => {
153 + const definition = createDefinition([
155 + name: "step1",
156 + type: "step",
157 + agent: "test-agent",
158 + prompt: (ctx: any) => `dynamic prompt based on ${ctx.inputValue}`,
159 + output: z.object({ result: z.string() }),
160 + },
161 + ]);
163 + const instance = store.createPipeline("test-pipe", {
164 + inputValue: "test-input",
165 + });
166 + const executor = createExecutor(definition);
167 + await executor.execute(instance.id, { inputValue: "test-input" });
169 + const execCall = (mockClient.session.prompt as any).mock.calls[1][0];
170 + expect(execCall.body.parts[0].text).toBe(
171 + "dynamic prompt based on test-input",
172 + );
173 + });
174 +});
176 +describe("Executor - Context flow", () => {
177 + test("context flows between steps", async () => {
178 + let capturedContext: any;
179 + let callCount = 0;
181 + const definition = createDefinition([
183 + name: "step1",
184 + type: "step",
185 + agent: "test-agent",
186 + prompt: "first step",
187 + output: z.object({ findings: z.string() }),
188 + },
190 + name: "step2",
191 + type: "step",
192 + agent: "test-agent",
193 + prompt: (ctx: any) => {
194 + capturedContext = ctx;
195 + return "second step";
196 + },
197 + output: z.object({ result: z.string() }),
198 + },
199 + ]);
201 + // Replace mock with one that returns different values based on call count
202 + mockClient.session.prompt = mock(() => {
203 + callCount++;
204 + // Odd calls are context injection (1, 3), even calls are execution (2, 4)
205 + if (callCount % 2 === 0) {
206 + // Execution call - return step1's output on second execution
207 + return Promise.resolve({
208 + data: { info: { structured_output: { findings: "important-data" } } },
209 + });
211 + // Context injection
212 + return Promise.resolve({});
213 + });
215 + const instance = store.createPipeline("test-pipe", {});
216 + const executor = createExecutor(definition);
217 + await executor.execute(instance.id, {});
219 + // The second step's prompt function should have received context with step1's output
220 + expect(capturedContext.step1).toEqual({ findings: "important-data" });
221 + });
222 +});
224 +describe("Executor - Retry logic", () => {
225 + test("retries on failure and succeeds", async () => {
226 + let attemptCount = 0;
227 + mockClient.session.prompt = mock(() => {
228 + attemptCount++;
229 + // Even calls (0, 2) are context injection, odd calls (1, 3) are execution
230 + if (attemptCount % 2 === 0) {
231 + // Execution prompt
232 + if (attemptCount < 4) {
233 + // First execution fails
234 + return Promise.reject(new AgentError("step1", "Temporary failure"));
236 + return Promise.resolve({
237 + data: { info: { structured_output: { result: "ok" } } },
238 + });
240 + // Context injection succeeds
241 + return Promise.resolve({});
242 + });
244 + const definition = createDefinition([
246 + name: "step1",
247 + type: "step",
248 + agent: "test-agent",
249 + prompt: "do thing",
250 + retry: { maxAttempts: 3, backoffMs: 1, retryOn: undefined },
251 + output: z.object({ result: z.string() }),
252 + },
253 + ]);
255 + const instance = store.createPipeline("test-pipe", {});
256 + const executor = createExecutor(definition);
257 + const result = await executor.execute(instance.id, {});
259 + expect(result.status).toBe("completed");
260 + expect(result.context.step1).toEqual({ result: "ok" });
261 + });
263 + test("gives up after maxAttempts", async () => {
264 + let attemptCount = 0;
265 + mockClient.session.prompt = mock(() => {
266 + attemptCount++;
267 + if (attemptCount % 2 === 0) {
268 + // Execution - always fails
269 + return Promise.reject(new AgentError("step1", "Permanent failure"));
271 + return Promise.resolve({});
272 + });
274 + const definition = createDefinition([
276 + name: "step1",
277 + type: "step",
278 + agent: "test-agent",
279 + prompt: "do thing",
280 + retry: { maxAttempts: 2, backoffMs: 1, retryOn: undefined },
281 + output: z.object({ result: z.string() }),
282 + },
283 + ]);
285 + const instance = store.createPipeline("test-pipe", {});
286 + const executor = createExecutor(definition);
287 + const result = await executor.execute(instance.id, {});
289 + expect(result.status).toBe("failed");
290 + expect(result.error).toContain("Permanent failure");
291 + });
293 + test("only retries on matching error types", async () => {
294 + let attemptCount = 0;
295 + mockClient.session.prompt = mock(() => {
296 + attemptCount++;
297 + if (attemptCount % 2 === 0) {
298 + // Execution - throws agent_error (not agent_timeout)
299 + return Promise.reject(new AgentError("step1", "Wrong error type"));
301 + return Promise.resolve({});
302 + });
304 + const definition = createDefinition([
306 + name: "step1",
307 + type: "step",
308 + agent: "test-agent",
309 + prompt: "do thing",
310 + retry: { maxAttempts: 3, backoffMs: 1, retryOn: ["agent_timeout"] },
311 + output: z.object({ result: z.string() }),
312 + },
313 + ]);
315 + const instance = store.createPipeline("test-pipe", {});
316 + const executor = createExecutor(definition);
317 + const result = await executor.execute(instance.id, {});
319 + // Should fail immediately because agent_error doesn't match retryOn
320 + expect(result.status).toBe("failed");
321 + expect(result.error).toContain("Wrong error type");
322 + // Only one attempt made (context injection + 1 execution)
323 + expect(attemptCount).toBe(2);
324 + });
326 + test("retries on 'all' error type", async () => {
327 + let attemptCount = 0;
328 + mockClient.session.prompt = mock(() => {
329 + attemptCount++;
330 + if (attemptCount % 2 === 0) {
331 + if (attemptCount < 4) {
332 + return Promise.reject(new AgentError("step1", "Some error"));
334 + return Promise.resolve({
335 + data: { info: { structured_output: { result: "ok" } } },
336 + });
338 + return Promise.resolve({});
339 + });
341 + const definition = createDefinition([
343 + name: "step1",
344 + type: "step",
345 + agent: "test-agent",
346 + prompt: "do thing",
347 + retry: { maxAttempts: 3, backoffMs: 1, retryOn: ["all"] },
348 + output: z.object({ result: z.string() }),
349 + },
350 + ]);
352 + const instance = store.createPipeline("test-pipe", {});
353 + const executor = createExecutor(definition);
354 + const result = await executor.execute(instance.id, {});
356 + expect(result.status).toBe("completed");
357 + expect(result.context.step1).toEqual({ result: "ok" });
358 + });
359 +});
361 +describe("Executor - Timeout", () => {
362 + test("step that takes too long throws AgentTimeoutError", async () => {
363 + let callCount = 0;
364 + mockClient.session.prompt = mock(() => {
365 + callCount++;
366 + // First call is context injection - resolve immediately
367 + if (callCount === 1) {
368 + return Promise.resolve({});
370 + // Second call (execution) - never resolves (will timeout)
371 + return new Promise(() => {});
372 + });
374 + const definition = createDefinition([
376 + name: "step1",
377 + type: "step",
378 + agent: "test-agent",
379 + prompt: "do thing",
380 + timeout: 10, // very short timeout
381 + output: z.object({ result: z.string() }),
382 + },
383 + ]);
385 + const instance = store.createPipeline("test-pipe", {});
386 + const executor = createExecutor(definition);
387 + const result = await executor.execute(instance.id, {});
389 + expect(result.status).toBe("failed");
390 + expect(result.error).toContain("timed out");
391 + });
392 +});
394 +describe("Executor - Session cleanup", () => {
395 + test("cleans up session on success", async () => {
396 + const definition = createDefinition([
398 + name: "step1",
399 + type: "step",
400 + agent: "test-agent",
401 + prompt: "do thing",
402 + output: z.object({ result: z.string() }),
403 + },
404 + ]);
406 + const instance = store.createPipeline("test-pipe", {});
407 + const executor = createExecutor(definition);
408 + await executor.execute(instance.id, {});
410 + expect(mockClient.session.delete).toHaveBeenCalled();
411 + const deleteCall = (mockClient.session.delete as any).mock.calls[0][0];
412 + expect(deleteCall.path.id).toBe("session-1");
413 + });
415 + test("cleans up session on failure", async () => {
416 + let attemptCount = 0;
417 + mockClient.session.prompt = mock(() => {
418 + attemptCount++;
419 + if (attemptCount % 2 === 0) {
420 + return Promise.reject(new AgentError("step1", "Failure"));
422 + return Promise.resolve({});
423 + });
425 + const definition = createDefinition([
427 + name: "step1",
428 + type: "step",
429 + agent: "test-agent",
430 + prompt: "do thing",
431 + retry: { maxAttempts: 1, backoffMs: 1, retryOn: undefined },
432 + output: z.object({ result: z.string() }),
433 + },
434 + ]);
436 + const instance = store.createPipeline("test-pipe", {});
437 + const executor = createExecutor(definition);
438 + await executor.execute(instance.id, {});
440 + expect(mockClient.session.delete).toHaveBeenCalled();
441 + });
443 + test("tracks leaked sessions when cleanup fails", async () => {
444 + mockClient.session.delete = mock(() =>
445 + Promise.reject(new Error("Delete failed"))
446 + );
448 + const definition = createDefinition([
450 + name: "step1",
451 + type: "step",
452 + agent: "test-agent",
453 + prompt: "do thing",
454 + output: z.object({ result: z.string() }),
455 + },
456 + ]);
458 + const instance = store.createPipeline("test-pipe", {});
459 + const executor = createExecutor(definition);
460 + const result = await executor.execute(instance.id, {});
462 + expect(result.status).toBe("completed");
463 + // The cleanup failed but pipeline still completed
464 + expect(mockClient.app.log).toHaveBeenCalled();
465 + });
466 +});
468 +describe("Executor - Gate execution", () => {
469 + test("gate with agent succeeds", async () => {
470 + const definition = createDefinition([
472 + name: "gate1",
473 + type: "gate",
474 + agent: "test-agent",
475 + expect: z.object({ result: z.string() }),
476 + },
477 + ]);
479 + const instance = store.createPipeline("test-pipe", {});
480 + const executor = createExecutor(definition);
481 + const result = await executor.execute(instance.id, {});
483 + expect(result.status).toBe("completed");
484 + expect(result.context.gate1).toEqual({ result: "ok" });
485 + });
487 + test("gate without agent validates context directly", async () => {
488 + const definition = createDefinition([
490 + name: "gate1",
491 + type: "gate",
492 + expect: z.object({ research: z.object({ findings: z.string() }) }),
493 + },
494 + ]);
496 + const instance = store.createPipeline("test-pipe", {
497 + research: { findings: "valid-data" },
498 + });
499 + const executor = createExecutor(definition);
500 + const result = await executor.execute(instance.id, {
501 + research: { findings: "valid-data" },
502 + });
504 + expect(result.status).toBe("completed");
505 + expect(result.context.gate1).toEqual({
506 + research: { findings: "valid-data" },
507 + });
508 + });
510 + test("gate failure with onFail loops back", async () => {
511 + let promptCallCount = 0;
513 + mockClient.session.prompt = mock((opts: any) => {
514 + promptCallCount++;
515 + // Flow:
516 + // Call 1: step1 context injection
517 + // Call 2: step1 execution
518 + // Call 3: gate1 context injection
519 + // Call 4: gate1 first evaluation (FAIL - loops back to step1)
520 + // Call 5: step1 retry context injection
521 + // Call 6: step1 retry execution
522 + // Call 7: gate1 second context injection
523 + // Call 8: gate1 second evaluation (SUCCEED)
524 + if (promptCallCount === 4) {
525 + // First gate evaluation - fail
526 + return Promise.reject(
527 + new GateFailureError("gate1", "Validation failed"),
528 + );
530 + if (promptCallCount === 8) {
531 + // Second gate evaluation - succeed
532 + return Promise.resolve({
533 + data: { info: { structured_output: { result: "gate-ok" } } },
534 + });
536 + // All other calls succeed
537 + return Promise.resolve({
538 + data: { info: { structured_output: { result: "ok" } } },
539 + });
540 + });
542 + const definition = createDefinition([
544 + name: "step1",
545 + type: "step",
546 + agent: "test-agent",
547 + prompt: "do step1",
548 + output: z.object({ result: z.string() }),
549 + },
551 + name: "gate1",
552 + type: "gate",
553 + agent: "test-agent",
554 + expect: z.object({ result: z.string() }),
555 + onFail: "step1",
556 + },
557 + ]);
559 + const instance = store.createPipeline("test-pipe", {});
560 + const executor = createExecutor(definition);
561 + const result = await executor.execute(instance.id, {});
563 + // Gate fails, loops back to step1, then gate succeeds
564 + expect(result.status).toBe("completed");
565 + expect(result.context.gate1).toEqual({ result: "gate-ok" });
566 + });
568 + test("gate failure without onFail fails pipeline", async () => {
569 + mockClient.session.prompt = mock(() =>
570 + Promise.reject(new GateFailureError("gate1", "Validation failed"))
571 + );
573 + const definition = createDefinition([
575 + name: "gate1",
576 + type: "gate",
577 + agent: "test-agent",
578 + expect: z.object({ result: z.string() }),
579 + },
580 + ]);
582 + const instance = store.createPipeline("test-pipe", {});
583 + const executor = createExecutor(definition);
584 + const result = await executor.execute(instance.id, {});
586 + expect(result.status).toBe("failed");
587 + expect(result.error).toContain("Validation failed");
588 + });
589 +});
591 +describe("Executor - Parallel execution", () => {
592 + test("executes all parallel steps", async () => {
593 + let sessionCreateCount = 0;
594 + const sessionStepMap = new Map<string, number>();
595 + const outputs = ["result-a", "result-b"];
597 + // Mock session.create to return unique IDs and track which step
598 + const originalCreate = mockClient.session.create;
599 + mockClient.session.create = mock(() => {
600 + sessionCreateCount++;
601 + const sessionId = `session-${sessionCreateCount}`;
602 + sessionStepMap.set(sessionId, sessionCreateCount - 1); // step index
603 + return Promise.resolve({ id: sessionId });
604 + });
606 + // Reset prompt mock to use the session mapping
607 + mockClient.session.prompt = mock((opts: any) => {
608 + const stepIndex = sessionStepMap.get(opts?.path?.id) ?? 0;
609 + // Context injection: noReply is true
610 + if (opts?.body?.noReply) {
611 + return Promise.resolve({});
613 + // Execution
614 + return Promise.resolve({
615 + data: { info: { structured_output: { value: outputs[stepIndex] } } },
616 + });
617 + });
619 + const definition = createDefinition([
621 + name: "parallel_0",
622 + type: "parallel",
623 + steps: [
625 + name: "step1",
626 + agent: "test-agent",
627 + prompt: "do thing A",
628 + output: z.object({ value: z.string() }),
629 + },
631 + name: "step2",
632 + agent: "test-agent",
633 + prompt: "do thing B",
634 + output: z.object({ value: z.string() }),
635 + },
636 + ],
637 + },
638 + ]);
640 + const instance = store.createPipeline("test-pipe", {});
641 + const executor = createExecutor(definition);
642 + const result = await executor.execute(instance.id, {});
644 + expect(result.status).toBe("completed");
645 + expect(result.context.parallel_0.step1).toEqual({ value: "result-a" });
646 + expect(result.context.parallel_0.step2).toEqual({ value: "result-b" });
647 + });
649 + test("parallel fails if any step fails", async () => {
650 + let callCount = 0;
651 + mockClient.session.prompt = mock(() => {
652 + callCount++;
653 + // Context injection: odd calls - succeed with empty structured output
654 + // Execution: even calls - fail with AgentError
655 + if (callCount % 2 === 0) {
656 + return Promise.reject(new AgentError("step1", "One step failed"));
658 + // Return a proper response structure for context injection
659 + return Promise.resolve({
660 + data: { info: { structured_output: {} } },
661 + });
662 + });
664 + const definition = createDefinition([
666 + name: "parallel_0",
667 + type: "parallel",
668 + steps: [
670 + name: "step1",
671 + agent: "test-agent",
672 + prompt: "do thing",
673 + output: z.object({ value: z.string() }),
674 + },
676 + name: "step2",
677 + agent: "test-agent",
678 + prompt: "do thing",
679 + output: z.object({ value: z.string() }),
680 + },
681 + ],
682 + },
683 + ]);
685 + const instance = store.createPipeline("test-pipe", {});
686 + const executor = createExecutor(definition);
687 + const result = await executor.execute(instance.id, {});
689 + expect(result.status).toBe("failed");
690 + expect(result.error).toContain("One step failed");
691 + });
692 +});
694 +describe("Executor - When/Loop", () => {
695 + test("when condition met causes loop", async () => {
696 + let whenCallCount = 0;
698 + const definition = createDefinition([
700 + name: "step1",
701 + type: "step",
702 + agent: "test-agent",
703 + prompt: "do thing",
704 + output: z.object({ result: z.string() }),
705 + },
707 + name: "when_0",
708 + type: "when",
709 + condition: (ctx: any) => {
710 + whenCallCount++;
711 + return whenCallCount < 2; // Loop once, then pass through
712 + },
713 + loopTarget: "step1",
714 + },
716 + name: "step2",
717 + type: "step",
718 + agent: "test-agent",
719 + prompt: "do next thing",
720 + output: z.object({ result: z.string() }),
721 + },
722 + ]);
724 + const instance = store.createPipeline("test-pipe", {});
725 + const executor = createExecutor(definition);
726 + const result = await executor.execute(instance.id, {});
728 + expect(result.status).toBe("completed");
729 + expect(whenCallCount).toBe(2); // Called twice - once to trigger loop, once to pass through
730 + });
732 + test("when condition not met passes through", async () => {
733 + const definition = createDefinition([
735 + name: "step1",
736 + type: "step",
737 + agent: "test-agent",
738 + prompt: "do thing",
739 + output: z.object({ result: z.string() }),
740 + },
742 + name: "when_0",
743 + type: "when",
744 + condition: () => false, // Never loop
745 + },
747 + name: "step2",
748 + type: "step",
749 + agent: "test-agent",
750 + prompt: "do next thing",
751 + output: z.object({ result: z.string() }),
752 + },
753 + ]);
755 + const instance = store.createPipeline("test-pipe", {});
756 + const executor = createExecutor(definition);
757 + const result = await executor.execute(instance.id, {});
759 + expect(result.status).toBe("completed");
760 + expect(result.context.step2).toEqual({ result: "ok" });
761 + });
763 + test("max iterations guard", async () => {
764 + const definition = createDefinition([
766 + name: "step1",
767 + type: "step",
768 + agent: "test-agent",
769 + prompt: "do thing",
770 + output: z.object({ result: z.string() }),
771 + },
773 + name: "when_0",
774 + type: "when",
775 + condition: () => true, // Always loop back
776 + loopTarget: "step1",
777 + },
778 + ]);
780 + const instance = store.createPipeline("test-pipe", {});
781 + const executor = createExecutor(definition, { maxLoopIterations: 3 });
782 + const result = await executor.execute(instance.id, {});
784 + expect(result.status).toBe("failed");
785 + expect(result.error).toContain("Max loop iterations");
786 + });
787 +});
789 +describe("Executor - Abort", () => {
790 + test("aborted pipeline stops execution", async () => {
791 + let stepCount = 0;
792 + let pipelineId: string | undefined;
794 + mockClient.session.prompt = mock(() => {
795 + stepCount++;
796 + if (stepCount === 2) {
797 + // After first step completes, abort the pipeline
798 + const instance = store.getPipeline(pipelineId!);
799 + if (instance) {
800 + store.updatePipeline(instance.id, { status: "aborted" });
803 + return Promise.resolve({
804 + data: { info: { structured_output: { result: "ok" } } },
805 + });
806 + });
808 + const definition = createDefinition([
810 + name: "step1",
811 + type: "step",
812 + agent: "test-agent",
813 + prompt: "do thing",
814 + output: z.object({ result: z.string() }),
815 + },
817 + name: "step2",
818 + type: "step",
819 + agent: "test-agent",
820 + prompt: "should not run",
821 + output: z.object({ result: z.string() }),
822 + },
823 + ]);
825 + const instance = store.createPipeline("test-pipe", {});
826 + pipelineId = instance.id;
827 + const executor = createExecutor(definition);
828 + const result = await executor.execute(instance.id, {});
830 + expect(result.status).toBe("aborted");
831 + // Only first step should have run
832 + expect(result.context.step1).toEqual({ result: "ok" });
833 + expect(result.context.step2).toBeUndefined();
834 + });
835 +});
837 +describe("Executor - Pipeline completion", () => {
838 + test("completed pipeline returns accumulated context", async () => {
839 + const outputs = [
840 + { data: { info: { structured_output: { a: 1 } } } },
841 + { data: { info: { structured_output: { b: 2 } } } },
842 + ];
843 + let outputIndex = 0;
845 + mockClient.session.prompt = mock(() => {
846 + const callIndex = (mockClient.session.prompt as any).mock.calls.length;
847 + if (callIndex % 2 === 0) {
848 + // Execution call
849 + return Promise.resolve(outputs[outputIndex++]);
851 + return Promise.resolve({});
852 + });
854 + const definition = createDefinition([
856 + name: "step1",
857 + type: "step",
858 + agent: "test-agent",
859 + prompt: "do first thing",
860 + output: z.object({ a: z.number() }),
861 + },
863 + name: "step2",
864 + type: "step",
865 + agent: "test-agent",
866 + prompt: "do second thing",
867 + output: z.object({ b: z.number() }),
868 + },
869 + ]);
871 + const instance = store.createPipeline("test-pipe", {});
872 + const executor = createExecutor(definition);
873 + const result = await executor.execute(instance.id, {});
875 + expect(result.status).toBe("completed");
876 + expect(result.context.step1).toEqual({ a: 1 });
877 + expect(result.context.step2).toEqual({ b: 2 });
878 + });
879 +});
881 +describe("Executor - Error classes", () => {
882 + test("exports correct error classes", async () => {
883 + // Verify all expected error classes exist
884 + expect(ChefError).toBeDefined();
885 + expect(AgentTimeoutError).toBeDefined();
886 + expect(AgentError).toBeDefined();
887 + expect(GateFailureError).toBeDefined();
888 + expect(MaxIterationsError).toBeDefined();
890 + // Verify they are Error subclasses
891 + const chefError = new ChefError("test", "test_type");
892 + expect(chefError).toBeInstanceOf(Error);
893 + expect(chefError.name).toBe("ChefError");
895 + const timeoutError = new AgentTimeoutError("step1", 1000);
896 + expect(timeoutError).toBeInstanceOf(ChefError);
897 + expect(timeoutError.name).toBe("AgentTimeoutError");
898 + expect(timeoutError.message).toContain("step1");
899 + expect(timeoutError.message).toContain("1000ms");
901 + const agentError = new AgentError("step1", "something went wrong");
902 + expect(agentError).toBeInstanceOf(ChefError);
903 + expect(agentError.name).toBe("AgentError");
904 + expect(agentError.message).toContain("step1");
905 + expect(agentError.message).toContain("something went wrong");
907 + const gateError = new GateFailureError("gate1", "validation failed");
908 + expect(gateError).toBeInstanceOf(ChefError);
909 + expect(gateError.name).toBe("GateFailureError");
910 + expect(gateError.message).toContain("gate1");
912 + const maxIterError = new MaxIterationsError(5);
913 + expect(maxIterError).toBeInstanceOf(ChefError);
914 + expect(maxIterError.name).toBe("MaxIterationsError");
915 + expect(maxIterError.message).toContain("5");
916 + });
917 +});

opencode/plugins/chef/test/store.test.ts

Added
new file mode 100644
1 +import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2 +import { mkdirSync, rmSync } from "node:fs";
3 +import { join } from "node:path";
4 +import { tmpdir } from "node:os";
5 +import { mkdtempSync } from "node:fs";
6 +import { Store } from "../store";
8 +let store: Store;
9 +let tempDir: string;
11 +beforeEach(() => {
12 + tempDir = mkdtempSync(join(tmpdir(), "chef-test-"));
13 + // Ensure the .opencode/chef directory exists for bun:sqlite
14 + mkdirSync(join(tempDir, ".opencode/chef"), { recursive: true });
15 + store = new Store(tempDir);
16 +});
18 +afterEach(() => {
19 + store.close();
20 + rmSync(tempDir, { recursive: true, force: true });
21 +});
23 +describe("Store - Pipeline operations", () => {
24 + test("creates a pipeline instance", () => {
25 + const pipeline = store.createPipeline("test-pipeline", { key: "value" });
27 + expect(pipeline).toMatchObject({
28 + id: expect.any(String),
29 + definition: "test-pipeline",
30 + status: "running",
31 + input: JSON.stringify({ key: "value" }),
32 + context: "{}",
33 + current_phase: 0,
34 + created_at: expect.any(Number),
35 + updated_at: expect.any(Number),
36 + });
37 + });
39 + test("gets pipeline by id", () => {
40 + const created = store.createPipeline("test-pipeline", { key: "value" });
41 + const retrieved = store.getPipeline(created.id);
43 + expect(retrieved).toMatchObject({
44 + id: created.id,
45 + definition: "test-pipeline",
46 + status: "running",
47 + input: JSON.stringify({ key: "value" }),
48 + context: "{}",
49 + current_phase: 0,
50 + });
51 + });
53 + test("returns null for nonexistent pipeline", () => {
54 + const result = store.getPipeline("nonexistent");
55 + expect(result).toBeNull();
56 + });
58 + test("updates pipeline status", () => {
59 + const pipeline = store.createPipeline("test-pipeline", {});
60 + store.updatePipeline(pipeline.id, { status: "completed" });
61 + const updated = store.getPipeline(pipeline.id);
63 + expect(updated?.status).toBe("completed");
64 + });
66 + test("updates pipeline context", () => {
67 + const pipeline = store.createPipeline("test-pipeline", {});
68 + store.updatePipeline(pipeline.id, {
69 + context: JSON.stringify({ foo: "bar" }),
70 + });
71 + const updated = store.getPipeline(pipeline.id);
73 + expect(updated?.context).toBe(JSON.stringify({ foo: "bar" }));
74 + });
76 + test("updates pipeline current_phase", () => {
77 + const pipeline = store.createPipeline("test-pipeline", {});
78 + store.updatePipeline(pipeline.id, { current_phase: 3 });
79 + const updated = store.getPipeline(pipeline.id);
81 + expect(updated?.current_phase).toBe(3);
82 + });
84 + test("updates multiple fields at once", () => {
85 + const pipeline = store.createPipeline("test-pipeline", {});
86 + store.updatePipeline(pipeline.id, { status: "failed", current_phase: 2 });
87 + const updated = store.getPipeline(pipeline.id);
89 + expect(updated?.status).toBe("failed");
90 + expect(updated?.current_phase).toBe(2);
91 + });
93 + test("lists all pipelines", () => {
94 + store.createPipeline("pipeline-1", {});
95 + store.createPipeline("pipeline-2", {});
96 + const pipelines = store.listPipelines();
98 + expect(pipelines).toHaveLength(2);
99 + });
101 + test("lists pipelines filtered by status", () => {
102 + const p1 = store.createPipeline("pipeline-1", {});
103 + store.createPipeline("pipeline-2", {});
104 + store.createPipeline("pipeline-3", {});
105 + store.updatePipeline(p1.id, { status: "completed" });
107 + const running = store.listPipelines("running");
108 + expect(running).toHaveLength(2);
109 + });
111 + test("lists pipelines filtered by completed status", () => {
112 + const p1 = store.createPipeline("pipeline-1", {});
113 + store.createPipeline("pipeline-2", {});
114 + store.updatePipeline(p1.id, { status: "completed" });
116 + const completed = store.listPipelines("completed");
117 + expect(completed).toHaveLength(1);
118 + });
119 +});
121 +describe("Store - Phase operations", () => {
122 + test("creates a phase", () => {
123 + const pipeline = store.createPipeline("test-pipeline", {});
124 + const phase = store.createPhase(pipeline.id, "step-1");
126 + expect(phase).toMatchObject({
127 + id: expect.any(String),
128 + pipeline_id: pipeline.id,
129 + name: "step-1",
130 + status: "pending",
131 + output: "{}",
132 + error: null,
133 + attempts: 0,
134 + started_at: null,
135 + completed_at: null,
136 + });
137 + });
139 + test("gets phase by id", () => {
140 + const pipeline = store.createPipeline("test-pipeline", {});
141 + const created = store.createPhase(pipeline.id, "step-1");
142 + const retrieved = store.getPhase(created.id);
144 + expect(retrieved).toMatchObject({
145 + id: created.id,
146 + pipeline_id: pipeline.id,
147 + name: "step-1",
148 + status: "pending",
149 + });
150 + });
152 + test("returns null for nonexistent phase", () => {
153 + const result = store.getPhase("nonexistent");
154 + expect(result).toBeNull();
155 + });
157 + test("updates phase status", () => {
158 + const pipeline = store.createPipeline("test-pipeline", {});
159 + const phase = store.createPhase(pipeline.id, "step-1");
160 + store.updatePhase(phase.id, {
161 + status: "completed",
162 + output: JSON.stringify({ result: true }),
163 + });
164 + const updated = store.getPhase(phase.id);
166 + expect(updated?.status).toBe("completed");
167 + expect(updated?.output).toBe(JSON.stringify({ result: true }));
168 + });
170 + test("updates phase error", () => {
171 + const pipeline = store.createPipeline("test-pipeline", {});
172 + const phase = store.createPhase(pipeline.id, "step-1");
173 + store.updatePhase(phase.id, { error: "something went wrong" });
174 + const updated = store.getPhase(phase.id);
176 + expect(updated?.error).toBe("something went wrong");
177 + });
179 + test("updates phase attempts", () => {
180 + const pipeline = store.createPipeline("test-pipeline", {});
181 + const phase = store.createPhase(pipeline.id, "step-1");
182 + store.updatePhase(phase.id, { attempts: 3 });
183 + const updated = store.getPhase(phase.id);
185 + expect(updated?.attempts).toBe(3);
186 + });
188 + test("gets phases by pipeline", () => {
189 + const pipeline = store.createPipeline("test-pipeline", {});
190 + store.createPhase(pipeline.id, "step-1");
191 + store.createPhase(pipeline.id, "step-2");
192 + const phases = store.getPhasesByPipeline(pipeline.id);
194 + expect(phases).toHaveLength(2);
195 + });
196 +});
198 +describe("Store - Column whitelist", () => {
199 + test("whitelist allows valid columns", () => {
200 + const pipeline = store.createPipeline("test-pipeline", {});
201 + store.updatePipeline(pipeline.id, { status: "completed" });
202 + const updated = store.getPipeline(pipeline.id);
204 + expect(updated?.status).toBe("completed");
205 + });
207 + test("whitelist blocks unknown columns", () => {
208 + const pipeline = store.createPipeline("test-pipeline", {});
209 + // This should not crash and should not set the evil column
210 + store.updatePipeline(pipeline.id, { evil_column: "hack" } as any);
211 + const updated = store.getPipeline(pipeline.id);
213 + // The pipeline should still exist and have original values
214 + expect(updated).not.toBeNull();
215 + expect(updated?.definition).toBe("test-pipeline");
216 + expect((updated as any).evil_column).toBeUndefined();
217 + });
218 +});
220 +describe("Store - Schema migration", () => {
221 + test("store works correctly after schema initialization", () => {
222 + // Schema initialization is implicitly tested by all other tests
223 + // This test verifies basic CRUD still works
224 + const pipeline = store.createPipeline("migrated-pipeline", { test: true });
225 + expect(pipeline.id).toBeDefined();
227 + const phase = store.createPhase(pipeline.id, "phase-1");
228 + expect(phase.id).toBeDefined();
230 + store.updatePipeline(pipeline.id, { status: "completed" });
231 + store.updatePhase(phase.id, { status: "completed" });
233 + const updatedPipeline = store.getPipeline(pipeline.id);
234 + const updatedPhase = store.getPhase(phase.id);
236 + expect(updatedPipeline?.status).toBe("completed");
237 + expect(updatedPhase?.status).toBe("completed");
238 + });
239 +});
241 +describe("Store - close", () => {
242 + test("close does not throw", () => {
243 + const testStore = new Store(tempDir);
244 + expect(() => testStore.close()).not.toThrow();
245 + });
246 +});