repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(ultra): subagentExtensions setting + feature workflow; fix render crash

78eb2136e249e4105c8b0216f6aa63e5d5d37126

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Add ultra.subagentExtensions ("none"|"all", default "all"): workflow
sub-agents load the host's extensions so a step can grant extension-provided
tools (e.g. web_search), while the step.tools allowlist stays the only gate on
what is active; ultra's own `workflow` tool is stripped from every sub-agent
allowlist (recursion defense). Set "none" to keep sub-agents on core tools.

Ship the `feature` workflow (research -> plan -> adversarial critique ->
implement -> security/quality review; only implement writes), and make /ultra
positional args soak the trailing free text into the last declared param so
`/ultra feature <task>` passes the whole description through.

Fix a crash where the workflow tool's live board threw state.phases.length on
a `details` value that was not a reducer state: renderUltraResult only guarded
null/undefined, so a truthy-but-foreign details escaped into renderToolBoard
and the uncaught throw took down the whole TUI render loop. The tool renderer
now shape-checks details (Array phases + rows) and falls back to an empty board.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Changed files (16)

docs/superpowers/plans/2026-06-29-ultra-subagent-extensions.md

Added
new file mode 100644
1 +# ultra Sub-agent Extension Loading — Implementation Plan
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
5 +**Goal:** Let ultra sub-agents reach extension-provided tools (e.g. `web_search`) via a single `ultra.subagentExtensions` setting, keeping the tool allowlist as the only gate and making `workflow` recursion impossible.
7 +**Architecture:** Flip only `noExtensions` on the sub-agent resource loader (other isolation flags stay on, so no skill/prompt/theme/context bloat). The existing `[...step.tools, structured_output]` allowlist stays authoritative over which tools are active; `workflow` is defensively stripped from every sub-agent allowlist. A new `none|all` setting (default `all`) drives the flip. The web `research` workflow that consumes this is **deferred** (spec Part B) and out of scope here.
9 +**Tech Stack:** TypeScript, Pi coding-agent SDK (`@earendil-works/pi-coding-agent`), TypeBox, vitest, biome, dprint, markdownlint.
11 +## Global Constraints
13 +- **Default `subagentExtensions` is `"all"`**; `"none"` is the opt-out. The setting union is exactly `"none" | "all"`.
14 +- **Only `noExtensions` flips.** `noSkills`, `noPromptTemplates`, `noThemes`, `noContextFiles` stay `true` in both modes.
15 +- **The tool allowlist is the gate.** `workflow` (ultra's own model-tool) is stripped from every sub-agent allowlist so a loaded ultra can't be re-entered.
16 +- **Factory-level default is isolation:** when `makeSessionFactory` gets no `loadExtensions` dep, it behaves as today (`noExtensions: true`). The product default (`"all"`) is applied at `index.ts`. These are intentionally different layers.
17 +- **Commits are gated on the user.** The user's standing instruction is "commit only when asked." Each "Commit" step means _stage the change and surface the proposed commit_; only run `git commit` when the user approves. Commit message trailer (verbatim): `Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>`. Current branch is `trunk` (default) — branch first before any real commit.
18 +- **Verify green with** `mise run ci` (lint + test + check). No `build` task. Biome binary: `/home/me/.local/share/mise/installs/biome/2.4.15/biome`.
19 +- **No fs writes from extension _runtime_ code** (it crashes pi). Test-file writes are fine.
20 +- If `.claude/settings.local.json` exists, move it to scratchpad before the final `mise run ci` (biome has no vcs block locally and false-positives on that gitignored file), then restore.
22 +---
24 +### Task 1: Spike — confirm the allowlist gates extension tools and auth carries (GATE)
26 +This is an **investigative gate**, not a TDD task. It uses a throwaway one-line hack to prove the mechanism before any real code. If it fails, stop and revisit the spec.
28 +**Files:**
30 +- Temporarily modify: `extensions/ultra/drivers.ts:62` (revert at the end)
31 +- Scratch: `<scratchpad>/spike-web.json`
33 +- [ ] **Step 1: Temporarily force extensions on**
35 +In `extensions/ultra/drivers.ts`, change line 62 from `noExtensions: true,` to `noExtensions: false,`. (Leave the other `no*` flags `true`.) This is a throwaway hack reverted in Step 5.
37 +- [ ] **Step 2: Write the spike workflow spec**
39 +Write `<scratchpad>/spike-web.json`:
41 +```json
43 + "name": "spike",
44 + "phases": [
45 + {
46 + "id": "probe",
47 + "kind": "single",
48 + "step": {
49 + "prompt": "You have a tool allowlist. Try to call web_search with the query 'anthropic claude' AND try to call web_fetch on https://example.com . Then answer in ONE line exactly: 'search=<ok|unavailable|error> fetch=<ok|unavailable|error>'. 'unavailable' means the tool was not in your toolset.",
50 + "tools": ["web_search"]
51 + }
52 + }
53 + ]
55 +```
57 +- [ ] **Step 3: Run headless and observe**
59 +Run (the prompt forces the model to call the `workflow` tool with the inline spec):
61 +```bash
62 +pi -p --mode json "Call the workflow tool with this exact spec argument (no name, use the inline spec): $(cat <scratchpad>/spike-web.json)"
63 +```
65 +Expected (the two assumptions): the probe agent reports **`search=ok`** (web_search ran AND returned results → auth/activation carried into the isolated sub-agent) and **`fetch=unavailable`** (web_fetch was NOT allowlisted → the allowlist gates _extension_ tools, not just core ones).
67 +- [ ] **Step 4: Record the result**
69 +Note in your working notes: did `search=ok`? did `fetch=unavailable`? These are the two kill criteria below.
71 +- [ ] **Step 5: Revert the hack**
73 +Restore `extensions/ultra/drivers.ts:62` to `noExtensions: true,`. Confirm `git diff extensions/ultra/drivers.ts` is empty.
75 +**Kill / adjust criteria (do NOT proceed past this task if either fails):**
77 +- If `fetch` is **`ok`** (a non-allowlisted extension tool was callable) → the allowlist does _not_ gate extension tools. Default `"all"` is unsafe. STOP, report, redesign.
78 +- If `search` is **`unavailable`/`error`** (auth didn't carry / extension didn't activate) → real web tools aren't reachable this way. STOP, report; the deferred Part B falls back to codebase-research.
79 +- If both pass → proceed to Task 2.
81 +---
83 +### Task 2: Add the `subagentExtensions` setting
85 +**Files:**
87 +- Modify: `extensions/ultra/settings.ts`
88 +- Test: `extensions/ultra/__tests__/settings.test.ts`
90 +**Interfaces:**
92 +- Produces: `UltraSettings.subagentExtensions: "none" | "all"`; `ULTRA_DEFAULTS.subagentExtensions === "all"`. Consumed by Task 5 (`index.ts`).
94 +- [ ] **Step 1: Write the failing tests**
96 +Add to `extensions/ultra/__tests__/settings.test.ts`:
98 +```ts
99 +describe("subagentExtensions setting", () => {
100 + it("defaults to \"all\"", () => {
101 + expect(ULTRA_DEFAULTS.subagentExtensions).toBe("all");
102 + });
104 + it("pickUltra keeps only the none|all union", () => {
105 + expect(pickUltra({ ultra: { subagentExtensions: "none" } })).toEqual({
106 + subagentExtensions: "none",
107 + });
108 + expect(pickUltra({ ultra: { subagentExtensions: "all" } })).toEqual({
109 + subagentExtensions: "all",
110 + });
111 + // bogus value dropped
112 + expect(pickUltra({ ultra: { subagentExtensions: "lots" } })).toEqual({});
113 + });
115 + it("mergeUltraSettings folds it; later wins, bad ignored", () => {
116 + expect(
117 + mergeUltraSettings({ subagentExtensions: "none" }).subagentExtensions,
118 + ).toBe("none");
119 + expect(
120 + mergeUltraSettings(
121 + { subagentExtensions: "none" },
122 + { subagentExtensions: "all" },
123 + ).subagentExtensions,
124 + ).toBe("all");
125 + expect(
126 + mergeUltraSettings({
127 + subagentExtensions: "bogus" as never,
128 + }).subagentExtensions,
129 + ).toBe("all"); // default kept
130 + });
131 +});
132 +```
134 +Also **update existing exact-shape assertions** so the new 5th field doesn't break them:
136 +- The `ULTRA_DEFAULTS` `toEqual({...})` test (around line 31) — add `subagentExtensions: "all",`.
137 +- Any `mergeUltraSettings(...)` test that asserts a full literal object (around line 78-84) — add `subagentExtensions: "all",`.
138 +- Any `loadUltraSettings(...)` test asserting a full literal object (around line 138-143) — add `subagentExtensions: "all",`. (Tests that assert `toEqual(ULTRA_DEFAULTS)` need no change — they reference the constant.)
140 +- [ ] **Step 2: Run to verify failure**
142 +Run: `npx vitest run extensions/ultra/__tests__/settings.test.ts`
143 +Expected: FAIL (`subagentExtensions` undefined / property missing).
145 +- [ ] **Step 3: Implement**
147 +In `extensions/ultra/settings.ts`:
149 +Add to the `UltraSettings` interface (after `defaultTimeoutMs`):
151 +```ts
152 +/** Load host extensions into sub-agents so their tools are grantable
153 + * (`"all"`, default) or keep sub-agents isolated to core tools (`"none"`).
154 + * The `step.tools` allowlist still gates which tools are actually active. */
155 +subagentExtensions: "none" | "all";
156 +```
158 +Add to `ULTRA_DEFAULTS`:
160 +```ts
161 +subagentExtensions: "all",
162 +```
164 +Add to `pickUltra` (before `return out;`):
166 +```ts
167 +if (ultra.subagentExtensions === "none" || ultra.subagentExtensions === "all") {
168 + out.subagentExtensions = ultra.subagentExtensions;
170 +```
172 +Add to the `mergeUltraSettings` reducer object:
174 +```ts
175 +subagentExtensions:
176 + p.subagentExtensions === "none" || p.subagentExtensions === "all"
177 + ? p.subagentExtensions
178 + : into.subagentExtensions,
179 +```
181 +- [ ] **Step 4: Run to verify pass**
183 +Run: `npx vitest run extensions/ultra/__tests__/settings.test.ts`
184 +Expected: PASS.
186 +- [ ] **Step 5: Commit** (staged; run `git commit` only on user approval)
188 +```bash
189 +git add extensions/ultra/settings.ts extensions/ultra/__tests__/settings.test.ts
190 +# proposed: feat(ultra): add subagentExtensions setting (default all)
191 +```
193 +---
195 +### Task 3: Thread `loadExtensions` into the session factory
197 +**Files:**
199 +- Modify: `extensions/ultra/drivers.ts`
200 +- Test: `extensions/ultra/__tests__/drivers.test.ts`
202 +**Interfaces:**
204 +- Consumes: nothing new.
205 +- Produces: `SessionFactoryDeps.loadExtensions?: boolean`. The factory sets `noExtensions: !loadExtensions` (omitted dep ⇒ `noExtensions: true`). Consumed by Task 5.
207 +- [ ] **Step 1: Write the failing test**
209 +Add to `extensions/ultra/__tests__/drivers.test.ts` (mirror the existing `makeSessionFactory` test's `FakeLoader` + `createAgentSession` fakes; capture the loader opts):
211 +```ts
212 +it("loadExtensions:true flips noExtensions to false; other isolation flags stay true", async () => {
213 + let loaderOpts: Record<string, unknown> = {};
214 + class FakeLoader {
215 + constructor(opts: Record<string, unknown>) {
216 + loaderOpts = opts;
218 + async reload() {}
220 + const fakeSession = { id: "s" };
221 + const createAgentSession = vi.fn(async () => ({ session: fakeSession }));
223 + const factory = makeSessionFactory({
224 + createAgentSession,
225 + DefaultResourceLoader: FakeLoader as any,
226 + getAgentDir: () => "/agent",
227 + cwd: "/cwd",
228 + modelRegistry: {},
229 + loadExtensions: true,
230 + });
231 + await factory({
232 + model: {},
233 + tools: ["web_search", "structured_output"],
234 + customTools: [],
235 + sessionManager: {},
236 + });
238 + expect(loaderOpts.noExtensions).toBe(false);
239 + // the other isolation flags are untouched
240 + expect(loaderOpts.noSkills).toBe(true);
241 + expect(loaderOpts.noPromptTemplates).toBe(true);
242 + expect(loaderOpts.noThemes).toBe(true);
243 + expect(loaderOpts.noContextFiles).toBe(true);
244 +});
245 +```
247 +(The existing test that asserts `noExtensions: true` with no `loadExtensions` dep stays valid — `!undefined === true`.)
249 +- [ ] **Step 2: Run to verify failure**
251 +Run: `npx vitest run extensions/ultra/__tests__/drivers.test.ts`
252 +Expected: FAIL (`loaderOpts.noExtensions` is `true`, not `false`).
254 +- [ ] **Step 3: Implement**
256 +In `extensions/ultra/drivers.ts`, add to `SessionFactoryDeps`:
258 +```ts
259 +/** When true, sub-agents load host extensions (their tools become grantable).
260 + * Omitted/false ⇒ isolated (`noExtensions: true`), today's behaviour. */
261 +loadExtensions?: boolean;
262 +```
264 +Change the resource-loader construction:
266 +```ts
267 +noExtensions: !deps.loadExtensions,
268 +```
270 +- [ ] **Step 4: Run to verify pass**
272 +Run: `npx vitest run extensions/ultra/__tests__/drivers.test.ts`
273 +Expected: PASS (both the new test and the existing `noExtensions: true` test).
275 +- [ ] **Step 5: Commit** (staged; gated)
277 +```bash
278 +git add extensions/ultra/drivers.ts extensions/ultra/__tests__/drivers.test.ts
279 +# proposed: feat(ultra): session factory honours loadExtensions
280 +```
282 +---
284 +### Task 4: Strip `workflow` from sub-agent allowlists (recursion defense)
286 +**Files:**
288 +- Modify: `extensions/ultra/runner.ts`
289 +- Test: `extensions/ultra/__tests__/runner.test.ts`
291 +**Interfaces:**
293 +- Produces: `ULTRA_OWN_TOOL_NAMES` (exported const). The tools passed to `sessionFactory` become `[...step.tools without any ULTRA_OWN_TOOL_NAMES, STRUCTURED_OUTPUT_TOOL_NAME]`.
295 +- [ ] **Step 1: Write the failing test**
297 +Add to `extensions/ultra/__tests__/runner.test.ts` (in the tool-using `sessionFactory` describe block; reuse the existing `harness`):
299 +```ts
300 +it("strips ultra's own `workflow` tool from the sub-agent allowlist (no recursion)", async () => {
301 + const harness = makeFactoryHarness();
302 + const drivers = makeDrivers({ sessionFactory: harness.factory });
303 + const runner = makeStepRunner(drivers, ctxLike, baseOpts);
304 + await runner({
305 + step: {
306 + prompt: "go",
307 + tools: ["read", "workflow"],
308 + schema: undefined,
309 + } as any,
310 + phase: "p",
311 + agentId: "a1",
312 + });
313 + // `workflow` removed; `read` kept; structured_output still appended last.
314 + expect(harness.captured.args?.tools).toEqual([
315 + "read",
316 + STRUCTURED_OUTPUT_TOOL_NAME,
317 + ]);
318 + expect(harness.captured.args?.tools).not.toContain("workflow");
319 +});
320 +```
322 +(Use the same harness/`makeDrivers`/`ctxLike`/`baseOpts` helpers the existing tool-using tests use — match their exact names from the top of the file.)
324 +- [ ] **Step 2: Run to verify failure**
326 +Run: `npx vitest run extensions/ultra/__tests__/runner.test.ts`
327 +Expected: FAIL (`args.tools` is `["read","workflow",structured_output]`).
329 +- [ ] **Step 3: Implement**
331 +In `extensions/ultra/runner.ts`, near `STRUCTURED_OUTPUT_TOOL_NAME`:
333 +```ts
334 +/** ultra's own model-callable tools, stripped from every sub-agent allowlist so
335 + * a sub-agent (which may load ultra when subagentExtensions="all") can never
336 + * re-enter the workflow engine, regardless of what a step lists. */
337 +export const ULTRA_OWN_TOOL_NAMES = ["workflow"] as const;
339 +function sanitizeSubagentTools(tools: string[] | undefined): string[] {
340 + const own = ULTRA_OWN_TOOL_NAMES as readonly string[];
341 + return (tools ?? []).filter((t) => !own.includes(t));
343 +```
345 +Change the `tools:` line in the `sessionFactory` call (the `[...(step.tools ?? []), STRUCTURED_OUTPUT_TOOL_NAME]` line):
347 +```ts
348 +tools: [...sanitizeSubagentTools(step.tools), STRUCTURED_OUTPUT_TOOL_NAME],
349 +```
351 +- [ ] **Step 4: Run to verify pass**
353 +Run: `npx vitest run extensions/ultra/__tests__/runner.test.ts`
354 +Expected: PASS (new test green; existing tools assertions unaffected — they list no `workflow`).
356 +- [ ] **Step 5: Commit** (staged; gated)
358 +```bash
359 +git add extensions/ultra/runner.ts extensions/ultra/__tests__/runner.test.ts
360 +# proposed: feat(ultra): strip workflow from sub-agent allowlist
361 +```
363 +---
365 +### Task 5: Wire the setting through `index.ts` + document, then full CI
367 +**Files:**
369 +- Modify: `extensions/ultra/index.ts` (the `buildStepRunner` → `makeSessionFactory` call, ~line 92)
370 +- Modify: `extensions/ultra/README.md` (Settings section)
372 +**Interfaces:**
374 +- Consumes: `cfg.subagentExtensions` (Task 2), `SessionFactoryDeps.loadExtensions` (Task 3).
376 +- [ ] **Step 1: Wire it**
378 +In `extensions/ultra/index.ts`, in the `makeSessionFactory({ ... })` call inside `buildStepRunner`, add the dep (alongside `cwd`, `modelRegistry`):
380 +```ts
381 +loadExtensions: cfg.subagentExtensions === "all",
382 +```
384 +(No unit test: `index.ts` is thin SDK glue — its own module comment notes the harness asserts registration only. The behaviour is covered by Tasks 2–4 + the Task 1 spike.)
386 +- [ ] **Step 2: Document the setting + portability contract**
388 +In `extensions/ultra/README.md` Settings section, add a short paragraph:
390 +```markdown
391 +`ultra.subagentExtensions` (`"all"` | `"none"`, default `"all"`) controls whether
392 +workflow sub-agents load the host's extensions. With `"all"`, a step can grant any
393 +tool an installed extension provides (e.g. `web_search`); with `"none"`, sub-agents
394 +are isolated to the core tools (`bash`, `find`, `grep`, `ls`, `read`, `ripgrep`).
395 +Either way the step's `tools` allowlist is the only gate on what's active, and
396 +ultra's own `workflow` tool is never grantable to a sub-agent. Workflows should
397 +name **tools**, never extensions — a workflow that lists a tool no installed
398 +extension provides simply runs without it.
399 +```
401 +- [ ] **Step 3: Full CI green**
403 +If present, move the gitignored local settings aside first:
405 +```bash
406 +[ -f .claude/settings.local.json ] && mv .claude/settings.local.json <scratchpad>/settings.local.json.bak || true
407 +mise run ci
408 +```
410 +Expected: lint 0 errors, all tests pass (settings/drivers/runner additions included), checks OK. Restore the file afterward if moved.
412 +- [ ] **Step 4: Commit** (staged; gated)
414 +```bash
415 +git add extensions/ultra/index.ts extensions/ultra/README.md
416 +# proposed: feat(ultra): enable subagent extension tools via setting
417 +```
419 +---
421 +## Self-Review
423 +**Spec coverage (Part A):**
425 +- Setting `none|all` default `all` → Task 2. ✓
426 +- Only `noExtensions` flips, other isolation flags stay → Task 3 (asserted). ✓
427 +- Tool allowlist is the gate → unchanged behaviour, proven by Task 1 spike. ✓
428 +- `workflow` recursion defense → Task 4. ✓
429 +- Wiring + docs → Task 5. ✓
430 +- Spike with kill criteria → Task 1. ✓
431 +- Part B (`research` workflow) → explicitly deferred, no task. ✓
433 +**Placeholder scan:** No TBD/TODO; every code + test step shows concrete code. The only "around line N" references are for locating _existing_ assertions to update (exact code given). ✓
435 +**Type consistency:** `subagentExtensions: "none" | "all"` used identically in settings type, defaults, pick, merge, and the `index.ts` `=== "all"` check. `loadExtensions?: boolean` consistent between Task 3 (def) and Task 5 (use). `ULTRA_OWN_TOOL_NAMES` / `sanitizeSubagentTools` consistent within Task 4. ✓

docs/superpowers/specs/2026-06-29-ultra-subagent-extensions-design.md

Added
new file mode 100644
1 +# ultra — sub-agent extension loading + a `research` workflow
3 +**Date:** 2026-06-29
4 +**Status:** Approved (2026-06-29). Part A is the active scope (gated on the
5 +spike). Part B (`research` workflow) is **deferred** by the user — recorded below
6 +as the follow-up plan, not built now.
8 +## Problem
10 +ultra workflows fan out into sub-agents created via `createAgentSession`. Those
11 +sub-agents are built with `noExtensions: true` (drivers.ts) so they don't
12 +recursively load the host repo's extensions (including ultra itself), skills,
13 +prompts, themes, and context files. The side effect: sub-agents can only grant
14 +the **core** coding-agent tools — `bash, find, grep, ls, read, ripgrep`.
16 +That means **no extension-provided tool is reachable inside a workflow** —
17 +notably the `web` extension's `web_search` / `web_fetch` / `web_map` /
18 +`understand_image`. So a faithful `/deep-research`-style workflow (fan out across
19 +search angles → fetch sources → cross-check → cited report) cannot run: its
20 +fan-out agents have no way to reach the web.
22 +We rejected forwarding the web tools as `customTools` (the path the
23 +structured-output tool uses): it is bespoke to one extension, doesn't generalize
24 +to other consumers, and likely loses the extension's activation state (API key /
25 +settings), since it forwards an `execute` closure without genuinely activating
26 +the extension.
28 +## Goals
30 +- A **generic** way for sub-agents to reach extension tools, naming **no**
31 + specific extension in base ultra.
32 +- **Portable:** workflows name only _tools_; base ultra assumes no particular
33 + extension is installed. A missing tool degrades gracefully.
34 +- Preserve the safety properties that `noExtensions: true` bought: no `workflow`
35 + recursion, no skill/prompt/theme/context bloat in sub-agents.
36 +- Ship the enabling mechanism in base ultra; the web `research` workflow is a
37 + _consumer_ of it, not a base-ultra dependency.
39 +## Non-goals
41 +- Per-extension selective loading by name (e.g. "load only `web`"). The SDK's
42 + resource loader exposes `noExtensions` as a **boolean** (all-or-none per
43 + sub-agent); no per-extension allowlist was found. Selective loading is a
44 + future SDK ask, explicitly out of scope here.
45 +- Making the web tools themselves portable across machines (they need whatever
46 + auth/keys the host already provides).
48 +## Part A — Configurable sub-agent extension loading (base ultra, the core change)
50 +### The setting
52 +`ultra.subagentExtensions: "none" | "all"`, **default `"all"`**.
54 +- `"all"` — sub-agents load the host's extensions, so their tools become
55 + grantable. Default, so ultra "just works" with whatever tools the consumer's
56 + extensions provide.
57 +- `"none"` — current behaviour: `noExtensions: true`, core tools only. The
58 + opt-out for lean / maximally-isolated runs.
60 +Resolved through `loadUltraSettings` like every other ultra setting (agent
61 +settings < `.pi/settings.json` < `settings.json` < runtime manager).
63 +> **Trade-off (accepted):** default `"all"` reverses today's isolation default
64 +> and boots every installed extension in **every** tool-using sub-agent — a real
65 +> per-agent cost and a larger blast radius. The tool allowlist (below) is what
66 +> keeps it safe; `"none"` is the escape hatch.
68 +### Mechanism
70 +Only `noExtensions` flips. Keep `noSkills / noPromptTemplates / noThemes /
71 +noContextFiles: true` — these are **independent** flags, so we get _tools_
72 +without skill/prompt/theme/context bloat. The flag is threaded from `cfg`
73 +(resolved in index.ts) into `makeSessionFactory` and applied at
74 +`createAgentSession({ noExtensions })` time.
76 +### The tool allowlist is the single gate
78 +Sub-agents already receive a strict `tools` allowlist (`[...step.tools,
79 +StructuredOutput]`). That stays authoritative: **only allowlisted tools are
80 +active, regardless of how many extensions loaded.** Two consequences:
82 +- **No recursion:** ultra loads in the sub-agent (so `workflow` is _registered_),
83 + but it isn't in any step's allowlist, so it can't be called. **Defensive
84 + belt-and-braces:** the runner strips `workflow` (and ultra's own command-side
85 + tool names, if any) from every sub-agent allowlist, so an authoring mistake
86 + can't re-enter ultra even if someone lists it.
87 +- **Read-only-fanout rule still holds.** It is _convention_, not validated in
88 + `spec.ts` (which accepts any `tools: string[]`); only the bundled `review`
89 + example asserts it in its test. `web_search`/`web_fetch` are read-only, so
90 + they honour the rule's spirit. We keep the rule as authoring guidance and note
91 + that web tools comply.
93 +### Spike (GATES the rest of Part A — do this first)
95 +The whole approach rests on two unverified assumptions. ~20 min, headless:
97 +1. **Allowlist gates extension tools.** With `noExtensions: false` and an
98 + allowlist of `["web_search","read"]`, confirm a sub-agent can call
99 + `web_search` **and** that non-allowlisted tools (esp. `workflow`, and some
100 + mutating extension tool) are **not** callable.
101 +2. **Auth carries.** Confirm a `web_search` invoked inside the isolated
102 + sub-agent actually fetches — i.e. the web extension genuinely activates and
103 + picks up its API key / settings in the sub-agent session.
105 +**Kill / adjust criteria:** if (1) fails (allowlist doesn't gate extension
106 +tools), the default cannot be `"all"` safely — stop and redesign. If (2) fails
107 +(auth doesn't carry), real web research isn't reachable this way — fall back to
108 +the codebase-research stopgap and file an SDK/extension-activation issue.
110 +### Files to change (Part A)
112 +- `settings.ts` — add `subagentExtensions` to `UltraSettings` + defaulting (`"all"`).
113 +- `drivers.ts` — `makeSessionFactory` takes a `loadExtensions` dep; sets
114 + `noExtensions: !loadExtensions`.
115 +- `index.ts` — pass `cfg.subagentExtensions === "all"` into the factory build.
116 +- `runner.ts` — strip `workflow` (+ ultra command tools) from the sub-agent
117 + allowlist defensively.
118 +- README / spec-format reference — document the setting and the "name tools, not
119 + extensions" portability contract.
121 +### Testing (Part A)
123 +- `settings.test.ts` — default is `"all"`; `"none"` parsed; precedence honoured.
124 +- `drivers.test.ts` — factory maps `"all"→noExtensions:false`,
125 + `"none"→noExtensions:true`; other isolation flags stay `true` in both.
126 +- `runner.test.ts` — `workflow` is stripped from a sub-agent allowlist even if a
127 + step lists it.
128 +- The spike's findings become a documented invariant, not a unit test (it needs
129 + a live web tool + key).
131 +## Part B — the `research` workflow (consumer of Part A) — DEFERRED
133 +> Deferred by the user on 2026-06-29. Part A ships first; this section is the
134 +> recorded plan for the follow-up, not current work.
136 +A deep-research clone, mirroring how `review` is structured. **Not a base-ultra
137 +dependency:** it needs a `web_search`/`web_fetch` tool, so it ships as a
138 +project/global workflow (or bundled-but-documented "requires a web_search tool"),
139 +never as something base ultra assumes is runnable.
141 +### Shape
143 +1. `plan` (single, tool-less) — decompose `{args.topic}` into N search angles.
144 + Schema `Plan { angles: string[] }`.
145 +2. `research` (fanout over `{plan.results[].angles[]}`, tools
146 + `["web_search","web_fetch","read"]`) — search the angle, fetch top sources,
147 + extract claims with source URLs. Schema `Findings { claims: [{claim, source,
148 + support}] }`.
149 +3. `verify` (fanout over `{research.results[].claims[]}`, tools `["web_fetch"]`)
150 + — re-fetch the source, adversarially check the claim, vote, echo `source` as
151 + the join key. Schema `Verdict { claim, real, source, why }`. Default
152 + `real=false` when uncertain.
153 +4. `report` (single, tool-less) — synthesise a cited Markdown report from
154 + `{verify.results | where real}`.
155 +5. `return` — the report text (or `{verify.results | where real}`).
157 +### Open sub-decision (Part B)
159 +`research` takes a **free-text topic**, but positional `params` map
160 +whitespace-split tokens one-per-name (great for `review`'s single `base` ref,
161 +wrong for a multi-word topic). Options: (a) use the JSON-args form `/ultra
162 +research {"topic":"..."}`; (b) extend positional mapping so the **last** declared
163 +param soaks the remaining tokens (`/ultra research rust async runtimes` →
164 +`topic="rust async runtimes"`). Lean (b) — it's a small, general improvement and
165 +keeps the `/ultra research <free text>` ergonomics. Decide at implementation.
167 +## Risks
169 +- **Cost / side-effects of default `"all"`** — every tool-using sub-agent boots
170 + all extensions. Mitigation: `"none"` opt-out; revisit selective loading if/when
171 + the SDK supports it.
172 +- **Spike could invalidate Part A** — see kill criteria. Part B is worthless
173 + without Part A, so spike first.
174 +- **Extension activation side-effects in sub-agents** — extensions must not do
175 + heavy work or fs writes on activation (extension fs writes crash pi). Keep
176 + `noSkills`/etc. on; rely on lazy-discovery discipline already in AGENTS.md.
178 +## Implementation order
180 +1. **Spike** (Part A gate). If green →
181 +2. Part A: setting + drivers + recursion defense + tests → `mise run ci` green.
182 +3. Part B: `research.json` + tests, shipped as project/global (or documented
183 + bundled). Decide the topic-arg ergonomics.

extensions/ultra/README.md

Modified
46 46 adversarially verifies each finding — run it with `/ultra review [base-ref]`
47 47 (no base ref reviews the working tree; a base ref reviews everything since it).
49 +The shipped `feature` workflow drives a small feature end to end —
50 +research → plan → adversarial critique → implement → security/quality review —
51 +run it with `/ultra feature <describe the task>` (the whole trailing text is the
52 +task). Only its `implement` phase writes; every other phase is read-only.
49 54 ## Settings
51 56 Read from the `ultra` block of agent settings, `<cwd>/.pi/settings.json`, and
52 57 `<cwd>/settings.json` (later overriding earlier), with the runtime settings
53 58 manager on top.
55 -| Key | Default | Meaning |
56 -| ------------------------ | -------- | ----------------------------------------------- |
57 -| `ultra.enabled` | `true` | When false, the tool + command refuse to run. |
58 -| `ultra.concurrency` | `5` | Max concurrent sub-agents in a `fanout` phase. |
59 -| `ultra.maxRetries` | `2` | Schema-validation retries per step. |
60 -| `ultra.defaultTimeoutMs` | `180000` | Per-step timeout when a step omits `timeoutMs`. |
60 +| Key | Default | Meaning |
61 +| -------------------------- | -------- | ----------------------------------------------- |
62 +| `ultra.enabled` | `true` | When false, the tool + command refuse to run. |
63 +| `ultra.concurrency` | `5` | Max concurrent sub-agents in a `fanout` phase. |
64 +| `ultra.maxRetries` | `2` | Schema-validation retries per step. |
65 +| `ultra.defaultTimeoutMs` | `180000` | Per-step timeout when a step omits `timeoutMs`. |
66 +| `ultra.subagentExtensions` | `"all"` | Load host extensions into sub-agents, or not. |
68 +`ultra.subagentExtensions` (`"all"` | `"none"`, default `"all"`) controls whether
69 +workflow sub-agents load the host's extensions. With `"all"`, a step can grant any
70 +tool an installed extension provides (e.g. `web_search`); with `"none"`, sub-agents
71 +are isolated to the core tools (`bash`, `find`, `grep`, `ls`, `read`, `ripgrep`).
72 +Either way the step's `tools` allowlist is the only gate on what's active, and
73 +ultra's own `workflow` tool is never grantable to a sub-agent. Workflows should
74 +name **tools**, never extensions — a workflow that lists a tool no installed
75 +extension provides simply runs without it.
62 77 ## Install / load

extensions/ultra/__tests__/drivers.test.ts

Modified
85 85 // Returns the destructured `.session`, not the wrapper.
86 86 expect(session).toBe(fakeSession);
89 + it("loadExtensions:true flips noExtensions to false; other isolation flags stay true", async () => {
90 + const loaderOpts: Record<string, unknown>[] = [];
91 + class FakeLoader {
92 + reload = vi.fn().mockResolvedValue(undefined);
93 + constructor(opts: Record<string, unknown>) {
94 + loaderOpts.push(opts);
95 + }
96 + }
97 + const createAgentSession = vi.fn(async () => ({ session: fakeSession }));
99 + const factory = makeSessionFactory({
100 + createAgentSession,
101 + DefaultResourceLoader: FakeLoader as any,
102 + getAgentDir: () => "/agent",
103 + cwd: "/work",
104 + modelRegistry: {},
105 + loadExtensions: true,
106 + });
107 + await factory({
108 + model: {},
109 + tools: ["web_search", "structured_output"],
110 + customTools: [],
111 + sessionManager: {},
112 + });
114 + // only noExtensions flips; the other isolation flags are untouched.
115 + expect(loaderOpts[0].noExtensions).toBe(false);
116 + expect(loaderOpts[0].noSkills).toBe(true);
117 + expect(loaderOpts[0].noPromptTemplates).toBe(true);
118 + expect(loaderOpts[0].noThemes).toBe(true);
119 + expect(loaderOpts[0].noContextFiles).toBe(true);
120 + });
90 123 describe("makeNewSessionManager", () => {

extensions/ultra/__tests__/feature.test.ts

Added
new file mode 100644
1 +import * as fs from "node:fs";
2 +import * as os from "node:os";
3 +import * as path from "node:path";
4 +import { fileURLToPath } from "node:url";
5 +import { describe, expect, it } from "vitest";
6 +import { resolveSelector } from "../interp.ts";
7 +import { discoverWorkflows, parseWorkflow } from "../spec.ts";
9 +// The shipped `feature` workflow — opencode-chef's feature pipeline, linearized
10 +// for ultra (which has no gate/loop/conditional): research → plan → critique →
11 +// implement → review. It lives beside the bundled-workflows lookup.
12 +const here = path.dirname(fileURLToPath(import.meta.url));
13 +const FEATURE_PATH = path.join(here, "..", "workflows", "feature.json");
15 +// Read-only allowlist for the v1 read-only-`fanout` rule. The single `implement`
16 +// phase is exempt (it writes via edit/write); only `fanout` steps are checked.
17 +const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls", "bash"]);
19 +function loadRaw(): string {
20 + return fs.readFileSync(FEATURE_PATH, "utf8");
23 +describe("feature shipped workflow", () => {
24 + it("parses through parseWorkflow (validates the actual shipped file)", () => {
25 + const spec = parseWorkflow(loadRaw());
26 + expect(spec.name).toBe("feature");
27 + expect(spec.phases.map((p) => p.id)).toEqual([
28 + "research",
29 + "plan",
30 + "critique",
31 + "implement",
32 + "review",
33 + ]);
34 + });
36 + it("takes a free-text task as a positional arg consumed by every phase", () => {
37 + const spec = parseWorkflow(loadRaw());
38 + expect(spec.args?.params).toEqual(["task"]);
39 + // research/critique/implement all scope to the task.
40 + for (const id of ["research", "critique", "implement"]) {
41 + const p = spec.phases.find((ph) => ph.id === id);
42 + expect(p?.step.prompt).toContain("{args.task}");
43 + }
44 + });
46 + it("chains the phases: each consumes its predecessors' results", () => {
47 + const spec = parseWorkflow(loadRaw());
48 + const get = (id: string) =>
49 + spec.phases.find((p) => p.id === id)?.step.prompt ?? "";
50 + expect(get("plan")).toContain("{research.results}");
51 + expect(get("critique")).toContain("{plan.results}");
52 + expect(get("implement")).toContain("{plan.results}");
53 + expect(get("implement")).toContain("{critique.results}");
54 + expect(get("review")).toContain("{implement.results}");
55 + });
57 + it("only `implement` (a single phase) may write; the fanout review stays read-only", () => {
58 + const spec = parseWorkflow(loadRaw());
59 + const implement = spec.phases.find((p) => p.id === "implement");
60 + expect(implement?.kind).toBe("single");
61 + expect(implement?.step.tools).toEqual(
62 + expect.arrayContaining(["edit", "write"]),
63 + );
65 + for (const phase of spec.phases) {
66 + if (phase.kind !== "fanout") continue; // the rule only binds fanout steps
67 + for (const t of phase.step.tools ?? []) {
68 + expect(READ_ONLY_TOOLS.has(t)).toBe(true);
69 + }
70 + }
71 + });
73 + it("reviews across security + quality, each echoing its dimension as the join key", () => {
74 + const spec = parseWorkflow(loadRaw());
75 + const review = spec.phases.find((p) => p.id === "review");
76 + expect(review?.kind).toBe("fanout");
77 + expect(review?.over).toEqual(["security", "quality"]);
78 + // the verdict echoes `dimension` so a result ties back to its lens
79 + expect(review?.step.prompt).toMatch(/dimension/);
80 + const verdict = spec.schemas?.Verdict as { required?: string[] };
81 + expect(verdict.required).toContain("dimension");
82 + });
84 + it("returns the review verdicts, and the selector keeps each full row", () => {
85 + const spec = parseWorkflow(loadRaw());
86 + expect(spec.return).toBe("{review.results}");
87 + const ctx = {
88 + results: {
89 + review: [
90 + { dimension: "security", passed: true, findings: [] },
91 + {
92 + dimension: "quality",
93 + passed: false,
94 + findings: ["no tests"],
95 + },
96 + ],
97 + },
98 + };
99 + const out = resolveSelector(spec.return ?? "", ctx) as Array<
100 + Record<string, unknown>
101 + >;
102 + expect(out).toHaveLength(2);
103 + expect(out[1]).toEqual({
104 + dimension: "quality",
105 + passed: false,
106 + findings: ["no tests"],
107 + });
108 + });
110 + it("is discoverable as a bundled workflow named `feature`", () => {
111 + const emptyCwd = fs.mkdtempSync(path.join(os.tmpdir(), "ultra-cwd-"));
112 + const emptyHome = fs.mkdtempSync(path.join(os.tmpdir(), "ultra-home-"));
113 + try {
114 + const found = discoverWorkflows(emptyCwd, { home: emptyHome });
115 + const feature = found.find((w) => w.name === "feature");
116 + expect(feature).toBeDefined();
117 + expect(feature?.source).toBe("bundled");
118 + } finally {
119 + fs.rmSync(emptyCwd, { recursive: true, force: true });
120 + fs.rmSync(emptyHome, { recursive: true, force: true });
122 + });
123 +});

extensions/ultra/__tests__/runner.test.ts

Modified
436 436 expect(result).toEqual({ ok: true, value: { verdict: "ok" } });
439 + it("strips ultra's own `workflow` tool from the sub-agent allowlist (no recursion)", async () => {
440 + const harness = makeSessionHarness({
441 + drive: happyDrive({ verdict: "ok" }),
442 + });
443 + const drivers = makeDrivers({ sessionFactory: harness.factory });
445 + const recursiveStep: Step = {
446 + prompt: "do X",
447 + tools: ["read", "workflow"],
448 + schema: VERDICT_SCHEMA,
449 + };
450 + await runStep(recursiveStep, makeCtx(), drivers, baseOpts());
452 + // `workflow` removed; `read` kept; structured_output still appended last.
453 + expect(harness.captured.args?.tools).toEqual([
454 + "read",
455 + STRUCTURED_OUTPUT_TOOL_NAME,
456 + ]);
457 + expect(harness.captured.args?.tools).not.toContain("workflow");
458 + });
439 460 it("the structured-output tool returns terminate:true and details = the validated params", async () => {
440 461 let returned: { details: unknown; terminate?: boolean } | undefined;
441 462 const harness = makeSessionHarness({

extensions/ultra/__tests__/settings.test.ts

Modified
33 33 concurrency: 5,
34 34 maxRetries: 2,
35 35 defaultTimeoutMs: 180000,
36 + subagentExtensions: "all",
41 +describe("subagentExtensions setting", () => {
42 + it('defaults to "all"', () => {
43 + expect(ULTRA_DEFAULTS.subagentExtensions).toBe("all");
44 + });
46 + it("pickUltra keeps only the none|all union", () => {
47 + expect(pickUltra({ ultra: { subagentExtensions: "none" } })).toEqual({
48 + subagentExtensions: "none",
49 + });
50 + expect(pickUltra({ ultra: { subagentExtensions: "all" } })).toEqual({
51 + subagentExtensions: "all",
52 + });
53 + // bogus value dropped
54 + expect(pickUltra({ ultra: { subagentExtensions: "lots" } })).toEqual({});
55 + });
57 + it("mergeUltraSettings folds it; later wins, bad ignored", () => {
58 + expect(
59 + mergeUltraSettings({ subagentExtensions: "none" }).subagentExtensions,
60 + ).toBe("none");
61 + expect(
62 + mergeUltraSettings(
63 + { subagentExtensions: "none" },
64 + { subagentExtensions: "all" },
65 + ).subagentExtensions,
66 + ).toBe("all");
67 + expect(
68 + mergeUltraSettings({
69 + subagentExtensions: "bogus" as never,
70 + }).subagentExtensions,
71 + ).toBe("all"); // default kept
72 + });
73 +});
40 75 describe("pickUltra", () => {
41 76 it("extracts only correctly-typed known keys from the `ultra` block", () => {
42 77 expect(
81 116 concurrency: 9,
82 117 maxRetries: 4,
83 118 defaultTimeoutMs: 180000,
119 + subagentExtensions: "all",
140 176 concurrency: 10, // runtime wins
141 177 maxRetries: 9, // only the agent file set it
142 178 defaultTimeoutMs: 180000, // default
179 + subagentExtensions: "all", // default

extensions/ultra/__tests__/ui.test.ts

Modified
184 184 expect(() => comp.render(80)).not.toThrow();
185 185 expect(comp.render(80).join("\n")).toContain("0/0 done");
188 + // Regression: a truthy `details` that is NOT a ReducerState — a resumed or
189 + // foreign tool result, a structured-output payload, a serialization double-wrap
190 + // — must fall back to an empty board, NEVER throw. An uncaught throw here is
191 + // fatal: it escapes tool-error handling and crashes the whole TUI render loop
192 + // (`state.phases.length` on an object without `phases`).
193 + it("tolerates a foreign (non-ReducerState) details without crashing the render loop", () => {
194 + const foreign = { results: [{ ok: true }] } as unknown as ReturnType<
195 + typeof initialReducerState
196 + >;
197 + for (const options of [
198 + { expanded: false, isPartial: false },
199 + { expanded: true, isPartial: true }, // expanded also reads `state.rows`
200 + ] as const) {
201 + const comp = renderUltraResult({ content: [], details: foreign }, options, theme);
202 + expect(() => comp.render(80)).not.toThrow();
203 + expect(comp.render(80).join("\n")).toContain("0/0 done");
205 + });
189 208 // --- Layer 7b — COMMAND overlay: board + drill-in transcript --------------

extensions/ultra/__tests__/wire.test.ts

Modified
271 271 expect(mapPositionalArgs("a b", ["x", "y"])).toEqual({ x: "a", y: "b" });
274 - it("ignores tokens beyond the declared params", () => {
275 - expect(mapPositionalArgs("main extra", ["base"])).toEqual({ base: "main" });
274 + it("soaks remaining tokens into the last declared param (free-text tail)", () => {
275 + // single free-text param keeps the whole remainder
276 + expect(mapPositionalArgs("add a dark-mode toggle", ["task"])).toEqual({
277 + task: "add a dark-mode toggle",
278 + });
279 + // only the LAST param soaks; earlier params take one token each
280 + expect(mapPositionalArgs("main fix the bug", ["base", "task"])).toEqual({
281 + base: "main",
282 + task: "fix the bug",
283 + });
278 286 it("returns undefined for an empty remainder or no declared params", () => {

extensions/ultra/drivers.ts

Modified
42 42 getAgentDir: () => string;
43 43 cwd: string;
44 44 modelRegistry: unknown;
45 + /** When true, sub-agents load host extensions (their tools become grantable).
46 + * Omitted/false ⇒ isolated (`noExtensions: true`), today's behaviour. */
47 + loadExtensions?: boolean;
47 50 export function makeSessionFactory(deps: SessionFactoryDeps): SessionFactory {
59 62 const resourceLoader = new deps.DefaultResourceLoader({
60 63 cwd: deps.cwd,
61 64 agentDir: deps.getAgentDir(),
62 - noExtensions: true,
65 + // Only this flag flips with the setting; the rest stay isolated so
66 + // sub-agents never inherit host skills/prompts/themes/context files.
67 + noExtensions: !deps.loadExtensions,
63 68 noSkills: true,
64 69 noPromptTemplates: true,
65 70 noThemes: true,

extensions/ultra/index.ts

Modified
97 97 getAgentDir,
98 98 cwd: ctx.cwd,
99 99 modelRegistry: ctx.modelRegistry,
100 + loadExtensions: cfg.subagentExtensions === "all",
101 102 resolveModel: makeResolveModel({
102 103 modelRegistry: ctx.modelRegistry,

extensions/ultra/runner.ts

Modified
182 182 /** Name of the injected terminating StructuredOutput tool (appended to the allowlist). */
183 183 export const STRUCTURED_OUTPUT_TOOL_NAME = "structured_output";
185 +/** ultra's own model-callable tools, stripped from every sub-agent allowlist so
186 + * a sub-agent (which may load ultra when `subagentExtensions: "all"`) can never
187 + * re-enter the workflow engine, regardless of what a step lists. */
188 +export const ULTRA_OWN_TOOL_NAMES = ["workflow"] as const;
190 +function sanitizeSubagentTools(tools: string[] | undefined): string[] {
191 + const own = ULTRA_OWN_TOOL_NAMES as readonly string[];
192 + return (tools ?? []).filter((t) => !own.includes(t));
185 195 // ---------------------------------------------------------------------------
186 196 // Internal helpers
187 197 // ---------------------------------------------------------------------------
489 499 thinkingLevel: step.thinkingLevel,
490 500 // The structured-output tool name is APPENDED to the step allowlist
491 501 // (correction #5) — it must be present or the registry filters it out.
492 - tools: [...(step.tools ?? []), STRUCTURED_OUTPUT_TOOL_NAME],
502 + // ultra's own `workflow` tool is stripped first (recursion defense).
503 + tools: [
504 + ...sanitizeSubagentTools(step.tools),
505 + STRUCTURED_OUTPUT_TOOL_NAME,
506 + ],
493 507 customTools: [structuredOutputTool],
494 508 sessionManager,

extensions/ultra/settings.ts

Modified
19 19 maxRetries: number;
20 20 /** Per-step timeout when the step omits `timeoutMs`. */
21 21 defaultTimeoutMs: number;
22 + /** Load host extensions into sub-agents so their tools are grantable
23 + * (`"all"`, default) or keep sub-agents isolated to core tools (`"none"`).
24 + * The `step.tools` allowlist still gates which tools are actually active. */
25 + subagentExtensions: "none" | "all";
24 28 /** Documented defaults (design §Settings table). */
27 31 concurrency: 5,
28 32 maxRetries: 2,
29 33 defaultTimeoutMs: 180000,
34 + subagentExtensions: "all",
32 37 function isPlainObject(v: unknown): v is Record<string, unknown> {
49 54 if (typeof ultra.maxRetries === "number") out.maxRetries = ultra.maxRetries;
50 55 if (typeof ultra.defaultTimeoutMs === "number")
51 56 out.defaultTimeoutMs = ultra.defaultTimeoutMs;
57 + if (ultra.subagentExtensions === "none" || ultra.subagentExtensions === "all")
58 + out.subagentExtensions = ultra.subagentExtensions;
52 59 return out;
78 85 typeof p.defaultTimeoutMs === "number"
79 86 ? p.defaultTimeoutMs
80 87 : into.defaultTimeoutMs,
88 + subagentExtensions:
89 + p.subagentExtensions === "none" || p.subagentExtensions === "all"
90 + ? p.subagentExtensions
91 + : into.subagentExtensions,
82 93 { ...ULTRA_DEFAULTS },

extensions/ultra/ui.ts

Modified
144 +/**
145 + * Accept `result.details` only when it structurally IS a reducer state. It
146 + * reaches us over an SDK-controlled channel (structured-cloned per `onUpdate`
147 + * tick, and re-hydrated from session persistence on resume), so a truthy-but-
148 + * foreign value can arrive — a resumed/foreign tool result, a payload from
149 + * another producer, a serialization wrapper. The board reads `state.phases`
150 + * and `state.rows` unguarded, so anything lacking them falls back to an empty
151 + * board. This is the single choke point: an uncaught throw in `renderResult`
152 + * escapes tool-error handling and crashes the whole TUI render loop.
153 + */
154 +function asReducerState(details: unknown): ReducerState {
155 + const d = details as Partial<ReducerState> | null | undefined;
156 + return d && Array.isArray(d.phases) && Array.isArray(d.rows)
157 + ? (d as ReducerState)
158 + : initialReducerState();
145 162 * Tool-surface `renderResult`: reads the reducer state off `result.details`
146 163 * (pushed through `onUpdate`) and returns a board `Component`. Read-only — no
153 170 theme: Theme,
154 171 _context?: unknown,
155 172 ): Component {
156 - const state =
157 - (result?.details as ReducerState | undefined) ?? initialReducerState();
158 - return new UltraResultComponent(state, options, theme);
173 + return new UltraResultComponent(asReducerState(result?.details), options, theme);
161 176 // ---------------------------------------------------------------------------

extensions/ultra/wire.ts

Modified
140 140 * Map a bare command-line remainder to named args using a workflow's declared
141 - * positional `params`: whitespace-split tokens fill `params` in order, extra
142 - * tokens are ignored. Returns `undefined` when nothing maps (empty remainder or
143 - * no declared params). Only the `/ultra` command uses this — the `workflow`
144 - * tool passes a structured `args` object directly.
141 + * positional `params`: whitespace-split tokens fill `params` in order, and the
142 + * last declared param soaks any remaining tokens so a trailing free-text arg
143 + * (e.g. a feature description) survives intact. Returns `undefined` when nothing
144 + * maps (empty remainder or no declared params). Only the `/ultra` command uses
145 + * this — the `workflow` tool passes a structured `args` object directly.
146 147 export function mapPositionalArgs(
147 148 rest: string,
151 152 if (tokens.length === 0 || params.length === 0) return undefined;
152 153 const out: Record<string, unknown> = {};
153 154 params.forEach((name, i) => {
154 - if (i < tokens.length) out[name] = tokens[i];
155 + if (i >= tokens.length) return;
156 + // The last declared param soaks the remaining tokens so a trailing
157 + // free-text arg (e.g. a feature description) survives intact; earlier
158 + // params take exactly one token each.
159 + out[name] = i === params.length - 1 ? tokens.slice(i).join(" ") : tokens[i];
156 161 return Object.keys(out).length > 0 ? out : undefined;

extensions/ultra/workflows/feature.json

Added
new file mode 100644
1 +{
2 + "name": "feature",
3 + "description": "Research the codebase, plan a feature, adversarially critique the plan, implement it, then review for security and quality.",
4 + "args": { "hint": "<task>", "params": ["task"] },
5 + "schemas": {
6 + "Research": {
7 + "type": "object",
8 + "properties": {
9 + "findings": {
10 + "type": "string",
11 + "description": "Summary of how the codebase handles this area"
12 + },
13 + "files": {
14 + "type": "array",
15 + "items": { "type": "string" },
16 + "description": "Relevant file paths"
17 + },
18 + "patterns": {
19 + "type": "array",
20 + "items": { "type": "string" },
21 + "description": "Existing conventions to follow"
22 + }
23 + },
24 + "required": ["findings", "files"]
25 + },
26 + "Plan": {
27 + "type": "object",
28 + "properties": {
29 + "tasks": {
30 + "type": "array",
31 + "items": { "type": "string" },
32 + "description": "Concrete implementation steps, in order"
33 + },
34 + "approach": {
35 + "type": "string",
36 + "description": "One-paragraph overall approach"
37 + },
38 + "risks": { "type": "array", "items": { "type": "string" } }
39 + },
40 + "required": ["tasks", "approach"]
41 + },
42 + "Critique": {
43 + "type": "object",
44 + "properties": {
45 + "approved": {
46 + "type": "boolean",
47 + "description": "true only if the plan is sound and complete"
48 + },
49 + "blocking": {
50 + "type": "array",
51 + "items": { "type": "string" },
52 + "description": "Each blocking gap the implementer must resolve"
53 + },
54 + "feedback": { "type": "string" }
55 + },
56 + "required": ["approved", "blocking"]
57 + },
58 + "Implementation": {
59 + "type": "object",
60 + "properties": {
61 + "summary": {
62 + "type": "string",
63 + "description": "What was changed and why"
64 + },
65 + "modified_files": { "type": "array", "items": { "type": "string" } },
66 + "completed": {
67 + "type": "array",
68 + "items": { "type": "string" },
69 + "description": "Plan tasks actually completed"
70 + }
71 + },
72 + "required": ["summary", "modified_files"]
73 + },
74 + "Verdict": {
75 + "type": "object",
76 + "properties": {
77 + "dimension": {
78 + "type": "string",
79 + "description": "echo of the review dimension, for correlation"
80 + },
81 + "passed": { "type": "boolean" },
82 + "findings": {
83 + "type": "array",
84 + "items": { "type": "string" },
85 + "description": "Blocking problems found (empty if passed)"
86 + }
87 + },
88 + "required": ["dimension", "passed"]
89 + }
90 + },
91 + "phases": [
92 + {
93 + "id": "research",
94 + "kind": "single",
95 + "step": {
96 + "prompt": "Research this codebase to implement the feature: {args.task}. Identify the files you'd touch, the existing patterns/conventions to follow, and any constraints. Inspect with read/grep/find/bash (e.g. `git log`, `git grep`); do not modify anything. Return JSON matching the Research schema.",
97 + "tools": ["read", "grep", "find", "ls", "bash"],
98 + "schema": "Research"
99 + }
100 + },
102 + "id": "plan",
103 + "kind": "single",
104 + "step": {
105 + "prompt": "Produce an implementation plan for: {args.task}. Ground it in this research: {research.results}. Give concrete ordered tasks, a one-paragraph approach, and the real risks. Read further if needed; do not modify anything. Return JSON matching the Plan schema.",
106 + "tools": ["read", "grep", "find", "ls", "bash"],
107 + "schema": "Plan"
109 + },
111 + "id": "critique",
112 + "kind": "single",
113 + "step": {
114 + "prompt": "Adversarially critique this plan BEFORE any code is written. Task: {args.task}. Plan: {plan.results}. Research: {research.results}. Hunt for missing steps, wrong assumptions, and unhandled edge cases. Set approved=false and list each blocking issue if the plan isn't ready; default approved=false when uncertain. Do not modify anything. Return JSON matching the Critique schema.",
115 + "tools": ["read", "grep", "find", "ls", "bash"],
116 + "schema": "Critique"
118 + },
120 + "id": "implement",
121 + "kind": "single",
122 + "step": {
123 + "prompt": "Implement the feature: {args.task}. Follow the plan and resolve EVERY blocking item from the critique. Plan: {plan.results}. Critique: {critique.results}. Make the actual edits with the edit/write tools, keep the change focused, and follow the conventions surfaced in research. Then return JSON matching the Implementation schema (list the files you changed and a concise summary).",
124 + "tools": ["read", "grep", "find", "ls", "bash", "edit", "write"],
125 + "schema": "Implementation"
127 + },
129 + "id": "review",
130 + "kind": "fanout",
131 + "over": ["security", "quality"],
132 + "step": {
133 + "prompt": "Review the just-made implementation of {args.task} from the {item} perspective. What changed: {implement.results}. Inspect the working tree with read/grep and `git diff`; do not modify anything. Set passed=false and list each blocking {item} problem you find. Echo the `dimension` field as \"{item}\" so the verdict ties back. Return JSON matching the Verdict schema.",
134 + "tools": ["read", "grep", "find", "ls", "bash"],
135 + "schema": "Verdict"
138 + ],
139 + "return": "{review.results}"