repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(ultra): expose failures to recovery phases

a48c0acc464428c346afcb575bfd42e4ab9f2ed7

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+195 / −28 text lines

Diff layout

extensions/ultra/__tests__/engine.test.ts

Modified

+83 / −10 text lines

5959 ...over,
6060});
62function failed(message: string): Extract<RunStepResult, { ok: false }> {
63 return {
64 ok: false,
65 value: null,
66 failure: {
67 code: "schema",
68 message,
69 retryable: true,
70 attempts: 2,
71 model: "test/model",
72 thinkingLevel: "high",
73 transcriptTail: "bad output",
74 },
75 };
76}
6278function memoryJournal(seed: Record<string, RunStepResult> = {}) {
6379 const entries = new Map(Object.entries(seed));
6480 return {
293309 { id: "after", ran: 1, ok: 1, dropped: 0 },
294310 ]);
295311 expect(res.phaseResults.conditional).toEqual([]);
312 expect(res.phaseFailures.conditional).toEqual([]);
296313 expect(res.result).toEqual(["saw []"]);
297314 });
316 it("runs one explicit recovery phase over prior failures", async () => {
317 const fr = fakeRunner((args) => {
318 if (args.phase === "work")
319 return args.item === "bad"
320 ? failed("invalid verdict")
321 : { ok: true, value: args.item };
322 return { ok: true, value: args.step.prompt };
323 });
324 const s = spec({
325 return: "{recover.results}",
326 phases: [
327 {
328 id: "work",
329 kind: "fanout",
330 over: ["good", "bad"],
331 step: { prompt: "work {item}" },
332 },
333 {
334 id: "recover",
335 kind: "fanout",
336 when: "{work.failures}",
337 over: "{work.failures}",
338 step: { prompt: "repair {item}" },
339 },
340 ],
341 });
343 const res = await runWorkflow(
344 s,
345 undefined,
346 baseDeps({ stepRunner: fr.runner }),
347 );
349 expect(fr.calls.filter((call) => call.phase === "recover")).toHaveLength(1);
350 expect(res.result).toHaveLength(1);
351 expect(String((res.result as string[])[0])).toContain('"code":"schema"');
352 });
299354 it("runs a phase when its selector resolves to a non-empty value", async () => {
300355 const events: UltraProgressEvent[] = [];
301356 const fr = fakeRunner(() => ({ ok: true, value: "ran" }));
433488 it("retains null positionally in a phase's results for dropped steps", async () => {
434489 const fr = fakeRunner((args) =>
435 args.item === 1
436 ? { ok: false, value: null, reason: "x" }
437 : { ok: true, value: { n: args.item } },
490 args.item === 1 ? failed("x") : { ok: true, value: { n: args.item } },
438491 );
439492 const s = spec({
440493 return: "{p.results}",
615668 it("a failed step yields null, increments dropped, and emits a board-only dropped end carrying the reason", async () => {
616669 const REASON = "schema invalid then null"; // deliberately NOT a DROP_STATUSES token
617670 const fr = fakeRunner((args) =>
618 args.item === "bad"
619 ? { ok: false, value: null, reason: REASON }
620 : { ok: true, value: args.item },
671 args.item === "bad" ? failed(REASON) : { ok: true, value: args.item },
621672 );
622673 const events: UltraProgressEvent[] = [];
623674 const s = spec({
663714 it("an all-null phase does not halt the workflow; later phases still run", async () => {
664715 const fr = fakeRunner((args) =>
665716 args.phase === "a"
666 ? { ok: false, value: null, reason: "all fail" }
717 ? failed("all fail")
667718 : { ok: true, value: `b-saw-${args.phase}` },
668719 );
669720 const s = spec({
724775 expect(res.phases[0].ran).toBe(2); // only the first concurrency-window launched
725776 expect(res.phases[0].ok).toBe(2);
726777 expect(res.phases[0].dropped).toBe(4); // 4 un-launched, counted as dropped
778 expect(res.phaseFailures.f).toHaveLength(4);
779 expect(res.phaseFailures.f[0]).toMatchObject({
780 agentId: "f#2",
781 index: 2,
782 item: 2,
783 code: "aborted",
784 retryable: true,
785 attempts: 0,
786 });
727787 const endIds = events
728788 .filter((event) => event.kind === "end")
729789 .map((event) => event.agentId);
754814 expect(fr.calls).toHaveLength(0);
755815 expect(res.phases[0]).toEqual({ id: "f", ran: 0, ok: 0, dropped: 3 });
816 expect(res.phaseFailures.f.map((failure) => failure.item)).toEqual([
817 1, 2, 3,
818 ]);
756819 });
757820});
765828 const fr = fakeRunner((args) => {
766829 if (args.phase === "review") {
767830 return args.item === "drop"
768 ? { ok: false, value: null, reason: "bad schema" }
831 ? failed("bad schema")
769832 : {
770833 ok: true,
771834 value: { findings: [{ title: String(args.item), file: "a.ts" }] },
804867 expect(res.result).toEqual([]);
805868 expect(res.phaseResults.review).toEqual([
806869 { ok: true, value: { findings: [{ title: "kept", file: "a.ts" }] } },
807 { ok: false, value: null, reason: "bad schema" },
870 failed("bad schema"),
871 ]);
872 expect(res.phaseFailures.review).toEqual([
873 {
874 agentId: "review#1",
875 index: 1,
876 item: "drop",
877 ...failed("bad schema").failure,
878 },
808879 ]);
809880 expect(res.phaseResults.verify).toEqual([
810881 { ok: true, value: { title: "refuted", real: false, file: "a.ts" } },
811882 ]);
812883 });
814 it("returns { workflow, phases:[{id,ran,ok,dropped}], phaseResults, result, steered, tokenUsage }", async () => {
885 it("returns phaseResults and phaseFailures with the aggregate", async () => {
815886 const fr = fakeRunner((args) => ({
816887 ok: true,
817888 value: args.item ?? "v",
839910 );
841912 expect(Object.keys(res).sort()).toEqual([
913 "phaseFailures",
842914 "phaseResults",
843915 "phases",
844916 "result",
850922 workflow: "demo",
851923 phases: [{ id: "p", ran: 1, ok: 1, dropped: 0 }],
852924 phaseResults: { p: [{ ok: true, value: "a" }] },
925 phaseFailures: { p: [] },
853926 result: ["a"],
854927 steered: false,
855928 tokenUsage: {

extensions/ultra/__tests__/interp.test.ts

Modified

+33 / −0 text lines

2525 { findings: ["c1"] }, // index 4: has findings but MISSING real
2626 ],
2727 },
28 failures: {
29 r: [
30 { code: "transport", retryable: true, message: "rate limited" },
31 { code: "auth", retryable: false, message: "missing key" },
32 ],
33 },
2834 };
5662 );
5763 });
65 it("renders prior phase failures", () => {
66 expect(resolveTemplate("repair {r.failures}", fixture())).toContain(
67 '"code":"transport"',
68 );
69 });
5971 it("throws SpecValidationError on an unknown token", () => {
6072 expect(() => resolveTemplate("x {foo.bar | map x} y", fixture())).toThrow(
6173 SpecValidationError,
91103 ]);
92104 });
106 it("resolves and filters {PHASE.failures}", () => {
107 expect(resolveSelector("{r.failures}", fixture())).toHaveLength(2);
108 expect(
109 resolveSelector("{r.failures | where retryable}", fixture()),
110 ).toEqual([
111 { code: "transport", retryable: true, message: "rate limited" },
112 ]);
113 });
115 it("rejects an unknown phase failure reference", () => {
116 expect(() => resolveSelector("{missing.failures}", fixture())).toThrow(
117 SpecValidationError,
118 );
119 });
94121 it("resolves {args.NAME}", () => {
95122 expect(resolveSelector("{args.tags}", fixture())).toEqual(["a", "b"]);
96123 });
162189 expect(resolveOver(lit, {})).toEqual(lit);
163190 });
192 it("resolves failures as a recovery fanout", () => {
193 expect(resolveOver("{r.failures}", fixture())).toEqual(
194 fixture().failures?.r,
195 );
196 });
165198 it("resolves an interpolation expression to its array", () => {
166199 expect(resolveOver("{r.results[].findings[]}", fixture())).toEqual([
167200 "a1",

extensions/ultra/engine.ts

Modified

+56 / −17 text lines

3131 PlannedPhase,
3232 UltraProgressEvent,
3333} from "./progress.ts";
34import type { RunStepResult, StepRunner, TokenUsage } from "./runner.ts";
34import type {
35 RunStepResult,
36 StepFailure,
37 StepRunner,
38 TokenUsage,
39} from "./runner.ts";
3540import type { Phase, Step, WorkflowSpec } from "./spec.ts";
3742// ---------------------------------------------------------------------------
7479 dropped: number;
77export interface PhaseSlotResult {
78 ok: boolean;
79 value: unknown;
80 reason?: string;
82export type PhaseSlotResult =
83 | { ok: true; value: unknown }
84 | { ok: false; value: null; failure: StepFailure };
86export interface PhaseFailure extends StepFailure {
87 agentId: string;
88 index: number;
89 item?: unknown;
8392/** The documented aggregate the `workflow` tool / `/ultra` command returns. */
8493export interface WorkflowResult {
8594 workflow: string;
8695 phases: PhaseResult[];
87 /** Full positional step outcomes for every phase, including drop reasons. */
96 /** Full positional step outcomes for every phase, including typed failures. */
8897 phaseResults: Record<string, PhaseSlotResult[]>;
98 /** Failed steps enriched with phase position and original fanout item. */
99 phaseFailures: Record<string, PhaseFailure[]>;
89100 result: unknown;
90101 steered: boolean;
91102 tokenUsage: TokenUsage;
109120): Promise<WorkflowResult> {
110121 const results: Record<string, unknown[]> = {};
111122 const phaseResults: Record<string, PhaseSlotResult[]> = {};
123 const phaseFailures: Record<string, PhaseFailure[]> = {};
112124 const phases: PhaseResult[] = [];
113125 const tokenUsage = zeroUsage();
114126 const steeredBox = { value: false };
118130 for (const phase of spec.phases) {
119131 if (
120132 phase.when !== undefined &&
121 !phaseEnabled(resolveSelector(phase.when, { args, results }))
133 !phaseEnabled(
134 resolveSelector(phase.when, { args, results, failures: phaseFailures }),
135 )
122136 ) {
123137 forward({
124138 kind: "phase",
128142 });
129143 results[phase.id] = [];
130144 phaseResults[phase.id] = [];
145 phaseFailures[phase.id] = [];
131146 phases.push({ id: phase.id, ran: 0, ok: 0, dropped: 0 });
132147 continue;
133148 }
134149 // Resolve `over` and every prompt up-front. Both own the interpolation
135150 // grammar; a bad token throws here (spec authoring error), before any step
136151 // launches — it is deliberately not a runtime drop.
137 const items = phaseItems(phase, { args, results });
152 const context = { args, results, failures: phaseFailures };
153 const items = phaseItems(phase, context);
138154 const resolved = items.map((item) => ({
139155 item,
140 step: resolveStep(phase.step, { args, results, item }),
156 step: resolveStep(phase.step, { ...context, item }),
141157 }));
142158 const agentIds = resolved.map((_, index) => `${phase.id}#${index}`);
143159 forward({
177193 phase: phase.id,
178194 kind: "end",
179195 status: "dropped",
180 text: res.reason,
196 text: res.failure.message,
181197 });
182198 }
183199 return res;
193209 let dropped = 0;
194210 const values: unknown[] = [];
195211 const outcomeSlots: PhaseSlotResult[] = [];
212 const failures: PhaseFailure[] = [];
196213 for (const [index, slot] of slots.entries()) {
214 const item = resolved[index]?.item;
215 const agentId = `${phase.id}#${index}`;
197216 if (isAborted(slot)) {
198217 forward({
199 agentId: `${phase.id}#${index}`,
218 agentId,
200219 phase: phase.id,
201220 kind: "end",
202221 status: "dropped",
203222 text: "aborted",
204223 });
224 const failure: StepFailure = {
225 code: "aborted",
226 message: "aborted before launch",
227 retryable: true,
228 attempts: 0,
229 };
205230 dropped++;
206231 values.push(null);
207 outcomeSlots.push({ ok: false, value: null, reason: "aborted" });
232 outcomeSlots.push({ ok: false, value: null, failure });
233 failures.push({
234 agentId,
235 index,
236 ...(item === undefined ? {} : { item }),
237 ...failure,
238 });
208239 continue;
209240 }
210241 addUsage(tokenUsage, slot.usage);
217248 }
218249 dropped++;
219250 values.push(null);
220 outcomeSlots.push({
221 ok: false,
222 value: null,
223 reason: slot.reason ?? "dropped",
251 outcomeSlots.push({ ok: false, value: null, failure: slot.failure });
252 failures.push({
253 agentId,
254 index,
255 ...(item === undefined ? {} : { item }),
256 ...slot.failure,
224257 });
225258 }
227260 results[phase.id] = values;
228261 phaseResults[phase.id] = outcomeSlots;
262 phaseFailures[phase.id] = failures;
229263 phases.push({ id: phase.id, ran, ok, dropped });
230264 forward({
231265 kind: "phase",
240274 const lastPhase = spec.phases[spec.phases.length - 1];
241275 const result =
242276 spec.return !== undefined
243 ? resolveSelector(spec.return, { args, results })
277 ? resolveSelector(spec.return, {
278 args,
279 results,
280 failures: phaseFailures,
281 })
244282 : results[lastPhase.id];
246284 if (!deps.signal?.aborted) await deps.journal?.complete?.();
249287 workflow: spec.name,
250288 phases,
251289 phaseResults,
290 phaseFailures,
252291 result,
253292 steered: steeredBox.value,
254293 tokenUsage,

extensions/ultra/interp.ts

Modified

+23 / −1 text lines

88// {args.NAME} — workflow input value
99// {item} — current fanout item (string verbatim; else compact JSON)
1010// {PHASE.results} — a prior phase's results array (nulls RETAINED positionally)
11// {PHASE.failures} — a prior phase's typed failure array
1112// {PHASE.results[].FIELD[]} — flatten: concat each result's FIELD array (null elems / missing FIELDs SKIPPED)
1213// {EXPR | where FIELD} — keep elements whose boolean FIELD is truthy (null elems / missing FIELD SKIPPED)
1314//
3233 args?: Record<string, unknown>;
3334 item?: unknown;
3435 results?: Record<string, unknown[]>;
36 failures?: Record<string, unknown[]>;
3739const IDENT = "[A-Za-z_][A-Za-z0-9_]*";
3840const RE_ARGS = new RegExp(`^args\\.(${IDENT})$`);
3941const RE_RESULTS = new RegExp(`^(${IDENT})\\.results$`);
42const RE_FAILURES = new RegExp(`^(${IDENT})\\.failures$`);
4043const RE_FLATTEN = new RegExp(
4144 `^(${IDENT})\\.results\\[\\]\\.(${IDENT})\\[\\]$`,
4245);
5053 | { kind: "args"; name: string }
5154 | { kind: "item" }
5255 | { kind: "results"; phase: string }
56 | { kind: "failures"; phase: string }
5357 | { kind: "flatten"; phase: string; field: string };
5559type Expr = Base | { kind: "where"; base: Base; field: string };
6872 const results = s.match(RE_RESULTS);
6973 if (results) return { kind: "results", phase: results[1] };
75 const failures = s.match(RE_FAILURES);
76 if (failures) return { kind: "failures", phase: failures[1] };
7178 const flatten = s.match(RE_FLATTEN);
7279 if (flatten) {
7380 return { kind: "flatten", phase: flatten[1], field: flatten[2] };
7481 }
7683 throw new SpecValidationError(
77 `unknown interpolation token "{${raw}}" (outside the v1 grammar; allowed: args.NAME, item, PHASE.results, PHASE.results[].FIELD[])`,
84 `unknown interpolation token "{${raw}}" (outside the v1 grammar; allowed: args.NAME, item, PHASE.results, PHASE.failures, PHASE.results[].FIELD[])`,
7885 );
116123 return results;
126function getFailures(ctx: InterpContext, phase: string): unknown[] {
127 const failures = ctx.failures?.[phase];
128 if (failures === undefined) {
129 throw new SpecValidationError(
130 `interpolation references unknown phase "${phase}"`,
131 );
132 }
133 if (!Array.isArray(failures)) {
134 throw new SpecValidationError(`phase "${phase}" failures is not an array`);
135 }
136 return failures;
137}
119139function resolveBase(base: Base, ctx: InterpContext): unknown {
120140 switch (base.kind) {
121141 case "item":
125145 case "results":
126146 // Retain nulls positionally — callers depend on length.
127147 return getResults(ctx, base.phase);
148 case "failures":
149 return getFailures(ctx, base.phase);
128150 case "flatten": {
129151 const out: unknown[] = [];
130152 for (const el of getResults(ctx, base.phase)) {