repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/U008.md

Raw

U008 Generated subagent extensions

Status

Implemented.

This document is binding for U008. If implementation pressure contradicts it, change this specification explicitly before changing behavior.

Outcome

Ultra may delegate creation, reuse, improvement, validation, and repair of purpose-built Pi extensions to builder subagents. Validated dynamic extensions load into later child sessions through each child's independent ResourceLoader and behave like normal extensions there.

The feature optimizes the user's task, not extension authoring itself. Ultra should encourage reusable dynamic extensions when they can encode specialized capability, deterministic operations, or repeated reasoning, because the shared catalog amortizes authoring cost across workflows.

Trust boundary

Dynamic extensions have the same authority as the orchestrator that authored them. They are not sandboxed and may use the complete Pi extension API and host permissions. Validation process isolation contains crashes, hangs, leaked handles, and mutated globals; it is not a security boundary.

Builders receive every available child tool, including loaded extension tools, except run_workflow. Ultra's recursion boundary remains unchanged.

Storage

Durable catalog

The catalog lives beneath Pi's agent directory:

<agentDir>/ultra/dynamic-extensions/catalog/
  <name>/
    current.json
    <sha256>/
      manifest.json
      package.json
      README.md
      index.ts
      index.test.ts
      benchmark.ts
      debug.ts
      .ultra-validation.json
      ...

<name> is stable extension identity. current.json selects the one canonical validated source directory for that name. Search indexes only the selected source, never non-current hash directories.

Ultra does not initialize, add, commit, or otherwise manage any version-control repository around agentDir. The catalog may itself be tracked by the user.

Platform cache

Transient state lives beneath the platform cache directory:

The cache contains:

runs/<parent-session-id>/<workflow-run-id>/<agent-id>/
locks/<catalog-path-hash>/<extension-name>.lock
logs/<child-session-id>/<extension-name>.jsonl

Completed workflows delete drafts. Interrupted workflows retain drafts for resume. Abandoned drafts are lazily pruned after seven days. Completed and interrupted debug logs are retained for seven days. No cleanup runs during ordinary Ultra startup.

Canonical publication

The source hash is SHA-256 over sorted relative paths and exact bytes of every artifact file, including documentation, tests, package metadata, benchmarks, and debug.ts. Only .ultra-validation.json is excluded. Symlinks are rejected. There is no file-count or artifact-size limit.

Cross-platform APIs cannot atomically replace an existing non-empty directory. Publication therefore writes a new immutable hash directory and atomically replaces the small current.json file. Publication points current.json at the new source only after the source and attestation are complete. Non-current source directories are excluded from discovery and may be removed after publication; crash leftovers are pruned lazily.

A per-name cross-process lock protects publication. Locks live in platform cache so a version-controlled agentDir receives no transient files. Publication compares the draft's recorded base hash with current canonical state. A stale base is rejected, never overwritten or textually auto-merged. The builder receives base/current hashes and paths, checks out current canonical state, reapplies its intent, and validates again. One stale-base retry is recommended, but not enforced by the runtime.

Validation publishes immediately, before consumer use. A validated extension that is never ultimately loaded may therefore remain canonical; this is an accepted simplification.

Manual edits to canonical source invalidate its attested hash. Search marks it unvalidated, and loading reports the exact path plus an instruction to call validate_dynamic_extension. Validation accepts both tool-created drafts and manually edited canonical directories. Canonical validation locks and republishes the edited source under its new hash.

Before child creation, Ultra resolves each stable name to current validated hash while holding the short name lock and copies that exact source into a run-local hash snapshot. The child loads the snapshot, not mutable catalog state. This prevents publication races between resolution and ResourceLoader execution.

Builder tools

Ultra supplies four strict-schema tools to builder children:

A workflow step selecting any builder tool must select all four. That complete set marks the child as a builder and injects the versioned builder contract. No search-only child role exists. Consumers receive no dynamic-extension instructions; loaded dynamic extensions look normal to them.

Search

search_dynamic_extensions requires a query and returns at most five deterministic matches. It tokenizes without a model: lowercase normalization, punctuation and identifier splitting, and simple plural normalization. Ranking weights exact phrase, name/topic, tags, scope, then the README Purpose, Scope, and Usage sections. Code blocks and remaining README prose are not indexed. Ties sort deterministically by name.

Results contain stable name, current hash, validation status, short description, topic, tags, tested-platform advisory metadata, and exact current source path. Platform metadata never filters or lowers thematic rank. The builder reads only relevant candidate READMEs before deciding reuse, checkout, or creation.

create_dynamic_extension requires a prior search call in the same builder session. The tool records returned candidates and requires explicit rejection rationale, including the no-match case, before creating a new topic.

Create

create_dynamic_extension requires:

It scaffolds an editable run-cache draft and returns its absolute path. The initial README is populated from these fields rather than empty headings. Validation rejects unresolved placeholders.

Checkout

checkout_dynamic_extension copies current canonical source into an editable run-cache draft and records its base hash. Normal tools edit the returned absolute path. Name and topic are immutable identity during checkout. Scope, non-goals, tags, API, docs, tests, benchmarks, and implementation may evolve within that topic. A different topic requires a new extension.

Validate

validate_dynamic_extension runs mandatory correctness gates and advisory performance checks. Correctness failure retains the draft and publishes nothing. Performance budget overruns produce warnings and do not block publication because scheduler load is not correctness evidence. Success returns stable name, full revision hash, description, and exact canonical source path.

Diagnostics report all independent failures in one call. Each diagnostic contains stable gate and code identifiers, path and line where available, expected and actual values, bounded output, elapsed limits, remediation, and retained draft path. Dependent skipped gates are reported as blocked rather than silently omitted.

Esc abort kills the validator process tree, retains the draft, publishes nothing, and returns a typed aborted result.

Builder orchestration

The root orchestrator receives concise guidance about when to delegate a builder. Only builders receive the full authoring contract. Pi API documentation and example locations already present in Pi's system prompt are not duplicated.

A builder brief is structured as:

The orchestrator does not paste transcripts, files, or general Pi documentation into the brief. Builders inspect relevant sources with their tools.

One builder owns one extension. Independent topics may use parallel builders when their fanout phase declares write isolation. Builders should not intentionally modify the same extension in parallel; stale-base validation still prevents clobbering across mistaken plans or separate Pi sessions.

Use big/high for new extension architecture and medium/high for bounded improvements unless configured models or task economics justify another deliberate choice.

Known canonical names may be loaded directly without a builder. Builders are required for discovery, creation, improvement, stale validation, and runtime repair.

A builder failure blocks later consumer phases. Blocking stops later phases while preserving the normal aggregate, typed builder failure, debug-log paths, and usage accounting. U008 has no normal-tool fallback.

Workflow schema

Dynamic extensions

Steps gain dynamicExtensions. It accepts either a literal array of stable catalog names or one existing interpolation selector resolving to such an array. Consumers interpolate stable names, not hashes.

Immediately before child creation, Ultra resolves each stable name to the exact validated hash and source snapshot. Resolved name and hash participate in the stable step key. A repaired canonical extension therefore invalidates only affected checkpoints; unchanged work remains reusable.

One consumer may load multiple dynamic extensions. Normal configured extensions load first and retain existing behavior. Dynamic extensions load afterward in declared array order. subagentExtensions: "none" suppresses only normal extensions, not explicit dynamicExtensions.

Generated tools must activate themselves during session_start, because Ultra cannot name them before loading. The real-loader validation gate verifies this behavior.

General mutating fanout

Fanout phases gain optional writeIsolation, a non-empty rationale explaining why each item owns disjoint mutation work.

Without writeIsolation, existing fanout law remains unchanged: initial tools are read-only plus bash, and the prompt must forbid mutation. With writeIsolation, mutating tools are allowed and the prompt assigns disjoint ownership. Ultra trusts the orchestrator's declaration. It does not gate edit/write paths, suppress normal extensions, or attempt to constrain arbitrary custom mutators.

This general fanout relaxation ships with U008.

Generated extension contract

Each extension covers one topic. Builders modify an existing extension when the responsibility remains within that topic and create a new extension only for a distinct responsibility.

Names are two-to-four-term kebab-case domain capabilities. Names contain no platform, version, model, session, helper, or utils terms. Descriptions state a concrete capability in one sentence.

The manifest records durable semantics only:

Provenance, validation results, timings, and source hash belong in .ultra-validation.json, not the manifest.

Every declared capability ID appears in the README test matrix and at least one node:test case name. The README contains Purpose, Scope, Non-goals, Alternatives considered, Decision rationale, Usage, Architecture, Test matrix, and Promotion notes. Alternatives and rationale remain durable documentation and are updated when overlap changes.

Generated extensions have no third-party runtime npm dependencies. Pi host packages are declared as peer dependencies and added only when imported. package.json remains private until manual promotion. External executables are allowed when useful; the manifest declares required versus optional tools, and startup checks PATH through native Node APIs.

Generated source and tests use erasable TypeScript supported directly by Pi's Node 22.19+ requirement. Transform-only enums, namespaces, parameter properties, and equivalent syntax are forbidden.

Entry modules stay thin. Core logic is exported through pure modules and tested with node:test. Tests use local fakes or loopback services and never external networks. The real loader separately verifies Pi integration.

Generated extensions must support headless print mode. TUI-only behavior guards TUI APIs, while the capability Ultra needs remains usable headlessly.

The built-in authoring contract requires:

Loaded extensions must not intentionally modify their own catalog source. Runtime state uses session entries or explicit project/user data paths; improvements go through checkout and validation. This is an authoring invariant, not a sandbox restriction. A later load detects source-hash drift.

Dynamic extensions may explicitly override normal registrations. The manifest lists exact qualified targets such as tool:read or provider:foo. Child composition blocks undeclared collisions with actionable diagnostics. Normal extensions load before declared dynamic overrides.

Mandatory scaffold

Every generated extension starts with:

manifest.json
package.json
README.md
index.ts
index.test.ts
benchmark.ts
debug.ts

Additional helpers and tests are allowed. debug.ts is copied from Ultra's versioned template. Builders may call it but validation compares it byte-for-byte and provides a restore instruction when changed. Validation writes .ultra-validation.json; builders do not author that file.

Validation gates

Validation uses one fresh Node subprocess rooted at the extension draft. It inherits the host environment and adds only CI plus validator temp/log paths. It has full host permissions. The parent captures bounded output, applies a hard timeout, and kills the process tree on abort or timeout.

U008 bundles no Biome, Vitest, formatter, linter, or TypeScript compiler. It installs no dependencies during workflows. Initial validation therefore includes:

  1. manifest schema, naming, one-topic fields, tags, capabilities, executable declarations, override declarations, and benchmark budgets
  2. README required sections, populated scaffold content, and capability/test-matrix mapping
  3. package constraints and absence of third-party runtime npm dependencies
  4. fixed debug.ts template
  5. symlink rejection and deterministic whole-artifact hashing
  6. all node:test files with capability mapping
  7. required benchmark.ts contract and advisory current-platform hot-path budget comparison
  8. real Pi SDK loading through scoped DefaultResourceLoader, in-memory AgentSession, bindExtensions({ mode: "print" }), session_start, registration inspection, and session_shutdown
  9. active generated-tool verification
  10. advisory marginal extension load timing
  11. attestation generation and canonical publication

Real loading uses Pi SDK directly and makes no model call. pi-test-harness is not required.

Five seconds is a warning target, not a quality gate. Fifteen seconds is the hard validator watchdog. The initial marginal load budget is 50 ms. Hot-path budgets are declared per platform. Builders may tighten an existing platform budget but may not loosen it. All thresholds are named constants for later adjustment.

Test runtime does not fail merely for exceeding the five-second target, because a hard short target would reward deleting tests. Capability mapping remains mandatory. The watchdog remains a deadlock ceiling. Marginal load and hot-path budget overruns are warnings because benchmark results require controlled conditions.

Validator-contract version participates in attestation validity. After a contract update, search marks old attestations outdated and loading requires revalidation.

Debug logs

Every generated extension writes minimal structured debug logs during normal use. Builders choose topic-relevant events and enough context to reconstruct branches, state transitions, I/O, timings, and failures. Logs may include arguments and results when diagnostically useful. Builders must redact credentials and bound individual values; this is an instruction, not a secret scanner.

Logs use NDJSON with at least:

The log path is:

<platform-cache>/pi/ultra/dynamic-extensions/logs/<child-session-id>/<extension-name>.jsonl

Ultra derives it from the persistent or in-memory child session ID. Each extension/child log is capped at 1 MiB. At the limit, the logger writes one truncation marker and drops later records.

Ultra never ingests logs automatically. Workflow results expose their paths so the orchestrator can inspect them with normal tools when extension involvement is plausible.

Runtime observation and repair

Intentional loading is the auditable usage boundary. Ultra observes successful loading, registrations, dynamic tool calls/results, transcripts, final step results, and debug-log paths. It cannot externally prove arbitrary hook semantics. Tests remain the validation proof; runtime logs provide diagnosis.

Validation is revision-wide, not a per-platform load gate. Search displays tested platforms as advisory metadata only. An extension validated on another platform may load optimistically on the current platform. Builders do not preemptively rewrite it solely because current-platform evidence is absent.

When a consumer behaves unexpectedly, Ultra returns extension identities, failure diagnostics, and log paths. The orchestrator inspects relevant logs, launches a repair builder for the same topic, validates the new canonical revision, and reruns the original workflow. There is no hard repair-cycle limit. Runtime failures do not globally mark canonical extensions unhealthy because failures may be task-specific.

Rerunning the original workflow reuses unaffected journal checkpoints. Canonical names resolve to the repaired hash, changing affected step keys and downstream resolved prompts.

Reporting

WorkflowResult gains a deduplicated dynamicExtensions array. Each entry contains:

Extensions loaded by successful, failed, or aborted steps are reported after successful binding. An attempted extension that failed before binding is diagnostic, not used. Cached/resumed workflow results preserve usage metadata without charging new model usage.

/ultra run prints one final dynamic-extension block containing only name, short description, and exact source path. The model-visible run_workflow result contains the complete metadata. The collapsed tool widget remains compact and shows per-extension information only when expanded.

Startup and lifecycle

Catalog directories, cleanup, search code, validator code, and generated-extension implementation are lazy-loaded on first dynamic-extension action or first dynamicExtensions resolution. Ordinary Ultra startup and reload perform no catalog scan, process spawn, cleanup, or Git operation. Reload remains terminal for the invoking handler.

Acceptance

U008 is complete only when automated tests cover:

Live acceptance must exercise creation, reuse, a stale or manually invalidated extension, consumer loading, debug-log inspection, repair, rerun checkpoint reuse, parallel isolated builders, cancellation, and final reporting.

Markdown source
File outline
# U008 Generated subagent extensions

## Status

Implemented.

This document is binding for U008.
If implementation pressure contradicts it, change this specification explicitly before changing behavior.

## Outcome

Ultra may delegate creation, reuse, improvement, validation, and repair of purpose-built Pi extensions to builder subagents.
Validated dynamic extensions load into later child sessions through each child's independent `ResourceLoader` and behave like normal extensions there.

The feature optimizes the user's task, not extension authoring itself.
Ultra should encourage reusable dynamic extensions when they can encode specialized capability, deterministic operations, or repeated reasoning, because the shared catalog amortizes authoring cost across workflows.

## Trust boundary

Dynamic extensions have the same authority as the orchestrator that authored them.
They are not sandboxed and may use the complete Pi extension API and host permissions.
Validation process isolation contains crashes, hangs, leaked handles, and mutated globals; it is not a security boundary.

Builders receive every available child tool, including loaded extension tools, except `run_workflow`.
Ultra's recursion boundary remains unchanged.

## Storage

### Durable catalog

The catalog lives beneath Pi's agent directory:

```text
<agentDir>/ultra/dynamic-extensions/catalog/
  <name>/
    current.json
    <sha256>/
      manifest.json
      package.json
      README.md
      index.ts
      index.test.ts
      benchmark.ts
      debug.ts
      .ultra-validation.json
      ...
```

`<name>` is stable extension identity.
`current.json` selects the one canonical validated source directory for that name.
Search indexes only the selected source, never non-current hash directories.

Ultra does not initialize, add, commit, or otherwise manage any version-control repository around `agentDir`.
The catalog may itself be tracked by the user.

### Platform cache

Transient state lives beneath the platform cache directory:

- Windows: `%LOCALAPPDATA%/pi/ultra/dynamic-extensions/`
- macOS: `~/Library/Caches/pi/ultra/dynamic-extensions/`
- Other platforms: `$XDG_CACHE_HOME/pi/ultra/dynamic-extensions/`, falling back to `~/.cache/pi/ultra/dynamic-extensions/`

The cache contains:

```text
runs/<parent-session-id>/<workflow-run-id>/<agent-id>/
locks/<catalog-path-hash>/<extension-name>.lock
logs/<child-session-id>/<extension-name>.jsonl
```

Completed workflows delete drafts.
Interrupted workflows retain drafts for resume.
Abandoned drafts are lazily pruned after seven days.
Completed and interrupted debug logs are retained for seven days.
No cleanup runs during ordinary Ultra startup.

## Canonical publication

The source hash is SHA-256 over sorted relative paths and exact bytes of every artifact file, including documentation, tests, package metadata, benchmarks, and `debug.ts`.
Only `.ultra-validation.json` is excluded.
Symlinks are rejected.
There is no file-count or artifact-size limit.

Cross-platform APIs cannot atomically replace an existing non-empty directory.
Publication therefore writes a new immutable hash directory and atomically replaces the small `current.json` file.
Publication points `current.json` at the new source only after the source and attestation are complete.
Non-current source directories are excluded from discovery and may be removed after publication; crash leftovers are pruned lazily.

A per-name cross-process lock protects publication.
Locks live in platform cache so a version-controlled `agentDir` receives no transient files.
Publication compares the draft's recorded base hash with current canonical state.
A stale base is rejected, never overwritten or textually auto-merged.
The builder receives base/current hashes and paths, checks out current canonical state, reapplies its intent, and validates again.
One stale-base retry is recommended, but not enforced by the runtime.

Validation publishes immediately, before consumer use.
A validated extension that is never ultimately loaded may therefore remain canonical; this is an accepted simplification.

Manual edits to canonical source invalidate its attested hash.
Search marks it unvalidated, and loading reports the exact path plus an instruction to call `validate_dynamic_extension`.
Validation accepts both tool-created drafts and manually edited canonical directories.
Canonical validation locks and republishes the edited source under its new hash.

Before child creation, Ultra resolves each stable name to current validated hash while holding the short name lock and copies that exact source into a run-local hash snapshot.
The child loads the snapshot, not mutable catalog state.
This prevents publication races between resolution and `ResourceLoader` execution.

## Builder tools

Ultra supplies four strict-schema tools to builder children:

- `search_dynamic_extensions`
- `create_dynamic_extension`
- `checkout_dynamic_extension`
- `validate_dynamic_extension`

A workflow step selecting any builder tool must select all four.
That complete set marks the child as a builder and injects the versioned builder contract.
No search-only child role exists.
Consumers receive no dynamic-extension instructions; loaded dynamic extensions look normal to them.

### Search

`search_dynamic_extensions` requires a query and returns at most five deterministic matches.
It tokenizes without a model: lowercase normalization, punctuation and identifier splitting, and simple plural normalization.
Ranking weights exact phrase, name/topic, tags, scope, then the README Purpose, Scope, and Usage sections.
Code blocks and remaining README prose are not indexed.
Ties sort deterministically by name.

Results contain stable name, current hash, validation status, short description, topic, tags, tested-platform advisory metadata, and exact current source path.
Platform metadata never filters or lowers thematic rank.
The builder reads only relevant candidate READMEs before deciding reuse, checkout, or creation.

`create_dynamic_extension` requires a prior search call in the same builder session.
The tool records returned candidates and requires explicit rejection rationale, including the no-match case, before creating a new topic.

### Create

`create_dynamic_extension` requires:

- name
- description
- topic
- scope
- non-goals
- tags
- considered candidates and rejection rationale

It scaffolds an editable run-cache draft and returns its absolute path.
The initial README is populated from these fields rather than empty headings.
Validation rejects unresolved placeholders.

### Checkout

`checkout_dynamic_extension` copies current canonical source into an editable run-cache draft and records its base hash.
Normal tools edit the returned absolute path.
Name and topic are immutable identity during checkout.
Scope, non-goals, tags, API, docs, tests, benchmarks, and implementation may evolve within that topic.
A different topic requires a new extension.

### Validate

`validate_dynamic_extension` runs mandatory correctness gates and advisory performance checks.
Correctness failure retains the draft and publishes nothing.
Performance budget overruns produce warnings and do not block publication because scheduler load is not correctness evidence.
Success returns stable name, full revision hash, description, and exact canonical source path.

Diagnostics report all independent failures in one call.
Each diagnostic contains stable gate and code identifiers, path and line where available, expected and actual values, bounded output, elapsed limits, remediation, and retained draft path.
Dependent skipped gates are reported as blocked rather than silently omitted.

Esc abort kills the validator process tree, retains the draft, publishes nothing, and returns a typed aborted result.

## Builder orchestration

The root orchestrator receives concise guidance about when to delegate a builder.
Only builders receive the full authoring contract.
Pi API documentation and example locations already present in Pi's system prompt are not duplicated.

A builder brief is structured as:

- topic, required
- outcome, required
- intended consumers, required
- done conditions, required
- assumptions, optional
- current platform, optional
- relevant paths or evidence, optional
- hard constraints, optional

The orchestrator does not paste transcripts, files, or general Pi documentation into the brief.
Builders inspect relevant sources with their tools.

One builder owns one extension.
Independent topics may use parallel builders when their fanout phase declares write isolation.
Builders should not intentionally modify the same extension in parallel; stale-base validation still prevents clobbering across mistaken plans or separate Pi sessions.

Use `big/high` for new extension architecture and `medium/high` for bounded improvements unless configured models or task economics justify another deliberate choice.

Known canonical names may be loaded directly without a builder.
Builders are required for discovery, creation, improvement, stale validation, and runtime repair.

A builder failure blocks later consumer phases.
Blocking stops later phases while preserving the normal aggregate, typed builder failure, debug-log paths, and usage accounting.
U008 has no normal-tool fallback.

## Workflow schema

### Dynamic extensions

Steps gain `dynamicExtensions`.
It accepts either a literal array of stable catalog names or one existing interpolation selector resolving to such an array.
Consumers interpolate stable names, not hashes.

Immediately before child creation, Ultra resolves each stable name to the exact validated hash and source snapshot.
Resolved name and hash participate in the stable step key.
A repaired canonical extension therefore invalidates only affected checkpoints; unchanged work remains reusable.

One consumer may load multiple dynamic extensions.
Normal configured extensions load first and retain existing behavior.
Dynamic extensions load afterward in declared array order.
`subagentExtensions: "none"` suppresses only normal extensions, not explicit `dynamicExtensions`.

Generated tools must activate themselves during `session_start`, because Ultra cannot name them before loading.
The real-loader validation gate verifies this behavior.

### General mutating fanout

Fanout phases gain optional `writeIsolation`, a non-empty rationale explaining why each item owns disjoint mutation work.

Without `writeIsolation`, existing fanout law remains unchanged: initial tools are read-only plus bash, and the prompt must forbid mutation.
With `writeIsolation`, mutating tools are allowed and the prompt assigns disjoint ownership.
Ultra trusts the orchestrator's declaration.
It does not gate edit/write paths, suppress normal extensions, or attempt to constrain arbitrary custom mutators.

This general fanout relaxation ships with U008.

## Generated extension contract

Each extension covers one topic.
Builders modify an existing extension when the responsibility remains within that topic and create a new extension only for a distinct responsibility.

Names are two-to-four-term kebab-case domain capabilities.
Names contain no platform, version, model, session, `helper`, or `utils` terms.
Descriptions state a concrete capability in one sentence.

The manifest records durable semantics only:

- schema version
- name
- description
- topic
- scope
- non-goals
- tags
- declared capabilities
- required and optional executables
- explicit qualified overrides
- per-platform hot-path benchmark budgets

Provenance, validation results, timings, and source hash belong in `.ultra-validation.json`, not the manifest.

Every declared capability ID appears in the README test matrix and at least one `node:test` case name.
The README contains Purpose, Scope, Non-goals, Alternatives considered, Decision rationale, Usage, Architecture, Test matrix, and Promotion notes.
Alternatives and rationale remain durable documentation and are updated when overlap changes.

Generated extensions have no third-party runtime npm dependencies.
Pi host packages are declared as peer dependencies and added only when imported.
`package.json` remains private until manual promotion.
External executables are allowed when useful; the manifest declares required versus optional tools, and startup checks PATH through native Node APIs.

Generated source and tests use erasable TypeScript supported directly by Pi's Node 22.19+ requirement.
Transform-only enums, namespaces, parameter properties, and equivalent syntax are forbidden.

Entry modules stay thin.
Core logic is exported through pure modules and tested with `node:test`.
Tests use local fakes or loopback services and never external networks.
The real loader separately verifies Pi integration.

Generated extensions must support headless `print` mode.
TUI-only behavior guards TUI APIs, while the capability Ultra needs remains usable headlessly.

The built-in authoring contract requires:

- thin, non-blocking startup
- lazy optional work
- no startup subprocess probes or broad scans
- abort propagation
- bounded tool output
- compact default and expanded detail rendering
- native Node APIs over shell helpers
- no third-party runtime npm dependencies
- typed, actionable errors
- fast tests and benchmarks
- semantic Markdown lines

Loaded extensions must not intentionally modify their own catalog source.
Runtime state uses session entries or explicit project/user data paths; improvements go through checkout and validation.
This is an authoring invariant, not a sandbox restriction.
A later load detects source-hash drift.

Dynamic extensions may explicitly override normal registrations.
The manifest lists exact qualified targets such as `tool:read` or `provider:foo`.
Child composition blocks undeclared collisions with actionable diagnostics.
Normal extensions load before declared dynamic overrides.

## Mandatory scaffold

Every generated extension starts with:

```text
manifest.json
package.json
README.md
index.ts
index.test.ts
benchmark.ts
debug.ts
```

Additional helpers and tests are allowed.
`debug.ts` is copied from Ultra's versioned template.
Builders may call it but validation compares it byte-for-byte and provides a restore instruction when changed.
Validation writes `.ultra-validation.json`; builders do not author that file.

## Validation gates

Validation uses one fresh Node subprocess rooted at the extension draft.
It inherits the host environment and adds only `CI` plus validator temp/log paths.
It has full host permissions.
The parent captures bounded output, applies a hard timeout, and kills the process tree on abort or timeout.

U008 bundles no Biome, Vitest, formatter, linter, or TypeScript compiler.
It installs no dependencies during workflows.
Initial validation therefore includes:

1. manifest schema, naming, one-topic fields, tags, capabilities, executable declarations, override declarations, and benchmark budgets
2. README required sections, populated scaffold content, and capability/test-matrix mapping
3. package constraints and absence of third-party runtime npm dependencies
4. fixed `debug.ts` template
5. symlink rejection and deterministic whole-artifact hashing
6. all `node:test` files with capability mapping
7. required `benchmark.ts` contract and advisory current-platform hot-path budget comparison
8. real Pi SDK loading through scoped `DefaultResourceLoader`, in-memory `AgentSession`, `bindExtensions({ mode: "print" })`, `session_start`, registration inspection, and `session_shutdown`
9. active generated-tool verification
10. advisory marginal extension load timing
11. attestation generation and canonical publication

Real loading uses Pi SDK directly and makes no model call.
`pi-test-harness` is not required.

Five seconds is a warning target, not a quality gate.
Fifteen seconds is the hard validator watchdog.
The initial marginal load budget is 50 ms.
Hot-path budgets are declared per platform.
Builders may tighten an existing platform budget but may not loosen it.
All thresholds are named constants for later adjustment.

Test runtime does not fail merely for exceeding the five-second target, because a hard short target would reward deleting tests.
Capability mapping remains mandatory.
The watchdog remains a deadlock ceiling.
Marginal load and hot-path budget overruns are warnings because benchmark results require controlled conditions.

Validator-contract version participates in attestation validity.
After a contract update, search marks old attestations outdated and loading requires revalidation.

## Debug logs

Every generated extension writes minimal structured debug logs during normal use.
Builders choose topic-relevant events and enough context to reconstruct branches, state transitions, I/O, timings, and failures.
Logs may include arguments and results when diagnostically useful.
Builders must redact credentials and bound individual values; this is an instruction, not a secret scanner.

Logs use NDJSON with at least:

- timestamp
- extension name and revision
- child session ID
- event name
- duration where applicable
- contextual data

The log path is:

```text
<platform-cache>/pi/ultra/dynamic-extensions/logs/<child-session-id>/<extension-name>.jsonl
```

Ultra derives it from the persistent or in-memory child session ID.
Each extension/child log is capped at 1 MiB.
At the limit, the logger writes one truncation marker and drops later records.

Ultra never ingests logs automatically.
Workflow results expose their paths so the orchestrator can inspect them with normal tools when extension involvement is plausible.

## Runtime observation and repair

Intentional loading is the auditable usage boundary.
Ultra observes successful loading, registrations, dynamic tool calls/results, transcripts, final step results, and debug-log paths.
It cannot externally prove arbitrary hook semantics.
Tests remain the validation proof; runtime logs provide diagnosis.

Validation is revision-wide, not a per-platform load gate.
Search displays tested platforms as advisory metadata only.
An extension validated on another platform may load optimistically on the current platform.
Builders do not preemptively rewrite it solely because current-platform evidence is absent.

When a consumer behaves unexpectedly, Ultra returns extension identities, failure diagnostics, and log paths.
The orchestrator inspects relevant logs, launches a repair builder for the same topic, validates the new canonical revision, and reruns the original workflow.
There is no hard repair-cycle limit.
Runtime failures do not globally mark canonical extensions unhealthy because failures may be task-specific.

Rerunning the original workflow reuses unaffected journal checkpoints.
Canonical names resolve to the repaired hash, changing affected step keys and downstream resolved prompts.

## Reporting

`WorkflowResult` gains a deduplicated `dynamicExtensions` array.
Each entry contains:

- name
- short description
- exact loaded name/hash selector
- exact loaded source path
- associated child debug-log paths

Extensions loaded by successful, failed, or aborted steps are reported after successful binding.
An attempted extension that failed before binding is diagnostic, not used.
Cached/resumed workflow results preserve usage metadata without charging new model usage.

`/ultra run` prints one final dynamic-extension block containing only name, short description, and exact source path.
The model-visible `run_workflow` result contains the complete metadata.
The collapsed tool widget remains compact and shows per-extension information only when expanded.

## Startup and lifecycle

Catalog directories, cleanup, search code, validator code, and generated-extension implementation are lazy-loaded on first dynamic-extension action or first `dynamicExtensions` resolution.
Ordinary Ultra startup and reload perform no catalog scan, process spawn, cleanup, or Git operation.
Reload remains terminal for the invoking handler.

## Acceptance

U008 is complete only when automated tests cover:

- lazy startup with no catalog/process work
- deterministic search ranking and bounded results
- required prior search and duplicate-topic rationale
- create and checkout scaffolds
- manual canonical validation
- all validation gates and structured multi-diagnostics
- validator timeout and abort process-tree cleanup
- source hashing and attestation invalidation
- concurrent publication without clobbering
- stale-base builder recovery
- atomic `current.json` publication on Windows, macOS, and Linux behavior paths
- exact run-local snapshot loading
- additive normal plus dynamic extension loading
- explicit override collision diagnostics
- generated tool activation during `session_start`
- builder-only prompt injection and full tool access without `run_workflow`
- known-name direct consumer loading
- multiple ordered dynamic extensions
- blocked consumer phases after builder failure
- general `writeIsolation` fanout behavior and preserved default read-only law
- dynamic hash participation in step keys and resume behavior
- debug-log format, cap, retention, and result paths
- success, failure, abort, cached, and resumed reporting
- unchanged collapsed tool-widget behavior
- no regression to token/cost accounting

Live acceptance must exercise creation, reuse, a stale or manually invalidated extension, consumer loading, debug-log inspection, repair, rerun checkpoint reuse, parallel isolated builders, cancellation, and final reporting.