Title: mcpx: lifecycle hooks on exec — prePrompt/postPrompt/onError as one declared list, script or prompt, with a declared effect · Issue #1929 · developing-today/code · GitHub
Open Graph Title: mcpx: lifecycle hooks on exec — prePrompt/postPrompt/onError as one declared list, script or prompt, with a declared effect · Issue #1929 · developing-today/code
X Title: mcpx: lifecycle hooks on exec — prePrompt/postPrompt/onError as one declared list, script or prompt, with a declared effect · Issue #1929 · developing-today/code
Description: Relocated from dezren39/darwin-nix#112 on 2026-10-28 (placement audit): mcpx's single source lives in developing-today/code (pkgs/mcpx); re-home tracked at #309. Original body below; issue references inside it are historical (dezren39/ni...
Open Graph Description: Relocated from dezren39/darwin-nix#112 on 2026-10-28 (placement audit): mcpx's single source lives in developing-today/code (pkgs/mcpx); re-home tracked at #309. Original body below; issue referenc...
X Description: Relocated from dezren39/darwin-nix#112 on 2026-10-28 (placement audit): mcpx's single source lives in developing-today/code (pkgs/mcpx); re-home tracked at #309. Original body below; issue refe...
Opengraph URL: https://github.com/developing-today/code/issues/1929
X: @github
Domain: github.com
IPv4 address: 140.82.114.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"mcpx: lifecycle hooks on exec — prePrompt/postPrompt/onError as one declared list, script or prompt, with a declared effect","articleBody":"Relocated from dezren39/nix#112 on 2026-10-28 (placement audit): mcpx's single source lives in developing-today/code (pkgs/mcpx); re-home tracked at #309. Original body below; issue references inside it are historical (dezren39/nix numbering).\n\nParent: #176\n\n## Summary\n\n`mcpx exec` runs a script and returns what it produced. This asks for the caller to be able to attach natural-language instructions to the *edges* of that run — before it, after it, on failure, on success — so the deterministic script stays deterministic and the fuzzy parts sit outside it.\n\nThat is a better factoring than it first appears. The script is the part that must be reproducible; \"make sure these dependencies exist wherever this runs\" and \"clean up the results and transform them\" are the parts that legitimately vary by environment and by caller. Keeping them out of the script means the same script file works everywhere and the variation is in the *options*, which is exactly the shape `ExecOptions` was designed for (#40, step 7: \"not a new method, an option\").\n\n## Original notes\n\n> - mcp-owned opencode api support\n> - accept prompt/prePrompt/postPrompt/onErrorPrompt/onSuccessPrompt\n> - the script interface just runs the scripts, but you can provide a prePrompt saying hey i added a bunch of dependencies please make sure they exist where the job runs, postPrompt to clean up the results and transform, either prompt/pre/post could say to fix error thing but onError gets provided above or below the error and is first seen with the error if theres an error. prompts can use templatevars to put content where they want it or for prompt overall to be stopped/resumed maybe.\n\n## Current state (what mcpx does today, with file refs)\n\n- **`execsvc.Options`** (`internal/execsvc/execsvc.go:101`) is the designated growth point: \"Deliberately one flat struct that grows rather than a new endpoint per capability.\" It carries `Runtime`, `Timeout`, `Permissions`, `Placeholders`, `Session`, `Cwd`, `Env`, `Stdin`, `Output`, `Capabilities`, `Artifacts`, `Task`, `NS`, `Args`, `Export`. There are no prompt fields.\n- **Placeholders already exist and already have substitution semantics worth copying.** Recipes declare holes in a header comment (`// @param repo:string`) and reference them as `@repo`; values are substituted **as JSON, never as text**, because \"a recipe runs with the user's credentials; raw substitution would make every placeholder an injection site\" (`docs/consumer.md` §3). Launchers use the same `@placeholder` spelling (#7). A recipe with an unfilled required hole is an invalid script, which is the right way round.\n- **`ScriptConfig.Prefix`** (`internal/config/config.go:236-248`) already layers *code* in front of a script from config, resolved across the config chain (`docs/proposals.md` §\"Layered script prefixes\"). It is the deterministic sibling of a prePrompt and the precedent for how layering should work.\n- **Deterministic edge hooks already ship — for the CLI and config, not for `/v1/exec`.** (Added in the 2026-09-30 issues pass, at 05c78b2; this issue predated them being noticed.) Five settings — `script.before`, `script.prefix`, `script.onSuccess`, `script.onError`, `script.suffix` (`internal/settings/registry.go:212-242`), layered through `ScriptConfig` (`internal/config/config.go:236-257`) and rendered as `runner.Phases` (`internal/runner/runner.go:190-205`) — inject source into a file script's launcher: `onSuccess` sees `result.value`, `onError` sees `result.error` and **the error is rethrown** (\"a hook, not a handler\"), `suffix` runs in a `finally`. They run inside the script's own process, and they are deliberately **not** on the wire `Options`: `execsvc.RunWith` keeps phases CLI-only (`internal/execsvc/execsvc.go:358-366`). So Approach B below is partly built already, in a different shape; what is missing is per-call hooks over `/v1` and MCP, a typed context, and prompt hooks. The shipped names are one of the four hook vocabularies in #181 collision 2.\n- **The exec stream has an ordering contract**: `start`, then `log`/`emit`/`stdout` interleaved, then `artifact`, then `result` or `error`, then `end`, with bodies strictly after `end` (`execsvc.Frame`, `docs/exec.md`). Any hook output has to find a place in that order, and that is a real design constraint, not a formality.\n- **`internal/diagnose`** produces structured diagnostics that already sit next to an error.\n- **Tasks** (`internal/tasks`) provide the pause/resume machinery the note's \"stopped/resumed maybe\" is reaching for, and `2026-07-28`'s MRTR pattern gives a caller-facing way to resume a request mid-flight.\n- mcpx has no model; see #110. Every rung below degrades to a no-op without one.\n\n## Approaches\n\n### Approach A — least recommended: five new string options, each handed to a model, each running arbitrary code\n\n`Options.Prompt`, `.PrePrompt`, `.PostPrompt`, `.OnErrorPrompt`, `.OnSuccessPrompt`, each sent to a model with a general-purpose agent loop that can do whatever it decides is needed.\n\nWhy not:\n\n- **Four of the five are the same thing at different times.** Five independent fields means five code paths, five sets of semantics, and five places to fix a bug. Lifecycle hooks are a list of (phase, instruction), and modelling them as one list with a phase is strictly better — `prompt` is then just \"the phase is `main`\", which is also what makes \"either prompt/pre/post could say to fix error thing\" fall out naturally instead of needing to be special-cased.\n- **An unbounded prePrompt is arbitrary code execution as a side door.** \"make sure these dependencies exist where the job runs\" resolved by a general agent means installing packages, which is the provisioning problem from #113 and needs its own confinement decisions. An exec option should not quietly be the more powerful interface.\n- **It puts the model on the default path.** Every run pays a round trip even when the hooks do nothing surprising. `docs/consumer.md`'s rule — \"never sample on a path that doesn't need it\" — is violated by construction if hooks are evaluated eagerly.\n- **Nothing is reproducible.** The same script plus the same prompts gives different behaviour run to run, which destroys the one property that makes `exec` worth having over a chat turn.\n\n### Approach B — middle: one `hooks` list, deterministic hooks only\n\nAdd one field:\n\n```jsonc\n\"options\": {\n \"hooks\": [\n { \"phase\": \"pre\", \"script\": \"ensure-deps.ts\" },\n { \"phase\": \"post\", \"script\": \"normalise.ts\" },\n { \"phase\": \"onError\", \"script\": \"cleanup.ts\" }\n ]\n}\n```\n\nPhases: `pre`, `main`, `post`, `onError`, `onSuccess`. Each hook is a script, run in the same content-addressed workdir with the same runtime and permissions, receiving a typed context (the run id, the result or the error plus its `diagnose.Diagnostic`, the artifact list). `post` transforms the result; `onError` sees the error first and may return a replacement result or re-raise — which differs from the shipped `script.onError`, where the error always propagates.\n\n**The phase names and hook semantics are not this issue's to decide (#181 collision 2).** Four vocabularies exist or are proposed — the shipped `script.*` phases, #81's hook points, #82's runtime hooks and this list — and the one vocabulary is being decided in a decision record SURFACES is writing under `pkgs/mcpx/docs/decisions/`, carried by #81. The phases here are input to that record; this issue adopts what it decides.\n\nThis is genuinely useful on its own — `ScriptConfig.Prefix` proves the demand for \"run this code around my code\" and hooks generalise it to the other three edges — and it is the thing the prompt version needs underneath it anyway, because a prompt hook's output has to *become* something executable. It is also fully deterministic, cacheable, and testable.\n\nWhat it does not give you is the actual ask: \"hey i added a bunch of dependencies please make sure they exist where the job runs\" is a sentence, not a script, and the whole point is not having to write the script.\n\n### Approach C — recommended: one `hooks` list where a hook is *either* a script or a prompt, with a declared effect\n\nBuild B's structure, and let each entry be a script **or** a prompt:\n\n```jsonc\n\"options\": {\n \"hooks\": [\n { \"phase\": \"pre\", \"prompt\": \"I added @deps — make sure they exist where this runs\",\n \"effect\": \"script\", \"model\": \"cheap\" },\n { \"phase\": \"post\", \"prompt\": \"flatten the result to {id, title} and drop nulls\",\n \"effect\": \"transform\" },\n { \"phase\": \"onError\", \"prompt\": \"if this is a rate limit, wait and say so; otherwise explain\",\n \"effect\": \"advise\" }\n ]\n}\n```\n\nFour decisions make this safe and small:\n\n**1. A hook declares its effect, and the effect bounds what it may do.**\n\n| `effect` | what the hook's output may be | runs code? |\n| --- | --- | --- |\n| `advise` | text, attached to the result or error | no |\n| `transform` | a replacement for the result value only | no |\n| `script` | TypeScript, diagnosed and typechecked, then run in the same sandbox | yes |\n| `retry` | a decision: retry / retry-with-changes / give up | via the repair ladder |\n\n`advise` is the default. This is the same dial as `repair.level` in #111 and should use the same vocabulary; a user who understands one understands the other. **#181 collision 3:** #111 carries that one dial vocabulary, via the SURFACES decision record under `pkgs/mcpx/docs/decisions/`; the `effect` values in this table are input to it, and #112 adopts what it decides rather than shipping its own. The ceiling a daemon puts on it is #185 (collision 5). A prompt hook whose effect is `script` is the only one that can execute anything, and it inherits `Options.Permissions` unchanged — a hook must never be able to do what the script it wraps could not.\n\n**2. Template variables reuse the placeholder machinery that exists, including its safety property.** `@name` is already the spelling in recipes and launchers, and recipe values are **JSON-encoded, not text-substituted**, precisely so a placeholder cannot become an injection site. A prompt is text and the same discipline applies at a different layer: the substituted value must be delimited and marked as data, and a hook prompt must never be able to redefine the hook's own `effect`. Beyond user placeholders, offer a small set of built-ins the note is clearly asking for — `@result`, `@error`, `@diagnostic`, `@calls`, `@artifacts`, `@source` — so \"onError gets provided above or below the error\" is expressible as `\"Here is what happened:\\n@error\\n@diagnostic\\nWhat should I do?\"` rather than being a positioning rule mcpx has to guess. **Position by template, not by convention**; when a prompt contains no built-in reference, mcpx appends the context after it, which is the sensible default the note describes.\n\n**3. Hooks are declarable in config, not just per call.** `ScriptConfig.Prefix` and the shipped `script.before`/`onSuccess`/`onError`/`suffix` already layer across the config chain; `script.hooks` (or whatever collision 2's record names it) should layer the same way, so \"always check dependencies before any run in this project\" is written once. Per-call hooks append to config hooks rather than replacing them, with the same nearest-wins resolution `ResolveLines` already implements.\n\n**4. Stop/resume is `internal/tasks`, not a new mechanism.** \"for prompt overall to be stopped/resumed maybe\" — a hook that needs a decision raises an elicitation through the existing broker (with a default and a deadline, as `elicit.Ask` enforces), and a run that must wait becomes a task with a handle, collectable from `/v1/tasks/{id}`. Both already exist and both already work for the recipe path. On `2026-07-28` this is also exactly MRTR: `resultType: \"input_required\"`, the client answers, the request is retried.\n\n**Stream placement**, since the `Frame` order is a contract (`docs/exec.md:137`). **#181 collision 7:** #111 owns the rule every new frame kind follows (declared placement relative to `result`, listed in the documented order, asserted by a test comparing documented and emitted order); the `hook` frame is added under that rule and the placement below is input to it: a hook emits `log`/`emit`/`stdout` frames tagged with its phase and a `hook` frame recording phase, effect, model used, duration and whether it changed anything. `pre` frames come after `start`; `post`/`onSuccess` frames come after the `result` frame and before `end`; `onError` frames come after `error` and before `end`. The final `result` reflects a `transform` hook's output, with the original preserved in the `hook` frame — a caller must be able to see what mcpx changed.\n\n**Cost and default posture.** Hooks are off unless declared. A prompt hook without an available model is a warning on the run, not a failure — the script still ran, and that is the honest degradation. `pre` hooks with `effect: script` should be cached by (prompt, placeholder values, catalogue fingerprint) so the same \"ensure my dependencies\" instruction resolves to the same generated script on every run instead of re-generating it; that caching is also what makes the generated script reviewable and promotable to a real hook script, which is how this feature should be expected to be *used* — prompt once, keep the script.\n\nRecommended because the structure is one list rather than five fields, because effect-declaration is what keeps a convenience feature from being an execution back door, because everything it needs — placeholders, prefixes, tasks, elicitation, diagnostics, artifacts — already exists and this mostly wires them to four new points in time, and because the deterministic half (Approach B) is independently valuable and ships first.\n\n## Open questions\n\n- Does `onSuccess` earn its own phase when `post` exists? `post` running only on success and `onError` on failure covers it; a separate `onSuccess` is only distinct if `post` is meant to run on both. Pick one and document it — this is the note's ambiguity, not a design difficulty.\n- Ordering when several hooks share a phase: declaration order across config layers, or an explicit `order`? Declaration order plus nearest-wins layering matches `ScriptPrefix`.\n- Should a `transform` hook be allowed to change artifacts, or only the result value? Only the value is far simpler and probably enough.\n- Timeout accounting: does a hook's time count against `Options.Timeout` or get its own budget? Its own, or a slow model silently eats the script's budget.\n- Is there a case for hooks on a *tool call* rather than a run (`before every call to this server, ...`)? That is closer to a server-level middleware feature and may belong with tool views.\n- Should a hook be able to abort the run before it starts (`pre` returning refuse)? Useful and cheap, but then a `pre` hook is a policy mechanism and needs the floor/ceiling clamping #185 owns.\n\n## Ease · Impact · Related\n\n**Ease** M (S for the deterministic half — much of it already ships as `script.*` launcher phases, so what remains is exposing them per call with a typed context; M with prompt hooks and effects; L if stop/resume gets its own machinery rather than reusing tasks) · **Impact** medium-high — it is what makes one script file portable across environments without the script knowing where it runs, which is the same goal #40 had for artifacts.\n\n**Depends on / related**: #81 (owns the hook vocabulary via the SURFACES decision record — #181 collision 2), #111 (owns the autonomy dial and the frame-order rule — collisions 3 and 7), #185 (owns `ClampedBy` — collision 5), #82 (runtime hook registration, the fourth vocabulary), #40 (closed, fixed in #57: ExecOptions is the home; \"not a new method, an option\" is the governing precedent), #41 (closed, fixed in #58: placeholders, elicitation defaults/deadlines, diagnostics as hook context), #7 (launcher `@placeholder` spelling), #5 (config chain, for layered hooks), #79 (hook cost must not regress exec latency). Siblings: #110 (where a prompt hook's model comes from), #113 (the dependency-provisioning half of the `pre` example; also #103/#104 in #175).\n\nSecurity/auth deferred; see tracker.\n\n","author":{"url":"https://github.com/dezren39","@type":"Person","name":"dezren39"},"datePublished":"2026-10-28T22:34:10Z","url":"https://github.com/developing-today/code/issues/1929"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:9e1444b8-e69f-8e3f-d8ff-8a7e3121ed10 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | CD0C:1293AE:34545E:44CEE0:6B0617FF |
| html-safe-nonce | 764198da7da097b581055f528fb4436660f13bf8e3d874d6dda94d48f82b29df |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDRDBDOjEyOTNBRTozNDU0NUU6NDRDRUUwOjZCMDYxN0ZGIiwidmlzaXRvcl9pZCI6IjY1ODIyODU5NTg0NDI3ODQ3NjgiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | a4968cbc593ead216c79ab29234441d461fd48cc42c31ea3255c5710fdacbce2 |
| hovercard-subject-tag | issue:6088743812 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/developing-today/code/1929/issue_layout |
| twitter:image | https://opengraph.githubassets.com/d66a1e7c1300d9ccb550672602bd042e1929a4418388606ce988a725c021c982/developing-today/code/issues/1929 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/d66a1e7c1300d9ccb550672602bd042e1929a4418388606ce988a725c021c982/developing-today/code/issues/1929 |
| og:image:alt | Relocated from dezren39/darwin-nix#112 on 2026-10-28 (placement audit): mcpx's single source lives in developing-today/code (pkgs/mcpx); re-home tracked at #309. Original body below; issue referenc... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | dezren39 |
| hostname | github.com |
| expected-hostname | github.com |
| None | 97d4714e567728e1f85f88b0cf68c89f0f8a3dc41e8869af7aeb8195ad990374 |
| turbo-cache-control | no-preview |
| go-import | github.com/developing-today/code git https://github.com/developing-today/code.git |
| octolytics-dimension-user_id | 26439447 |
| octolytics-dimension-user_login | developing-today |
| octolytics-dimension-repository_id | 627308783 |
| octolytics-dimension-repository_nwo | developing-today/code |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 627308783 |
| octolytics-dimension-repository_network_root_nwo | developing-today/code |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 866f202ebf7ac5aff8f633417d9fd8a53818a977 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width